blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
201
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
7
100
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
260 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
11.4k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
80 values
src_encoding
stringclasses
28 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
8
9.86M
extension
stringclasses
52 values
content
stringlengths
8
9.86M
authors
listlengths
1
1
author
stringlengths
0
119
d720aed69e0faa632905dfa8aa4e318aae73e31b
5e95e1a37fdb4713c5eb30bfbf1e5be2cf311915
/src/UniverseAdvanced/CloudUtilities/ComponentInstaller.h
dd63a3b4c8f4c84ebd8fbacddd46322bf8d30ca6
[]
no_license
CycCoder/OpenUniverse
bd489d2be99665ce702c31b1aae74c66f8ab7490
cba537a9fedb7ea1f31637a813283e9226f82f33
refs/heads/master
2023-04-03T00:43:09.523448
2021-02-02T00:11:51
2021-02-02T00:11:51
null
0
0
null
null
null
null
GB18030
C++
false
false
2,312
h
/******************************************************************************** * Web Runtime for Application - Version 1.0.0.202102020022 * ******************************************************************************** * Copyright (C) 2002-2021 by Tangram Team. All Rights Reserved. * There are Three Key Features of Webruntime: * 1. Built-in Modern Web Browser: Independent Browser Window and Browser Window * as sub windows of other windows are supported in the application process; * 2. DOM Plus: DOMPlus is a natural extension of the standard DOM system. * It allows the application system to support a kind of generalized web pages, * which are composed of standard DOM elements and binary components supported * by the application system; * 3. JavaScript for Application: Similar to VBA in MS office, JavaScript will * become a built-in programmable language in the application system, so that * the application system can be expanded and developed for the Internet based * on modern javscript/Web technology. * Use of this source code is governed by a BSD-style license that * can be found in the LICENSE file. * * CONTACT INFORMATION: * mailto:tangramteam@outlook.com or mailto:sunhuizlz@yeah.net * https://www.tangram.dev *******************************************************************************/ #pragma once #include "XZip.h" namespace Utilities { class CComponentInstaller { public: CComponentInstaller(void); ~CComponentInstaller(void); CString m_strHostFile; //压缩一个文件 BOOL Zip(LPCTSTR lpszZipArchive, LPCTSTR lpszSrcFile); //解压压缩包内的文件 void VerifyZip(HZIP hz, LPCTSTR lpszFile, LPCTSTR lpszPath); //进行文件比较 BOOL Compare(LPCTSTR lpszFile1, LPCTSTR lpszFile2, BOOL *pbResult); //解压压缩包内的文件,支持一个文件,并以strName命名,strName带路径 BOOL UnZip(CString strZip, CString strName); //解压压缩包内的文件,支持多个文件,并不改名 BOOL UnMultiZip(CString strZip, CString strPath); BOOL UnMultiZip2(CString strZip, CString strPath); BOOL InstallComponent(CString strXml); BOOL RegComDll(const CString& strDllLib); BOOL UnRegComDll(const CString& strDllLib); BOOL SetDirectory(CString strFile); }; }
[ "sunhuizlz@yeah.net" ]
sunhuizlz@yeah.net
9412d9fc562eb874c5d25af5cf965c89948030b2
a2ee7bdda1ec77faf3f68b158da3523de425987e
/tp-entrega-03/common/Jugador.cpp
f5cac30f243756482bdb9c197f7de2842761ef5f
[]
no_license
MauroToscano/Taller-de-Programacion-I-Grupo-8
e495cbc27b76533619e0fc36c9826fe8a51e1645
1b5e6c6e3eda8eb1c11ab905fa75e75a571234a5
refs/heads/master
2022-07-20T04:00:08.267771
2020-02-25T23:44:10
2020-02-25T23:44:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
418
cpp
#include "Jugador.h" Jugador::Jugador() { this->idCliente = -1; this->nombreDeUsuario.assign(""); } Jugador::~Jugador() { } void Jugador::setIdCliente(int idCliente){ this->idCliente = idCliente; } int Jugador::getIdCliente(){ return this->idCliente; } void Jugador::setPosicionAvion(Posicion pos) { this->poscion = pos; } Posicion Jugador::getPosicion() { return this->poscion; }
[ "cbenez@gmail.com" ]
cbenez@gmail.com
3d64f467567e90221fd1ef2739bc740f135e12d0
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/httpd/gumtree/httpd_repos_function_2743_httpd-2.2.11.cpp
c692018c017bbc29fb31e60bfd88e1cf4b225b9e
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,240
cpp
static void check_error(apr_dbd_t *dbc, const char *step, SQLRETURN rc, SQLSMALLINT type, SQLHANDLE h, int line) { SQLCHAR buffer[512]; SQLCHAR sqlstate[128]; SQLINTEGER native; SQLSMALLINT reslength; char *res, *p, *end, *logval=NULL; int i; apr_status_t r; /* set info about last error in dbc - fast return for SQL_SUCCESS */ if (rc == SQL_SUCCESS) { char successMsg[] = "[dbd_odbc] SQL_SUCCESS "; dbc->lasterrorcode = SQL_SUCCESS; strcpy(dbc->lastError, successMsg); strcpy(dbc->lastError+sizeof(successMsg)-1, step); return; } switch (rc) { case SQL_INVALID_HANDLE : { res = "SQL_INVALID_HANDLE"; break; } case SQL_ERROR : { res = "SQL_ERROR"; break; } case SQL_SUCCESS_WITH_INFO : { res = "SQL_SUCCESS_WITH_INFO"; break; } case SQL_STILL_EXECUTING : { res = "SQL_STILL_EXECUTING"; break; } case SQL_NEED_DATA : { res = "SQL_NEED_DATA"; break; } case SQL_NO_DATA : { res = "SQL_NO_DATA"; break; } default : { res = "unrecognized SQL return code"; } } /* these two returns are expected during normal execution */ if (rc != SQL_SUCCESS_WITH_INFO && rc != SQL_NO_DATA) dbc->can_commit = 0; p = dbc->lastError; end = p + sizeof(dbc->lastError); dbc->lasterrorcode = rc; p += sprintf(p, "[dbd_odbc] %.64s returned %.30s (%d) at %.24s:%d ", step, res, rc, SOURCE_FILE, line-1); for (i=1, rc=0 ; rc==0 ; i++) { rc = SQLGetDiagRec(type, h, i, sqlstate, &native, buffer, sizeof(buffer), &reslength); if (SQL_SUCCEEDED(rc) && (p < (end-280))) p += sprintf(p, "%.256s %.20s ", buffer, sqlstate); } r = apr_env_get(&logval, "apr_dbd_odbc_log", dbc->pool); /* if env var was set or call was init/open (no dbname) - log to stderr */ if (logval || !dbc->dbname ) { char timestamp[APR_CTIME_LEN]; apr_file_t *se; apr_ctime(timestamp, apr_time_now()); apr_file_open_stderr(&se, dbc->pool); apr_file_printf(se, "[%s] %s\n", timestamp, dbc->lastError); } }
[ "993273596@qq.com" ]
993273596@qq.com
0d625b5eedc74539649e7f5c9bd1dda67df330b1
5a39a122d0c41bbff0f997cf358c6bc03775a881
/boostExamples/Algorithm.cpp
d655672a824217a396f043d6f0438a5c6158f66c
[ "MIT" ]
permissive
tejasCodes/boostExamples
e1df6d8a45c876c37197f65f914dfb9945e6fad7
676bb6810482e7fb95c66cdedd5b3ab67bf7efc9
refs/heads/master
2020-05-07T20:16:43.165549
2019-04-11T20:24:34
2019-04-11T20:24:34
180,852,479
0
0
null
null
null
null
UTF-8
C++
false
false
859
cpp
#include "stdafx.h" // project includes #include "Algorithm.h" // windows includes #include <Windows.h> // boost includes #include "boost\algorithm\searching\boyer_moore.hpp" void Algorithm::BoyerMooreSerach() { std::vector<std::wstring> names; names.push_back(L"Rahul"); names.push_back(L"John"); names.push_back(L"Alexa"); names.push_back(L"Tejas"); names.push_back(L"Alexandra"); std::vector<std::wstring> pattern; pattern.push_back(L"Alexandr"); auto itr = boost::algorithm::boyer_moore_search<std::vector<std::wstring>, std::vector<std::wstring>>(names, pattern); if (itr != names.end()) { OutputDebugString(std::wstring(L"pattern found in the names " + *itr).c_str()); } else { OutputDebugString(std::wstring(L"pattern not found in the names").c_str()); } }
[ "tejaskatakdhond@gmail.com" ]
tejaskatakdhond@gmail.com
ca638166d8c362049f74b0e857e421f5a5de9e8a
59b2d9114592a1151713996a8888456a7fbfe56c
/class/OS/d.cpp
e839ed4b5a8670c323a2c299987d587637c3a68d
[]
no_license
111qqz/ACM-ICPC
8a8e8f5653d8b6dc43524ef96b2cf473135e28bf
0a1022bf13ddf1c1e3a705efcc4a12df506f5ed2
refs/heads/master
2022-04-02T21:43:33.759517
2020-01-18T14:14:07
2020-01-18T14:14:07
98,531,401
1
1
null
null
null
null
UTF-8
C++
false
false
971
cpp
/* *********************************************** Author :111qqz Created Time :2016年04月22日 星期五 10时34分37秒 File Name :d.cpp ************************************************ */ #include <cstdio> #include <cstring> #include <iostream> #include <algorithm> #include <vector> #include <queue> #include <set> #include <map> #include <string> #include <cmath> #include <cstdlib> #include <ctime> #define fst first #define sec second #define lson l,m,rt<<1 #define rson m+1,r,rt<<1|1 #define ms(a,x) memset(a,x,sizeof(a)) typedef long long LL; #define pi pair < int ,int > #define MP make_pair using namespace std; const double eps = 1E-8; const int dx4[4]={1,0,0,-1}; const int dy4[4]={0,-1,1,0}; const int inf = 0x3f3f3f3f; int main() { #ifndef ONLINE_JUDGE freopen("code/in.txt","r",stdin); int ne = -1; if (ne<0) cout<<"wooooo"<<endl; if (ne==-1) cout<<"yoooooo"<<endl; #endif #ifndef ONLINE_JUDGE fclose(stdin); #endif return 0; }
[ "111qqz" ]
111qqz
410522e72520b2c236d8ce72ce7db994d7b4d588
ef7ad96103876b24bbb45be8dfba7e80771c76e7
/ui-qt/ToolLib/Detection/ContourPoints/FWContourPointLabel.cpp
04255cf37209352d203c99e7bea80f3635b03dc3
[ "MIT" ]
permissive
TinySlik/FPGA-Industrial-Smart-Camera
ecb6274f4ef16cf9174cd73812486644f821152a
54b3e2c2661cf7f6774a7fb4d6ae637fa73cba32
refs/heads/master
2021-06-25T11:09:21.212466
2017-09-01T07:23:58
2017-09-01T07:23:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
164
cpp
#include "FWContourPointLabel.h" FWContourPointLabel::FWContourPointLabel(QWidget *parent) : QLabel(parent) { } FWContourPointLabel::~FWContourPointLabel() { }
[ "1245552661@qq.com" ]
1245552661@qq.com
b052e1f1ccc94a8d38727410fab2d65abbd171a5
10ecd7454a082e341eb60817341efa91d0c7fd0b
/SDK/ALK_WieldableObject_Compass_classes.h
d52cb57629a90a10c104400b16778af37e10043b
[]
no_license
Blackstate/Sot-SDK
1dba56354524572894f09ed27d653ae5f367d95b
cd73724ce9b46e3eb5b075c468427aa5040daf45
refs/heads/main
2023-04-10T07:26:10.255489
2021-04-23T01:39:08
2021-04-23T01:39:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
793
h
#pragma once // Name: SoT, Version: 2.1.0.1 /*!!DEFINE!!*/ /*!!HELPER_DEF!!*/ /*!!HELPER_INC!!*/ #ifdef _MSC_VER #pragma pack(push, 0x01) #endif namespace CG { //--------------------------------------------------------------------------- // Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass ALK_WieldableObject_Compass.ALK_WieldableObject_Compass_C // 0x0000 (FullSize[0x0028] - InheritedSize[0x0028]) class UALK_WieldableObject_Compass_C : public UWieldableItemAnimationStoreId { public: static UClass* StaticClass() { static auto ptr = UObject::FindClass("BlueprintGeneratedClass ALK_WieldableObject_Compass.ALK_WieldableObject_Compass_C"); return ptr; } }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "ploszjanos9844@gmail.com" ]
ploszjanos9844@gmail.com
188bd800202246cf378bfd0136a9e9220824f5c2
3ade933f7b4e7e0dd4d3b404dda6f009a52682f3
/general/Echantillon.h
671ece9e6ce194e9ff7d93f5cc5f30cc5c419fe5
[]
no_license
Lauryverhoeven/ProjetMontagne
af76c1c9c5d33cf601c8a6e4bac0a3a26e48b644
eebb38349e73a9977bcd1f3a17476e7d50ec595d
refs/heads/main
2023-05-14T14:55:48.276965
2021-06-03T14:21:06
2021-06-03T14:21:06
373,308,007
0
0
null
null
null
null
UTF-8
C++
false
false
997
h
// // Created by Ömer Doruk Süder on 22.04.2021. // #ifndef PROGICC_ECHANTILLON_H #define PROGICC_ECHANTILLON_H #endif //PROGICC_ECHANTILLON_H #pragma once #include <array> //superclasse de champPotentiels et Ciel (permet de regrouper leurs attributs communs) class Echantillon { protected: std:: array <unsigned int,3> nbCubes{}; //vecteur qui contient le nombre de petits cubes dans chaque direction std:: array <double,3> cotes{}; //vecteur qui indique la longueur des cotes du gros cube double lambda; public: Echantillon() = default; //constructeur par défaut Echantillon(unsigned int Nx,unsigned int Ny, unsigned int Nz, double lambda) : nbCubes({Nx, Ny, Nz}), cotes({(Nx) * lambda, (Ny) * lambda, (Nz) * lambda}),lambda(lambda) {} //constructeur unsigned int getNx() const; unsigned int getNy() const; unsigned int getNz() const; double getlambda() const; void update(unsigned int Nx,unsigned int Ny, unsigned int Nz, double lambda); };
[ "noreply@github.com" ]
noreply@github.com
385c79fb819aced625046c3e87ffd7db08fc7cfa
912ec9f6e968b22f2ac77ec6084645386b70bea1
/trunk/tutorial/SceneEditor/TerrainTextureState.cpp
45651996de146611153af1ca9491244af348087f
[]
no_license
cpzhang/zen
9156413d93f7dc9c5b48b9bd1e5cdb5a5b1657da
6d6e06278aa37eb279e05c9097fd964bf476c939
refs/heads/master
2016-09-05T15:24:06.565446
2013-03-19T12:29:28
2013-03-19T12:29:28
7,439,357
0
1
null
null
null
null
GB18030
C++
false
false
6,484
cpp
#include "TerrainTextureState.h" #include "misc/helper.h" #include "misc/windowsHead.h" #include "scene/Terrain.h" #include "scene/SceneManager.h" #include "scene/Chunk.h" #include "render/math.h" #include "render/Decal.h" #include "scene/QuadNode.h" #include "font/FlowText.h" #include "Global.h" void TerrainTextureState::update() { if (getSceneManager() && getSceneManager()->getTerrain() && BrushDecalInner_ && BrushDecalOuter_) { Vector2 pp = getSceneManager()->getPickingPoint(); BrushDecalInner_->setCenter(Vector4(pp.x, 0, pp.y, 1)); BrushDecalOuter_->setCenter(Vector4(pp.x, 0, pp.y, 1)); } if (isKeyDown(VK_LBUTTON)) { if (getBrushTextureFile().empty()) { FlowText::getSingletonP()->add("无法刷地表,未选中地表纹理文件", Vector4(1, 1, 1, 1)); return; } if (getSceneManager() && getSceneManager()->getTerrain()) { Terrain* t = getSceneManager()->getTerrain(); Vector4 center = BrushDecalOuter_->getCenter(); LOD* d = getSceneManager()->getLOD(); int n = d->getVerticesNumberOneSide(); float alphaMapInterval = d->getChunkSize() / (Chunk::tAlphaMapUnCompressedSize - 1); float radius = BrushDecalOuter_->getRadius(); RectangleT rc; rc.left_ = center.x - radius; rc.right_ = center.x + radius; rc.bottom_ = center.z - radius; rc.top_ = center.z + radius; ChunkVec cs; getSceneManager()->getChunks(cs, getSceneManager()->getTerrainQuadTreeRoot(), rc); for (size_t i = 0; i != cs.size(); ++i) { Chunk* c0 = cs[i]; c0->setSelected(true); // eTerrainLayer ln = c0->getLayer(getBrushTextureFile()); if (ln == eTerrainLayer_Size)//没找到该层 { ln = c0->getNextLayer();//新加一层 if (ln == eTerrainLayer_Size) { FlowText::getSingletonP()->add("纹理已满,无法增加Layer或修改AlphaMap", Vector4(1, 1, 1, 1)); continue;//已满,需要删除某层才能继续添加 } c0->setLayer(ln, getBrushTextureFile()); } Vector2 baseP = c0->getWorldCoordination(0, n - 1); bool dirty = false; for (int x = 0; x != Chunk::tAlphaMapUnCompressedSize; ++x) for (int y = 0; y != Chunk::tAlphaMapUnCompressedSize; ++y) { Vector2 p; p.x = baseP.x + x * alphaMapInterval; p.y = baseP.y - y * alphaMapInterval; float distance2 = (p.x - center.x)*(p.x - center.x) + (p.y - center.z)*(p.y - center.z); { int c = 0; float outRadius2 = getBrushRadiusOuter(); outRadius2 *= outRadius2; if (distance2 > outRadius2) { c = 0; } else { float inRadius2 = getBrushRadiusInner(); inRadius2 *= inRadius2; if (distance2 > inRadius2) { float r = (outRadius2 - distance2) / (outRadius2 - inRadius2); c = r * 255; } else { c = 255; } } if (c > 0) { dirty = true; c *= (getBrushStrength() / 255.0f); Vector4 a = c0->getAlphaMapUncompressed(x, y);//argb //如果是最外面一层,alpha累加 if (ln == eTerrainLayer_3 || c0->getLayer((eTerrainLayer)(ln + 1))->getFileName().empty()) { a[ln] += c; if (a[ln] > 255) { a[ln] = 255; } } //否则,其上面的层递减,递减为零时,自己那层再累加 else { bool aboveHasAlpha = false; for (int lay = ln + 1; lay != eTerrainLayer_Size; ++lay) { if (!c0->getLayer((eTerrainLayer)lay)->getFileName().empty()) { a[lay] -= c; if (a[lay] < 0) { a[lay] = 0; } if (a[lay] > 0) { aboveHasAlpha = true; } } } // if (!aboveHasAlpha) { a[ln] += c; if (a[ln] > 255) { a[ln] = 255; } } } c0->setAlphaMapUncompressed(x, y, Vector4(a.y, a.z, a.w, a.x));//rgba } } } if (dirty) { c0->refreshBlend(); } //c0->saveAlphaMap("c:\\am.raw"); } } } } TerrainTextureState::~TerrainTextureState() { } TerrainTextureState::TerrainTextureState() { type_ = eState_TerrainTexture; BrushRadiusInner_ = 3; BrushRadiusOuter_ = 6; BrushDecalOuter_ = NULL; BrushDecalInner_ = NULL; BrushStrength_ = 10.0f; } void TerrainTextureState::enter() { if (BrushDecalInner_ == NULL && BrushDecalOuter_ == NULL) { createBrushDecal(); } BrushDecalInner_->setVisible(true); BrushDecalOuter_->setVisible(true); } void TerrainTextureState::leave() { BrushDecalInner_->setVisible(false); BrushDecalOuter_->setVisible(false); } void TerrainTextureState::destroy() { } void TerrainTextureState::setBrushTextureFile( const tstring& n ) { std::ostringstream ss; ss<<"地表纹理刷选择文件:"<<n; FlowText::getSingletonP()->add(ss.str(), Vector4(1, 1, 1, 1)); BrushTextureFileSelected_ = n; } void TerrainTextureState::setBrushRadiusInner( float f ) { std::ostringstream ss; ss<<"画刷内径:"<<f; FlowText::getSingletonP()->add(ss.str(), Vector4(1, 1, 1, 1)); BrushRadiusInner_ = f; if (BrushDecalInner_) { BrushDecalInner_->setRadius(BrushRadiusInner_); } } void TerrainTextureState::setBrushRadiusOuter( float f ) { std::ostringstream ss; ss<<"画刷外径:"<<f; FlowText::getSingletonP()->add(ss.str(), Vector4(1, 1, 1, 1)); BrushRadiusOuter_ = f; if (BrushDecalOuter_) { BrushDecalOuter_->setRadius(BrushRadiusOuter_); } } bool TerrainTextureState::createBrushDecal() { BrushDecalInner_ = getSceneManager()->createDecal(TEXT("BrushDecalInner")); BrushDecalInner_->setFxFile(TEXT("\\shader\\PositionDecal.fx")); BrushDecalInner_->setTexture(TEXT("\\brush\\heighttool.dds")); BrushDecalInner_->setRadius(getBrushRadiusInner()); // BrushDecalOuter_ = getSceneManager()->createDecal(TEXT("BrushDecalOuter")); BrushDecalOuter_->setFxFile(TEXT("\\shader\\PositionDecal.fx")); BrushDecalOuter_->setTexture(TEXT("\\brush\\heighttool.dds")); BrushDecalOuter_->setRadius(getBrushRadiusOuter()); return true; } void TerrainTextureState::setBrushStrength( float f ) { BrushStrength_ = f; } void TerrainTextureState::setModelFile( const tstring& mf ) { BrushTextureFileSelected_ = "brush\\"; BrushTextureFileSelected_ += mf; std::ostringstream ss; ss<<"地表纹理刷选择文件:"<<BrushTextureFileSelected_; FlowText::getSingletonP()->add(ss.str(), Vector4(1, 1, 1, 1)); }
[ "297191409@qq.com" ]
297191409@qq.com
4ce51cc2baf4f23e5cb2cfd0f1515251c96f1306
9099b7ed407eb4bdc3ddb598303d0a77a5bfc76e
/yukicoder/657/y657.cpp
11fa7431be40237891130510a162c8858a2c12ec
[]
no_license
hitoyozake/competitive_programming
a84f98bab92c311269ebd7043c036f6c01d98975
c6e8cc22029d8ab6ff778e2791e7f230d087b19c
refs/heads/master
2021-08-10T12:33:54.268085
2021-06-20T11:18:31
2021-06-20T11:18:31
128,379,804
0
0
null
null
null
null
UTF-8
C++
false
false
769
cpp
#include <iostream> #include <map> #include <vector> int tetra(std::map<int, long long int> & map, long long int const n) { if(n<=3) return 0; if(n==4) return 1; if(map.find(n) == map.end()) { map[n] = (tetra(map, n-1) + tetra(map, n-2) + tetra(map, n-3) + tetra(map, n-4))%17; } return map[n]; } int main() { int num = 0; std::map<int, long long int> map; std::cin >> num; std::vector<int> v; for( int i = 0; i < num; ++i) { int x = 0; std::cin >> x; for(int j = 0; j < x; ++j) { tetra(map, j); } v.push_back(tetra(map, x)); } for( auto i: v) { std::cout << i%17 << std::endl; } return 0; }
[ "mikoto_1122@yahoo.co.jp" ]
mikoto_1122@yahoo.co.jp
fcf2d4161a97ca3e2c2772cd53ddec9444b54a42
b35d2463ee923ced614827fa8cdb5f31bf41ca49
/minSpanTree/main.cpp
9f92a1c286cad5bd8183e34da717a6598c342ec9
[]
no_license
dengqian/file_backup
a204855faf31fdce692340982e4ccbd488fdf4c9
33bdcd0484ca2e16ae8aa1cb5f3098b448f01d04
refs/heads/master
2021-01-01T16:05:47.401938
2015-01-27T13:08:59
2015-01-27T13:08:59
29,914,590
0
0
null
null
null
null
UTF-8
C++
false
false
1,346
cpp
#include<iostream> #include<stdio.h> #include<limits> #include<algorithm> #include<vector> #define N 100 using namespace std; struct edge{ int cost; int from; int to; }; int fa[N]; edge e[27*15]; bool cmp(edge a,edge b){ return a.cost<b.cost; } void init(int n){ for(int i=0;i<n;i++){ fa[i] = i; } } int root(int x){ return x == fa[x] ? x : fa[x] = root(fa[x]); } void unin(int a,int b){ int aa = root(a); int bb = root(b); if(aa != bb){ fa[bb] = aa; } } int main(){ int n = 0; char a; int num; char b; int cost; while(scanf("%d",&n) != EOF && n != 0){ init(N); int cnt = 0; for(int i=0;i<n-1;i++){ //scanf("%c%d",&a,&num); cin>>a>>num; for(int j=0;j<num;j++){ //scanf("%c%d",&b,&cost); cin>>b>>cost; e[cnt].cost = cost; e[cnt].from = a - 'A'; e[cnt++].to = b - 'A'; } } sort(e,e+cnt,cmp); int sum = 0; for(int k=0;k<cnt;k++){ int from = root(e[k].from); int to = root(e[k].to); if(from != to){ sum += e[k].cost; unin(from,to); } } printf("%d\n",sum); } return 0; }
[ "dengqiancici@163.com" ]
dengqiancici@163.com
0b37056b098fee558af894c54924842ce3ec5f20
6f504f7f2442f68fed3688fd49179b1dbfe00728
/TRABALHO_CAIXEIRO VIAJANTE/PCV_TB_II.cpp
4f8b5987727217372d3d3f037c18a8e836af9a0e
[]
no_license
HemersonRafael/implementacoes_c_cplusplus
d26ea53c6ee0307fa2430c15254fd33e3b68c97f
68f7b69c83df564b58d89dee534ebf7bcf4c22e7
refs/heads/master
2020-03-16T17:28:20.398786
2018-09-25T02:22:42
2018-09-25T02:22:42
null
0
0
null
null
null
null
ISO-8859-1
C++
false
false
4,991
cpp
/* TRABALHO DA SEGUNDA UNIDADE DE LINGUAGEM DE PROGRAMAÇÃO - ECT2303 Problema do Caixeiro Viajante (PCV) Participantes: Nome: HEMERSON RAFAEL PEREIRA PONTES Matrícula: 20160106641 Turma: 02B Nome: JOÃO LUCAS DE OLIVEIRA ARAUJO Matrícula: 20160001748 Turma: 02A */ #include <iostream> #include <ctime> #include <cstdlib> #define CIDADES 10 using namespace std; int Aleatorio(){ int teste; do{ teste = ( 2 + rand() % 10 ); }while( teste > 10 ); return teste; } bool BuscaValor(int v[CIDADES], int chave, int n){ for( int i = 1 ; i < n ; i++ ){ if( v[i] == chave ){ return true; } } return false; } void GeraSolucaoInicial( int v[CIDADES], int n ){ int teste, cont = 1; do{ teste = Aleatorio(); if( false == BuscaValor( v, teste, n ) ){ v[cont] = teste; cont++; } }while(cont<=n-1); } float CustoDaSolucao( int v[CIDADES], float b[CIDADES][CIDADES], int n ){ float soma = 0; for( int i = 0 ; i < n-1 ; i++ ){ soma = soma + b[v[i] - 1][v[i+1] - 1]; } soma = soma + b[v[n-1] - 1][v[0] - 1]; return soma; } void Movimento2Opt( int RA[CIDADES], int NR[CIDADES], int i, int k, int n ){ for( int a = 1 ; a <= i-1 ; a++ ){ NR[a] = RA[a]; } int cont = i; for( int b = k ; b >= i ; b-- ){ NR[cont++] = RA[b]; } for( int c = k+1 ; c < n ; c++ ){ NR[c] = RA[c]; } } int main(){ srand(1); float Distancias[CIDADES][CIDADES]={ {0, 281, 20.9, 18.1, 29, 39.7, 273, 214, 187, 38.4}, {281, 0,269, 263, 254, 255, 192, 73.7, 207, 286}, {20.9, 269, 0, 24.5, 16.5, 40.6, 261, 201, 175, 19.6}, {18.1, 263, 24.5, 0, 9.3, 21.5, 255, 196, 169, 42.2}, {29, 254, 16.5, 9.3, 0, 30.8, 246, 187, 160, 33.4}, {39.7, 255, 40.6, 21.5, 30.8, 0, 276, 188, 190, 63.4}, {273, 192, 261, 255, 246, 276, 0, 135, 87.3, 277}, {214, 73.7, 201, 196, 187, 188, 135, 0, 140, 218}, {187, 207, 175, 169, 160, 190, 87.3, 140, 0, 192}, {38.4, 286, 19.6, 42.2, 33.4, 63.4, 277, 218, 192, 0} }; int RotaAtual[CIDADES] = {1, 0, 0, 0, 0, 0, 0, 0, 0, 0}, RotaNova[CIDADES] = {1, 0, 0, 0, 0, 0, 0, 0, 0, 0}, repetir = 1; float MelhorCusto, NovoCusto; GeraSolucaoInicial( RotaAtual, CIDADES ); for( int z = 0 ; z < CIDADES ; z++ ){ cout << RotaAtual[z] << " "; } cout << endl; do{ inicio: MelhorCusto = CustoDaSolucao( RotaAtual, Distancias, CIDADES); for( int i = 1; i < CIDADES - 1; i++ ) { for( int k = i + 1; k < CIDADES; k++ ) { Movimento2Opt( RotaAtual, RotaNova, i, k, CIDADES ); NovoCusto = CustoDaSolucao( RotaNova, Distancias, CIDADES ); if( NovoCusto < MelhorCusto ) { for( int a = 0 ; a < CIDADES ; a++ ){ RotaAtual[a] = RotaNova[a]; } goto inicio; } } } repetir = 0; }while( repetir != 0 ); MelhorCusto = CustoDaSolucao( RotaAtual, Distancias, CIDADES); for( int z = 0 ; z < CIDADES ; z++ ){ cout << RotaAtual[z] << " "; } cout << endl; cout << endl << "Deslocamento minimo em Km : " << MelhorCusto << endl; cout << endl << "Ordem de visitacao das cidades:" << endl << endl; for( int z = 0 ; z < CIDADES ; z++ ){ switch ( RotaAtual[z] ){ case 1: cout << "NATAL"; break; case 2: cout << "MOSSORO"; break; case 3: cout << "PARNAMIRIM"; break; case 4: cout << "SAO GONCALO DO AMARANTE"; break; case 5: cout << "MACAIBA"; break; case 6: cout << "CEARA-MIRIM"; break; case 7: cout << "CAICO"; break; case 8: cout << "ASSU"; break; case 9: cout << "CURRAIS NOVOS"; break; case 10: cout << "SAO JOSE DE MIPIBU"; break; } if( z < CIDADES - 1 ){ cout << " => "; } } cout << " => NATAL" << endl << endl; system( "pause" ); return 0; }
[ "rafaelpontes1995@gmail.com" ]
rafaelpontes1995@gmail.com
3c805a9820fe02293eb17fb2f310a7988e1ecf71
23d6d61a3163ea5a84ee26deaa1887fa8ea51473
/Pointer İşlemleri.cpp
f97370947530285eef71e7dd25f9c2f16fd3eb43
[]
no_license
oguzhancevik/Cplusplus
7f90dd9a10ff11b5d55d14a11a8d3e189e2519a7
1a6cb922a06a2a8e847f174062706e56e59094e5
refs/heads/master
2021-01-11T20:36:11.730071
2017-05-12T18:15:58
2017-05-12T18:15:58
79,150,126
0
0
null
null
null
null
UTF-8
C++
false
false
2,494
cpp
#include <iostream> using namespace std; void main () { int a; int *p, *d; p = new int; *p= 45; cout << "P Pointerinin kendi bulundugu adres = " << &p << endl; cout << "P Pointerinin isaret ettigi adres = " << p << endl; cout << "P Pointerinin isaret ettigi datasi = " << *p << endl; d=p; cout << "D Pointerinin isaret ettigi datasi = " << *d << endl; cout << "==================\n"; system ("pause"); p=new int; *p=34; cout << "P Pointerinin adresi = " << p << endl; cout << "P Pointerinin datasi = " << *p << endl; cout << "d Pointerinin adresi = " << d << endl; cout << "d Pointerinin datasi = " << *d << endl; cout << "==================\n"; system ("pause"); d=p; cout << "p Pointerinin datasi= " << *p << endl; cout << "d Pointerinin datasi = " << *d << endl; system ("pause"); cout <<"P nin datasi 2 arttirildi sonuc \n\n"; *p = *p+2; cout << "p Pointerinin datasi= " << *p << endl; cout << "d Pointerinin datasi = " << *d << endl; system ("pause"); cout << "?????????????????????????????\n"; d=new int[5]; int i; for (i=0; i<5; i++) { cout << "Dizinin " << i <<" . elemanina deger giriniz ="; cin >> d[i]; } for (i=0; i<5; i++) cout << "Dizinin " << i <<" . elemanina deger =" << d[i] << endl; system ("pause"); cout << "==================\n"; cout << "Dizini 0 elemani = " << *d << endl; cout << "==================\n"; cout << "Dizini 2 elemani = " << *(d+2) <<endl; cout << "==================\n"; cout << "Dizini 2 elemani = " << (*d)+2 <<endl; cout << "==================\n"; cout << "Dizini 2 elemani = " << *d+2 <<endl; system ("pause"); d++; cout << "==================\n"; cout << "Dizini 0 elemani = " << *d << endl; cout << "Dizini 0 elemani = " << d[0] << endl; system ("pause"); cout << "==================\n"; for (i=0; i<5; i++) cout << "Dizinin " << i <<" . elemanina deger =" << d[i] << endl; system ("pause"); d--; (*d)++; d[1]++; cout << "==================\n"; for (i=0; i<5; i++) cout << "Dizinin " << i <<" . elemanina deger =" << d[i] << endl; system("pause"); p=d+2; cout << "==================\n"; for (i=0; i<5; i++) cout << "Dizinin " << i <<" . elemanina deger =" << d[i] << endl; cout << "==================\n"; cout << " p degiskenin degeri = "<< *p << endl; for (i=0; i<3; i++) cout << "Dizinin " << i <<" . elemanina deger =" << p[i] << endl; cout << "+++++++++++++++++++++\n"; system("pause"); }
[ "noreply@github.com" ]
noreply@github.com
d9b6d7d297073a4be4a36c209f73142ed0c5d815
4a932794d96c4cf3cc81461d1ed8605a2af201f1
/include/Frame.h
64d232a00229edd329fd8c26ab1baaf7701b6a33
[]
no_license
fishmarch/ManhattanTracking
bd2a6f66ff01b917bfc0d4c38194cb909ce3ff47
1fd2acc4d814c5001c591b4b3e6afd6eae794458
refs/heads/master
2020-05-14T18:14:27.748231
2019-04-29T07:37:12
2019-04-29T07:37:12
181,906,469
6
0
null
null
null
null
UTF-8
C++
false
false
2,208
h
#ifndef MANHATTANTRACKING_FRAME_H #define MANHATTANTRACKING_FRAME_H #include <iostream> #include <vector> #include <Eigen/Core> #include <Eigen/Dense> #include <pcl/io/io.h> #include <pcl/io/pcd_io.h> #include <pcl/features/integral_image_normal.h> #include <pcl/visualization/cloud_viewer.h> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> using namespace std; namespace MANHATTAN_TRACKING { typedef pcl::PointXYZ PointT; typedef pcl::PointCloud<PointT> PointCloud; struct Camera{ float factor; float cx; float cy; float fx; float fy; Camera(): fx(0),fy(0),cx(0),cy(0),factor(0){} }; class Frame{ public: Frame(const cv::Mat& depth, const cv::Mat& rgb, const Eigen::Matrix3f R); Frame(const cv::Mat& depth, const cv::Mat& rgb); //First Frame inline long unsigned int Id(); inline PointCloud::Ptr RiemannPoints(); inline pcl::PointCloud<pcl::PointXYZRGB>::Ptr Cloud(); inline PointCloud::Ptr NormalPoints(); inline vector<PointCloud::Ptr>& RiemannPointCloud(); private: void GenerateCloud(const cv::Mat& depth, const cv::Mat& rgb); void NormalExtract(); void RiemannMapping(); void FirstRiemannMapping(); PointCloud::Ptr mRiemannPoints; vector<PointCloud::Ptr> mRiemannPointCloud; pcl::PointCloud<pcl::PointXYZRGB>::Ptr mCloud; PointCloud::Ptr mNormalPoints; long unsigned int mId; Eigen::Matrix3f mLastR; static long unsigned int mLastId; public: static Camera mCamera; static void SetCameraParameter(float fx_, float fy_, float cx_, float cy_, float factor_); };// CLASS FRAME unsigned long int Frame::Id() { return mId; } pcl::PointCloud<pcl::PointXYZRGB>::Ptr Frame::Cloud(){ return mCloud; } PointCloud::Ptr Frame::NormalPoints(){ return mNormalPoints; } PointCloud::Ptr Frame::RiemannPoints(){ return mRiemannPoints; } vector<PointCloud::Ptr>& Frame::RiemannPointCloud(){ return mRiemannPointCloud; } } #endif //MANHATTANTRACKING_FRAME_H
[ "zhang_xy@buaa.edu.cn" ]
zhang_xy@buaa.edu.cn
28ea7bb91c5d43a5c9766fbba303c45ebd4c5fd6
0e737d2bd3ac7dcbfb8c852091d1c08e78983c30
/src/key.cpp
7d44c4ae7978865955b22d964d0c620896e511ba
[ "MIT" ]
permissive
tdrml/zurbank
83751c8274a1c921bb44c7618e5423c91ea33856
0bdf00eee561f84d7deee049571ce19d68a85adc
refs/heads/main
2023-03-27T04:39:25.359338
2021-03-10T18:04:03
2021-03-10T18:04:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
14,717
cpp
// Copyright (c) 2009-2018 The Bitcoin Core developers // Copyright (c) 2017 The Zcash developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <key.h> #include <arith_uint256.h> #include <crypto/common.h> #include <crypto/hmac_sha512.h> #include <random.h> #include <secp256k1.h> #include <secp256k1_recovery.h> static secp256k1_context* secp256k1_context_sign = nullptr; /** These functions are taken from the libsecp256k1 distribution and are very ugly. */ /** * This parses a format loosely based on a DER encoding of the ECPrivateKey type from * section C.4 of SEC 1 <http://www.secg.org/sec1-v2.pdf>, with the following caveats: * * * The octet-length of the SEQUENCE must be encoded as 1 or 2 octets. It is not * required to be encoded as one octet if it is less than 256, as DER would require. * * The octet-length of the SEQUENCE must not be greater than the remaining * length of the key encoding, but need not match it (i.e. the encoding may contain * junk after the encoded SEQUENCE). * * The privateKey OCTET STRING is zero-filled on the left to 32 octets. * * Anything after the encoding of the privateKey OCTET STRING is ignored, whether * or not it is validly encoded DER. * * out32 must point to an output buffer of length at least 32 bytes. */ static int ec_privkey_import_der(const secp256k1_context* ctx, unsigned char *out32, const unsigned char *privkey, size_t privkeylen) { const unsigned char *end = privkey + privkeylen; memset(out32, 0, 32); /* sequence header */ if (end - privkey < 1 || *privkey != 0x30u) { return 0; } privkey++; /* sequence length constructor */ if (end - privkey < 1 || !(*privkey & 0x80u)) { return 0; } ptrdiff_t lenb = *privkey & ~0x80u; privkey++; if (lenb < 1 || lenb > 2) { return 0; } if (end - privkey < lenb) { return 0; } /* sequence length */ ptrdiff_t len = privkey[lenb-1] | (lenb > 1 ? privkey[lenb-2] << 8 : 0u); privkey += lenb; if (end - privkey < len) { return 0; } /* sequence element 0: version number (=1) */ if (end - privkey < 3 || privkey[0] != 0x02u || privkey[1] != 0x01u || privkey[2] != 0x01u) { return 0; } privkey += 3; /* sequence element 1: octet string, up to 32 bytes */ if (end - privkey < 2 || privkey[0] != 0x04u) { return 0; } ptrdiff_t oslen = privkey[1]; privkey += 2; if (oslen > 32 || end - privkey < oslen) { return 0; } memcpy(out32 + (32 - oslen), privkey, oslen); if (!secp256k1_ec_seckey_verify(ctx, out32)) { memset(out32, 0, 32); return 0; } return 1; } /** * This serializes to a DER encoding of the ECPrivateKey type from section C.4 of SEC 1 * <http://www.secg.org/sec1-v2.pdf>. The optional parameters and publicKey fields are * included. * * privkey must point to an output buffer of length at least CKey::PRIVATE_KEY_SIZE bytes. * privkeylen must initially be set to the size of the privkey buffer. Upon return it * will be set to the number of bytes used in the buffer. * key32 must point to a 32-byte raw private key. */ static int ec_privkey_export_der(const secp256k1_context *ctx, unsigned char *privkey, size_t *privkeylen, const unsigned char *key32, bool compressed) { assert(*privkeylen >= CKey::PRIVATE_KEY_SIZE); secp256k1_pubkey pubkey; size_t pubkeylen = 0; if (!secp256k1_ec_pubkey_create(ctx, &pubkey, key32)) { *privkeylen = 0; return 0; } if (compressed) { static const unsigned char begin[] = { 0x30,0x81,0xD3,0x02,0x01,0x01,0x04,0x20 }; static const unsigned char middle[] = { 0xA0,0x81,0x85,0x30,0x81,0x82,0x02,0x01,0x01,0x30,0x2C,0x06,0x07,0x2A,0x86,0x48, 0xCE,0x3D,0x01,0x01,0x02,0x21,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFE,0xFF,0xFF,0xFC,0x2F,0x30,0x06,0x04,0x01,0x00,0x04,0x01,0x07,0x04, 0x21,0x02,0x79,0xBE,0x66,0x7E,0xF9,0xDC,0xBB,0xAC,0x55,0xA0,0x62,0x95,0xCE,0x87, 0x0B,0x07,0x02,0x9B,0xFC,0xDB,0x2D,0xCE,0x28,0xD9,0x59,0xF2,0x81,0x5B,0x16,0xF8, 0x17,0x98,0x02,0x21,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFE,0xBA,0xAE,0xDC,0xE6,0xAF,0x48,0xA0,0x3B,0xBF,0xD2,0x5E, 0x8C,0xD0,0x36,0x41,0x41,0x02,0x01,0x01,0xA1,0x24,0x03,0x22,0x00 }; unsigned char *ptr = privkey; memcpy(ptr, begin, sizeof(begin)); ptr += sizeof(begin); memcpy(ptr, key32, 32); ptr += 32; memcpy(ptr, middle, sizeof(middle)); ptr += sizeof(middle); pubkeylen = CPubKey::COMPRESSED_PUBLIC_KEY_SIZE; secp256k1_ec_pubkey_serialize(ctx, ptr, &pubkeylen, &pubkey, SECP256K1_EC_COMPRESSED); ptr += pubkeylen; *privkeylen = ptr - privkey; assert(*privkeylen == CKey::COMPRESSED_PRIVATE_KEY_SIZE); } else { static const unsigned char begin[] = { 0x30,0x82,0x01,0x13,0x02,0x01,0x01,0x04,0x20 }; static const unsigned char middle[] = { 0xA0,0x81,0xA5,0x30,0x81,0xA2,0x02,0x01,0x01,0x30,0x2C,0x06,0x07,0x2A,0x86,0x48, 0xCE,0x3D,0x01,0x01,0x02,0x21,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFE,0xFF,0xFF,0xFC,0x2F,0x30,0x06,0x04,0x01,0x00,0x04,0x01,0x07,0x04, 0x41,0x04,0x79,0xBE,0x66,0x7E,0xF9,0xDC,0xBB,0xAC,0x55,0xA0,0x62,0x95,0xCE,0x87, 0x0B,0x07,0x02,0x9B,0xFC,0xDB,0x2D,0xCE,0x28,0xD9,0x59,0xF2,0x81,0x5B,0x16,0xF8, 0x17,0x98,0x48,0x3A,0xDA,0x77,0x26,0xA3,0xC4,0x65,0x5D,0xA4,0xFB,0xFC,0x0E,0x11, 0x08,0xA8,0xFD,0x17,0xB4,0x48,0xA6,0x85,0x54,0x19,0x9C,0x47,0xD0,0x8F,0xFB,0x10, 0xD4,0xB8,0x02,0x21,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFE,0xBA,0xAE,0xDC,0xE6,0xAF,0x48,0xA0,0x3B,0xBF,0xD2,0x5E, 0x8C,0xD0,0x36,0x41,0x41,0x02,0x01,0x01,0xA1,0x44,0x03,0x42,0x00 }; unsigned char *ptr = privkey; memcpy(ptr, begin, sizeof(begin)); ptr += sizeof(begin); memcpy(ptr, key32, 32); ptr += 32; memcpy(ptr, middle, sizeof(middle)); ptr += sizeof(middle); pubkeylen = CPubKey::PUBLIC_KEY_SIZE; secp256k1_ec_pubkey_serialize(ctx, ptr, &pubkeylen, &pubkey, SECP256K1_EC_UNCOMPRESSED); ptr += pubkeylen; *privkeylen = ptr - privkey; assert(*privkeylen == CKey::PRIVATE_KEY_SIZE); } return 1; } bool CKey::Check(const unsigned char *vch) { return secp256k1_ec_seckey_verify(secp256k1_context_sign, vch); } void CKey::MakeNewKey(bool fCompressedIn) { do { GetStrongRandBytes(keydata.data(), keydata.size()); } while (!Check(keydata.data())); fValid = true; fCompressed = fCompressedIn; } CPrivKey CKey::GetPrivKey() const { assert(fValid); CPrivKey privkey; int ret; size_t privkeylen; privkey.resize(PRIVATE_KEY_SIZE); privkeylen = PRIVATE_KEY_SIZE; ret = ec_privkey_export_der(secp256k1_context_sign, privkey.data(), &privkeylen, begin(), fCompressed); assert(ret); privkey.resize(privkeylen); return privkey; } CPubKey CKey::GetPubKey() const { assert(fValid); secp256k1_pubkey pubkey; size_t clen = CPubKey::PUBLIC_KEY_SIZE; CPubKey result; int ret = secp256k1_ec_pubkey_create(secp256k1_context_sign, &pubkey, begin()); assert(ret); secp256k1_ec_pubkey_serialize(secp256k1_context_sign, (unsigned char*)result.begin(), &clen, &pubkey, fCompressed ? SECP256K1_EC_COMPRESSED : SECP256K1_EC_UNCOMPRESSED); assert(result.size() == clen); assert(result.IsValid()); return result; } // Check that the sig has a low R value and will be less than 71 bytes bool SigHasLowR(const secp256k1_ecdsa_signature* sig) { unsigned char compact_sig[64]; secp256k1_ecdsa_signature_serialize_compact(secp256k1_context_sign, compact_sig, sig); // In DER serialization, all values are interpreted as big-endian, signed integers. The highest bit in the integer indicates // its signed-ness; 0 is positive, 1 is negative. When the value is interpreted as a negative integer, it must be converted // to a positive value by prepending a 0x00 byte so that the highest bit is 0. We can avoid this prepending by ensuring that // our highest bit is always 0, and thus we must check that the first byte is less than 0x80. return compact_sig[0] < 0x80; } bool CKey::Sign(const uint256 &hash, std::vector<unsigned char>& vchSig, bool grind, uint32_t test_case) const { if (!fValid) return false; vchSig.resize(CPubKey::SIGNATURE_SIZE); size_t nSigLen = CPubKey::SIGNATURE_SIZE; unsigned char extra_entropy[32] = {0}; WriteLE32(extra_entropy, test_case); secp256k1_ecdsa_signature sig; uint32_t counter = 0; int ret = secp256k1_ecdsa_sign(secp256k1_context_sign, &sig, hash.begin(), begin(), secp256k1_nonce_function_rfc6979, (!grind && test_case) ? extra_entropy : nullptr); // Grind for low R while (ret && !SigHasLowR(&sig) && grind) { WriteLE32(extra_entropy, ++counter); ret = secp256k1_ecdsa_sign(secp256k1_context_sign, &sig, hash.begin(), begin(), secp256k1_nonce_function_rfc6979, extra_entropy); } assert(ret); secp256k1_ecdsa_signature_serialize_der(secp256k1_context_sign, vchSig.data(), &nSigLen, &sig); vchSig.resize(nSigLen); return true; } bool CKey::VerifyPubKey(const CPubKey& pubkey) const { if (pubkey.IsCompressed() != fCompressed) { return false; } unsigned char rnd[8]; std::string str = "Zurcoin key verification\n"; GetRandBytes(rnd, sizeof(rnd)); uint256 hash; CHash256().Write((unsigned char*)str.data(), str.size()).Write(rnd, sizeof(rnd)).Finalize(hash.begin()); std::vector<unsigned char> vchSig; Sign(hash, vchSig); return pubkey.Verify(hash, vchSig); } bool CKey::SignCompact(const uint256 &hash, std::vector<unsigned char>& vchSig) const { if (!fValid) return false; vchSig.resize(CPubKey::COMPACT_SIGNATURE_SIZE); int rec = -1; secp256k1_ecdsa_recoverable_signature sig; int ret = secp256k1_ecdsa_sign_recoverable(secp256k1_context_sign, &sig, hash.begin(), begin(), secp256k1_nonce_function_rfc6979, nullptr); assert(ret); ret = secp256k1_ecdsa_recoverable_signature_serialize_compact(secp256k1_context_sign, &vchSig[1], &rec, &sig); assert(ret); assert(rec != -1); vchSig[0] = 27 + rec + (fCompressed ? 4 : 0); return true; } bool CKey::Load(const CPrivKey &privkey, const CPubKey &vchPubKey, bool fSkipCheck=false) { if (!ec_privkey_import_der(secp256k1_context_sign, (unsigned char*)begin(), privkey.data(), privkey.size())) return false; fCompressed = vchPubKey.IsCompressed(); fValid = true; if (fSkipCheck) return true; return VerifyPubKey(vchPubKey); } bool CKey::Derive(CKey& keyChild, ChainCode &ccChild, unsigned int nChild, const ChainCode& cc) const { assert(IsValid()); assert(IsCompressed()); std::vector<unsigned char, secure_allocator<unsigned char>> vout(64); if ((nChild >> 31) == 0) { CPubKey pubkey = GetPubKey(); assert(pubkey.size() == CPubKey::COMPRESSED_PUBLIC_KEY_SIZE); BIP32Hash(cc, nChild, *pubkey.begin(), pubkey.begin()+1, vout.data()); } else { assert(size() == 32); BIP32Hash(cc, nChild, 0, begin(), vout.data()); } memcpy(ccChild.begin(), vout.data()+32, 32); memcpy((unsigned char*)keyChild.begin(), begin(), 32); bool ret = secp256k1_ec_privkey_tweak_add(secp256k1_context_sign, (unsigned char*)keyChild.begin(), vout.data()); keyChild.fCompressed = true; keyChild.fValid = ret; return ret; } bool CExtKey::Derive(CExtKey &out, unsigned int _nChild) const { out.nDepth = nDepth + 1; CKeyID id = key.GetPubKey().GetID(); memcpy(&out.vchFingerprint[0], &id, 4); out.nChild = _nChild; return key.Derive(out.key, out.chaincode, _nChild, chaincode); } void CExtKey::SetSeed(const unsigned char *seed, unsigned int nSeedLen) { static const unsigned char hashkey[] = {'B','i','t','c','o','i','n',' ','s','e','e','d'}; std::vector<unsigned char, secure_allocator<unsigned char>> vout(64); CHMAC_SHA512(hashkey, sizeof(hashkey)).Write(seed, nSeedLen).Finalize(vout.data()); key.Set(vout.data(), vout.data() + 32, true); memcpy(chaincode.begin(), vout.data() + 32, 32); nDepth = 0; nChild = 0; memset(vchFingerprint, 0, sizeof(vchFingerprint)); } CExtPubKey CExtKey::Neuter() const { CExtPubKey ret; ret.nDepth = nDepth; memcpy(&ret.vchFingerprint[0], &vchFingerprint[0], 4); ret.nChild = nChild; ret.pubkey = key.GetPubKey(); ret.chaincode = chaincode; return ret; } void CExtKey::Encode(unsigned char code[BIP32_EXTKEY_SIZE]) const { code[0] = nDepth; memcpy(code+1, vchFingerprint, 4); code[5] = (nChild >> 24) & 0xFF; code[6] = (nChild >> 16) & 0xFF; code[7] = (nChild >> 8) & 0xFF; code[8] = (nChild >> 0) & 0xFF; memcpy(code+9, chaincode.begin(), 32); code[41] = 0; assert(key.size() == 32); memcpy(code+42, key.begin(), 32); } void CExtKey::Decode(const unsigned char code[BIP32_EXTKEY_SIZE]) { nDepth = code[0]; memcpy(vchFingerprint, code+1, 4); nChild = (code[5] << 24) | (code[6] << 16) | (code[7] << 8) | code[8]; memcpy(chaincode.begin(), code+9, 32); key.Set(code+42, code+BIP32_EXTKEY_SIZE, true); } bool ECC_InitSanityCheck() { CKey key; key.MakeNewKey(true); CPubKey pubkey = key.GetPubKey(); return key.VerifyPubKey(pubkey); } void ECC_Start() { assert(secp256k1_context_sign == nullptr); secp256k1_context *ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN); assert(ctx != nullptr); { // Pass in a random blinding seed to the secp256k1 context. std::vector<unsigned char, secure_allocator<unsigned char>> vseed(32); GetRandBytes(vseed.data(), 32); bool ret = secp256k1_context_randomize(ctx, vseed.data()); assert(ret); } secp256k1_context_sign = ctx; } void ECC_Stop() { secp256k1_context *ctx = secp256k1_context_sign; secp256k1_context_sign = nullptr; if (ctx) { secp256k1_context_destroy(ctx); } }
[ "33366277+risingstar2018@users.noreply.github.com" ]
33366277+risingstar2018@users.noreply.github.com
a23048b1491bf36004a090d76fcb0a8fd2491367
7a9b52021b71c1aba25186215893071948af8401
/OptCom/DataProcessor.cpp
6fd05001182e2accb71935113616cb9151710437
[]
no_license
yyzidea/OptCom
74fcec34d0e4b2162734c5dbffc0db9dd2a1f11e
6d3ae92ca9897d107b1933f0e120fddd7b5c1ade
refs/heads/master
2021-01-21T14:17:03.747699
2016-06-10T16:36:54
2016-06-10T16:36:54
58,459,823
0
1
null
2016-06-10T16:36:55
2016-05-10T12:34:11
C++
GB18030
C++
false
false
15,184
cpp
#include "stdafx.h" namespace Common{ ////////////////////////////////////////////////////////////////////////// // bool c_hex_data_processor::process_some(bool follow, const unsigned char* ba, int cb, int* pn) // { // char buf[1024]; // char* str; // int pos = _count % (COMMON_LINE_CCH_RECV); // int outlen = cb; // str = c_text_formatting::hex2str(const_cast<unsigned char*>(ba), &outlen, COMMON_LINE_CCH_RECV, pos, // buf, sizeof(buf), c_text_formatting::newline_type::NLT_CRLF); // _editor->append_text(str); // if (str != buf) memory.free((void**)&str, ""); // _count += cb; // *pn = cb; // return false; // } // void c_hex_data_processor::reset_buffer() // { // _count = 0; // } // void c_hex_data_receiver::receive(const unsigned char* ba, int cb) // { // for (; cb > 0;){ // if (_pre_proc){ // 可能处理后cb==0, 所以不管process的返回值 // process(_pre_proc, true, &ba, &cb, &_pre_proc); // continue; // } // if (process(_proc_hex, false, &ba, &cb, &_pre_proc) || cb==0) // continue; // } // } ////////////////////////////////////////////////////////////////////////// bool c_single_byte_processor::process_some(bool follow, const unsigned char* ba, int cb, int* pn) { // SMART_ASSERT(_richedit != NULL).Fatal(); // SMART_ASSERT(follow == false).Warning(); // SMART_ASSERT(cb == 1)(cb).Fatal(); char buf[5]; sprintf_s(buf,SPRINTF_BUFFER_LENGTH,"<%02X>", *ba); _richedit->append_text(buf); *pn = 1; return false; } ////////////////////////////////////////////////////////////////////////// bool c_crlf_data_processor::process_some(bool follow, const unsigned char* ba, int cb, int* pn) { char inner_buf[1024]; // 内部缓冲 int n = 0; // 记录新crlf的个数 char* str=""; if (!follow){ _post_len = 0; _data.empty(); } while (n < cb && (ba[n] == '\r' || ba[n] == '\n')){ n++; } if (n <= 0){ *pn = 0; return false; } _data.append(ba, n); //Todo: Transfer the hex to char //str = c_text_formatting::hex2chs((unsigned char*)_data.get_data(), _data.get_size(),inner_buf, __ARRAY_SIZE(inner_buf), c_text_formatting::NLT_CR); do{ int newcrlen = strlen(str); int diff = newcrlen - _post_len; if (diff > 0){ _richedit->append_text(str + _post_len); } else{ _richedit->back_delete_char(-diff); } } while ((0)); _post_len = strlen(str); if (str != inner_buf) memory.free((void**)&str, ""); *pn = n; return true; } void c_crlf_data_processor::reset_buffer() { _post_len = 0; _data.empty(); } ////////////////////////////////////////////////////////////////////////// static int read_integer(char* str, int* pi) { int r = 0; char* p = str; while (*p >= '0' && *p <= '9'){ r *= 10; r += *p - '0'; p++; } *pi = r; return (int)p - (int)str; } bool c_escape_data_processor::process_some(bool follow, const unsigned char* ba, int cb, int* pn) { int i = 0; int step; if (!follow){ reset_buffer(); } bool r = true; for (i = 0; i < cb; i += step){ step = 0; switch (_state) { case LCS_NONE: if (ba[i] == '\033'){ _state = LCS_ESC; step = 1; _data.append_char(ba[i]); } else{ // debug_out(("state: LCS_NONE: expect:\\033, but 0x%02X!\n", ba[i])); r = false; goto _exit; } break; case LCS_ESC: if (ba[i] == '['){ _state = LCS_BRACKET; step = 1; _data.append_char(ba[i]); } else{ // debug_out(("state: LCS_ESC: expect: [, but 0x%02X\n", ba[i])); _state = LCS_NONE; r = false; goto _exit; } break; case LCS_BRACKET: if (ba[i] >= '0' && ba[i] <= '9'){ while (i + step<cb && ba[i + step] >= '0' && ba[i + step] <= '9'){ _data.append_char(ba[i + step]); step++; } _state = LCS_VAL; } else if (ba[i] == 'H'){ _data.append_char('H'); step = 1; _state = LCS_H; } else if (ba[i] == 'f'){ _data.append_char('f'); step = 1; _state = LCS_f; } else if (ba[i] == 'm'){ _data.append_char('m'); step = 1; _state = LCS_m; } else if (ba[i] == 's'){ _data.append_char('s'); step = 1; _state = LCS_s; } else if (ba[i] == 'u'){ _data.append_char('u'); step = 1; _state = LCS_u; } else if (ba[i] == 'K'){ _data.append_char('K'); step = 1; _state = LCS_K; } else if (ba[i] == 'm'){ _data.append_char('m'); step = 1; _state = LCS_m; } else if (ba[i] == '='){ _data.append_char('='); step = 1; _state = LCS_EQU; } else if (ba[i] == 'A'){ _data.append_char('A'); step = 1; _state = LCS_A; } else if (ba[i] == 'B'){ _data.append_char('B'); step = 1; _state = LCS_B; } else if (ba[i] == 'C'){ _data.append_char('C'); step = 1; _state = LCS_C; } else if (ba[i] == 'D'){ _data.append_char('D'); step = 1; _state = LCS_D; } else{ // debug_out(("state: LCS_BRACKET: unexpected token: %02X\n", ba[i])); _state = LCS_NONE; r = false; goto _exit; } break; case LCS_VAL: if (ba[i] >= '0' && ba[i] <= '9'){ while (i + step < cb && ba[i + step] >= '0' && ba[i + step] <= '9'){ _data.append_char(ba[i + step]); step++; } _state = LCS_VAL; goto _no_push_state; } if (_stack[_stack.size() - 2] == LCS_BRACKET){ if (ba[i] == ';'){ _state = LCS_SEMI; step = 1; _data.append_char(';'); } else if (ba[i] == 'A'){ _state = LCS_A; step = 1; _data.append_char('A'); } else if (ba[i] == 'B'){ _state = LCS_B; step = 1; _data.append_char('B'); } else if (ba[i] == 'C'){ _state = LCS_C; step = 1; _data.append_char('C'); } else if (ba[i] == 'D'){ _state = LCS_D; step = 1; _data.append_char('D'); } else if (ba[i] == 'j'){ _state = LCS_j; step = 1; _data.append_char('j'); } else if (ba[i] == 'm'){ _state = LCS_m; step = 1; _data.append_char('m'); } else{ // debug_out(("state: LCS_VAL: unknown token: %02X\n", ba[i])); _state = LCS_NONE; r = false; goto _exit; } } else if (_stack[_stack.size() - 2] == LCS_EQU){ if (ba[i] == 'h'){ _state = LCS_h; step = 1; _data.append_char('h'); } else if (ba[i] == 'l'){ _state = LCS_l; step = 1; _data.append_char('l'); } else{ // debug_out(("state: LCS_EQU+LCS_VAL: unexpected token: %02X\n", ba[i])); _state = LCS_NONE; r = false; goto _exit; } } else if (_stack[_stack.size() - 2] == LCS_SEMI){ if (_stack.size() == 5){ if (ba[i] == 'H'){ _state = LCS_H; step = 1; _data.append_char('H'); goto _push_state; } else if (ba[i] == 'f'){ _state = LCS_f; step = 1; _data.append_char('f'); goto _push_state; } } if(ba[i] == ';'){ _state = LCS_SEMI; step = 1; _data.append_char(';'); } else if (ba[i] == 'm'){ _state = LCS_m; step = 1; _data.append_char('m'); } else{ // debug_out(("state: LCS_SEMI+LCS_VAL: unexpected token: %02X\n", ba[i])); _state = LCS_NONE; r = false; goto _exit; } } else{ // debug_out(("state: LCS_VAL: unexpected token: %02X\n", ba[i])); r = false; goto _exit; } break; case LCS_SEMI: if (ba[i] >= '0' && ba[i] <= '9'){ while (i+step<cb && ba[i + step] >= '0' && ba[i + step] <= '9'){ _data.append_char(ba[i + step]); step++; } _state = LCS_VAL; } else if (ba[i] == 'm'){ _state = LCS_m; step = 1; _data.append_char('m'); } else if (ba[i] == 'H'){ _state = LCS_H; step = 1; _data.append_char('H'); } else if (ba[i] == 'f'){ _state = LCS_f; step = 1; _data.append_char('f'); } else if (ba[i] == ';'){ _state = LCS_SEMI; step = 1; _data.append_char(';'); } else{ // debug_out(("state: LCS_SEMI: unknown token: %02X\n", ba[i])); r = false; goto _exit; } break; case LCS_EQU: if (ba[i] >= '0' && ba[i] <= '9'){ while (i + step < cb && ba[i + step] >= '0' && ba[i + step] <= '9'){ _data.append_char(ba[i + step]); step++; } _state = LCS_VAL; } else if (ba[i] == 'h'){ _state = LCS_h; step = 1; _data.append_char('h'); } else if (ba[i] == 'l'){ _state = LCS_l; step = 1; _data.append_char('l'); } else{ // debug_out(("state: LCS_EQU: unknown token %02X\n", ba[i])); r = false; _state = LCS_NONE; goto _exit; } break; case LCS_H: case LCS_f: case LCS_A: case LCS_B: case LCS_C: case LCS_D: case LCS_s: case LCS_u: case LCS_j: case LCS_K: case LCS_m: case LCS_h: case LCS_l: // debug_out(("parsing completed\n")); r = false; _state = LCS_NONE; _data.append_char('\0'); _richedit->apply_linux_attributes((char*)_data.get_data()); goto _exit; default: // debug_out(("unknown lcs token\n")); r = false; _state = LCS_NONE; goto _exit; } _push_state: _stack.push_back(_state); _no_push_state: ; } _exit: *pn = i; return r; } void c_escape_data_processor::reset_buffer() { _state = LCS_NONE; _stack.clear(); _stack.push_back(_state); _data.empty(); } ////////////////////////////////////////////////////////////////////////// bool c_ascii_data_processor::process_some(bool follow, const unsigned char* ba, int cb, int* pn) { char buf[1024]; int n = 0; while (n < cb && n<sizeof(buf)-1 && ba[n] >= 0x20 && ba[n] <=0x7F){ buf[n] = ba[n]; n++; } buf[n] = '\0'; _richedit->append_text(buf); *pn = n; return false; } void c_ascii_data_processor::reset_buffer() { } ////////////////////////////////////////////////////////////////////////// void c_text_data_receiver::receive(const unsigned char* ba, int cb) { for (; cb > 0;){ if (_pre_proc){// 可能处理后cb==0, 所以不管process的返回值 process(_pre_proc, true, &ba, &cb, &_pre_proc); continue; } // 控制字符/特殊字符处理 if (0 <= *ba && *ba <= 0x1F){ // Bell, 响铃, 7 if (*ba == 7){ ::Beep(800, 300); ba += 1; cb -= 1; } // 删除(退格), 8 else if (*ba == '\b'){ int n = 0; while (n < cb && ba[n] == '\b') n++; _rich_editor->back_delete_char(n); ba += n; cb -= n; } // 水平制表, 9 else if (*ba == '\t'){ int n = 0; char buf[64]; while (n < cb && n < sizeof(buf) - 1 && ba[n] == '\t'){ buf[n] = '\t'; n++; } buf[n] = '\0'; _rich_editor->append_text(buf); ba += n; cb -= n; } // 回车与换行 (13,10) else if (*ba == '\r' || *ba == '\n'){ process(_proc_crlf, false, &ba, &cb, &_pre_proc); } // Linux终端, nCursors 控制字符处理 else if (*ba == '\033'){ process(_proc_escape, false, &ba, &cb, &_pre_proc); } // 其它 未作处理/不可显示 字符处理 else{ process(_proc_byte, false, &ba, &cb, &_pre_proc); } } // 空格以后的ASCII标准字符处理 else if (0x20 <= *ba && *ba <= 0x7F){ process(_proc_ascii, false, &ba, &cb, &_pre_proc); } // 扩展ASCII(Extended ASCII / EUC)字符处理 else{ // 当前只处理GB2312 // 非gb2312编码区 if (0x80 <= *ba && *ba <= 0xA0){ process(_proc_byte, false, &ba, &cb, &_pre_proc); } // gb2312编码区 else if (0xA1 <= *ba && *ba <= 0xFE){ process(_proc_gb2312, false, &ba, &cb, &_pre_proc); } //非gb2312编码区 else{ process(_proc_byte, false, &ba, &cb, &_pre_proc); } } } } ////////////////////////////////////////////////////////////////////////// // 关于 gb2312 // 低字节: // 01-94位, 全部使用, 范围: 0xA1->0xFE // 高字节: // 01-09区为特殊符号: 范围: 0xA1->0xA9 // 10-15区: 未使用, 范围: 0xAA->0xAF // 16-55区: 一级汉字, 按拼音排序, 范围: 0xB0->0xD7 // 56-87区: 二级汉字, 按部首/笔画排序, 范围: 0xD8->0xF7 // 88-94区: 未使用, 范围: 0xF8->0xFE // // 关于中文处理的正确性保证: // 串口设备由于协议的某种不完整性, 很难保证数据总是完全无误, // 如果在处理过程中遇到错误的编码就很难显示出正确的中文了, 包括后续的字符, 可能导致一错多错 bool c_gb2312_data_processor::process_some(bool follow, const unsigned char* ba, int cb, int* pn) { // 是否继续上一次未完的处理? if (follow){ unsigned char chs[16]; if (*ba >= 0xA1 && *ba <= 0xFE){ // 有编码区 if (0xA1 <= _lead_byte && _lead_byte <= 0xAF || 0xB0 <= _lead_byte && _lead_byte <= 0xF7) { chs[0] = _lead_byte; chs[1] = *ba; chs[2] = '\0'; _richedit->append_text((const char*)chs); } // 无编码区 else{ sprintf_s((char*)chs,SPRINTF_BUFFER_LENGTH,"<A+%02X%02X>", _lead_byte, *ba); _richedit->append_text((const char*)chs); } _lead_byte = 0; *pn = 1; return false; } else{ // 这里该如何处理是好? // 返回1? // 还是把_lead_byte和当前字节显示了? sprintf_s((char*)chs, SPRINTF_BUFFER_LENGTH, "<%02X>", _lead_byte); _richedit->append_text((const char*)chs); _lead_byte = 0; *pn = 0; return false; } } // 开始新的处理 else{ _lead_byte = 0; const int kPairs = 512; // 一次最多处理512个中文字符 int npairs = 0; // 有多少对中文需要处理 char buf[kPairs*2+1]; // 先把能处理的处理掉, 其它的交给下一次处理 while (npairs <= kPairs && (npairs + 1) * 2 <= cb){ // 处理第npairs对时要求的字节数, 从0开始, 比如3: 需要至少8个字节 unsigned char b1 = ba[npairs * 2 + 0]; unsigned char b2 = ba[npairs * 2 + 1]; if ((0xA1 <= b1 && b1 <= 0xFE) && (0xA1 <= b2 && b2 <= 0xFE)){ npairs++; } else{ break; } } if (npairs){ // BUG: 未处理非编码区 ::memcpy(buf, ba, npairs * 2); buf[npairs * 2] = '\0'; _richedit->append_text(buf); *pn = npairs * 2; return false; } else{ // 只存在一个字节满足的情况 // 或是当前中剩下一个字节需要处理 if (cb < 2){ // only can equal to 1 // SMART_ASSERT(cb == 1)(cb).Fatal(); _lead_byte = *ba; *pn = 1; return true; } else{ sprintf_s(buf, SPRINTF_BUFFER_LENGTH, "<%02X>", ba[0]); _richedit->append_text(buf); *pn = 1; return false; } } } } void c_gb2312_data_processor::reset_buffer() { _lead_byte = 0; //中文前导不可能为零, 所以这样做是完全没问题的 } }
[ "yyzidea@hotmail.com" ]
yyzidea@hotmail.com
21eef0ec03d70516e967f300848573ebeb574494
655c5207329de8e4d53414ca60f7ab0f7ba0b6a7
/engine/src/Entity/Components/STBoundsComponent.h
3c943f8887f122fef07c29b735a8c891782fe992
[]
no_license
SwingInnovations/SwingTech-1
979316e89f4c0a9e50a64b1ba8d538ff9e5c4eb6
4e5f4be97f6a48c16e72fb150080bf817e75881c
refs/heads/master
2020-12-03T00:00:18.898257
2018-02-13T20:42:26
2018-02-13T20:42:26
44,465,172
2
1
null
null
null
null
UTF-8
C++
false
false
330
h
#ifndef SWINGTECH1_STBOUNDSCOMPONENT_H #define SWINGTECH1_STBOUNDSCOMPONENT_H #include "STComponent.h" class STBoundsComponent : public STComponent{ public: virtual void calculateBounds() = 0; virtual bool contains(STEntity*) = 0; virtual bool intersects(STEntity*) = 0; }; #endif //SWINGTECH1_STBOUNDSCOMPONENT_H
[ "nathan@danque.net" ]
nathan@danque.net
0c59ecec37250228845f8ebb9e351ef50b52266f
d391121e5cb476e9aa6d8043ca02454fa40dbd6c
/uva/299-train-swapping/1.cpp
7116899a28ad489039c7567d9fab3a3ed2977fd7
[]
no_license
alirezaomidi/acm
57171e94399d731a75691ec0d5bb24b2f2274a8f
8a4031a2b8b4d1b971100314817d931e3a71555d
refs/heads/master
2021-01-17T02:54:01.034119
2017-11-22T14:38:21
2017-11-22T14:38:21
22,310,949
8
3
null
2015-12-31T12:55:28
2014-07-27T12:58:40
C++
UTF-8
C++
false
false
779
cpp
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef pair<int, int> ii; typedef pair<int, ii> iii; typedef vector<int> vi; typedef vector<vi> vvi; typedef vector<ii> vii; typedef vector<iii> viii; typedef vector<vii> vvii; typedef set<int> si; typedef vector<si> vsi; typedef pair<double, double> dd; const int inf = 1e9; int main() { ios::sync_with_stdio(false); int n; cin >> n; while (n--) { int l; cin >> l; vi train(l, 0); for (int i = 0; i < l; i++) cin >> train[i]; // bubble sort int ans = 0; for (int i = 0; i < l; i++) for (int j = i + 1; j < l; j++) if (train[i] > train[j]) { ans++; swap(train[i], train[j]); } cout << "Optimal train swapping takes " << ans << " swaps." << endl; } return 0; }
[ "alireza530@gmail.com" ]
alireza530@gmail.com
9aad4d563a5c1cc8ade917a660fa6f1880df3bde
89dff65f94f46c6431a9348599b1d6b53fa4ac6b
/Aqua.ino
ae6f151aedc35c9abc5937e2569febdaee9853b5
[]
no_license
semi10/Aqua
320f3448133a9f89dd5093812621cf641161a6c6
704e524ad1ae5bbe5ad7f2ed6deee0a1729b86f9
refs/heads/master
2021-01-10T21:49:38.078370
2015-06-01T11:40:56
2015-06-01T11:40:56
35,015,962
0
0
null
null
null
null
UTF-8
C++
false
false
5,527
ino
const int Note_C = 239; const int Note_CS = 225; const int Note_D = 213; const int Note_DS = 201; const int Note_E = 190; const int Note_F = 179; const int Note_FS = 169; const int Note_G = 159; const int Note_GS = 150; const int Note_A = 142; const int Note_AS = 134; const int Note_B = 127; typedef struct { byte sec; byte minute; byte hour; unsigned int day; } time; time sleep; time awake; time feed; time current = {0, 0, 0, 0}; time carry = {0, 0, 0, 0}; time real = {0, 0, 0, 0}; const int button = 2; const int leds = 0; const int autoModeLed = 3; const int hungryLed = 4; const int buzzer = 1; boolean autoMode; //If automation is turned on boolean hungry; //If fish is hungry boolean lightOn; //If light turned on byte brightness; //Brightness of lights (0-255) byte lastSec = 0; void setup() { //Serial.begin(9600); autoMode = false; lightOn = true; pinMode(buzzer, OUTPUT); pinMode(button, INPUT); pinMode(autoModeLed, OUTPUT); pinMode(hungryLed, OUTPUT); analogWrite(leds, 255); TinyTone(Note_C, 4, 200); TinyTone(Note_C, 5, 300); delay(3000); } void loop() { if(millis() < 2000){ time current = {0, 0, 0, 0}; time carry = {real.sec, real.minute, real.hour, real.day}; } current.sec = millis()/1000 - 60*(current.day*24*60 + (current.hour*60 + current.minute)); if(current.sec>59){ current.minute++; current.sec = 0; } if(current.minute>59){ current.hour++; current.minute = 0; } if(current.hour>23){ current.day++; current.hour = 0; } real.sec = current.sec + carry.sec; if (real.sec > 59){ real.sec-=60; real.minute++; } real.minute = current.minute + carry.minute; if (real.minute > 59){ real.minute -=60; real.hour++; } real.hour = current.hour + carry.hour; if (real.hour > 23){ real.hour -=24; real.day++; } real.day = current.day + carry.day; if(lastSec != real.sec){ lastSec = real.sec; if(autoMode) checkStatus(); } if(digitalRead(button)){ delay(100); unsigned long start = millis(); while (digitalRead(button)){ unsigned long now = millis(); if(abs(now - start) > 3000){ set(); return; } } if(hungry) { hungry = false; TinyTone(Note_B, 4, 250); delay(50); TinyTone(Note_B, 4, 250); } else if(lightOn){ lightOn = false; brightness = 0; } else{ lightOn = true; brightness = 255; } analogWrite(leds, brightness); } } //****************************************************************** void set(){ autoMode = true; if(lightOn){ lightOn = false; brightness = 0; sleep.sec = real.sec; sleep.minute = real.minute; sleep.hour = real.hour; awake.sec = real.sec; awake.minute = real.minute; awake.hour = (real.hour + 7) % 24; feed.sec = real.sec; feed.minute = real.minute; feed.hour = (real.hour + 20) % 24; } else{ lightOn = true; brightness = 255; sleep.sec = real.sec; sleep.minute = real.minute; sleep.hour = (real.hour + 17) % 24; awake.sec = real.sec; awake.minute = real.minute; awake.hour = real.hour; feed.sec = real.sec; feed.minute = real.minute; feed.hour = (real.hour + 13) % 24; } /* Serial.print("Awake: "); Serial.print(awake.hour); Serial.print(":"); Serial.print(awake.minute); Serial.print(":"); Serial.println(awake.sec); Serial.print("Feed: "); Serial.print(feed.hour); Serial.print(":"); Serial.print(feed.minute); Serial.print(":"); Serial.println(feed.sec); Serial.print("Sleep: "); Serial.print(sleep.hour); Serial.print(":"); Serial.print(sleep.minute); Serial.print(":"); Serial.println(sleep.sec); Serial.println(); analogWrite(leds, brightness); */ analogWrite(leds, brightness); TinyTone(Note_E, 4, 800); } //****************************************************************** void checkStatus(){ if(real.sec % 15 == 0){ if(lightOn && brightness < 255){ brightness++; } else if (!lightOn && brightness > 0){ brightness--; } analogWrite(leds, brightness); } if(real.sec == 0){ if(real.minute == awake.minute && real.hour == awake.hour){ lightOn = true; } else if(real.minute == sleep.minute && real.hour == sleep.hour){ lightOn = false; } else if(real.minute == feed.minute && real.hour == feed.hour){ hungry = true; } } (autoMode)?(digitalWrite(autoModeLed,HIGH)):(digitalWrite(autoModeLed,LOW)); (hungry)?(digitalWrite(hungryLed,HIGH)):(digitalWrite(hungryLed,LOW)); if(hungry && (real.sec == 0) && ((real.minute % 15) == 0)){ TinyTone(Note_E, 4, 300); delay(100); TinyTone(Note_E, 4, 300); } /* Serial.print("Current: "); Serial.print(real.day); Serial.print(" "); Serial.print(real.hour); Serial.print(":"); Serial.print(real.minute); Serial.print(":"); Serial.print(real.sec); Serial.print(" Brightness:"); Serial.print(brightness); Serial.println(" "); Serial.println(); */ } //****************************************************************** void TinyTone(unsigned char divisor, unsigned char octave, unsigned long duration) { TCCR1 = 0x90 | (8-octave); // for 1MHz clock // TCCR1 = 0x90 | (11-octave); // for 8MHz clock OCR1C = divisor-1; // set the OCR delay(duration); TCCR1 = 0x90; // stop the counter }
[ "f.semion89@gmail.com" ]
f.semion89@gmail.com
0659de6c1583e3d7644181912af698eef050b6b6
a84ca8996f03e327797ca8385c0b0d8ed2b1a3cd
/syneight/base/memory_monitoring/memory_operators.hpp
3cbf17dde7f4128efdff1a16937bbe6c56c1748d
[]
no_license
arafato/syneight
d031b3438729469a0b623baf4bc2e8c1288a21e7
c860b9d88c0fa327e6f9965c5f106567b4a9c17c
refs/heads/master
2021-01-01T18:18:29.026815
2014-09-29T13:25:40
2014-09-29T13:25:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,178
hpp
/*----------------------------------------------------------------------------- * Syneight - A soft-realtime transaction monitor. * Copyright (C) 2003-2004 The Syneight Group. * * TODO: License. *---------------------------------------------------------------------------*/ /** * @file syneight/base/memory_monitoring/memory_operators.hpp * * @author Christian Schallhart * @author $Author: esdentem $ * * @version $Id: memory_operators.hpp 1053 2005-06-07 12:14:38Z esdentem $ * * @brief The standard new/delete operators for memory monitoring. * * TODO: Long description. * * @note DOCUMENTED * * @todo TODO */ #ifndef SYNEIGHT__BASE__MEMORY_MONITORING__MEMORY_OPERATORS_HPP #define SYNEIGHT__BASE__MEMORY_MONITORING__MEMORY_OPERATORS_HPP #include <syneight/diagsnotics/memory_monitoring_facility.hpp> #include <cstdlib> // for ::std::size_t #include <new> void* operator new(::std::size_t const len) throw(::std::bad_alloc) { void* const result(::std::malloc(len)); ::syneight::memory_monitoring::Memory_Monitoring_Facility::register_allocation(result,len); return result; } void operator delete(void * const p,::std::size_t const len) { if(p==NULL) return; if(::syneight::memory_monitoring::Memory_Monitoring_Facility::register_deallocation(p)) ::std::free(p); } void operator delete(void * const p) throw() { if(p==NULL) return; if(::syneight::memory_monitoring::Memory_Monitoring_Facility::register_deallocation(p)) ::std::free(p); } void* operator new[](::std::size_t const len) throw(::std::bad_alloc) { void* const result(::std::malloc(len)); ::syneight::memory_monitoring::Memory_Monitoring_Facility::register_allocation(result,len); return result; } void operator delete[](void * const p,::std::size_t const len) { if(p==NULL) return; if(::syneight::memory_monitoring::Memory_Monitoring_Facility::register_deallocation(p)) ::std::free(p); } void operator delete[](void * const p) throw() { if(p==NULL) return; if(::syneight::memory_monitoring::Memory_Monitoring_Facility::register_deallocation(p)) ::std::free(p); } #endif // vim:ts=4:sw=4
[ "g@gh.com" ]
g@gh.com
dfd4533836f0d1c7f0cc6e673a1bd21d0fb29dd2
cc3692e7beae4b4b1a561095adbd4b0ad9267eb8
/CS Academy C++/round77p4_expected_lcp_trie/Round77P4_Trie.cpp
477e67bde32e3f2efe8de96ee6f94cbe8a4d9ff1
[]
no_license
ailyanlu1/Contests
a5946fe82b4ae5f5a6f02e1454410e0c9bcef94b
5aa2ada86703f8b869e0e9363b99a007e2740f7a
refs/heads/master
2020-03-26T13:03:45.790085
2018-08-16T00:34:40
2018-08-16T00:34:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,110
cpp
// https://csacademy.com/contest/round-77/task/expected-lcp/ #include <bits/stdc++.h> using namespace std; #define INT_INF 0x3f3f3f3f #define LL_INF 0x3f3f3f3f3f3f3f3f #define D_INF numeric_limits<double>::infinity() #define MIN(a, b) ((a) = min((a), (b))) #define MAX(a, b) ((a) = max((a), (b))) #define pb push_back #define eb emplace_back #define mp make_pair #define f first #define s second #define all(a) (a).begin(), (a).end() #define For(i, a, b) for (auto i = (a); i < (b); i++) #define FOR(i, b) For(i, 0, b) #define Rev(i, a, b) for (auto i = (a); i > (b); i--) #define REV(i, a) Rev(i, a, -1) #define sz(a) ((int) (a).size()) #define nl '\n' #define sp ' ' #define ll long long #define ld long double #define pii pair<int, int> #define pll pair<ll, ll> #define pill pair<int, ll> #define plli pair<ll, int> #define pdd pair<double, double> #define uset unordered_set #define umap unordered_map #define pq priority_queue template<typename T> using minpq = pq<T, vector<T>, greater<T>>; template<typename T> using maxpq = pq<T, vector<T>, less<T>>; template<typename T1, typename T2> struct pair_hash {size_t operator ()(const pair<T1, T2> &p) const {return 31 * hash<T1> {}(p.first) + hash<T2> {}(p.second);}}; int N; ll ans = 0; struct Node { unordered_map<char, Node*> child; int cnt = 0; }; void insert(Node *root, string &s) { Node *cur = root; for (char c : s) { if (cur->child.count(c)) cur = cur->child[c]; else cur = cur->child[c] = new Node(); cur->cnt++; } } double dfs(Node *cur) { double ret = cur->cnt * (cur->cnt - 1); for (pair<char, Node*> p : cur->child) ret += dfs(p.s); return ret; } Node *root = new Node(); int main() { // freopen("in.txt", "r", stdin); // freopen("out.txt", "w", stdout); ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); cin >> N; string s; FOR(i, N) { cin >> s; insert(root, s); } cout << fixed << setprecision(9) << dfs(root) / ((ll) N * (N - 1)) << nl; return 0; }
[ "wesley.a.leung@gmail.com" ]
wesley.a.leung@gmail.com
5019994a1497b0bafc56a23628a1512a6a10eecd
358b90bd4bfdbd1dc1ec9435b3460d08a74a8023
/src/symtable.cpp
834a7f395a08faea6bd16d0276d875ad27ee144a
[]
no_license
poncovka/vype-compiler
d3765be81bda5a22c412d14c1b9d068131702768
f206cd38d442534f8b27831971dcff482860ecc0
refs/heads/master
2021-01-22T13:47:57.666921
2016-08-22T10:30:38
2016-08-22T10:30:38
25,217,322
0
0
null
null
null
null
UTF-8
C++
false
false
6,486
cpp
/* * Project: VYPe 2014 * * Authors: * Vendula Poncová, xponco00 * Martin Šifra, xsifra00 * * File: symtable.cpp * Definitions of methods for symbols and symbol tables. */ #include "symtable.h" //////////////////////////////////// Symtable string Symtable::str(Symtable::Type type) { static const string STR[] = {"void", "int", "char", "string"}; return STR[type]; } string Symtable::str(Symtable::Operator op) { static const string STR[] = {"+", "-", "*", "/", "%", "<", "<=", ">", ">=", "==", "!=", "&&", "||", "!"}; return STR[op]; } //////////////////////////////////// Variable Variable::Variable(Symtable::Type type) { this->type = type; } Variable::Variable(string &id, Symtable::Type type) { this->type = type; this->id = id; } string Variable::str() { std::stringstream stream; stream << Symtable::str(type) << " " << id; return stream.str(); } //////////////////////////////////// VariableTable bool VariableTable::insert(Variable *var) { treturn ret; ret = symtable.insert(tpair(var->id, var)); return ret.second; } Variable* VariableTable::lookup(string &id) { tmap::iterator i; i = symtable.find(id); if (i == symtable.end()) { return NULL; } return i->second; } VariableTable::~VariableTable() { for(tmap::iterator i=symtable.begin(); i != symtable.end(); ++i) { delete i->second; } } //////////////////////////////////// Function Function::Function(string &id, list<Variable*> params, Symtable::Type type) { this->type = type; this->id = id; this->params.splice(this->params.begin(), params); this->isdef = true; this->isbuiltin = false; } Function::~Function() { clear(); } Function* Function::createDeclaration(string &id, list<Variable*> params, Symtable::Type type) { Function *f = new Function(id, params, type); f->isdef = false; return f; } Function* Function::createBuiltin(string &id, list<Variable*> params, Symtable::Type type) { Function *f = new Function(id, params, type); f->isdef = false; f->isbuiltin = true; return f; } VariableTable* Function::createVariableTable() { VariableTable *table = new VariableTable; variables.push_back(table); return table; } bool Function::checkParameters(list<Variable*> variables) { list<Variable*>::iterator i, j; i = params.begin(); j = variables.begin(); while(i != params.end() && j != variables.end() && (*i)->type == (*j)->type) { ++i; ++j; } return (i == params.end() && j == variables.end()); } bool Function::checkParameters(list<Expression*> expressions) { list<Variable*>::iterator i = params.begin(); list<Expression*>::iterator j = expressions.begin(); while(i != params.end() && j != expressions.end() && (*i)->type == (*j)->var->type) { ++i; ++j; } return (i == params.end() && j == expressions.end()); } string Function::str() { std::stringstream stream; stream << Symtable::str(type) << " " << id << "("; bool first = true; for(list<Variable*>::iterator i = params.begin(); i != params.end(); ++i) { if (!first) { stream << ", "; } stream << (*i)->str(); first = false; } stream << ")"; return stream.str(); } void Function::clear() { if (!isdef) { freeVariables(params); } params.clear(); freeInstructions(instructions); freeVariableTables(variables); } //////////////////////////////////// UnlimitedBuiltinFunction UnlimitedBuiltinFunction::UnlimitedBuiltinFunction (string &id, int minparams, Symtable::Type type) : Function() { this->type = type; this->id = id; this->minparams = minparams; this->isdef = false; this->isbuiltin = true; } bool UnlimitedBuiltinFunction::checkParameters(list<Variable*> variables) { return (variables.size() >= minparams); } bool UnlimitedBuiltinFunction::checkParameters(list<Expression*> expressions) { return (expressions.size() >= minparams); } //////////////////////////////////// FunctionTable bool FunctionTable::insert(Function *func) { treturn ret; ret = symtable.insert(tpair(func->id, func)); return ret.second; } Function* FunctionTable::lookup(string &id) { tmap::iterator i; i = symtable.find(id); if (i == symtable.end()) { return NULL; } return i->second; } FunctionTable::~FunctionTable() { for(tmap::iterator i=symtable.begin(); i != symtable.end(); ++i) { delete i->second; } } //////////////////////////////////// SymbolTable SymbolTable::SymbolTable() { main = NULL; actualFunction = NULL; } SymbolTable::~SymbolTable() { stack.clear(); } bool SymbolTable::insert(Function *func) { return functions.insert(func); } bool SymbolTable::insert(Variable *var) { if (stack.empty()) return false; VariableTable *table = stack.front(); return table->insert(var); } Function* SymbolTable::lookupFunction(string &id) { return functions.lookup(id); } Variable* SymbolTable::lookupVariable(string &id) { VariableTable *table; Variable *var = NULL; for(tstack::iterator i = stack.begin(); i != stack.end(); ++i) { table = *i; var = table->lookup(id); if (var != NULL) break; } return var; } void SymbolTable::enterBlock(Function *func) { actualFunction = func; enterBlock(); } void SymbolTable::enterBlock() { VariableTable *table = actualFunction->createVariableTable(); stack.push_front(table); } void SymbolTable::leaveBlock() { stack.pop_front(); if(stack.empty()) { actualFunction = NULL; } } //////////////////////////////////// Expression Expression::Expression() { this->var = NULL; } Expression::Expression(Variable *var, InstructionList *l) { this->var = var; this->inst.splice(this->inst.begin(), *l); } Expression::~Expression() { freeInstructions(inst); } //////////////////////////////////// free void freeVariables(list<Variable*> &l) { while(!l.empty()) { Variable *var = l.front(); l.pop_front(); delete var; } } void freeVariableTables(list<VariableTable*> &l) { while(!l.empty()) { VariableTable *tab = l.front(); l.pop_front(); delete tab; } } void freeExpressions(list<Expression*> &l) { while(!l.empty()) { Expression *expr = l.front(); l.pop_front(); delete expr; } } void freeInstructions(list<Instruction*> &l) { while(!l.empty()) { Instruction *i = l.front(); l.pop_front(); delete i; } } /* end of file */
[ "poncovka@gmail.com" ]
poncovka@gmail.com
01fc0c3caefa54a154b4eae3ac2eb111d75d72f2
5ebd5cee801215bc3302fca26dbe534e6992c086
/blaze/math/constraints/VecEvalExpr.h
13c83d4192a5a2dc2802684ae3b21fdc53ce5146
[ "BSD-3-Clause" ]
permissive
mhochsteger/blaze
c66d8cf179deeab4f5bd692001cc917fe23e1811
fd397e60717c4870d942055496d5b484beac9f1a
refs/heads/master
2020-09-17T01:56:48.483627
2019-11-20T05:40:29
2019-11-20T05:41:35
223,951,030
0
0
null
null
null
null
UTF-8
C++
false
false
4,128
h
//================================================================================================= /*! // \file blaze/math/constraints/VecEvalExpr.h // \brief Constraint on the data type // // Copyright (C) 2012-2019 Klaus Iglberger - All Rights Reserved // // This file is part of the Blaze library. You can redistribute it and/or modify it under // the terms of the New (Revised) BSD License. Redistribution and use in source and binary // forms, with or without modification, are permitted provided that the following conditions // are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, this list // of conditions and the following disclaimer in the documentation and/or other materials // provided with the distribution. // 3. Neither the names of the Blaze development group nor the names of its contributors // may be used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT // SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED // TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR // BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH // DAMAGE. */ //================================================================================================= #ifndef _BLAZE_MATH_CONSTRAINTS_VECEVALEXPR_H_ #define _BLAZE_MATH_CONSTRAINTS_VECEVALEXPR_H_ //************************************************************************************************* // Includes //************************************************************************************************* #include <blaze/math/typetraits/IsVecEvalExpr.h> namespace blaze { //================================================================================================= // // MUST_BE_VECEVALEXPR_TYPE CONSTRAINT // //================================================================================================= //************************************************************************************************* /*!\brief Constraint on the data type. // \ingroup math_constraints // // In case the given data type \a T is not a vector evaluation expression (i.e. a type derived // from the VecEvalExpr base class), a compilation error is created. */ #define BLAZE_CONSTRAINT_MUST_BE_VECEVALEXPR_TYPE(T) \ static_assert( ::blaze::IsVecEvalExpr_v<T>, "Non-vector evaluation expression type detected" ) //************************************************************************************************* //================================================================================================= // // MUST_NOT_BE_VECEVALEXPR_TYPE CONSTRAINT // //================================================================================================= //************************************************************************************************* /*!\brief Constraint on the data type. // \ingroup math_constraints // // In case the given data type \a T is a vector evaluation expression (i.e. a type derived from // the VecEvalExpr base class), a compilation error is created. */ #define BLAZE_CONSTRAINT_MUST_NOT_BE_VECEVALEXPR_TYPE(T) \ static_assert( !::blaze::IsVecEvalExpr_v<T>, "Vector evaluation expression type detected" ) //************************************************************************************************* } // namespace blaze #endif
[ "klaus.iglberger@gmail.com" ]
klaus.iglberger@gmail.com
68ee92cbfa663e177b71b50bcb525c0aaaf58384
699ff10c347dc9b6d5af7f531a1c941dbfecd558
/leetcode/cpp/4-median-of-two-sorted-arrays.cpp
dced69af8821645bb05e0f57857a312b8994dfb2
[]
no_license
iampkuhz/OnlineJudge_cpp
71a7637c54d81be2aa066a6132aab31b798bbe6b
737b9bac5a73c319e46cda8c3e9d729f734d7792
refs/heads/master
2021-01-10T10:16:37.589855
2017-03-06T12:45:20
2017-03-06T12:45:20
24,891,815
0
0
null
null
null
null
UTF-8
C++
false
false
1,221
cpp
/** * 在2个排序的数组中找中位数| */ class Solution { int sz1, sz2; public: double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) { sz1 = nums1.size(), sz2 = nums2.size(); int am1 = findK((sz1+sz2+1)/2, nums1, nums2); int am2 = findK((sz1+sz2)/2+1, nums1, nums2); return (0.0+am1+am2)/2; } int findK(int k, vector<int>& n1, vector<int>& n2){ int a1 = 0, b1 = sz1-1; int a2 = 0, b2 = sz2-1; while(k >= 0){ if(a1 > b1) return n2[a2+k-1]; if(a2 > b2) return n1[a1+k-1]; int m1 = (b1+a1)/2; if(m1-a1+1>=k){ if(m1 - a1 + 1 == k && n1[m1] <= n2[a2]) return n1[m1]; b1 = m1-1;continue; } int m2 = k-(m1-a1+1)+a2-1; if(m2 > b2){ k -= m1-a1+1; a1 = m1 +1; continue; } if(n1[m1] > n2[m2]){ b1 = m1; k -= m2-a2+1; a2 = m2+1; } else{ k -= m1-a1+1; a1 = m1+1; b2 = m2; } } } };
[ "iampkuhz@gmail.com" ]
iampkuhz@gmail.com
046115d06c772aac9cb38c514187e05d247b6805
40e773b9ce2653154706e220e06decce22eb1f12
/ExternalResources/reactphysics3d-0.7.1/testbed/nanogui/src/popupbutton.cpp
a4c960b33a26d30e90e7c8f060aca3dc47064e72
[ "Zlib", "MIT", "BSD-3-Clause", "LicenseRef-scancode-generic-cla", "CC-BY-SA-4.0" ]
permissive
BEEMO197/Reality-Game-Engine
4ff29560a25e1dc9888ed023d825b301e00e5d7d
08ff9d9b02790e31bef5ec1c3a50f1b36d43a572
refs/heads/master
2020-12-26T16:20:13.957754
2020-03-01T02:53:26
2020-03-01T02:53:26
237,561,059
1
0
MIT
2020-03-01T01:47:51
2020-02-01T04:22:19
null
UTF-8
C++
false
false
3,140
cpp
/* src/popupbutton.cpp -- Button which launches a popup widget NanoGUI was developed by Wenzel Jakob <wenzel.jakob@epfl.ch>. The widget drawing code is based on the NanoVG demo application by Mikko Mononen. All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE.txt file. */ #include <nanogui/popupbutton.h> #include <nanogui/theme.h> #include <nanogui/opengl.h> #include <nanogui/serializer/core.h> NAMESPACE_BEGIN(nanogui) PopupButton::PopupButton(Widget *parent, const std::string &caption, int buttonIcon) : Button(parent, caption, buttonIcon) { mChevronIcon = mTheme->mPopupChevronRightIcon; setFlags(Flags::ToggleButton | Flags::PopupButton); Window *parentWindow = window(); mPopup = new Popup(parentWindow->parent(), window()); mPopup->setSize(Vector2i(320, 250)); mPopup->setVisible(false); mIconExtraScale = 0.8f;// widget override } Vector2i PopupButton::preferredSize(NVGcontext *ctx) const { return Button::preferredSize(ctx) + Vector2i(15, 0); } void PopupButton::draw(NVGcontext* ctx) { if (!mEnabled && mPushed) mPushed = false; mPopup->setVisible(mPushed); Button::draw(ctx); if (mChevronIcon) { auto icon = utf8(mChevronIcon); NVGcolor textColor = mTextColor.w() == 0 ? mTheme->mTextColor : mTextColor; nvgFontSize(ctx, (mFontSize < 0 ? mTheme->mButtonFontSize : mFontSize) * icon_scale()); nvgFontFace(ctx, "icons"); nvgFillColor(ctx, mEnabled ? textColor : mTheme->mDisabledTextColor); nvgTextAlign(ctx, NVG_ALIGN_LEFT | NVG_ALIGN_MIDDLE); float iw = nvgTextBounds(ctx, 0, 0, icon.data(), nullptr, nullptr); Vector2f iconPos(0, mPos.y() + mSize.y() * 0.5f - 1); if (mPopup->side() == Popup::Right) iconPos[0] = mPos.x() + mSize.x() - iw - 8; else iconPos[0] = mPos.x() + 8; nvgText(ctx, iconPos.x(), iconPos.y(), icon.data(), nullptr); } } void PopupButton::performLayout(NVGcontext *ctx) { Widget::performLayout(ctx); const Window *parentWindow = window(); int posY = absolutePosition().y() - parentWindow->position().y() + mSize.y() /2; if (mPopup->side() == Popup::Right) mPopup->setAnchorPos(Vector2i(parentWindow->width() + 15, posY)); else mPopup->setAnchorPos(Vector2i(0 - 15, posY)); } void PopupButton::setSide(Popup::Side side) { if (mPopup->side() == Popup::Right && mChevronIcon == mTheme->mPopupChevronRightIcon) setChevronIcon(mTheme->mPopupChevronLeftIcon); else if (mPopup->side() == Popup::Left && mChevronIcon == mTheme->mPopupChevronLeftIcon) setChevronIcon(mTheme->mPopupChevronRightIcon); mPopup->setSide(side); } void PopupButton::save(Serializer &s) const { Button::save(s); s.set("chevronIcon", mChevronIcon); } bool PopupButton::load(Serializer &s) { if (!Button::load(s)) return false; if (!s.get("chevronIcon", mChevronIcon)) return false; return true; } NAMESPACE_END(nanogui)
[ "abhishekchandra2005@gmail.com" ]
abhishekchandra2005@gmail.com
1acc717744a9af1d8fefb97566b155dca8e7f34e
a08acc24f53d5f19bcd591576b163065fab2b649
/controller/src/outputs/display.h
6a68adc155eee71950263a7128458ed6864a87f1
[ "MIT" ]
permissive
benjylxwang/rc-car
6f142c671a601f76c8b4d2c43fb4df2180d49c4c
002ed1ef9d1dff195f110263245622792a4d733d
refs/heads/main
2023-03-31T02:26:42.270894
2021-04-06T14:35:33
2021-04-06T14:35:33
331,080,276
0
0
null
null
null
null
UTF-8
C++
false
false
427
h
#ifndef DISPLAY_H #define DISPLAY_H #include <LiquidCrystal_I2C.h> #include "../state.h" class Display { public: Display(); void setup(); void printState(State state); private: // Display LiquidCrystal_I2C lcd; unsigned long lastPrint; // Flashing bool leftIndicator; bool rightIndicator; unsigned long lastFlash; bool isInFlash; void printLightInfo(State state); }; #endif
[ "benjylxwang64@gmail.com" ]
benjylxwang64@gmail.com
db59caee390b3815773ca057fbe2b181fa6f3f03
482f4c1c15d383653ea32115f611dbfaf2489ae2
/src/lessonClass/test.cpp
d6c8eb266d53b60e2418eb576f5c97143312cd86
[]
no_license
minhtblaser/CBasic_baitapnhomlaptrinh
b6a410bde8b9f2f1c932f5f3ecf0ed75a6e12c9a
7a032c14619229fec2b279fb64ece3d2a1870d04
refs/heads/main
2023-02-03T03:57:17.257824
2020-12-27T06:55:52
2020-12-27T06:55:52
321,887,820
0
1
null
2020-12-22T13:24:51
2020-12-16T06:17:47
C++
UTF-8
C++
false
false
2,130
cpp
#include<stdio.h> #include<math.h> #define MAX_SIZE 100 struct Array{ int numbers[MAX_SIZE];//các phần tử int size;//số phần tử trong mảng }; void enter(Array &input); void printValue(Array output); Array findEvenNumbers(Array source); void printEvenNumbers(Array source); bool isPrime(Array source); Array findPrime(Array source); void printPrime(Array source); int main(){ Array list; enter(list); printValue(list); printEvenNumbers(list); printPrime(list); } void enter(Array &input){ int temp; printf("Enter the size of array: "); scanf("%d", &input.size); for(int index = 0; index < input.size; index++){ printf("enter number a[%d]: ",index); scanf("%d", &temp); input.numbers[index] = temp; } } void printValue(Array output){ for(int index = 0; index < output.size; index++){ printf("%4d",output.numbers[index]); } } Array findEvenNumbers(Array source){ Array even_numbers; even_numbers.size = 0; for(int index = 0; index < source.size; index++){ if(source.numbers[index] % 2 == 0){ even_numbers.size++; even_numbers.numbers[even_numbers.size-1] = source.numbers[index]; } } return even_numbers; } void printEvenNumbers(Array source){ Array even_numbers = findEvenNumbers(source); printf("\nyour result: "); printValue(even_numbers); } bool isPrime(Array source){ int isPrime = true; if(source.size<2){ isPrime = false; } for(int index =2;index<sqrt(source.size);index++){ if(source.size%index==0){ isPrime=false; break; } } return isPrime; } Array findPrime(Array source){ Array findPrime; findPrime.size=0; for(int index=0;index<source.size;index++){ if(isPrime(source)){ findPrime.size++; findPrime.numbers[findPrime.size-1] = source.numbers[index]; } } return findPrime; } void printPrime(Array source){ Array prime=findPrime(source); printf("\nPrime number in Array is: "); printValue(prime); }
[ "trinhngocminh.9a1@gmail.com" ]
trinhngocminh.9a1@gmail.com
0d7406b74b351a2dce5ec814581ff606e33fcd5f
7241303f19dacea5a6c4e2436a522cc5811b8bfb
/legacy/tools/oauth/login.cpp
66f977ee6ad6bb977f4e21d1c2651679c2b54ded
[]
no_license
wingfiring/nix
50f5bb8d02765b4184e4cf96789b486873e9e4b4
7ffc90bb4870a5d22e5b02f52b738b109caf06cd
refs/heads/master
2022-05-03T20:08:31.511938
2018-02-22T10:10:36
2018-02-22T10:10:36
114,869,039
0
0
null
null
null
null
UTF-8
C++
false
false
11,187
cpp
#include <xirang2/string.h> #include <xirang2/context_except.h> #include <xirang2/io.h> #include <xirang2/string_algo/string.h> #include <xirang2/path.h> #pragma warning( disable : 4005 ) #include <boost/asio.hpp> #include <boost/asio/io_service.hpp> #include <boost/asio/ip/tcp.hpp> #include <boost/asio/spawn.hpp> #include <boost/asio/steady_timer.hpp> #include <boost/asio/write.hpp> #include <boost/asio/ssl.hpp> #include <boost/algorithm/string/trim.hpp> #include <boost/lexical_cast.hpp> #include <boost/algorithm/string.hpp> #include <iostream> #include <memory> #include <map> #include <sstream> XR_INTERNAL_EXCEPTION_TYPE(network_exception); #if 0 namespace http { class parameters; class parameter_map; class parameter_multi_map; class parameter_iterator; class headers; class header_map; class header_multi_map; class header_iterator; class content : public xirang2::io::reader {}; class connection { request talk(); }; class request { response send(); }; class response { request complete(); }; class session_mgr { }; struct cookie { }; void foo() { connection* conn = make_conn( io_service, url, cookies, headers, ); } } #endif typedef std::map<std::string, std::string> CookieMap; typedef std::multimap<std::string, std::string> HeadMap; struct httpHead { std::string version, code, status; std::string header_str; HeadMap headers; }; std::multimap<std::string, std::string> load_headers_(std::istream& sstr) { std::multimap<std::string, std::string> ret; while (sstr) { std::string name, line; sstr >> name; getline(sstr, line); if (!name.empty()) name.resize(name.size() - 1); if (name.empty()) continue; boost::trim(line); boost::to_lower(name); ret.insert({ name, line }); } return ret; } void saveCookies(const HeadMap& hmap, CookieMap& cookies) { auto range = hmap.equal_range("set-cookie"); for (auto pos = range.first; pos != range.second; ++pos) { std::vector<std::string> cookie; boost::split(cookie, pos->second, [](char ch) { return ch == ';'; }); if (cookie.empty()) continue; for (auto itr = ++cookie.begin(); itr != cookie.end(); ++itr) if (*itr == "HttpOnly") continue; auto& cookie_pair = *cookie.begin(); auto itr = std::find(cookie_pair.begin(), cookie_pair.end(), '='); std::string name = std::string(cookie_pair.begin(), itr); if (itr != cookie_pair.end()) ++itr; std::string value = std::string(itr, cookie_pair.end()); cookies[name] = value; } } std::string genCookieHeader(CookieMap& cookies){ std::string cookie_head("Cookie:"); for (auto& i : cookies) { cookie_head.push_back(' '); cookie_head += i.first; cookie_head.push_back('='); cookie_head += i.second; cookie_head.push_back(';'); } if (!cookies.empty()) cookie_head.resize(cookie_head.size() - 1); return cookie_head; } void connectHttps(const std::string& host, boost::asio::ssl::stream<boost::asio::ip::tcp::socket>& socket, boost::asio::yield_context& yield, const std::string& port = "443") { using boost::asio::ip::tcp; boost::system::error_code ec; auto& io_service = socket.get_io_service(); tcp::resolver resolver(io_service); auto itr = resolver.async_resolve(tcp::resolver::query(host.c_str(), port), yield[ec]); if (ec) XR_THROW(network_exception)("Failed to resolve login_site ")(host.c_str()); for (tcp::resolver::iterator end; itr != end; ++itr) { boost::asio::async_connect(socket.lowest_layer(), itr, yield[ec]); if (!ec) break; } if (!socket.lowest_layer().is_open()) XR_THROW(network_exception)("connect login_site ")(host.c_str()); socket.async_handshake(boost::asio::ssl::stream_base::client, yield[ec]); if (ec) { std::cout << "async_handshake:" << ec.message() << std::endl; XR_THROW(network_exception)("TLS handshake ")(host.c_str()); } } httpHead httpsSend(boost::asio::ssl::stream<boost::asio::ip::tcp::socket>& socket, const std::string& in, std::vector<char>& data, boost::asio::yield_context& yield) { boost::system::error_code ec; boost::asio::async_write(socket, boost::asio::buffer(in), yield[ec]); if (ec) XR_THROW(network_exception)("Send request:\n")(in.c_str()); data.resize(65536); std::size_t n = socket.async_read_some(boost::asio::buffer(data), yield[ec]); if (ec) XR_THROW(network_exception)("Failed to read response"); data.resize(n); static const std::string CRLF_Dim = "\r\n\r\n"; auto crlfcrlf = std::search(data.begin(), data.end(), CRLF_Dim.begin(), CRLF_Dim.end()); if (crlfcrlf == data.end()) XR_THROW(network_exception)("Bad response header"); httpHead head; std::string headers(data.begin(), crlfcrlf); std::stringstream sheader(headers); sheader >> head.version >> head.code; std::getline(sheader, head.status); std::cout << "response with code " << head.code << std::endl; head.headers = load_headers_(sheader); head.header_str = headers; return head; } const xirang2::string login_url("https://accounts-dev.autodesk.com/Authentication/LogOn"); const xirang2::string login_site("accounts-dev.autodesk.com"); const xirang2::string oauth_site("developer-dev.api.autodesk.com"); void test_login() { using boost::asio::ip::tcp; boost::asio::io_service io_service; boost::asio::spawn(io_service, [&](boost::asio::yield_context yield) { boost::system::error_code ec; //boost::asio::ssl::context ssl_context(boost::asio::ssl::context::tlsv12); boost::asio::ssl::context ssl_context(boost::asio::ssl::context::tlsv12); /// Connect boost::asio::ssl::stream<boost::asio::ip::tcp::socket> socket(io_service, ssl_context); connectHttps(login_site.c_str(), socket, yield); //// call Authentication/LogOn: std::string scontent ="UserName=jackson.sun%40autodesk.com&Password=jqmthmlsb123"; std::stringstream sstr; /// send logon request sstr << "POST /Authentication/LogOn HTTP/1.1""\r\n" "Host: accounts-dev.autodesk.com""\r\n" "Connection: keep-alive""\r\n" "Content-Length : " << scontent.size() << "\r\n" "Content-Type: application/x-www-form-urlencoded; charset=UTF-8""\r\n" "Accept: */*""\r\n""\r\n" << scontent ; auto request = sstr.str(); std::vector<char> data; auto login_response_head = httpsSend(socket, request, data, yield); std::cout << "\n\tResponse:\n" << login_response_head.header_str << std::endl; CookieMap cookies; saveCookies(login_response_head.headers, cookies); // OAuth2 step 1, get code xirang2::file_path url("https://developer-dev.api.autodesk.com/authentication/v1/authorize?response_type=code&client_id=5xraq7vtIPiBmY4RdC502oo5FWFL2KFc&redirect_uri=https%3A%2F%2Ficerote.net%2Fblog", xirang2::pp_none); xirang2::file_path redirect_site(xirang2::literal("icerote.net")); std::string code; xirang2::string current_site; for (;;) { auto uri_info = xirang2::parse_uri(url); if (uri_info.site == redirect_site.str()) { std::string path = uri_info.path.str().c_str(); auto pos = xirang2::find(path, '='); if (pos != path.end()) ++pos; code = std::string(pos, path.end()); break; } else if (uri_info.site.empty()) uri_info.site = current_site; else current_site = uri_info.site; if (uri_info.port.empty()) uri_info.port = "443"; boost::asio::ssl::stream<boost::asio::ip::tcp::socket> socket_oauth(io_service, ssl_context); connectHttps(uri_info.site.c_str(), socket_oauth, yield, uri_info.port.c_str()); sstr.str(std::string()); sstr.clear(); sstr << "GET " << uri_info.path.str() << " HTTP/1.1""\r\n" "Host: "<< uri_info.site << "\r\n" "Connection: keep-alive""\r\n" << genCookieHeader(cookies) << "\r\n" "Accept: */*""\r\n\r\n" ; request = sstr.str(); std::cout << "\n\tRequest:\n" << request << "\n\twith cookie\n" << genCookieHeader(cookies) << std::endl; auto res_head = httpsSend(socket_oauth, request, data, yield); saveCookies(res_head.headers, cookies); std::cout << "\n\tResponse:\n" << res_head.header_str << std::endl; if (!res_head.code.empty() && res_head.code[0] != '3') break; auto itr = res_head.headers.find("location"); if (itr != res_head.headers.end()) { url = xirang2::file_path(itr->second.c_str(), xirang2::pp_none); } } //// Get Token xirang2::file_path token_url("https://developer.api.autodesk.com/authentication/v1/gettoken"); sstr.str(std::string()); sstr.clear(); std::string content = "client_id=5xraq7vtIPiBmY4RdC502oo5FWFL2KFc&" "client_secret=gZgY3WzdCrFV8ccC&" "grant_type=authorization_code&code=" + code //+ "&redirect_uri=https%3A%2F%2Ficerote.net%2Fblog" + "&redirect_uri=https://icerote.net/blog" ; sstr << "POST /authentication/v1/gettoken HTTP/1.1""\r\n" "Host: developer-dev.api.autodesk.com""\r\n" "Connection: keep-alive""\r\n" "Content-Length : " << content.size() << "\r\n" "Content-Type: application/x-www-form-urlencoded""\r\n" // << genCookieHeader(cookies) << "\r\n" "Accept: */*""\r\n\r\n" << content ; request = sstr.str(); std::cout << "\n\tRequest:\n" << request << std::endl; boost::asio::ssl::stream<boost::asio::ip::tcp::socket> socket3(io_service, ssl_context); connectHttps("developer-dev.api.autodesk.com", socket3, yield); auto response = httpsSend(socket3, request, data, yield); std::cout << "\n\tResponse:\n" << response.header_str << std::endl; return; }); try { boost::asio::ssl::context ssl_context(boost::asio::ssl::context::sslv23); io_service.run(); } catch (xirang2::exception& e) { std::cout << "XR Error " << e.what() << std::endl; } catch (std::exception& e) { std::cout << "Error " << e.what() << std::endl; } catch (...) { std::cout << "Unknown error\n"; } }
[ "scy@icerote.com" ]
scy@icerote.com
2aef991a1f68f0140cd0c623142e94c2e241a975
1594e369b3536f825e12e4d995d3921a0109f3b7
/src/remote_control/src/LAN/robot_control/performancerecorder.cpp
62c0a18c09361d4e8337382327487c5d42f95ab7
[]
no_license
CastielLiu/robot_ws
c3f2575b61fdfdad539c05fa202db2a543697b02
2a005231ad82ae2622d9a6f06c50dff56630abe2
refs/heads/master
2021-08-08T23:52:40.437193
2021-07-01T01:26:50
2021-07-01T01:26:50
208,391,320
0
1
null
null
null
null
UTF-8
C++
false
false
772
cpp
#include "performancerecorder.h" PerformanceRecorder::PerformanceRecorder(QString file) { file_ = file; } void PerformanceRecorder::writePerformance(const QString& key, const QString& value, QString group) { //创建配置文件操作对象 QSettings *config = new QSettings(file_, QSettings::IniFormat); //将信息写入配置文件 config->beginGroup(group); config->setValue(key, value); config->endGroup(); delete config; } void PerformanceRecorder::readPerformance(const QString &key, QString &value, QString group) { //创建配置文件操作对象 QSettings *config = new QSettings(file_, QSettings::IniFormat); //读取配置信息 value = config->value(group + "/" + key).toString(); delete config; }
[ "ubuntu@localhost.localdomain" ]
ubuntu@localhost.localdomain
119ed359f492131b20a896b915a7497a3e03d496
3438e8c139a5833836a91140af412311aebf9e86
/content/browser/site_per_process_browsertest.cc
67ff7ca2eee5792ba26c4f2bac9b60a00a32501a
[ "BSD-3-Clause" ]
permissive
Exstream-OpenSource/Chromium
345b4336b2fbc1d5609ac5a67dbf361812b84f54
718ca933938a85c6d5548c5fad97ea7ca1128751
refs/heads/master
2022-12-21T20:07:40.786370
2016-10-18T04:53:43
2016-10-18T04:53:43
71,210,435
0
2
BSD-3-Clause
2022-12-18T12:14:22
2016-10-18T04:58:13
null
UTF-8
C++
false
false
360,620
cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/site_per_process_browsertest.h" #include <stddef.h> #include <stdint.h> #include <algorithm> #include <vector> #include "base/command_line.h" #include "base/location.h" #include "base/macros.h" #include "base/path_service.h" #include "base/single_thread_task_runner.h" #include "base/strings/pattern.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "base/test/test_timeouts.h" #include "base/threading/thread_task_runner_handle.h" #include "build/build_config.h" #include "content/browser/frame_host/cross_process_frame_connector.h" #include "content/browser/frame_host/frame_tree.h" #include "content/browser/frame_host/interstitial_page_impl.h" #include "content/browser/frame_host/navigator.h" #include "content/browser/frame_host/render_frame_proxy_host.h" #include "content/browser/frame_host/render_widget_host_view_child_frame.h" #include "content/browser/gpu/compositor_util.h" #include "content/browser/loader/resource_dispatcher_host_impl.h" #include "content/browser/renderer_host/input/synthetic_tap_gesture.h" #include "content/browser/renderer_host/render_view_host_impl.h" #include "content/browser/renderer_host/render_widget_host_input_event_router.h" #include "content/browser/renderer_host/render_widget_host_view_aura.h" #include "content/browser/web_contents/web_contents_impl.h" #include "content/common/child_process_messages.h" #include "content/common/frame_messages.h" #include "content/common/input/synthetic_tap_gesture_params.h" #include "content/common/input_messages.h" #include "content/common/renderer.mojom.h" #include "content/common/view_messages.h" #include "content/public/browser/interstitial_page_delegate.h" #include "content/public/browser/navigation_handle.h" #include "content/public/browser/notification_observer.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/notification_types.h" #include "content/public/browser/resource_dispatcher_host.h" #include "content/public/common/browser_side_navigation_policy.h" #include "content/public/common/content_switches.h" #include "content/public/common/url_constants.h" #include "content/public/test/browser_test_utils.h" #include "content/public/test/content_browser_test_utils.h" #include "content/public/test/test_navigation_observer.h" #include "content/public/test/test_utils.h" #include "content/test/content_browser_test_utils_internal.h" #include "content/test/test_frame_navigation_observer.h" #include "ipc/ipc.mojom.h" #include "ipc/ipc_security_test_util.h" #include "net/dns/mock_host_resolver.h" #include "net/test/embedded_test_server/embedded_test_server.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/WebKit/public/platform/WebInsecureRequestPolicy.h" #include "third_party/WebKit/public/web/WebInputEvent.h" #include "third_party/WebKit/public/web/WebSandboxFlags.h" #include "ui/display/display_switches.h" #include "ui/display/screen.h" #include "ui/events/event.h" #include "ui/events/event_utils.h" #include "ui/events/latency_info.h" #include "ui/gfx/geometry/point.h" #if defined(USE_AURA) #include "content/browser/renderer_host/render_widget_host_view_aura.h" #endif #if defined(OS_MACOSX) #include "ui/base/test/scoped_preferred_scroller_style_mac.h" #endif namespace content { namespace { // Helper function to send a postMessage and wait for a reply message. The // |post_message_script| is executed on the |sender_ftn| frame, and the sender // frame is expected to post |reply_status| from the DOMAutomationController // when it receives a reply. void PostMessageAndWaitForReply(FrameTreeNode* sender_ftn, const std::string& post_message_script, const std::string& reply_status) { // Subtle: msg_queue needs to be declared before the ExecuteScript below, or // else it might miss the message of interest. See https://crbug.com/518729. DOMMessageQueue msg_queue; bool success = false; EXPECT_TRUE(ExecuteScriptAndExtractBool( sender_ftn, "window.domAutomationController.send(" + post_message_script + ");", &success)); EXPECT_TRUE(success); std::string status; while (msg_queue.WaitForMessage(&status)) { if (status == reply_status) break; } } // Helper function to extract and return "window.receivedMessages" from the // |sender_ftn| frame. This variable is used in post_message.html to count the // number of messages received via postMessage by the current window. int GetReceivedMessages(FrameTreeNode* ftn) { int received_messages = 0; EXPECT_TRUE(ExecuteScriptAndExtractInt( ftn, "window.domAutomationController.send(window.receivedMessages);", &received_messages)); return received_messages; } // Helper function to perform a window.open from the |caller_frame| targeting a // frame with the specified name. void NavigateNamedFrame(const ToRenderFrameHost& caller_frame, const GURL& url, const std::string& name) { bool success = false; EXPECT_TRUE(ExecuteScriptAndExtractBool( caller_frame, "window.domAutomationController.send(" " !!window.open('" + url.spec() + "', '" + name + "'));", &success)); EXPECT_TRUE(success); } // Helper function to generate a click on the given RenderWidgetHost. The // mouse event is forwarded directly to the RenderWidgetHost without any // hit-testing. void SimulateMouseClick(RenderWidgetHost* rwh, int x, int y) { blink::WebMouseEvent mouse_event; mouse_event.type = blink::WebInputEvent::MouseDown; mouse_event.button = blink::WebPointerProperties::Button::Left; mouse_event.x = x; mouse_event.y = y; rwh->ForwardMouseEvent(mouse_event); } // Retrieve document.origin for the frame |ftn|. std::string GetDocumentOrigin(FrameTreeNode* ftn) { std::string origin; EXPECT_TRUE(ExecuteScriptAndExtractString( ftn, "domAutomationController.send(document.origin)", &origin)); return origin; } class RenderWidgetHostMouseEventMonitor { public: explicit RenderWidgetHostMouseEventMonitor(RenderWidgetHost* host) : host_(host), event_received_(false) { host_->AddMouseEventCallback( base::Bind(&RenderWidgetHostMouseEventMonitor::MouseEventCallback, base::Unretained(this))); } ~RenderWidgetHostMouseEventMonitor() { host_->RemoveMouseEventCallback( base::Bind(&RenderWidgetHostMouseEventMonitor::MouseEventCallback, base::Unretained(this))); } bool EventWasReceived() const { return event_received_; } void ResetEventReceived() { event_received_ = false; } const blink::WebMouseEvent& event() const { return event_; } private: bool MouseEventCallback(const blink::WebMouseEvent& event) { event_received_ = true; event_ = event; return false; } RenderWidgetHost* host_; bool event_received_; blink::WebMouseEvent event_; DISALLOW_COPY_AND_ASSIGN(RenderWidgetHostMouseEventMonitor); }; class TestInputEventObserver : public RenderWidgetHost::InputEventObserver { public: explicit TestInputEventObserver(RenderWidgetHost* host) : host_(host) { host_->AddInputEventObserver(this); } ~TestInputEventObserver() override { host_->RemoveInputEventObserver(this); } bool EventWasReceived() const { return !events_received_.empty(); } void ResetEventsReceived() { events_received_.clear(); } blink::WebInputEvent::Type EventType() const { DCHECK(EventWasReceived()); return events_received_.front(); } const std::vector<blink::WebInputEvent::Type>& events_received() { return events_received_; } void OnInputEvent(const blink::WebInputEvent& event) override { events_received_.push_back(event.type); }; private: RenderWidgetHost* host_; std::vector<blink::WebInputEvent::Type> events_received_; DISALLOW_COPY_AND_ASSIGN(TestInputEventObserver); }; // Helper function that performs a surface hittest. void SurfaceHitTestTestHelper( Shell* shell, net::test_server::EmbeddedTestServer* embedded_test_server) { GURL main_url(embedded_test_server->GetURL( "/frame_tree/page_with_positioned_frame.html")); NavigateToURL(shell, main_url); // It is safe to obtain the root frame tree node here, as it doesn't change. FrameTreeNode* root = static_cast<WebContentsImpl*>(shell->web_contents()) ->GetFrameTree() ->root(); ASSERT_EQ(1U, root->child_count()); FrameTreeNode* child_node = root->child_at(0); GURL site_url(embedded_test_server->GetURL("baz.com", "/title1.html")); EXPECT_EQ(site_url, child_node->current_url()); EXPECT_NE(shell->web_contents()->GetSiteInstance(), child_node->current_frame_host()->GetSiteInstance()); // Create listeners for mouse events. RenderWidgetHostMouseEventMonitor main_frame_monitor( root->current_frame_host()->GetRenderWidgetHost()); RenderWidgetHostMouseEventMonitor child_frame_monitor( child_node->current_frame_host()->GetRenderWidgetHost()); RenderWidgetHostInputEventRouter* router = static_cast<WebContentsImpl*>(shell->web_contents()) ->GetInputEventRouter(); RenderWidgetHostViewBase* root_view = static_cast<RenderWidgetHostViewBase*>( root->current_frame_host()->GetRenderWidgetHost()->GetView()); RenderWidgetHostViewBase* rwhv_child = static_cast<RenderWidgetHostViewBase*>( child_node->current_frame_host()->GetRenderWidgetHost()->GetView()); SurfaceHitTestReadyNotifier notifier( static_cast<RenderWidgetHostViewChildFrame*>(rwhv_child)); notifier.WaitForSurfaceReady(); // Target input event to child frame. blink::WebMouseEvent child_event; child_event.type = blink::WebInputEvent::MouseDown; child_event.button = blink::WebPointerProperties::Button::Left; child_event.x = 75; child_event.y = 75; child_event.clickCount = 1; main_frame_monitor.ResetEventReceived(); child_frame_monitor.ResetEventReceived(); router->RouteMouseEvent(root_view, &child_event, ui::LatencyInfo()); EXPECT_TRUE(child_frame_monitor.EventWasReceived()); EXPECT_EQ(23, child_frame_monitor.event().x); EXPECT_EQ(23, child_frame_monitor.event().y); EXPECT_FALSE(main_frame_monitor.EventWasReceived()); child_frame_monitor.ResetEventReceived(); main_frame_monitor.ResetEventReceived(); // Target input event to main frame. blink::WebMouseEvent main_event; main_event.type = blink::WebInputEvent::MouseDown; main_event.button = blink::WebPointerProperties::Button::Left; main_event.x = 1; main_event.y = 1; main_event.clickCount = 1; // Ladies and gentlemen, THIS is the main_event! router->RouteMouseEvent(root_view, &main_event, ui::LatencyInfo()); EXPECT_FALSE(child_frame_monitor.EventWasReceived()); EXPECT_TRUE(main_frame_monitor.EventWasReceived()); EXPECT_EQ(1, main_frame_monitor.event().x); EXPECT_EQ(1, main_frame_monitor.event().y); } class RedirectNotificationObserver : public NotificationObserver { public: // Register to listen for notifications of the given type from either a // specific source, or from all sources if |source| is // NotificationService::AllSources(). RedirectNotificationObserver(int notification_type, const NotificationSource& source); ~RedirectNotificationObserver() override; // Wait until the specified notification occurs. If the notification was // emitted between the construction of this object and this call then it // returns immediately. void Wait(); // Returns NotificationService::AllSources() if we haven't observed a // notification yet. const NotificationSource& source() const { return source_; } const NotificationDetails& details() const { return details_; } // NotificationObserver: void Observe(int type, const NotificationSource& source, const NotificationDetails& details) override; private: bool seen_; bool seen_twice_; bool running_; NotificationRegistrar registrar_; NotificationSource source_; NotificationDetails details_; scoped_refptr<MessageLoopRunner> message_loop_runner_; DISALLOW_COPY_AND_ASSIGN(RedirectNotificationObserver); }; RedirectNotificationObserver::RedirectNotificationObserver( int notification_type, const NotificationSource& source) : seen_(false), running_(false), source_(NotificationService::AllSources()) { registrar_.Add(this, notification_type, source); } RedirectNotificationObserver::~RedirectNotificationObserver() {} void RedirectNotificationObserver::Wait() { if (seen_ && seen_twice_) return; running_ = true; message_loop_runner_ = new MessageLoopRunner; message_loop_runner_->Run(); EXPECT_TRUE(seen_); } void RedirectNotificationObserver::Observe( int type, const NotificationSource& source, const NotificationDetails& details) { source_ = source; details_ = details; seen_twice_ = seen_; seen_ = true; if (!running_) return; message_loop_runner_->Quit(); running_ = false; } // This observer keeps track of the number of created RenderFrameHosts. Tests // can use this to ensure that a certain number of child frames has been // created after navigating. class RenderFrameHostCreatedObserver : public WebContentsObserver { public: RenderFrameHostCreatedObserver(WebContents* web_contents, int expected_frame_count) : WebContentsObserver(web_contents), expected_frame_count_(expected_frame_count), frames_created_(0), message_loop_runner_(new MessageLoopRunner) {} ~RenderFrameHostCreatedObserver() override; // Runs a nested message loop and blocks until the expected number of // RenderFrameHosts is created. void Wait(); private: // WebContentsObserver void RenderFrameCreated(RenderFrameHost* render_frame_host) override; // The number of RenderFrameHosts to wait for. int expected_frame_count_; // The number of RenderFrameHosts that have been created. int frames_created_; // The MessageLoopRunner used to spin the message loop. scoped_refptr<MessageLoopRunner> message_loop_runner_; DISALLOW_COPY_AND_ASSIGN(RenderFrameHostCreatedObserver); }; RenderFrameHostCreatedObserver::~RenderFrameHostCreatedObserver() { } void RenderFrameHostCreatedObserver::Wait() { message_loop_runner_->Run(); } void RenderFrameHostCreatedObserver::RenderFrameCreated( RenderFrameHost* render_frame_host) { frames_created_++; if (frames_created_ == expected_frame_count_) { message_loop_runner_->Quit(); } } // This observer detects when WebContents receives notification of a user // gesture having occurred, following a user input event targeted to // a RenderWidgetHost under that WebContents. class UserInteractionObserver : public WebContentsObserver { public: explicit UserInteractionObserver(WebContents* web_contents) : WebContentsObserver(web_contents), user_interaction_received_(false) {} ~UserInteractionObserver() override {} // Retrieve the flag. There is no need to wait on a loop since // DidGetUserInteraction() should be called synchronously with the input // event processing in the browser process. bool WasUserInteractionReceived() { return user_interaction_received_; } void Reset() { user_interaction_received_ = false; } private: // WebContentsObserver void DidGetUserInteraction(const blink::WebInputEvent::Type type) override { user_interaction_received_ = true; } bool user_interaction_received_; DISALLOW_COPY_AND_ASSIGN(UserInteractionObserver); }; // This observer is used to wait for its owner FrameTreeNode to become deleted. class FrameDeletedObserver : public FrameTreeNode::Observer { public: FrameDeletedObserver(FrameTreeNode* owner) : owner_(owner), message_loop_runner_(new MessageLoopRunner) { owner->AddObserver(this); } void Wait() { message_loop_runner_->Run(); } private: // FrameTreeNode::Observer void OnFrameTreeNodeDestroyed(FrameTreeNode* node) override { if (node == owner_) message_loop_runner_->Quit(); } FrameTreeNode* owner_; scoped_refptr<MessageLoopRunner> message_loop_runner_; DISALLOW_COPY_AND_ASSIGN(FrameDeletedObserver); }; // Helper function to focus a frame by sending it a mouse click and then // waiting for it to become focused. void FocusFrame(FrameTreeNode* frame) { FrameFocusedObserver focus_observer(frame->current_frame_host()); SimulateMouseClick(frame->current_frame_host()->GetRenderWidgetHost(), 1, 1); focus_observer.Wait(); } // A BrowserMessageFilter that drops SwapOut ACK messages. class SwapoutACKMessageFilter : public BrowserMessageFilter { public: SwapoutACKMessageFilter() : BrowserMessageFilter(FrameMsgStart) {} protected: ~SwapoutACKMessageFilter() override {} private: // BrowserMessageFilter: bool OnMessageReceived(const IPC::Message& message) override { return message.type() == FrameHostMsg_SwapOut_ACK::ID; } DISALLOW_COPY_AND_ASSIGN(SwapoutACKMessageFilter); }; class RenderWidgetHostVisibilityObserver : public NotificationObserver { public: explicit RenderWidgetHostVisibilityObserver(RenderWidgetHostImpl* rwhi, bool expected_visibility_state) : expected_visibility_state_(expected_visibility_state), was_observed_(false), did_fail_(false), source_(rwhi) { registrar_.Add(this, NOTIFICATION_RENDER_WIDGET_VISIBILITY_CHANGED, source_); message_loop_runner_ = new MessageLoopRunner; } bool WaitUntilSatisfied() { if (!was_observed_) message_loop_runner_->Run(); registrar_.Remove(this, NOTIFICATION_RENDER_WIDGET_VISIBILITY_CHANGED, source_); return !did_fail_; } private: void Observe(int type, const NotificationSource& source, const NotificationDetails& details) override { was_observed_ = true; did_fail_ = expected_visibility_state_ != (*static_cast<const Details<bool>&>(details).ptr()); if (message_loop_runner_->loop_running()) message_loop_runner_->Quit(); } bool expected_visibility_state_; scoped_refptr<MessageLoopRunner> message_loop_runner_; NotificationRegistrar registrar_; bool was_observed_; bool did_fail_; Source<RenderWidgetHost> source_; DISALLOW_COPY_AND_ASSIGN(RenderWidgetHostVisibilityObserver); }; class TestInterstitialDelegate : public InterstitialPageDelegate { private: // InterstitialPageDelegate: std::string GetHTMLContents() override { return "<p>Interstitial</p>"; } }; } // namespace // // SitePerProcessBrowserTest // SitePerProcessBrowserTest::SitePerProcessBrowserTest() { }; std::string SitePerProcessBrowserTest::DepictFrameTree(FrameTreeNode* node) { return visualizer_.DepictFrameTree(node); } void SitePerProcessBrowserTest::SetUpCommandLine( base::CommandLine* command_line) { IsolateAllSitesForTesting(command_line); }; void SitePerProcessBrowserTest::SetUpOnMainThread() { host_resolver()->AddRule("*", "127.0.0.1"); ASSERT_TRUE(embedded_test_server()->Start()); SetupCrossSiteRedirector(embedded_test_server()); } // // SitePerProcessHighDPIBrowserTest // class SitePerProcessHighDPIBrowserTest : public SitePerProcessBrowserTest { public: const double kDeviceScaleFactor = 2.0; SitePerProcessHighDPIBrowserTest() {} protected: void SetUpCommandLine(base::CommandLine* command_line) override { SitePerProcessBrowserTest::SetUpCommandLine(command_line); command_line->AppendSwitchASCII( switches::kForceDeviceScaleFactor, base::StringPrintf("%f", kDeviceScaleFactor)); } }; // SitePerProcessIgnoreCertErrorsBrowserTest class SitePerProcessIgnoreCertErrorsBrowserTest : public SitePerProcessBrowserTest { public: SitePerProcessIgnoreCertErrorsBrowserTest() {} protected: void SetUpCommandLine(base::CommandLine* command_line) override { SitePerProcessBrowserTest::SetUpCommandLine(command_line); command_line->AppendSwitch(switches::kIgnoreCertificateErrors); } }; // SitePerProcessEmbedderCSPEnforcementBrowserTest class SitePerProcessEmbedderCSPEnforcementBrowserTest : public SitePerProcessBrowserTest { public: SitePerProcessEmbedderCSPEnforcementBrowserTest() {} protected: void SetUpCommandLine(base::CommandLine* command_line) override { SitePerProcessBrowserTest::SetUpCommandLine(command_line); // TODO(amalika): Remove this switch when the EmbedderCSPEnforcement becomes // stable command_line->AppendSwitchASCII(switches::kEnableBlinkFeatures, "EmbedderCSPEnforcement"); } }; double GetFrameDeviceScaleFactor(const ToRenderFrameHost& adapter) { double device_scale_factor; const char kGetFrameDeviceScaleFactor[] = "window.domAutomationController.send(window.devicePixelRatio);"; EXPECT_TRUE(ExecuteScriptAndExtractDouble(adapter, kGetFrameDeviceScaleFactor, &device_scale_factor)); return device_scale_factor; } IN_PROC_BROWSER_TEST_F(SitePerProcessHighDPIBrowserTest, SubframeLoadsWithCorrectDeviceScaleFactor) { GURL main_url(embedded_test_server()->GetURL( "a.com", "/cross_site_iframe_factory.html?a(b)")); NavigateToURL(shell(), main_url); EXPECT_EQ(SitePerProcessHighDPIBrowserTest::kDeviceScaleFactor, GetFrameDeviceScaleFactor(web_contents())); FrameTreeNode* root = web_contents()->GetFrameTree()->root(); FrameTreeNode* child = root->child_at(0); EXPECT_EQ(SitePerProcessHighDPIBrowserTest::kDeviceScaleFactor, GetFrameDeviceScaleFactor(child)); } // Ensure that navigating subframes in --site-per-process mode works and the // correct documents are committed. #if defined(OS_WIN) // This test is flaky on Windows, see https://crbug.com/629419. #define MAYBE_CrossSiteIframe DISABLED_CrossSiteIframe #else #define MAYBE_CrossSiteIframe CrossSiteIframe #endif IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, MAYBE_CrossSiteIframe) { GURL main_url(embedded_test_server()->GetURL( "a.com", "/cross_site_iframe_factory.html?a(a,a(a,a(a)))")); NavigateToURL(shell(), main_url); // It is safe to obtain the root frame tree node here, as it doesn't change. FrameTreeNode* root = web_contents()->GetFrameTree()->root(); TestNavigationObserver observer(shell()->web_contents()); // Load same-site page into iframe. FrameTreeNode* child = root->child_at(0); GURL http_url(embedded_test_server()->GetURL("a.com", "/title1.html")); NavigateFrameToURL(child, http_url); EXPECT_EQ(http_url, observer.last_navigation_url()); EXPECT_TRUE(observer.last_navigation_succeeded()); { // There should be only one RenderWidgetHost when there are no // cross-process iframes. std::set<RenderWidgetHostView*> views_set = web_contents()->GetRenderWidgetHostViewsInTree(); EXPECT_EQ(1U, views_set.size()); } EXPECT_EQ( " Site A\n" " |--Site A\n" " +--Site A\n" " |--Site A\n" " +--Site A\n" " +--Site A\n" "Where A = http://a.com/", DepictFrameTree(root)); // Load cross-site page into iframe. GURL url = embedded_test_server()->GetURL("foo.com", "/title2.html"); NavigateFrameToURL(root->child_at(0), url); // Verify that the navigation succeeded and the expected URL was loaded. EXPECT_TRUE(observer.last_navigation_succeeded()); EXPECT_EQ(url, observer.last_navigation_url()); // Ensure that we have created a new process for the subframe. ASSERT_EQ(2U, root->child_count()); SiteInstance* site_instance = child->current_frame_host()->GetSiteInstance(); RenderViewHost* rvh = child->current_frame_host()->render_view_host(); RenderProcessHost* rph = child->current_frame_host()->GetProcess(); EXPECT_NE(shell()->web_contents()->GetRenderViewHost(), rvh); EXPECT_NE(shell()->web_contents()->GetSiteInstance(), site_instance); EXPECT_NE(shell()->web_contents()->GetRenderProcessHost(), rph); { // There should be now two RenderWidgetHosts, one for each process // rendering a frame. std::set<RenderWidgetHostView*> views_set = web_contents()->GetRenderWidgetHostViewsInTree(); EXPECT_EQ(2U, views_set.size()); } RenderFrameProxyHost* proxy_to_parent = child->render_manager()->GetProxyToParent(); EXPECT_TRUE(proxy_to_parent); EXPECT_TRUE(proxy_to_parent->cross_process_frame_connector()); // The out-of-process iframe should have its own RenderWidgetHost, // independent of any RenderViewHost. EXPECT_NE( rvh->GetWidget()->GetView(), proxy_to_parent->cross_process_frame_connector()->get_view_for_testing()); EXPECT_TRUE(child->current_frame_host()->GetRenderWidgetHost()); EXPECT_EQ( " Site A ------------ proxies for B\n" " |--Site B ------- proxies for A\n" " +--Site A ------- proxies for B\n" " |--Site A -- proxies for B\n" " +--Site A -- proxies for B\n" " +--Site A -- proxies for B\n" "Where A = http://a.com/\n" " B = http://foo.com/", DepictFrameTree(root)); // Load another cross-site page into the same iframe. url = embedded_test_server()->GetURL("bar.com", "/title3.html"); NavigateFrameToURL(root->child_at(0), url); EXPECT_TRUE(observer.last_navigation_succeeded()); EXPECT_EQ(url, observer.last_navigation_url()); // Check again that a new process is created and is different from the // top level one and the previous one. ASSERT_EQ(2U, root->child_count()); child = root->child_at(0); EXPECT_NE(shell()->web_contents()->GetRenderViewHost(), child->current_frame_host()->render_view_host()); EXPECT_NE(rvh, child->current_frame_host()->render_view_host()); EXPECT_NE(shell()->web_contents()->GetSiteInstance(), child->current_frame_host()->GetSiteInstance()); EXPECT_NE(site_instance, child->current_frame_host()->GetSiteInstance()); EXPECT_NE(shell()->web_contents()->GetRenderProcessHost(), child->current_frame_host()->GetProcess()); EXPECT_NE(rph, child->current_frame_host()->GetProcess()); { std::set<RenderWidgetHostView*> views_set = web_contents()->GetRenderWidgetHostViewsInTree(); EXPECT_EQ(2U, views_set.size()); } EXPECT_EQ(proxy_to_parent, child->render_manager()->GetProxyToParent()); EXPECT_TRUE(proxy_to_parent->cross_process_frame_connector()); EXPECT_NE( child->current_frame_host()->render_view_host()->GetWidget()->GetView(), proxy_to_parent->cross_process_frame_connector()->get_view_for_testing()); EXPECT_TRUE(child->current_frame_host()->GetRenderWidgetHost()); EXPECT_EQ( " Site A ------------ proxies for C\n" " |--Site C ------- proxies for A\n" " +--Site A ------- proxies for C\n" " |--Site A -- proxies for C\n" " +--Site A -- proxies for C\n" " +--Site A -- proxies for C\n" "Where A = http://a.com/\n" " C = http://bar.com/", DepictFrameTree(root)); } // Ensure that title updates affect the correct NavigationEntry after a new // subframe navigation with an out-of-process iframe. https://crbug.com/616609. IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, TitleAfterCrossSiteIframe) { // Start at an initial page. GURL initial_url(embedded_test_server()->GetURL("a.com", "/title1.html")); EXPECT_TRUE(NavigateToURL(shell(), initial_url)); // Navigate to a same-site page with a same-site iframe. GURL main_url(embedded_test_server()->GetURL( "a.com", "/cross_site_iframe_factory.html?a(a)")); EXPECT_TRUE(NavigateToURL(shell(), main_url)); FrameTreeNode* root = web_contents()->GetFrameTree()->root(); // Make the main frame update its title after the subframe loads. EXPECT_TRUE(ExecuteScript(shell()->web_contents(), "document.querySelector('iframe').onload = " " function() { document.title = 'loaded'; };")); EXPECT_TRUE( ExecuteScript(shell()->web_contents(), "document.title = 'not loaded';")); base::string16 expected_title(base::UTF8ToUTF16("loaded")); TitleWatcher title_watcher(shell()->web_contents(), expected_title); // Navigate the iframe cross-site. TestNavigationObserver load_observer(shell()->web_contents()); GURL frame_url = embedded_test_server()->GetURL("b.com", "/title2.html"); EXPECT_TRUE( ExecuteScript(root->child_at(0)->current_frame_host(), "window.location.href = '" + frame_url.spec() + "';")); load_observer.Wait(); // Wait for the title to update and ensure it affects the right NavEntry. EXPECT_EQ(expected_title, title_watcher.WaitAndGetTitle()); NavigationEntry* entry = shell()->web_contents()->GetController().GetLastCommittedEntry(); EXPECT_EQ(expected_title, entry->GetTitle()); } // Class to sniff incoming IPCs for FrameHostMsg_FrameRectChanged messages. class FrameRectChangedMessageFilter : public content::BrowserMessageFilter { public: FrameRectChangedMessageFilter() : content::BrowserMessageFilter(FrameMsgStart), message_loop_runner_(new content::MessageLoopRunner), frame_rect_received_(false) {} bool OnMessageReceived(const IPC::Message& message) override { IPC_BEGIN_MESSAGE_MAP(FrameRectChangedMessageFilter, message) IPC_MESSAGE_HANDLER(FrameHostMsg_FrameRectChanged, OnFrameRectChanged) IPC_END_MESSAGE_MAP() return false; } gfx::Rect last_rect() const { return last_rect_; } void Wait() { message_loop_runner_->Run(); } void Reset() { last_rect_ = gfx::Rect(); message_loop_runner_ = new content::MessageLoopRunner; frame_rect_received_ = false; } private: ~FrameRectChangedMessageFilter() override {} void OnFrameRectChanged(const gfx::Rect& rect) { content::BrowserThread::PostTask( content::BrowserThread::UI, FROM_HERE, base::Bind(&FrameRectChangedMessageFilter::OnFrameRectChangedOnUI, this, rect)); } void OnFrameRectChangedOnUI(const gfx::Rect& rect) { last_rect_ = rect; if (!frame_rect_received_) { frame_rect_received_ = true; message_loop_runner_->Quit(); } } scoped_refptr<content::MessageLoopRunner> message_loop_runner_; bool frame_rect_received_; gfx::Rect last_rect_; DISALLOW_COPY_AND_ASSIGN(FrameRectChangedMessageFilter); }; // Test that the view bounds for an out-of-process iframe are set and updated // correctly, including accounting for local frame offsets in the parent and // scroll positions. #if defined(OS_ANDROID) // Browser process hit testing is not implemented on Android. // https://crbug.com/491334 #define MAYBE_ViewBoundsInNestedFrameTest DISABLED_ViewBoundsInNestedFrameTest #else #define MAYBE_ViewBoundsInNestedFrameTest ViewBoundsInNestedFrameTest #endif IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, MAYBE_ViewBoundsInNestedFrameTest) { GURL main_url(embedded_test_server()->GetURL( "a.com", "/cross_site_iframe_factory.html?a(a)")); NavigateToURL(shell(), main_url); // It is safe to obtain the root frame tree node here, as it doesn't change. FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents()) ->GetFrameTree() ->root(); RenderWidgetHostViewBase* rwhv_root = static_cast<RenderWidgetHostViewBase*>( root->current_frame_host()->GetRenderWidgetHost()->GetView()); ASSERT_EQ(1U, root->child_count()); FrameTreeNode* parent_iframe_node = root->child_at(0); GURL site_url(embedded_test_server()->GetURL( "a.com", "/frame_tree/page_with_positioned_frame.html")); NavigateFrameToURL(parent_iframe_node, site_url); EXPECT_EQ( " Site A ------------ proxies for B\n" " +--Site A ------- proxies for B\n" " +--Site B -- proxies for A\n" "Where A = http://a.com/\n" " B = http://baz.com/", DepictFrameTree(root)); FrameTreeNode* nested_iframe_node = parent_iframe_node->child_at(0); RenderWidgetHostViewBase* rwhv_nested = static_cast<RenderWidgetHostViewBase*>( nested_iframe_node->current_frame_host() ->GetRenderWidgetHost() ->GetView()); SurfaceHitTestReadyNotifier notifier( static_cast<RenderWidgetHostViewChildFrame*>(rwhv_nested)); notifier.WaitForSurfaceReady(); // Verify the view bounds of the nested iframe, which should account for the // relative offset of its direct parent within the root frame. gfx::Rect bounds = rwhv_nested->GetViewBounds(); EXPECT_EQ(bounds.x() - rwhv_root->GetViewBounds().x(), 397); EXPECT_EQ(bounds.y() - rwhv_root->GetViewBounds().y(), 112); scoped_refptr<FrameRectChangedMessageFilter> filter = new FrameRectChangedMessageFilter(); root->current_frame_host()->GetProcess()->AddFilter(filter.get()); // Scroll the parent frame downward to verify that the child rect gets updated // correctly. blink::WebMouseWheelEvent scroll_event; scroll_event.type = blink::WebInputEvent::MouseWheel; scroll_event.x = 387; scroll_event.y = 110; scroll_event.deltaX = 0.0f; scroll_event.deltaY = -30.0f; rwhv_root->ProcessMouseWheelEvent(scroll_event, ui::LatencyInfo()); filter->Wait(); // The precise amount of scroll for the first view position update is not // deterministic, so this simply verifies that the OOPIF moved from its // earlier position. gfx::Rect update_rect = filter->last_rect(); EXPECT_LT(update_rect.y(), bounds.y() - rwhv_root->GetViewBounds().y()); } // Test that scrolling a nested out-of-process iframe bubbles unused scroll // delta to a parent frame. // Browser process hit testing is not implemented on Android. // https://crbug.com/491334 // Flaky: https://crbug.com/627238 IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, DISABLED_ScrollBubblingFromOOPIFTest) { GURL main_url(embedded_test_server()->GetURL( "a.com", "/cross_site_iframe_factory.html?a(b)")); NavigateToURL(shell(), main_url); // It is safe to obtain the root frame tree node here, as it doesn't change. FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents()) ->GetFrameTree() ->root(); ASSERT_EQ(1U, root->child_count()); FrameTreeNode* parent_iframe_node = root->child_at(0); // This test uses the position of the nested iframe within the parent iframe // to infer the scroll position of the parent. FrameRectChangedMessageFilter // catches updates to the position in order to avoid busy waiting. // It gets created early to catch the initial rects from the navigation. scoped_refptr<FrameRectChangedMessageFilter> filter = new FrameRectChangedMessageFilter(); parent_iframe_node->current_frame_host()->GetProcess()->AddFilter( filter.get()); GURL site_url(embedded_test_server()->GetURL( "b.com", "/frame_tree/page_with_positioned_frame.html")); NavigateFrameToURL(parent_iframe_node, site_url); // Navigate the nested frame to a page large enough to have scrollbars. FrameTreeNode* nested_iframe_node = parent_iframe_node->child_at(0); GURL nested_site_url(embedded_test_server()->GetURL( "baz.com", "/tall_page.html")); NavigateFrameToURL(nested_iframe_node, nested_site_url); EXPECT_EQ( " Site A ------------ proxies for B C\n" " +--Site B ------- proxies for A C\n" " +--Site C -- proxies for A B\n" "Where A = http://a.com/\n" " B = http://b.com/\n" " C = http://baz.com/", DepictFrameTree(root)); RenderWidgetHostViewBase* rwhv_parent = static_cast<RenderWidgetHostViewBase*>( parent_iframe_node->current_frame_host() ->GetRenderWidgetHost() ->GetView()); RenderWidgetHostViewBase* rwhv_nested = static_cast<RenderWidgetHostViewBase*>( nested_iframe_node->current_frame_host() ->GetRenderWidgetHost() ->GetView()); SurfaceHitTestReadyNotifier notifier( static_cast<RenderWidgetHostViewChildFrame*>(rwhv_nested)); notifier.WaitForSurfaceReady(); // Save the original offset as a point of reference. filter->Wait(); gfx::Rect update_rect = filter->last_rect(); int initial_y = update_rect.y(); filter->Reset(); // Scroll the parent frame downward. blink::WebMouseWheelEvent scroll_event; scroll_event.type = blink::WebInputEvent::MouseWheel; scroll_event.x = 1; scroll_event.y = 1; scroll_event.deltaX = 0.0f; scroll_event.deltaY = -5.0f; rwhv_parent->ProcessMouseWheelEvent(scroll_event, ui::LatencyInfo()); // Ensure that the view position is propagated to the child properly. filter->Wait(); update_rect = filter->last_rect(); EXPECT_LT(update_rect.y(), initial_y); filter->Reset(); // Now scroll the nested frame upward, which should bubble to the parent. // The upscroll exceeds the amount that the frame was initially scrolled // down to account for rounding. scroll_event.deltaY = 6.0f; rwhv_nested->ProcessMouseWheelEvent(scroll_event, ui::LatencyInfo()); filter->Wait(); // This loop isn't great, but it accounts for the possibility of multiple // incremental updates happening as a result of the scroll animation. // A failure condition of this test is that the loop might not terminate // due to bubbling not working properly. If the overscroll bubbles to the // parent iframe then the nested frame's y coord will return to its // initial position. update_rect = filter->last_rect(); while (update_rect.y() > initial_y) { base::RunLoop run_loop; base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, run_loop.QuitClosure(), TestTimeouts::tiny_timeout()); run_loop.Run(); update_rect = filter->last_rect(); } filter->Reset(); // Scroll the parent down again in order to test scroll bubbling from // gestures. scroll_event.deltaY = -5.0f; rwhv_parent->ProcessMouseWheelEvent(scroll_event, ui::LatencyInfo()); // Ensure ensuing offset change is received, and then reset the filter. filter->Wait(); filter->Reset(); // Scroll down the nested iframe via gesture. This requires 3 separate input // events. blink::WebGestureEvent gesture_event; gesture_event.type = blink::WebGestureEvent::GestureScrollBegin; gesture_event.sourceDevice = blink::WebGestureDeviceTouchpad; gesture_event.x = 1; gesture_event.y = 1; rwhv_nested->GetRenderWidgetHost()->ForwardGestureEvent(gesture_event); gesture_event.type = blink::WebGestureEvent::GestureScrollUpdate; gesture_event.data.scrollUpdate.deltaX = 0.0f; gesture_event.data.scrollUpdate.deltaY = 6.0f; gesture_event.data.scrollUpdate.velocityX = 0; gesture_event.data.scrollUpdate.velocityY = 0; rwhv_nested->GetRenderWidgetHost()->ForwardGestureEvent(gesture_event); gesture_event.type = blink::WebGestureEvent::GestureScrollEnd; rwhv_nested->GetRenderWidgetHost()->ForwardGestureEvent(gesture_event); filter->Wait(); update_rect = filter->last_rect(); // As above, if this loop does not terminate then it indicates an issue // with scroll bubbling. while (update_rect.y() > initial_y) { base::RunLoop run_loop; base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, run_loop.QuitClosure(), TestTimeouts::tiny_timeout()); run_loop.Run(); update_rect = filter->last_rect(); } // Test that when the child frame absorbs all of the scroll delta, it does // not propagate to the parent (see https://crbug.com/621624). filter->Reset(); scroll_event.deltaY = -5.0f; rwhv_nested->ProcessMouseWheelEvent(scroll_event, ui::LatencyInfo()); // It isn't possible to busy loop waiting on the renderer here because we // are explicitly testing that something does *not* happen. This creates a // small chance of false positives but shouldn't result in false negatives, // so flakiness implies this test is failing. { base::RunLoop run_loop; base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, run_loop.QuitClosure(), TestTimeouts::action_timeout()); run_loop.Run(); } DCHECK_EQ(filter->last_rect().x(), 0); DCHECK_EQ(filter->last_rect().y(), 0); } // Test that an ET_SCROLL event sent to an out-of-process iframe correctly // results in a scroll. This is only handled by RenderWidgetHostViewAura // and is needed for trackpad scrolling on Chromebooks. #if !defined(USE_AURA) #define MAYBE_ScrollEventToOOPIF DISABLED_ScrollEventToOOPIF #else #define MAYBE_ScrollEventToOOPIF ScrollEventToOOPIF #endif IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, MAYBE_ScrollEventToOOPIF) { GURL main_url(embedded_test_server()->GetURL( "/frame_tree/page_with_positioned_frame.html")); NavigateToURL(shell(), main_url); // It is safe to obtain the root frame tree node here, as it doesn't change. FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents()) ->GetFrameTree() ->root(); ASSERT_EQ(1U, root->child_count()); FrameTreeNode* child_node = root->child_at(0); GURL site_url(embedded_test_server()->GetURL("baz.com", "/title1.html")); EXPECT_EQ(site_url, child_node->current_url()); EXPECT_NE(shell()->web_contents()->GetSiteInstance(), child_node->current_frame_host()->GetSiteInstance()); RenderWidgetHostViewAura* rwhv_parent = static_cast<RenderWidgetHostViewAura*>( root->current_frame_host()->GetRenderWidgetHost()->GetView()); RenderWidgetHostViewBase* rwhv_child = static_cast<RenderWidgetHostViewBase*>( child_node->current_frame_host()->GetRenderWidgetHost()->GetView()); SurfaceHitTestReadyNotifier notifier( static_cast<RenderWidgetHostViewChildFrame*>(rwhv_child)); notifier.WaitForSurfaceReady(); // Create listener for input events. TestInputEventObserver child_frame_monitor( child_node->current_frame_host()->GetRenderWidgetHost()); // Send a ui::ScrollEvent that will hit test to the child frame. ui::ScrollEvent scroll_event(ui::ET_SCROLL, gfx::Point(75, 75), ui::EventTimeForNow(), ui::EF_NONE, 0, 10, // Offsets 0, 10, // Offset ordinals 2); rwhv_parent->OnScrollEvent(&scroll_event); // Verify that this a mouse wheel event was sent to the child frame renderer. EXPECT_TRUE(child_frame_monitor.EventWasReceived()); EXPECT_EQ(child_frame_monitor.EventType(), blink::WebInputEvent::MouseWheel); } // Test that mouse events are being routed to the correct RenderWidgetHostView // based on coordinates. #if defined(OS_ANDROID) || defined(THREAD_SANITIZER) // Browser process hit testing is not implemented on Android. // https://crbug.com/491334 // The test times out often on TSAN bot. // https://crbug.com/591170. #define MAYBE_SurfaceHitTestTest DISABLED_SurfaceHitTestTest #else #define MAYBE_SurfaceHitTestTest SurfaceHitTestTest #endif IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, MAYBE_SurfaceHitTestTest) { SurfaceHitTestTestHelper(shell(), embedded_test_server()); } // Same test as above, but runs in high-dpi mode. #if defined(OS_ANDROID) || defined(OS_WIN) // Browser process hit testing is not implemented on Android. // https://crbug.com/491334 // Windows is disabled because of https://crbug.com/545547. #define MAYBE_HighDPISurfaceHitTestTest DISABLED_SurfaceHitTestTest #else #define MAYBE_HighDPISurfaceHitTestTest SurfaceHitTestTest #endif IN_PROC_BROWSER_TEST_F(SitePerProcessHighDPIBrowserTest, MAYBE_HighDPISurfaceHitTestTest) { SurfaceHitTestTestHelper(shell(), embedded_test_server()); } // Test that mouse events are being routed to the correct RenderWidgetHostView // when there are nested out-of-process iframes. #if defined(OS_ANDROID) // Browser process hit testing is not implemented on Android. // https://crbug.com/491334 #define MAYBE_NestedSurfaceHitTestTest DISABLED_NestedSurfaceHitTestTest #else #define MAYBE_NestedSurfaceHitTestTest NestedSurfaceHitTestTest #endif IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, MAYBE_NestedSurfaceHitTestTest) { GURL main_url(embedded_test_server()->GetURL( "/frame_tree/page_with_positioned_nested_frames.html")); NavigateToURL(shell(), main_url); // It is safe to obtain the root frame tree node here, as it doesn't change. FrameTreeNode* root = web_contents()->GetFrameTree()->root(); ASSERT_EQ(1U, root->child_count()); FrameTreeNode* parent_iframe_node = root->child_at(0); GURL site_url(embedded_test_server()->GetURL( "a.com", "/frame_tree/page_with_positioned_frame.html")); EXPECT_EQ(site_url, parent_iframe_node->current_url()); EXPECT_NE(shell()->web_contents()->GetSiteInstance(), parent_iframe_node->current_frame_host()->GetSiteInstance()); FrameTreeNode* nested_iframe_node = parent_iframe_node->child_at(0); GURL nested_site_url( embedded_test_server()->GetURL("baz.com", "/title1.html")); EXPECT_EQ(nested_site_url, nested_iframe_node->current_url()); EXPECT_NE(shell()->web_contents()->GetSiteInstance(), nested_iframe_node->current_frame_host()->GetSiteInstance()); EXPECT_NE(parent_iframe_node->current_frame_host()->GetSiteInstance(), nested_iframe_node->current_frame_host()->GetSiteInstance()); // Create listeners for mouse events. RenderWidgetHostMouseEventMonitor main_frame_monitor( root->current_frame_host()->GetRenderWidgetHost()); RenderWidgetHostMouseEventMonitor nested_frame_monitor( nested_iframe_node->current_frame_host()->GetRenderWidgetHost()); RenderWidgetHostInputEventRouter* router = web_contents()->GetInputEventRouter(); RenderWidgetHostViewBase* root_view = static_cast<RenderWidgetHostViewBase*>( root->current_frame_host()->GetRenderWidgetHost()->GetView()); RenderWidgetHostViewBase* rwhv_nested = static_cast<RenderWidgetHostViewBase*>( nested_iframe_node->current_frame_host() ->GetRenderWidgetHost() ->GetView()); SurfaceHitTestReadyNotifier notifier( static_cast<RenderWidgetHostViewChildFrame*>(rwhv_nested)); notifier.WaitForSurfaceReady(); // Target input event to nested frame. blink::WebMouseEvent nested_event; nested_event.type = blink::WebInputEvent::MouseDown; nested_event.button = blink::WebPointerProperties::Button::Left; nested_event.x = 125; nested_event.y = 125; nested_event.clickCount = 1; nested_frame_monitor.ResetEventReceived(); main_frame_monitor.ResetEventReceived(); router->RouteMouseEvent(root_view, &nested_event, ui::LatencyInfo()); EXPECT_TRUE(nested_frame_monitor.EventWasReceived()); EXPECT_EQ(21, nested_frame_monitor.event().x); EXPECT_EQ(21, nested_frame_monitor.event().y); EXPECT_FALSE(main_frame_monitor.EventWasReceived()); } // This test tests that browser process hittesting ignores frames with // pointer-events: none. #if defined(OS_ANDROID) // Browser process hit testing is not implemented on Android. // https://crbug.com/491334 #define MAYBE_SurfaceHitTestPointerEventsNone \ DISABLED_SurfaceHitTestPointerEventsNone #elif defined(THREAD_SANITIZER) // Flaky on TSAN. https://crbug.com/582277 #define MAYBE_SurfaceHitTestPointerEventsNone \ DISABLED_SurfaceHitTestPointerEventsNone #else #define MAYBE_SurfaceHitTestPointerEventsNone SurfaceHitTestPointerEventsNone #endif IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, MAYBE_SurfaceHitTestPointerEventsNone) { GURL main_url(embedded_test_server()->GetURL( "/frame_tree/page_with_positioned_frame_pointer-events_none.html")); NavigateToURL(shell(), main_url); // It is safe to obtain the root frame tree node here, as it doesn't change. FrameTreeNode* root = web_contents()->GetFrameTree()->root(); ASSERT_EQ(1U, root->child_count()); FrameTreeNode* child_node = root->child_at(0); GURL site_url(embedded_test_server()->GetURL("baz.com", "/title1.html")); EXPECT_EQ(site_url, child_node->current_url()); EXPECT_NE(shell()->web_contents()->GetSiteInstance(), child_node->current_frame_host()->GetSiteInstance()); // Create listeners for mouse events. RenderWidgetHostMouseEventMonitor main_frame_monitor( root->current_frame_host()->GetRenderWidgetHost()); RenderWidgetHostMouseEventMonitor child_frame_monitor( child_node->current_frame_host()->GetRenderWidgetHost()); RenderWidgetHostInputEventRouter* router = web_contents()->GetInputEventRouter(); RenderWidgetHostViewBase* root_view = static_cast<RenderWidgetHostViewBase*>( root->current_frame_host()->GetRenderWidgetHost()->GetView()); RenderWidgetHostViewBase* rwhv_child = static_cast<RenderWidgetHostViewBase*>( child_node->current_frame_host()->GetRenderWidgetHost()->GetView()); SurfaceHitTestReadyNotifier notifier( static_cast<RenderWidgetHostViewChildFrame*>(rwhv_child)); notifier.WaitForSurfaceReady(); // Target input event to child frame. blink::WebMouseEvent child_event; child_event.type = blink::WebInputEvent::MouseDown; child_event.button = blink::WebPointerProperties::Button::Left; child_event.x = 75; child_event.y = 75; child_event.clickCount = 1; main_frame_monitor.ResetEventReceived(); child_frame_monitor.ResetEventReceived(); router->RouteMouseEvent(root_view, &child_event, ui::LatencyInfo()); EXPECT_TRUE(main_frame_monitor.EventWasReceived()); EXPECT_EQ(75, main_frame_monitor.event().x); EXPECT_EQ(75, main_frame_monitor.event().y); EXPECT_FALSE(child_frame_monitor.EventWasReceived()); } // This test verifies that MouseEnter and MouseLeave events fire correctly // when the mouse cursor moves between processes. #if defined(OS_ANDROID) // Browser process hit testing is not implemented on Android. // https://crbug.com/491334 #define MAYBE_CrossProcessMouseEnterAndLeaveTest \ DISABLED_CrossProcessMouseEnterAndLeaveTest #else #define MAYBE_CrossProcessMouseEnterAndLeaveTest \ CrossProcessMouseEnterAndLeaveTest #endif IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, MAYBE_CrossProcessMouseEnterAndLeaveTest) { GURL main_url(embedded_test_server()->GetURL( "a.com", "/cross_site_iframe_factory.html?a(b,c(d))")); NavigateToURL(shell(), main_url); FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents()) ->GetFrameTree() ->root(); EXPECT_EQ( " Site A ------------ proxies for B C D\n" " |--Site B ------- proxies for A C D\n" " +--Site C ------- proxies for A B D\n" " +--Site D -- proxies for A B C\n" "Where A = http://a.com/\n" " B = http://b.com/\n" " C = http://c.com/\n" " D = http://d.com/", DepictFrameTree(root)); FrameTreeNode* b_node = root->child_at(0); FrameTreeNode* c_node = root->child_at(1); FrameTreeNode* d_node = c_node->child_at(0); RenderWidgetHostViewBase* rwhv_a = static_cast<RenderWidgetHostViewBase*>( root->current_frame_host()->GetRenderWidgetHost()->GetView()); RenderWidgetHostViewBase* rwhv_b = static_cast<RenderWidgetHostViewBase*>( b_node->current_frame_host()->GetRenderWidgetHost()->GetView()); RenderWidgetHostViewBase* rwhv_d = static_cast<RenderWidgetHostViewBase*>( d_node->current_frame_host()->GetRenderWidgetHost()->GetView()); // Verifying surfaces are ready in B and D are sufficient, since other // surfaces contain at least one of them. SurfaceHitTestReadyNotifier notifier_b( static_cast<RenderWidgetHostViewChildFrame*>(rwhv_b)); notifier_b.WaitForSurfaceReady(); SurfaceHitTestReadyNotifier notifier_d( static_cast<RenderWidgetHostViewChildFrame*>(rwhv_d)); notifier_d.WaitForSurfaceReady(); // Create listeners for mouse events. These are used to verify that the // RenderWidgetHostInputEventRouter is generating MouseLeave, etc for // the right renderers. RenderWidgetHostMouseEventMonitor root_frame_monitor( root->current_frame_host()->GetRenderWidgetHost()); RenderWidgetHostMouseEventMonitor a_frame_monitor( root->current_frame_host()->GetRenderWidgetHost()); RenderWidgetHostMouseEventMonitor b_frame_monitor( b_node->current_frame_host()->GetRenderWidgetHost()); RenderWidgetHostMouseEventMonitor c_frame_monitor( c_node->current_frame_host()->GetRenderWidgetHost()); RenderWidgetHostMouseEventMonitor d_frame_monitor( d_node->current_frame_host()->GetRenderWidgetHost()); gfx::Point point_in_a_frame(2, 2); gfx::Point point_in_b_frame(313, 147); gfx::Point point_in_d_frame(471, 207); blink::WebMouseEvent mouse_event; mouse_event.type = blink::WebInputEvent::MouseMove; mouse_event.x = point_in_a_frame.x(); mouse_event.y = point_in_a_frame.y(); // Send an initial MouseMove to the root view, which shouldn't affect the // other renderers. web_contents()->GetInputEventRouter()->RouteMouseEvent(rwhv_a, &mouse_event, ui::LatencyInfo()); EXPECT_TRUE(a_frame_monitor.EventWasReceived()); a_frame_monitor.ResetEventReceived(); EXPECT_FALSE(b_frame_monitor.EventWasReceived()); EXPECT_FALSE(c_frame_monitor.EventWasReceived()); EXPECT_FALSE(d_frame_monitor.EventWasReceived()); // Next send a MouseMove to B frame, which shouldn't affect C or D but // A should receive a MouseMove event. mouse_event.x = point_in_b_frame.x(); mouse_event.y = point_in_b_frame.y(); web_contents()->GetInputEventRouter()->RouteMouseEvent(rwhv_a, &mouse_event, ui::LatencyInfo()); EXPECT_TRUE(a_frame_monitor.EventWasReceived()); EXPECT_EQ(a_frame_monitor.event().type, blink::WebInputEvent::MouseMove); a_frame_monitor.ResetEventReceived(); EXPECT_TRUE(b_frame_monitor.EventWasReceived()); b_frame_monitor.ResetEventReceived(); EXPECT_FALSE(c_frame_monitor.EventWasReceived()); EXPECT_FALSE(d_frame_monitor.EventWasReceived()); // Next send a MouseMove to D frame, which should have side effects in every // other RenderWidgetHostView. mouse_event.x = point_in_d_frame.x(); mouse_event.y = point_in_d_frame.y(); web_contents()->GetInputEventRouter()->RouteMouseEvent(rwhv_a, &mouse_event, ui::LatencyInfo()); EXPECT_TRUE(a_frame_monitor.EventWasReceived()); EXPECT_EQ(a_frame_monitor.event().type, blink::WebInputEvent::MouseMove); EXPECT_TRUE(b_frame_monitor.EventWasReceived()); EXPECT_EQ(b_frame_monitor.event().type, blink::WebInputEvent::MouseLeave); EXPECT_TRUE(c_frame_monitor.EventWasReceived()); EXPECT_EQ(c_frame_monitor.event().type, blink::WebInputEvent::MouseMove); EXPECT_TRUE(d_frame_monitor.EventWasReceived()); } // Verify that mouse capture works on a RenderWidgetHostView level, so that // dragging scroll bars and selecting text continues even when the mouse // cursor crosses over cross-process frame boundaries. #if defined(OS_ANDROID) // Browser process hit testing is not implemented on Android. // https://crbug.com/491334 #define MAYBE_CrossProcessMouseCapture DISABLED_CrossProcessMouseCapture #else #define MAYBE_CrossProcessMouseCapture CrossProcessMouseCapture #endif IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, MAYBE_CrossProcessMouseCapture) { GURL main_url(embedded_test_server()->GetURL( "/frame_tree/page_with_positioned_frame.html")); EXPECT_TRUE(NavigateToURL(shell(), main_url)); // It is safe to obtain the root frame tree node here, as it doesn't change. FrameTreeNode* root = web_contents()->GetFrameTree()->root(); ASSERT_EQ(1U, root->child_count()); FrameTreeNode* child_node = root->child_at(0); GURL site_url(embedded_test_server()->GetURL("baz.com", "/title1.html")); EXPECT_EQ(site_url, child_node->current_url()); EXPECT_NE(shell()->web_contents()->GetSiteInstance(), child_node->current_frame_host()->GetSiteInstance()); // Create listeners for mouse events. RenderWidgetHostMouseEventMonitor main_frame_monitor( root->current_frame_host()->GetRenderWidgetHost()); RenderWidgetHostMouseEventMonitor child_frame_monitor( child_node->current_frame_host()->GetRenderWidgetHost()); RenderWidgetHostInputEventRouter* router = web_contents()->GetInputEventRouter(); RenderWidgetHostViewBase* root_view = static_cast<RenderWidgetHostViewBase*>( root->current_frame_host()->GetRenderWidgetHost()->GetView()); RenderWidgetHostViewBase* rwhv_child = static_cast<RenderWidgetHostViewBase*>( child_node->current_frame_host()->GetRenderWidgetHost()->GetView()); SurfaceHitTestReadyNotifier notifier( static_cast<RenderWidgetHostViewChildFrame*>(rwhv_child)); notifier.WaitForSurfaceReady(); // Target MouseDown to child frame. blink::WebMouseEvent mouse_event; mouse_event.type = blink::WebInputEvent::MouseDown; mouse_event.button = blink::WebPointerProperties::Button::Left; mouse_event.x = 75; mouse_event.y = 75; mouse_event.clickCount = 1; main_frame_monitor.ResetEventReceived(); child_frame_monitor.ResetEventReceived(); router->RouteMouseEvent(root_view, &mouse_event, ui::LatencyInfo()); EXPECT_FALSE(main_frame_monitor.EventWasReceived()); EXPECT_TRUE(child_frame_monitor.EventWasReceived()); // Target MouseMove to main frame. This should still be routed to the // child frame because it is now capturing mouse input. mouse_event.type = blink::WebInputEvent::MouseMove; mouse_event.modifiers = blink::WebInputEvent::LeftButtonDown; mouse_event.x = 1; mouse_event.y = 1; // Note that this event is sent twice, with the monitors cleared after // the first time, because the first MouseMove to the child frame // causes a MouseMove to be sent to the main frame also, which we // need to ignore. router->RouteMouseEvent(root_view, &mouse_event, ui::LatencyInfo()); main_frame_monitor.ResetEventReceived(); child_frame_monitor.ResetEventReceived(); mouse_event.x = 1; mouse_event.y = 2; router->RouteMouseEvent(root_view, &mouse_event, ui::LatencyInfo()); EXPECT_FALSE(main_frame_monitor.EventWasReceived()); EXPECT_TRUE(child_frame_monitor.EventWasReceived()); // A MouseUp to the child frame should cancel the mouse capture. mouse_event.type = blink::WebInputEvent::MouseUp; mouse_event.modifiers = 0; mouse_event.x = 75; mouse_event.y = 75; main_frame_monitor.ResetEventReceived(); child_frame_monitor.ResetEventReceived(); router->RouteMouseEvent(root_view, &mouse_event, ui::LatencyInfo()); EXPECT_FALSE(main_frame_monitor.EventWasReceived()); EXPECT_TRUE(child_frame_monitor.EventWasReceived()); // Subsequent MouseMove events targeted to the main frame should be routed // to that frame. mouse_event.type = blink::WebInputEvent::MouseMove; mouse_event.x = 1; mouse_event.y = 3; // Sending the MouseMove twice for the same reason as above. router->RouteMouseEvent(root_view, &mouse_event, ui::LatencyInfo()); main_frame_monitor.ResetEventReceived(); child_frame_monitor.ResetEventReceived(); mouse_event.x = 1; mouse_event.y = 4; router->RouteMouseEvent(root_view, &mouse_event, ui::LatencyInfo()); EXPECT_TRUE(main_frame_monitor.EventWasReceived()); EXPECT_FALSE(child_frame_monitor.EventWasReceived()); // Target MouseDown to the main frame to cause it to capture input. mouse_event.type = blink::WebInputEvent::MouseDown; mouse_event.x = 1; mouse_event.y = 1; main_frame_monitor.ResetEventReceived(); child_frame_monitor.ResetEventReceived(); router->RouteMouseEvent(root_view, &mouse_event, ui::LatencyInfo()); EXPECT_TRUE(main_frame_monitor.EventWasReceived()); EXPECT_FALSE(child_frame_monitor.EventWasReceived()); // Sending a MouseMove to the child frame should still result in the main // frame receiving the event. mouse_event.type = blink::WebInputEvent::MouseMove; mouse_event.modifiers = blink::WebInputEvent::LeftButtonDown; mouse_event.x = 75; mouse_event.y = 75; main_frame_monitor.ResetEventReceived(); child_frame_monitor.ResetEventReceived(); router->RouteMouseEvent(root_view, &mouse_event, ui::LatencyInfo()); EXPECT_TRUE(main_frame_monitor.EventWasReceived()); EXPECT_FALSE(child_frame_monitor.EventWasReceived()); } // Tests OOPIF rendering by checking that the RWH of the iframe generates // OnSwapCompositorFrame message. IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, CompositorFrameSwapped) { GURL main_url(embedded_test_server()->GetURL( "a.com", "/cross_site_iframe_factory.html?a(baz)")); NavigateToURL(shell(), main_url); // It is safe to obtain the root frame tree node here, as it doesn't change. FrameTreeNode* root = web_contents()->GetFrameTree()->root(); ASSERT_EQ(1U, root->child_count()); FrameTreeNode* child_node = root->child_at(0); GURL site_url(embedded_test_server()->GetURL( "baz.com", "/cross_site_iframe_factory.html?baz()")); EXPECT_EQ(site_url, child_node->current_url()); EXPECT_NE(shell()->web_contents()->GetSiteInstance(), child_node->current_frame_host()->GetSiteInstance()); RenderWidgetHostViewBase* rwhv_base = static_cast<RenderWidgetHostViewBase*>( child_node->current_frame_host()->GetRenderWidgetHost()->GetView()); // Wait for OnSwapCompositorFrame message. while (rwhv_base->RendererFrameNumber() <= 0) { // TODO(lazyboy): Find a better way to avoid sleeping like this. See // http://crbug.com/405282 for details. base::RunLoop run_loop; base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, run_loop.QuitClosure(), base::TimeDelta::FromMilliseconds(10)); run_loop.Run(); } } // Ensure that OOPIFs are deleted after navigating to a new main frame. IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, CleanupCrossSiteIframe) { GURL main_url(embedded_test_server()->GetURL( "a.com", "/cross_site_iframe_factory.html?a(a,a(a,a(a)))")); NavigateToURL(shell(), main_url); // It is safe to obtain the root frame tree node here, as it doesn't change. FrameTreeNode* root = web_contents()->GetFrameTree()->root(); TestNavigationObserver observer(shell()->web_contents()); // Load a cross-site page into both iframes. GURL foo_url = embedded_test_server()->GetURL("foo.com", "/title2.html"); NavigateFrameToURL(root->child_at(0), foo_url); EXPECT_TRUE(observer.last_navigation_succeeded()); EXPECT_EQ(foo_url, observer.last_navigation_url()); NavigateFrameToURL(root->child_at(1), foo_url); EXPECT_TRUE(observer.last_navigation_succeeded()); EXPECT_EQ(foo_url, observer.last_navigation_url()); // Ensure that we have created a new process for the subframes. EXPECT_EQ( " Site A ------------ proxies for B\n" " |--Site B ------- proxies for A\n" " +--Site B ------- proxies for A\n" "Where A = http://a.com/\n" " B = http://foo.com/", DepictFrameTree(root)); int subframe_process_id = root->child_at(0) ->current_frame_host() ->GetSiteInstance() ->GetProcess() ->GetID(); int subframe_rvh_id = root->child_at(0) ->current_frame_host() ->render_view_host() ->GetRoutingID(); EXPECT_TRUE(RenderViewHost::FromID(subframe_process_id, subframe_rvh_id)); // Use Javascript in the parent to remove one of the frames and ensure that // the subframe goes away. EXPECT_TRUE(ExecuteScript(shell(), "document.body.removeChild(" "document.querySelectorAll('iframe')[0])")); ASSERT_EQ(1U, root->child_count()); // Load a new same-site page in the top-level frame and ensure the other // subframe goes away. GURL new_url(embedded_test_server()->GetURL("a.com", "/title1.html")); NavigateToURL(shell(), new_url); ASSERT_EQ(0U, root->child_count()); // Ensure the RVH for the subframe gets cleaned up when the frame goes away. EXPECT_FALSE(RenderViewHost::FromID(subframe_process_id, subframe_rvh_id)); } // Ensure that root frames cannot be detached. IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, RestrictFrameDetach) { GURL main_url(embedded_test_server()->GetURL( "a.com", "/cross_site_iframe_factory.html?a(a,a(a,a(a)))")); NavigateToURL(shell(), main_url); // It is safe to obtain the root frame tree node here, as it doesn't change. FrameTreeNode* root = web_contents()->GetFrameTree()->root(); TestNavigationObserver observer(shell()->web_contents()); // Load cross-site pages into both iframes. GURL foo_url = embedded_test_server()->GetURL("foo.com", "/title2.html"); NavigateFrameToURL(root->child_at(0), foo_url); EXPECT_TRUE(observer.last_navigation_succeeded()); EXPECT_EQ(foo_url, observer.last_navigation_url()); GURL bar_url = embedded_test_server()->GetURL("bar.com", "/title2.html"); NavigateFrameToURL(root->child_at(1), bar_url); EXPECT_TRUE(observer.last_navigation_succeeded()); EXPECT_EQ(bar_url, observer.last_navigation_url()); // Ensure that we have created new processes for the subframes. ASSERT_EQ(2U, root->child_count()); FrameTreeNode* foo_child = root->child_at(0); SiteInstance* foo_site_instance = foo_child->current_frame_host()->GetSiteInstance(); EXPECT_NE(shell()->web_contents()->GetSiteInstance(), foo_site_instance); FrameTreeNode* bar_child = root->child_at(1); SiteInstance* bar_site_instance = bar_child->current_frame_host()->GetSiteInstance(); EXPECT_NE(shell()->web_contents()->GetSiteInstance(), bar_site_instance); EXPECT_EQ( " Site A ------------ proxies for B C\n" " |--Site B ------- proxies for A C\n" " +--Site C ------- proxies for A B\n" "Where A = http://a.com/\n" " B = http://foo.com/\n" " C = http://bar.com/", DepictFrameTree(root)); // Simulate an attempt to detach the root frame from foo_site_instance. This // should kill foo_site_instance's process. RenderFrameProxyHost* foo_mainframe_rfph = root->render_manager()->GetRenderFrameProxyHost(foo_site_instance); content::RenderProcessHostWatcher foo_terminated( foo_mainframe_rfph->GetProcess(), content::RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT); FrameHostMsg_Detach evil_msg2(foo_mainframe_rfph->GetRoutingID()); IPC::IpcSecurityTestUtil::PwnMessageReceived( foo_mainframe_rfph->GetProcess()->GetChannel(), evil_msg2); foo_terminated.Wait(); EXPECT_EQ( " Site A ------------ proxies for B C\n" " |--Site B ------- proxies for A C\n" " +--Site C ------- proxies for A B\n" "Where A = http://a.com/\n" " B = http://foo.com/ (no process)\n" " C = http://bar.com/", DepictFrameTree(root)); } #if defined(OS_WIN) // This test is flaky on Windows, see https://crbug.com/629419. #define MAYBE_NavigateRemoteFrame DISABLED_NavigateRemoteFrame #else #define MAYBE_NavigateRemoteFrame NavigateRemoteFrame #endif IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, MAYBE_NavigateRemoteFrame) { GURL main_url(embedded_test_server()->GetURL( "a.com", "/cross_site_iframe_factory.html?a(a,a(a,a(a)))")); NavigateToURL(shell(), main_url); // It is safe to obtain the root frame tree node here, as it doesn't change. FrameTreeNode* root = web_contents()->GetFrameTree()->root(); TestNavigationObserver observer(shell()->web_contents()); // Load same-site page into iframe. FrameTreeNode* child = root->child_at(0); GURL http_url(embedded_test_server()->GetURL("a.com", "/title1.html")); NavigateFrameToURL(child, http_url); EXPECT_EQ(http_url, observer.last_navigation_url()); EXPECT_TRUE(observer.last_navigation_succeeded()); // Load cross-site page into iframe. GURL url = embedded_test_server()->GetURL("foo.com", "/title2.html"); NavigateFrameToURL(root->child_at(0), url); EXPECT_TRUE(observer.last_navigation_succeeded()); EXPECT_EQ(url, observer.last_navigation_url()); // Ensure that we have created a new process for the subframe. EXPECT_EQ( " Site A ------------ proxies for B\n" " |--Site B ------- proxies for A\n" " +--Site A ------- proxies for B\n" " |--Site A -- proxies for B\n" " +--Site A -- proxies for B\n" " +--Site A -- proxies for B\n" "Where A = http://a.com/\n" " B = http://foo.com/", DepictFrameTree(root)); SiteInstance* site_instance = child->current_frame_host()->GetSiteInstance(); EXPECT_NE(shell()->web_contents()->GetSiteInstance(), site_instance); // Emulate the main frame changing the src of the iframe such that it // navigates cross-site. url = embedded_test_server()->GetURL("bar.com", "/title3.html"); NavigateIframeToURL(shell()->web_contents(), "child-0", url); EXPECT_TRUE(observer.last_navigation_succeeded()); EXPECT_EQ(url, observer.last_navigation_url()); // Check again that a new process is created and is different from the // top level one and the previous one. EXPECT_EQ( " Site A ------------ proxies for C\n" " |--Site C ------- proxies for A\n" " +--Site A ------- proxies for C\n" " |--Site A -- proxies for C\n" " +--Site A -- proxies for C\n" " +--Site A -- proxies for C\n" "Where A = http://a.com/\n" " C = http://bar.com/", DepictFrameTree(root)); // Navigate back to the parent's origin and ensure we return to the // parent's process. NavigateFrameToURL(child, http_url); EXPECT_EQ(http_url, observer.last_navigation_url()); EXPECT_TRUE(observer.last_navigation_succeeded()); EXPECT_EQ(shell()->web_contents()->GetSiteInstance(), child->current_frame_host()->GetSiteInstance()); } IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, NavigateRemoteFrameToBlankAndDataURLs) { GURL main_url(embedded_test_server()->GetURL( "a.com", "/cross_site_iframe_factory.html?a(a,a(a))")); NavigateToURL(shell(), main_url); // It is safe to obtain the root frame tree node here, as it doesn't change. FrameTreeNode* root = web_contents()->GetFrameTree()->root(); TestNavigationObserver observer(shell()->web_contents()); // Load same-site page into iframe. FrameTreeNode* child = root->child_at(0); GURL http_url(embedded_test_server()->GetURL("a.com", "/title1.html")); NavigateFrameToURL(child, http_url); EXPECT_EQ(http_url, observer.last_navigation_url()); EXPECT_TRUE(observer.last_navigation_succeeded()); EXPECT_EQ( " Site A\n" " |--Site A\n" " +--Site A\n" " +--Site A\n" "Where A = http://a.com/", DepictFrameTree(root)); // Load cross-site page into iframe. GURL url = embedded_test_server()->GetURL("foo.com", "/title2.html"); NavigateFrameToURL(child, url); EXPECT_TRUE(observer.last_navigation_succeeded()); EXPECT_EQ(url, observer.last_navigation_url()); EXPECT_EQ( " Site A ------------ proxies for B\n" " |--Site B ------- proxies for A\n" " +--Site A ------- proxies for B\n" " +--Site A -- proxies for B\n" "Where A = http://a.com/\n" " B = http://foo.com/", DepictFrameTree(root)); // Navigate iframe to a data URL. The navigation happens from a script in the // parent frame, so the data URL should be committed in the same SiteInstance // as the parent frame. RenderFrameDeletedObserver deleted_observer1( root->child_at(0)->current_frame_host()); GURL data_url("data:text/html,dataurl"); NavigateIframeToURL(shell()->web_contents(), "child-0", data_url); EXPECT_TRUE(observer.last_navigation_succeeded()); EXPECT_EQ(data_url, observer.last_navigation_url()); // Wait for the old process to exit, to verify that the proxies go away. deleted_observer1.WaitUntilDeleted(); // Ensure that we have navigated using the top level process. EXPECT_EQ( " Site A\n" " |--Site A\n" " +--Site A\n" " +--Site A\n" "Where A = http://a.com/", DepictFrameTree(root)); // Load cross-site page into iframe. url = embedded_test_server()->GetURL("bar.com", "/title2.html"); NavigateFrameToURL(child, url); EXPECT_TRUE(observer.last_navigation_succeeded()); EXPECT_EQ(url, observer.last_navigation_url()); EXPECT_EQ( " Site A ------------ proxies for C\n" " |--Site C ------- proxies for A\n" " +--Site A ------- proxies for C\n" " +--Site A -- proxies for C\n" "Where A = http://a.com/\n" " C = http://bar.com/", DepictFrameTree(root)); // Navigate iframe to about:blank. The navigation happens from a script in the // parent frame, so it should be committed in the same SiteInstance as the // parent frame. RenderFrameDeletedObserver deleted_observer2( root->child_at(0)->current_frame_host()); GURL about_blank_url("about:blank"); NavigateIframeToURL(shell()->web_contents(), "child-0", about_blank_url); EXPECT_TRUE(observer.last_navigation_succeeded()); EXPECT_EQ(about_blank_url, observer.last_navigation_url()); // Wait for the old process to exit, to verify that the proxies go away. deleted_observer2.WaitUntilDeleted(); // Ensure that we have navigated using the top level process. EXPECT_EQ( " Site A\n" " |--Site A\n" " +--Site A\n" " +--Site A\n" "Where A = http://a.com/", DepictFrameTree(root)); // Load cross-site page into iframe again. url = embedded_test_server()->GetURL("f00.com", "/title3.html"); NavigateFrameToURL(child, url); EXPECT_TRUE(observer.last_navigation_succeeded()); EXPECT_EQ(url, observer.last_navigation_url()); EXPECT_EQ( " Site A ------------ proxies for D\n" " |--Site D ------- proxies for A\n" " +--Site A ------- proxies for D\n" " +--Site A -- proxies for D\n" "Where A = http://a.com/\n" " D = http://f00.com/", DepictFrameTree(root)); // Navigate the iframe itself to about:blank using a script executing in its // own context. It should stay in the same SiteInstance as before, not the // parent one. std::string script( "window.domAutomationController.send(" "window.location.href = 'about:blank');"); TestFrameNavigationObserver frame_observer(child); EXPECT_TRUE(ExecuteScript(child, script)); frame_observer.Wait(); EXPECT_EQ(about_blank_url, child->current_url()); // Ensure that we have navigated using the top level process. EXPECT_EQ( " Site A ------------ proxies for D\n" " |--Site D ------- proxies for A\n" " +--Site A ------- proxies for D\n" " +--Site A -- proxies for D\n" "Where A = http://a.com/\n" " D = http://f00.com/", DepictFrameTree(root)); } // This test checks that killing a renderer process of a remote frame // and then navigating some other frame to the same SiteInstance of the killed // process works properly. // This can be illustrated as follows, // where 1/2/3 are FrameTreeNode-s and A/B are processes and B* is the killed // B process: // // 1 A A A // / \ -> / \ -> Kill B -> / \ -> Navigate 3 to B -> / \ . // 2 3 B A B* A B* B // // Initially, node1.proxy_hosts_ = {B} // After we kill B, we make sure B stays in node1.proxy_hosts_, then we navigate // 3 to B and we expect that to complete normally. // See http://crbug.com/432107. // // Note that due to http://crbug.com/450681, node2 cannot be re-navigated to // site B and stays in not rendered state. IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, NavigateRemoteFrameToKilledProcess) { GURL main_url(embedded_test_server()->GetURL( "foo.com", "/cross_site_iframe_factory.html?foo.com(bar.com, foo.com)")); NavigateToURL(shell(), main_url); // It is safe to obtain the root frame tree node here, as it doesn't change. FrameTreeNode* root = web_contents()->GetFrameTree()->root(); TestNavigationObserver observer(shell()->web_contents()); ASSERT_EQ(2U, root->child_count()); // Make sure node2 points to the correct cross-site page. GURL site_b_url = embedded_test_server()->GetURL( "bar.com", "/cross_site_iframe_factory.html?bar.com()"); FrameTreeNode* node2 = root->child_at(0); EXPECT_EQ(site_b_url, node2->current_url()); // Kill that cross-site renderer. RenderProcessHost* child_process = node2->current_frame_host()->GetProcess(); RenderProcessHostWatcher crash_observer( child_process, RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT); child_process->Shutdown(0, false); crash_observer.Wait(); // Now navigate the second iframe (node3) to the same site as the node2. FrameTreeNode* node3 = root->child_at(1); NavigateFrameToURL(node3, site_b_url); EXPECT_TRUE(observer.last_navigation_succeeded()); EXPECT_EQ(site_b_url, observer.last_navigation_url()); } // This test is similar to // SitePerProcessBrowserTest.NavigateRemoteFrameToKilledProcess with // addition that node2 also has a cross-origin frame to site C. // // 1 A A A // / \ / \ / \ / \ . // 2 3 -> B A -> Kill B -> B* A -> Navigate 3 -> B* B // / / // 4 C // // Initially, node1.proxy_hosts_ = {B, C} // After we kill B, we make sure B stays in node1.proxy_hosts_, but // C gets cleared from node1.proxy_hosts_. // // Note that due to http://crbug.com/450681, node2 cannot be re-navigated to // site B and stays in not rendered state. IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, NavigateRemoteFrameToKilledProcessWithSubtree) { GURL main_url(embedded_test_server()->GetURL( "a.com", "/cross_site_iframe_factory.html?a(bar(baz), a)")); NavigateToURL(shell(), main_url); // It is safe to obtain the root frame tree node here, as it doesn't change. FrameTreeNode* root = web_contents()->GetFrameTree()->root(); TestNavigationObserver observer(shell()->web_contents()); ASSERT_EQ(2U, root->child_count()); GURL site_b_url(embedded_test_server()->GetURL( "bar.com", "/cross_site_iframe_factory.html?bar(baz())")); // We can't use a TestNavigationObserver to verify the URL here, // since the frame has children that may have clobbered it in the observer. EXPECT_EQ(site_b_url, root->child_at(0)->current_url()); // Ensure that a new process is created for node2. EXPECT_NE(shell()->web_contents()->GetSiteInstance(), root->child_at(0)->current_frame_host()->GetSiteInstance()); // Ensure that a new process is *not* created for node3. EXPECT_EQ(shell()->web_contents()->GetSiteInstance(), root->child_at(1)->current_frame_host()->GetSiteInstance()); ASSERT_EQ(1U, root->child_at(0)->child_count()); // Make sure node4 points to the correct cross-site page. FrameTreeNode* node4 = root->child_at(0)->child_at(0); GURL site_c_url(embedded_test_server()->GetURL( "baz.com", "/cross_site_iframe_factory.html?baz()")); EXPECT_EQ(site_c_url, node4->current_url()); // |site_instance_c| is expected to go away once we kill |child_process_b| // below, so create a local scope so we can extend the lifetime of // |site_instance_c| with a refptr. { // Initially each frame has proxies for the other sites. EXPECT_EQ( " Site A ------------ proxies for B C\n" " |--Site B ------- proxies for A C\n" " | +--Site C -- proxies for A B\n" " +--Site A ------- proxies for B C\n" "Where A = http://a.com/\n" " B = http://bar.com/\n" " C = http://baz.com/", DepictFrameTree(root)); // Kill the render process for Site B. RenderProcessHost* child_process_b = root->child_at(0)->current_frame_host()->GetProcess(); RenderProcessHostWatcher crash_observer( child_process_b, RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT); child_process_b->Shutdown(0, false); crash_observer.Wait(); // The Site C frame (a child of the crashed Site B frame) should go away, // and there should be no remaining proxies for site C anywhere. EXPECT_EQ( " Site A ------------ proxies for B\n" " |--Site B ------- proxies for A\n" " +--Site A ------- proxies for B\n" "Where A = http://a.com/\n" " B = http://bar.com/ (no process)", DepictFrameTree(root)); } // Now navigate the second iframe (node3) to Site B also. FrameTreeNode* node3 = root->child_at(1); GURL url = embedded_test_server()->GetURL("bar.com", "/title1.html"); NavigateFrameToURL(node3, url); EXPECT_TRUE(observer.last_navigation_succeeded()); EXPECT_EQ(url, observer.last_navigation_url()); EXPECT_EQ( " Site A ------------ proxies for B\n" " |--Site B ------- proxies for A\n" " +--Site B ------- proxies for A\n" "Where A = http://a.com/\n" " B = http://bar.com/", DepictFrameTree(root)); } // Ensure that the renderer process doesn't crash when the main frame navigates // a remote child to a page that results in a network error. // See https://crbug.com/558016. IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, NavigateRemoteAfterError) { GURL main_url(embedded_test_server()->GetURL( "a.com", "/cross_site_iframe_factory.html?a(a)")); NavigateToURL(shell(), main_url); // It is safe to obtain the root frame tree node here, as it doesn't change. FrameTreeNode* root = web_contents()->GetFrameTree()->root(); // Load same-site page into iframe. { TestNavigationObserver observer(shell()->web_contents()); FrameTreeNode* child = root->child_at(0); GURL http_url(embedded_test_server()->GetURL("a.com", "/title1.html")); NavigateFrameToURL(child, http_url); EXPECT_EQ(http_url, observer.last_navigation_url()); EXPECT_TRUE(observer.last_navigation_succeeded()); observer.Wait(); } // Load cross-site page into iframe. { TestNavigationObserver observer(shell()->web_contents()); FrameTreeNode* child = root->child_at(0); GURL url = embedded_test_server()->GetURL("foo.com", "/title2.html"); NavigateFrameToURL(root->child_at(0), url); EXPECT_TRUE(observer.last_navigation_succeeded()); EXPECT_EQ(url, observer.last_navigation_url()); observer.Wait(); // Ensure that we have created a new process for the subframe. EXPECT_EQ( " Site A ------------ proxies for B\n" " +--Site B ------- proxies for A\n" "Where A = http://a.com/\n" " B = http://foo.com/", DepictFrameTree(root)); SiteInstance* site_instance = child->current_frame_host()->GetSiteInstance(); EXPECT_NE(shell()->web_contents()->GetSiteInstance(), site_instance); } // Stop the test server and try to navigate the remote frame. { GURL url = embedded_test_server()->GetURL("bar.com", "/title3.html"); EXPECT_TRUE(embedded_test_server()->ShutdownAndWaitUntilComplete()); NavigateIframeToURL(shell()->web_contents(), "child-0", url); } } // Ensure that a cross-site page ends up in the correct process when it // successfully loads after earlier encountering a network error for it. // See https://crbug.com/560511. // TODO(creis): Make the net error page show in the correct process as well, // per https://crbug.com/588314. IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, ProcessTransferAfterError) { GURL main_url(embedded_test_server()->GetURL( "a.com", "/cross_site_iframe_factory.html?a(a)")); EXPECT_TRUE(NavigateToURL(shell(), main_url)); // It is safe to obtain the root frame tree node here, as it doesn't change. FrameTreeNode* root = web_contents()->GetFrameTree()->root(); FrameTreeNode* child = root->child_at(0); GURL url_a = child->current_url(); // Disable host resolution in the test server and try to navigate the subframe // cross-site, which will lead to a committed net error (which looks like // success to the TestNavigationObserver). GURL url_b = embedded_test_server()->GetURL("b.com", "/title3.html"); host_resolver()->ClearRules(); TestNavigationObserver observer(shell()->web_contents()); NavigateIframeToURL(shell()->web_contents(), "child-0", url_b); EXPECT_TRUE(observer.last_navigation_succeeded()); EXPECT_EQ(url_b, observer.last_navigation_url()); EXPECT_EQ(2, shell()->web_contents()->GetController().GetEntryCount()); // PlzNavigate: Ensure that we have created a new process for the subframe. if (IsBrowserSideNavigationEnabled()) { EXPECT_EQ( " Site A ------------ proxies for B\n" " +--Site B ------- proxies for A\n" "Where A = http://a.com/\n" " B = http://b.com/", DepictFrameTree(root)); EXPECT_NE(shell()->web_contents()->GetSiteInstance(), child->current_frame_host()->GetSiteInstance()); } // The FrameTreeNode should update its URL (so that we don't affect other uses // of the API), but the frame's last_successful_url shouldn't change and the // origin should be empty. // PlzNavigate: We have switched RenderFrameHosts for the subframe, so the // last succesful url should be empty (since the frame only loaded an error // page). if (IsBrowserSideNavigationEnabled()) EXPECT_EQ(GURL(), child->current_frame_host()->last_successful_url()); else EXPECT_EQ(url_a, child->current_frame_host()->last_successful_url()); EXPECT_EQ(url_b, child->current_url()); EXPECT_EQ("null", child->current_origin().Serialize()); // Try again after re-enabling host resolution. host_resolver()->AddRule("*", "127.0.0.1"); NavigateIframeToURL(shell()->web_contents(), "child-0", url_b); EXPECT_TRUE(observer.last_navigation_succeeded()); EXPECT_EQ(url_b, observer.last_navigation_url()); // The FrameTreeNode should have updated its URL and origin. EXPECT_EQ(url_b, child->current_frame_host()->last_successful_url()); EXPECT_EQ(url_b, child->current_url()); EXPECT_EQ(url_b.GetOrigin().spec(), child->current_origin().Serialize() + '/'); // Ensure that we have created a new process for the subframe. // PlzNavigate: the subframe should still be in its separate process. EXPECT_EQ( " Site A ------------ proxies for B\n" " +--Site B ------- proxies for A\n" "Where A = http://a.com/\n" " B = http://b.com/", DepictFrameTree(root)); EXPECT_NE(shell()->web_contents()->GetSiteInstance(), child->current_frame_host()->GetSiteInstance()); // Make sure that the navigation replaced the error page and that going back // ends up on the original site. EXPECT_EQ(2, shell()->web_contents()->GetController().GetEntryCount()); { RenderFrameDeletedObserver deleted_observer(child->current_frame_host()); TestNavigationObserver back_load_observer(shell()->web_contents()); shell()->web_contents()->GetController().GoBack(); back_load_observer.Wait(); // Wait for the old process to exit, to verify that the proxies go away. deleted_observer.WaitUntilDeleted(); } EXPECT_EQ( " Site A\n" " +--Site A\n" "Where A = http://a.com/", DepictFrameTree(root)); EXPECT_EQ(shell()->web_contents()->GetSiteInstance(), child->current_frame_host()->GetSiteInstance()); EXPECT_EQ(url_a, child->current_frame_host()->last_successful_url()); EXPECT_EQ(url_a, child->current_url()); EXPECT_EQ(url_a.GetOrigin().spec(), child->current_origin().Serialize() + '/'); } // Verify that killing a cross-site frame's process B and then navigating a // frame to B correctly recreates all proxies in B. // // 1 A A A // / | \ / | \ / | \ / | \ . // 2 3 4 -> B A A -> Kill B -> B* A A -> B* B A // // After the last step, the test sends a postMessage from node 3 to node 4, // verifying that a proxy for node 4 has been recreated in process B. This // verifies the fix for https://crbug.com/478892. IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, NavigatingToKilledProcessRestoresAllProxies) { // Navigate to a page with three frames: one cross-site and two same-site. GURL main_url(embedded_test_server()->GetURL( "a.com", "/frame_tree/page_with_three_frames.html")); NavigateToURL(shell(), main_url); // It is safe to obtain the root frame tree node here, as it doesn't change. FrameTreeNode* root = web_contents()->GetFrameTree()->root(); TestNavigationObserver observer(shell()->web_contents()); EXPECT_EQ( " Site A ------------ proxies for B\n" " |--Site B ------- proxies for A\n" " |--Site A ------- proxies for B\n" " +--Site A ------- proxies for B\n" "Where A = http://a.com/\n" " B = http://b.com/", DepictFrameTree(root)); // Kill the first subframe's b.com renderer. RenderProcessHost* child_process = root->child_at(0)->current_frame_host()->GetProcess(); RenderProcessHostWatcher crash_observer( child_process, RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT); child_process->Shutdown(0, false); crash_observer.Wait(); // Navigate the second subframe to b.com to recreate the b.com process. GURL b_url = embedded_test_server()->GetURL("b.com", "/post_message.html"); NavigateFrameToURL(root->child_at(1), b_url); EXPECT_TRUE(observer.last_navigation_succeeded()); EXPECT_EQ(b_url, observer.last_navigation_url()); EXPECT_TRUE(root->child_at(1)->current_frame_host()->IsRenderFrameLive()); EXPECT_EQ( " Site A ------------ proxies for B\n" " |--Site B ------- proxies for A\n" " |--Site B ------- proxies for A\n" " +--Site A ------- proxies for B\n" "Where A = http://a.com/\n" " B = http://b.com/", DepictFrameTree(root)); // Check that third subframe's proxy is available in the b.com process by // sending it a postMessage from second subframe, and waiting for a reply. PostMessageAndWaitForReply(root->child_at(1), "postToSibling('subframe-msg','frame3')", "\"done-frame2\""); } // Verify that proxy creation doesn't recreate a crashed process if no frame // will be created in it. // // 1 A A A // / | \ / | \ / | \ / | \ . // 2 3 4 -> B A A -> Kill B -> B* A A -> B* A A // \ . // A // // The test kills process B (node 2), creates a child frame of node 4 in // process A, and then checks that process B isn't resurrected to create a // proxy for the new child frame. See https://crbug.com/476846. IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, CreateChildFrameAfterKillingProcess) { // Navigate to a page with three frames: one cross-site and two same-site. GURL main_url(embedded_test_server()->GetURL( "a.com", "/frame_tree/page_with_three_frames.html")); EXPECT_TRUE(NavigateToURL(shell(), main_url)); // It is safe to obtain the root frame tree node here, as it doesn't change. FrameTreeNode* root = web_contents()->GetFrameTree()->root(); EXPECT_EQ( " Site A ------------ proxies for B\n" " |--Site B ------- proxies for A\n" " |--Site A ------- proxies for B\n" " +--Site A ------- proxies for B\n" "Where A = http://a.com/\n" " B = http://b.com/", DepictFrameTree(root)); SiteInstance* b_site_instance = root->child_at(0)->current_frame_host()->GetSiteInstance(); // Kill the first subframe's renderer (B). RenderProcessHost* child_process = root->child_at(0)->current_frame_host()->GetProcess(); RenderProcessHostWatcher crash_observer( child_process, RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT); child_process->Shutdown(0, false); crash_observer.Wait(); // Add a new child frame to the third subframe. RenderFrameHostCreatedObserver frame_observer(shell()->web_contents(), 1); EXPECT_TRUE(ExecuteScript( root->child_at(2), "document.body.appendChild(document.createElement('iframe'));")); frame_observer.Wait(); // The new frame should have a RenderFrameProxyHost for B, but it should not // be alive, and B should still not have a process (verified by last line of // expected DepictFrameTree output). EXPECT_EQ( " Site A ------------ proxies for B\n" " |--Site B ------- proxies for A\n" " |--Site A ------- proxies for B\n" " +--Site A ------- proxies for B\n" " +--Site A -- proxies for B\n" "Where A = http://a.com/\n" " B = http://b.com/ (no process)", DepictFrameTree(root)); FrameTreeNode* grandchild = root->child_at(2)->child_at(0); RenderFrameProxyHost* grandchild_rfph = grandchild->render_manager()->GetRenderFrameProxyHost(b_site_instance); EXPECT_FALSE(grandchild_rfph->is_render_frame_proxy_live()); // Navigate the second subframe to b.com to recreate process B. TestNavigationObserver observer(shell()->web_contents()); GURL b_url = embedded_test_server()->GetURL("b.com", "/title1.html"); NavigateFrameToURL(root->child_at(1), b_url); EXPECT_TRUE(observer.last_navigation_succeeded()); EXPECT_EQ(b_url, observer.last_navigation_url()); // Ensure that the grandchild RenderFrameProxy in B was created when process // B was restored. EXPECT_TRUE(grandchild_rfph->is_render_frame_proxy_live()); } // Verify that creating a child frame after killing and reloading an opener // process doesn't crash. See https://crbug.com/501152. // 1. Navigate to site A. // 2. Open a popup with window.open and navigate it cross-process to site B. // 3. Kill process A for the original tab. // 4. Reload the original tab to resurrect process A. // 5. Add a child frame to the top-level frame in the popup tab B. // In step 5, we try to create proxies for the child frame in all SiteInstances // for which its parent has proxies. This includes A. However, even though // process A is live (step 4), the parent proxy in A is not live (which was // incorrectly assumed previously). This is because step 4 does not resurrect // proxies for popups opened before the crash. IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, CreateChildFrameAfterKillingOpener) { GURL main_url(embedded_test_server()->GetURL("a.com", "/title1.html")); EXPECT_TRUE(NavigateToURL(shell(), main_url)); // It is safe to obtain the root frame tree node here, as it doesn't change. FrameTreeNode* root = web_contents()->GetFrameTree()->root(); SiteInstance* site_instance_a = root->current_frame_host()->GetSiteInstance(); // Open a popup and navigate it cross-process to b.com. ShellAddedObserver new_shell_observer; EXPECT_TRUE(ExecuteScript(root, "popup = window.open('about:blank');")); Shell* popup = new_shell_observer.GetShell(); GURL popup_url(embedded_test_server()->GetURL("b.com", "/title2.html")); EXPECT_TRUE(NavigateToURL(popup, popup_url)); // Verify that each top-level frame has proxies in the other's SiteInstance. FrameTreeNode* popup_root = static_cast<WebContentsImpl*>(popup->web_contents()) ->GetFrameTree() ->root(); EXPECT_EQ( " Site A ------------ proxies for B\n" "Where A = http://a.com/\n" " B = http://b.com/", DepictFrameTree(root)); EXPECT_EQ( " Site B ------------ proxies for A\n" "Where A = http://a.com/\n" " B = http://b.com/", DepictFrameTree(popup_root)); // Kill the first window's renderer (a.com). RenderProcessHost* child_process = root->current_frame_host()->GetProcess(); RenderProcessHostWatcher crash_observer( child_process, RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT); child_process->Shutdown(0, false); crash_observer.Wait(); EXPECT_FALSE(root->current_frame_host()->IsRenderFrameLive()); // The proxy for the popup in a.com should've died. RenderFrameProxyHost* rfph = popup_root->render_manager()->GetRenderFrameProxyHost(site_instance_a); EXPECT_FALSE(rfph->is_render_frame_proxy_live()); // Recreate the a.com renderer. EXPECT_TRUE(NavigateToURL(shell(), main_url)); EXPECT_TRUE(root->current_frame_host()->IsRenderFrameLive()); // The popup's proxy in a.com should still not be live. Re-navigating the // main window to a.com doesn't reinitialize a.com proxies for popups // previously opened from the main window. EXPECT_FALSE(rfph->is_render_frame_proxy_live()); // Add a new child frame on the popup. RenderFrameHostCreatedObserver frame_observer(popup->web_contents(), 1); EXPECT_TRUE(ExecuteScript( popup, "document.body.appendChild(document.createElement('iframe'));")); frame_observer.Wait(); // Both the child frame's and its parent's proxies should still not be live. // The main page can't reach them since it lost reference to the popup after // it crashed, so there is no need to create them. EXPECT_FALSE(rfph->is_render_frame_proxy_live()); RenderFrameProxyHost* child_rfph = popup_root->child_at(0)->render_manager()->GetRenderFrameProxyHost( site_instance_a); EXPECT_TRUE(child_rfph); EXPECT_FALSE(child_rfph->is_render_frame_proxy_live()); } // In A-embed-B-embed-C scenario, verify that killing process B clears proxies // of C from the tree. // // 1 A A // / \ / \ / \ . // 2 3 -> B A -> Kill B -> B* A // / / // 4 C // // node1 is the root. // Initially, both node1.proxy_hosts_ and node3.proxy_hosts_ contain C. // After we kill B, make sure proxies for C are cleared. IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, KillingRendererClearsDescendantProxies) { GURL main_url(embedded_test_server()->GetURL( "a.com", "/frame_tree/page_with_two_frames_nested.html")); NavigateToURL(shell(), main_url); // It is safe to obtain the root frame tree node here, as it doesn't change. FrameTreeNode* root = web_contents()->GetFrameTree()->root(); ASSERT_EQ(2U, root->child_count()); GURL site_b_url( embedded_test_server()->GetURL( "bar.com", "/frame_tree/page_with_one_frame.html")); // We can't use a TestNavigationObserver to verify the URL here, // since the frame has children that may have clobbered it in the observer. EXPECT_EQ(site_b_url, root->child_at(0)->current_url()); // Ensure that a new process is created for node2. EXPECT_NE(shell()->web_contents()->GetSiteInstance(), root->child_at(0)->current_frame_host()->GetSiteInstance()); // Ensure that a new process is *not* created for node3. EXPECT_EQ(shell()->web_contents()->GetSiteInstance(), root->child_at(1)->current_frame_host()->GetSiteInstance()); ASSERT_EQ(1U, root->child_at(0)->child_count()); // Make sure node4 points to the correct cross-site-page. FrameTreeNode* node4 = root->child_at(0)->child_at(0); GURL site_c_url(embedded_test_server()->GetURL("baz.com", "/title1.html")); EXPECT_EQ(site_c_url, node4->current_url()); // |site_instance_c|'s frames and proxies are expected to go away once we kill // |child_process_b| below. scoped_refptr<SiteInstanceImpl> site_instance_c = node4->current_frame_host()->GetSiteInstance(); // Initially proxies for both B and C will be present in the root. EXPECT_EQ( " Site A ------------ proxies for B C\n" " |--Site B ------- proxies for A C\n" " | +--Site C -- proxies for A B\n" " +--Site A ------- proxies for B C\n" "Where A = http://a.com/\n" " B = http://bar.com/\n" " C = http://baz.com/", DepictFrameTree(root)); EXPECT_GT(site_instance_c->active_frame_count(), 0U); // Kill process B. RenderProcessHost* child_process_b = root->child_at(0)->current_frame_host()->GetProcess(); RenderProcessHostWatcher crash_observer( child_process_b, RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT); child_process_b->Shutdown(0, false); crash_observer.Wait(); // Make sure proxy C has gone from root. // Make sure proxy C has gone from node3 as well. // Make sure proxy B stays around in root and node3. EXPECT_EQ( " Site A ------------ proxies for B\n" " |--Site B ------- proxies for A\n" " +--Site A ------- proxies for B\n" "Where A = http://a.com/\n" " B = http://bar.com/ (no process)", DepictFrameTree(root)); EXPECT_EQ(0U, site_instance_c->active_frame_count()); } // Crash a subframe and ensures its children are cleared from the FrameTree. // See http://crbug.com/338508. IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, CrashSubframe) { GURL main_url(embedded_test_server()->GetURL( "a.com", "/cross_site_iframe_factory.html?a(b)")); NavigateToURL(shell(), main_url); // Check the subframe process. FrameTreeNode* root = web_contents()->GetFrameTree()->root(); EXPECT_EQ( " Site A ------------ proxies for B\n" " +--Site B ------- proxies for A\n" "Where A = http://a.com/\n" " B = http://b.com/", DepictFrameTree(root)); FrameTreeNode* child = root->child_at(0); EXPECT_TRUE( child->current_frame_host()->render_view_host()->IsRenderViewLive()); EXPECT_TRUE(child->current_frame_host()->IsRenderFrameLive()); // Crash the subframe process. RenderProcessHost* root_process = root->current_frame_host()->GetProcess(); RenderProcessHost* child_process = child->current_frame_host()->GetProcess(); { RenderProcessHostWatcher crash_observer( child_process, RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT); child_process->Shutdown(0, false); crash_observer.Wait(); } // Ensure that the child frame still exists but has been cleared. EXPECT_EQ( " Site A ------------ proxies for B\n" " +--Site B ------- proxies for A\n" "Where A = http://a.com/\n" " B = http://b.com/ (no process)", DepictFrameTree(root)); EXPECT_EQ(1U, root->child_count()); EXPECT_EQ(main_url, root->current_url()); EXPECT_EQ(GURL(), child->current_url()); EXPECT_FALSE( child->current_frame_host()->render_view_host()->IsRenderViewLive()); EXPECT_FALSE(child->current_frame_host()->IsRenderFrameLive()); EXPECT_FALSE(child->current_frame_host()->render_frame_created_); // Now crash the top-level page to clear the child frame. { RenderProcessHostWatcher crash_observer( root_process, RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT); root_process->Shutdown(0, false); crash_observer.Wait(); } EXPECT_EQ(0U, root->child_count()); EXPECT_EQ(GURL(), root->current_url()); } // When a new subframe is added, related SiteInstances that can reach the // subframe should create proxies for it (https://crbug.com/423587). This test // checks that if A embeds B and later adds a new subframe A2, A2 gets a proxy // in B's process. IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, CreateProxiesForNewFrames) { GURL main_url(embedded_test_server()->GetURL( "b.com", "/frame_tree/page_with_one_frame.html")); EXPECT_TRUE(NavigateToURL(shell(), main_url)); // It is safe to obtain the root frame tree node here, as it doesn't change. FrameTreeNode* root = web_contents()->GetFrameTree()->root(); ASSERT_EQ(1U, root->child_count()); // Make sure the frame starts out at the correct cross-site URL. EXPECT_EQ(embedded_test_server()->GetURL("baz.com", "/title1.html"), root->child_at(0)->current_url()); EXPECT_EQ( " Site A ------------ proxies for B\n" " +--Site B ------- proxies for A\n" "Where A = http://b.com/\n" " B = http://baz.com/", DepictFrameTree(root)); // Add a new child frame to the top-level frame. RenderFrameHostCreatedObserver frame_observer(shell()->web_contents(), 1); EXPECT_TRUE(ExecuteScript(shell(), "addFrame('data:text/html,foo');")); frame_observer.Wait(); // The new frame should have a proxy in Site B, for use by the old frame. EXPECT_EQ( " Site A ------------ proxies for B\n" " |--Site B ------- proxies for A\n" " +--Site A ------- proxies for B\n" "Where A = http://b.com/\n" " B = http://baz.com/", DepictFrameTree(root)); } // TODO(nasko): Disable this test until out-of-process iframes is ready and the // security checks are back in place. IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, DISABLED_CrossSiteIframeRedirectOnce) { net::EmbeddedTestServer https_server(net::EmbeddedTestServer::TYPE_HTTPS); https_server.ServeFilesFromSourceDirectory("content/test/data"); ASSERT_TRUE(https_server.Start()); GURL main_url(embedded_test_server()->GetURL("/site_per_process_main.html")); GURL http_url(embedded_test_server()->GetURL("/title1.html")); GURL https_url(https_server.GetURL("/title1.html")); NavigateToURL(shell(), main_url); TestNavigationObserver observer(shell()->web_contents()); { // Load cross-site client-redirect page into Iframe. // Should be blocked. GURL client_redirect_https_url( https_server.GetURL("/client-redirect?/title1.html")); EXPECT_TRUE(NavigateIframeToURL(shell()->web_contents(), "test", client_redirect_https_url)); // DidFailProvisionalLoad when navigating to client_redirect_https_url. EXPECT_EQ(observer.last_navigation_url(), client_redirect_https_url); EXPECT_FALSE(observer.last_navigation_succeeded()); } { // Load cross-site server-redirect page into Iframe, // which redirects to same-site page. GURL server_redirect_http_url( https_server.GetURL("/server-redirect?" + http_url.spec())); EXPECT_TRUE(NavigateIframeToURL(shell()->web_contents(), "test", server_redirect_http_url)); EXPECT_EQ(observer.last_navigation_url(), http_url); EXPECT_TRUE(observer.last_navigation_succeeded()); } { // Load cross-site server-redirect page into Iframe, // which redirects to cross-site page. GURL server_redirect_http_url( https_server.GetURL("/server-redirect?/title1.html")); EXPECT_TRUE(NavigateIframeToURL(shell()->web_contents(), "test", server_redirect_http_url)); // DidFailProvisionalLoad when navigating to https_url. EXPECT_EQ(observer.last_navigation_url(), https_url); EXPECT_FALSE(observer.last_navigation_succeeded()); } { // Load same-site server-redirect page into Iframe, // which redirects to cross-site page. GURL server_redirect_http_url( embedded_test_server()->GetURL("/server-redirect?" + https_url.spec())); EXPECT_TRUE(NavigateIframeToURL(shell()->web_contents(), "test", server_redirect_http_url)); EXPECT_EQ(observer.last_navigation_url(), https_url); EXPECT_FALSE(observer.last_navigation_succeeded()); } { // Load same-site client-redirect page into Iframe, // which redirects to cross-site page. GURL client_redirect_http_url( embedded_test_server()->GetURL("/client-redirect?" + https_url.spec())); RedirectNotificationObserver load_observer2( NOTIFICATION_LOAD_STOP, Source<NavigationController>( &shell()->web_contents()->GetController())); EXPECT_TRUE(NavigateIframeToURL(shell()->web_contents(), "test", client_redirect_http_url)); // Same-site Client-Redirect Page should be loaded successfully. EXPECT_EQ(observer.last_navigation_url(), client_redirect_http_url); EXPECT_TRUE(observer.last_navigation_succeeded()); // Redirecting to Cross-site Page should be blocked. load_observer2.Wait(); EXPECT_EQ(observer.last_navigation_url(), https_url); EXPECT_FALSE(observer.last_navigation_succeeded()); } { // Load same-site server-redirect page into Iframe, // which redirects to same-site page. GURL server_redirect_http_url( embedded_test_server()->GetURL("/server-redirect?/title1.html")); EXPECT_TRUE(NavigateIframeToURL(shell()->web_contents(), "test", server_redirect_http_url)); EXPECT_EQ(observer.last_navigation_url(), http_url); EXPECT_TRUE(observer.last_navigation_succeeded()); } { // Load same-site client-redirect page into Iframe, // which redirects to same-site page. GURL client_redirect_http_url( embedded_test_server()->GetURL("/client-redirect?" + http_url.spec())); RedirectNotificationObserver load_observer2( NOTIFICATION_LOAD_STOP, Source<NavigationController>( &shell()->web_contents()->GetController())); EXPECT_TRUE(NavigateIframeToURL(shell()->web_contents(), "test", client_redirect_http_url)); // Same-site Client-Redirect Page should be loaded successfully. EXPECT_EQ(observer.last_navigation_url(), client_redirect_http_url); EXPECT_TRUE(observer.last_navigation_succeeded()); // Redirecting to Same-site Page should be loaded successfully. load_observer2.Wait(); EXPECT_EQ(observer.last_navigation_url(), http_url); EXPECT_TRUE(observer.last_navigation_succeeded()); } } // TODO(nasko): Disable this test until out-of-process iframes is ready and the // security checks are back in place. IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, DISABLED_CrossSiteIframeRedirectTwice) { net::EmbeddedTestServer https_server(net::EmbeddedTestServer::TYPE_HTTPS); https_server.ServeFilesFromSourceDirectory("content/test/data"); ASSERT_TRUE(https_server.Start()); GURL main_url(embedded_test_server()->GetURL("/site_per_process_main.html")); GURL http_url(embedded_test_server()->GetURL("/title1.html")); GURL https_url(https_server.GetURL("/title1.html")); NavigateToURL(shell(), main_url); TestNavigationObserver observer(shell()->web_contents()); { // Load client-redirect page pointing to a cross-site client-redirect page, // which eventually redirects back to same-site page. GURL client_redirect_https_url( https_server.GetURL("/client-redirect?" + http_url.spec())); GURL client_redirect_http_url(embedded_test_server()->GetURL( "/client-redirect?" + client_redirect_https_url.spec())); // We should wait until second client redirect get cancelled. RedirectNotificationObserver load_observer2( NOTIFICATION_LOAD_STOP, Source<NavigationController>( &shell()->web_contents()->GetController())); EXPECT_TRUE(NavigateIframeToURL(shell()->web_contents(), "test", client_redirect_http_url)); // DidFailProvisionalLoad when navigating to client_redirect_https_url. load_observer2.Wait(); EXPECT_EQ(observer.last_navigation_url(), client_redirect_https_url); EXPECT_FALSE(observer.last_navigation_succeeded()); } { // Load server-redirect page pointing to a cross-site server-redirect page, // which eventually redirect back to same-site page. GURL server_redirect_https_url( https_server.GetURL("/server-redirect?" + http_url.spec())); GURL server_redirect_http_url(embedded_test_server()->GetURL( "/server-redirect?" + server_redirect_https_url.spec())); EXPECT_TRUE(NavigateIframeToURL(shell()->web_contents(), "test", server_redirect_http_url)); EXPECT_EQ(observer.last_navigation_url(), http_url); EXPECT_TRUE(observer.last_navigation_succeeded()); } { // Load server-redirect page pointing to a cross-site server-redirect page, // which eventually redirects back to cross-site page. GURL server_redirect_https_url( https_server.GetURL("/server-redirect?" + https_url.spec())); GURL server_redirect_http_url(embedded_test_server()->GetURL( "/server-redirect?" + server_redirect_https_url.spec())); EXPECT_TRUE(NavigateIframeToURL(shell()->web_contents(), "test", server_redirect_http_url)); // DidFailProvisionalLoad when navigating to https_url. EXPECT_EQ(observer.last_navigation_url(), https_url); EXPECT_FALSE(observer.last_navigation_succeeded()); } { // Load server-redirect page pointing to a cross-site client-redirect page, // which eventually redirects back to same-site page. GURL client_redirect_http_url( https_server.GetURL("/client-redirect?" + http_url.spec())); GURL server_redirect_http_url(embedded_test_server()->GetURL( "/server-redirect?" + client_redirect_http_url.spec())); EXPECT_TRUE(NavigateIframeToURL(shell()->web_contents(), "test", server_redirect_http_url)); // DidFailProvisionalLoad when navigating to client_redirect_http_url. EXPECT_EQ(observer.last_navigation_url(), client_redirect_http_url); EXPECT_FALSE(observer.last_navigation_succeeded()); } } // Ensure that when navigating a frame cross-process RenderFrameProxyHosts are // created in the FrameTree skipping the subtree of the navigating frame. IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, ProxyCreationSkipsSubtree) { GURL main_url(embedded_test_server()->GetURL( "a.com", "/cross_site_iframe_factory.html?a(a,a(a,a(a)))")); NavigateToURL(shell(), main_url); // It is safe to obtain the root frame tree node here, as it doesn't change. FrameTreeNode* root = web_contents()->GetFrameTree()->root(); EXPECT_TRUE(root->child_at(1) != NULL); EXPECT_EQ(2U, root->child_at(1)->child_count()); { // Load same-site page into iframe. TestNavigationObserver observer(shell()->web_contents()); GURL http_url(embedded_test_server()->GetURL("a.com", "/title1.html")); NavigateFrameToURL(root->child_at(0), http_url); EXPECT_EQ(http_url, observer.last_navigation_url()); EXPECT_TRUE(observer.last_navigation_succeeded()); EXPECT_EQ( " Site A\n" " |--Site A\n" " +--Site A\n" " |--Site A\n" " +--Site A\n" " +--Site A\n" "Where A = http://a.com/", DepictFrameTree(root)); } // Create the cross-site URL to navigate to. GURL cross_site_url = embedded_test_server()->GetURL("foo.com", "/frame_tree/title2.html"); // Load cross-site page into the second iframe without waiting for the // navigation to complete. Once LoadURLWithParams returns, we would expect // proxies to have been created in the frame tree, but children of the // navigating frame to still be present. The reason is that we don't run the // message loop, so no IPCs that alter the frame tree can be processed. FrameTreeNode* child = root->child_at(1); SiteInstance* site = NULL; bool browser_side_navigation = IsBrowserSideNavigationEnabled(); std::string cross_site_rfh_type = browser_side_navigation ? "speculative" : "pending"; { TestNavigationObserver observer(shell()->web_contents()); TestFrameNavigationObserver navigation_observer(child); NavigationController::LoadURLParams params(cross_site_url); params.transition_type = PageTransitionFromInt(ui::PAGE_TRANSITION_LINK); params.frame_tree_node_id = child->frame_tree_node_id(); child->navigator()->GetController()->LoadURLWithParams(params); if (browser_side_navigation) { site = child->render_manager() ->speculative_frame_host() ->GetSiteInstance(); } else { site = child->render_manager()->pending_frame_host()->GetSiteInstance(); } EXPECT_NE(shell()->web_contents()->GetSiteInstance(), site); std::string tree = base::StringPrintf( " Site A ------------ proxies for B\n" " |--Site A ------- proxies for B\n" " +--Site A (B %s)\n" " |--Site A\n" " +--Site A\n" " +--Site A\n" "Where A = http://a.com/\n" " B = http://foo.com/", cross_site_rfh_type.c_str()); EXPECT_EQ(tree, DepictFrameTree(root)); // Now that the verification is done, run the message loop and wait for the // navigation to complete. navigation_observer.Wait(); EXPECT_FALSE(child->render_manager()->pending_frame_host()); EXPECT_TRUE(observer.last_navigation_succeeded()); EXPECT_EQ(cross_site_url, observer.last_navigation_url()); EXPECT_EQ( " Site A ------------ proxies for B\n" " |--Site A ------- proxies for B\n" " +--Site B ------- proxies for A\n" "Where A = http://a.com/\n" " B = http://foo.com/", DepictFrameTree(root)); } // Load another cross-site page into the same iframe. cross_site_url = embedded_test_server()->GetURL("bar.com", "/title3.html"); { // Perform the same checks as the first cross-site navigation, since // there have been issues in subsequent cross-site navigations. Also ensure // that the SiteInstance has properly changed. // TODO(nasko): Once we have proper cleanup of resources, add code to // verify that the intermediate SiteInstance/RenderFrameHost have been // properly cleaned up. TestNavigationObserver observer(shell()->web_contents()); TestFrameNavigationObserver navigation_observer(child); NavigationController::LoadURLParams params(cross_site_url); params.transition_type = PageTransitionFromInt(ui::PAGE_TRANSITION_LINK); params.frame_tree_node_id = child->frame_tree_node_id(); child->navigator()->GetController()->LoadURLWithParams(params); SiteInstance* site2; if (browser_side_navigation) { site2 = child->render_manager() ->speculative_frame_host() ->GetSiteInstance(); } else { site2 = child->render_manager()->pending_frame_host()->GetSiteInstance(); } EXPECT_NE(shell()->web_contents()->GetSiteInstance(), site2); EXPECT_NE(site, site2); std::string tree = base::StringPrintf( " Site A ------------ proxies for B C\n" " |--Site A ------- proxies for B C\n" " +--Site B (C %s) -- proxies for A\n" "Where A = http://a.com/\n" " B = http://foo.com/\n" " C = http://bar.com/", cross_site_rfh_type.c_str()); EXPECT_EQ(tree, DepictFrameTree(root)); navigation_observer.Wait(); EXPECT_TRUE(observer.last_navigation_succeeded()); EXPECT_EQ(cross_site_url, observer.last_navigation_url()); EXPECT_EQ(0U, child->child_count()); } } // Verify that "scrolling" property on frame elements propagates to child frames // correctly. // Does not work on android since android has scrollbars overlayed. #if defined(OS_ANDROID) #define MAYBE_FrameOwnerPropertiesPropagationScrolling \ DISABLED_FrameOwnerPropertiesPropagationScrolling #else #define MAYBE_FrameOwnerPropertiesPropagationScrolling \ FrameOwnerPropertiesPropagationScrolling #endif IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, MAYBE_FrameOwnerPropertiesPropagationScrolling) { #if defined(OS_MACOSX) ui::test::ScopedPreferredScrollerStyle scroller_style_override(false); #endif GURL main_url(embedded_test_server()->GetURL( "a.com", "/frame_owner_properties_scrolling.html")); NavigateToURL(shell(), main_url); // It is safe to obtain the root frame tree node here, as it doesn't change. FrameTreeNode* root = web_contents()->GetFrameTree()->root(); ASSERT_EQ(1u, root->child_count()); EXPECT_EQ( " Site A ------------ proxies for B\n" " +--Site B ------- proxies for A\n" "Where A = http://a.com/\n" " B = http://b.com/", DepictFrameTree(root)); FrameTreeNode* child = root->child_at(0); // If the available client width within the iframe is smaller than the // frame element's width, we assume there's a scrollbar. // Also note that just comparing clientHeight and scrollHeight of the frame's // document will not work. auto has_scrollbar = [](RenderFrameHostImpl* rfh) { int client_width; EXPECT_TRUE(ExecuteScriptAndExtractInt(rfh, "window.domAutomationController.send(document.body.clientWidth);", &client_width)); const int kFrameElementWidth = 200; return client_width < kFrameElementWidth; }; auto set_scrolling_property = [](RenderFrameHostImpl* parent_rfh, const std::string& value) { EXPECT_TRUE(ExecuteScript( parent_rfh, base::StringPrintf( "document.getElementById('child-1').setAttribute(" " 'scrolling', '%s');", value.c_str()))); }; // Run the test over variety of parent/child cases. GURL urls[] = { // Remote to remote. embedded_test_server()->GetURL("c.com", "/tall_page.html"), // Remote to local. embedded_test_server()->GetURL("a.com", "/tall_page.html"), // Local to remote. embedded_test_server()->GetURL("b.com", "/tall_page.html") }; const std::string scrolling_values[] = { "yes", "auto", "no" }; for (size_t i = 0; i < arraysize(scrolling_values); ++i) { bool expect_scrollbar = scrolling_values[i] != "no"; set_scrolling_property(root->current_frame_host(), scrolling_values[i]); for (size_t j = 0; j < arraysize(urls); ++j) { NavigateFrameToURL(child, urls[j]); EXPECT_EQ(expect_scrollbar, has_scrollbar(child->current_frame_host())); } } } // Verify that "marginwidth" and "marginheight" properties on frame elements // propagate to child frames correctly. IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, FrameOwnerPropertiesPropagationMargin) { GURL main_url(embedded_test_server()->GetURL( "a.com", "/frame_owner_properties_margin.html")); NavigateToURL(shell(), main_url); // It is safe to obtain the root frame tree node here, as it doesn't change. FrameTreeNode* root = web_contents()->GetFrameTree()->root(); ASSERT_EQ(1u, root->child_count()); EXPECT_EQ( " Site A ------------ proxies for B\n" " +--Site B ------- proxies for A\n" "Where A = http://a.com/\n" " B = http://b.com/", DepictFrameTree(root)); FrameTreeNode* child = root->child_at(0); std::string margin_width; EXPECT_TRUE(ExecuteScriptAndExtractString( child, "window.domAutomationController.send(" "document.body.getAttribute('marginwidth'));", &margin_width)); EXPECT_EQ("10", margin_width); std::string margin_height; EXPECT_TRUE(ExecuteScriptAndExtractString( child, "window.domAutomationController.send(" "document.body.getAttribute('marginheight'));", &margin_height)); EXPECT_EQ("50", margin_height); // Run the test over variety of parent/child cases. GURL urls[] = { // Remote to remote. embedded_test_server()->GetURL("c.com", "/title2.html"), // Remote to local. embedded_test_server()->GetURL("a.com", "/title1.html"), // Local to remote. embedded_test_server()->GetURL("b.com", "/title2.html") }; int current_margin_width = 15; int current_margin_height = 25; // Before each navigation, we change the marginwidth and marginheight // properties of the frame. We then check whether those properties are applied // correctly after the navigation has completed. for (size_t i = 0; i < arraysize(urls); ++i) { // Change marginwidth and marginheight before navigating. EXPECT_TRUE(ExecuteScript( root, base::StringPrintf("document.getElementById('child-1').setAttribute(" " 'marginwidth', '%d');", current_margin_width))); EXPECT_TRUE(ExecuteScript( root, base::StringPrintf("document.getElementById('child-1').setAttribute(" " 'marginheight', '%d');", current_margin_height))); NavigateFrameToURL(child, urls[i]); std::string actual_margin_width; EXPECT_TRUE(ExecuteScriptAndExtractString( child, "window.domAutomationController.send(" "document.body.getAttribute('marginwidth'));", &actual_margin_width)); EXPECT_EQ(base::IntToString(current_margin_width), actual_margin_width); std::string actual_margin_height; EXPECT_TRUE(ExecuteScriptAndExtractString( child, "window.domAutomationController.send(" "document.body.getAttribute('marginheight'));", &actual_margin_height)); EXPECT_EQ(base::IntToString(current_margin_height), actual_margin_height); current_margin_width += 5; current_margin_height += 10; } } // Verify that "csp" property on frame elements propagates to child frames // correctly. See https://crbug.com/647588 IN_PROC_BROWSER_TEST_F(SitePerProcessEmbedderCSPEnforcementBrowserTest, FrameOwnerPropertiesPropagationCSP) { GURL main_url(embedded_test_server()->GetURL( "a.com", "/frame_owner_properties_csp.html")); EXPECT_TRUE(NavigateToURL(shell(), main_url)); // It is safe to obtain the root frame tree node here, as it doesn't change. FrameTreeNode* root = web_contents()->GetFrameTree()->root(); ASSERT_EQ(1u, root->child_count()); EXPECT_EQ( " Site A ------------ proxies for B\n" " +--Site B ------- proxies for A\n" "Where A = http://a.com/\n" " B = http://b.com/", DepictFrameTree(root)); FrameTreeNode* child = root->child_at(0); std::string csp; EXPECT_TRUE(ExecuteScriptAndExtractString( root, "window.domAutomationController.send(" "document.getElementById('child-1').getAttribute('csp'));", &csp)); EXPECT_EQ("object-src \'none\'", csp); // Run the test over variety of parent/child cases. GURL urls[] = {// Remote to remote. embedded_test_server()->GetURL("c.com", "/title2.html"), // Remote to local. embedded_test_server()->GetURL("a.com", "/title1.html"), // Local to remote. embedded_test_server()->GetURL("b.com", "/title2.html")}; std::vector<std::string> csp_values = {"default-src a.com", "default-src b.com", "img-src c.com"}; // Before each navigation, we change the csp property of the frame. // We then check whether that property is applied // correctly after the navigation has completed. for (size_t i = 0; i < arraysize(urls); ++i) { // Change csp before navigating. EXPECT_TRUE(ExecuteScript( root, base::StringPrintf("document.getElementById('child-1').setAttribute(" " 'csp', '%s');", csp_values[i].c_str()))); NavigateFrameToURL(child, urls[i]); EXPECT_EQ(csp_values[i], child->frame_owner_properties().required_csp); // TODO(amalika): add checks that the CSP replication takes effect } } // Verify origin replication with an A-embed-B-embed-C-embed-A hierarchy. IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, OriginReplication) { GURL main_url(embedded_test_server()->GetURL( "a.com", "/cross_site_iframe_factory.html?a(b(c(a),b), a)")); EXPECT_TRUE(NavigateToURL(shell(), main_url)); // It is safe to obtain the root frame tree node here, as it doesn't change. FrameTreeNode* root = web_contents()->GetFrameTree()->root(); EXPECT_EQ( " Site A ------------ proxies for B C\n" " |--Site B ------- proxies for A C\n" // tiptop_child " | |--Site C -- proxies for A B\n" // middle_child " | | +--Site A -- proxies for B C\n" // lowest_child " | +--Site B -- proxies for A C\n" " +--Site A ------- proxies for B C\n" "Where A = http://a.com/\n" " B = http://b.com/\n" " C = http://c.com/", DepictFrameTree(root)); std::string a_origin = embedded_test_server()->GetURL("a.com", "/").spec(); std::string b_origin = embedded_test_server()->GetURL("b.com", "/").spec(); std::string c_origin = embedded_test_server()->GetURL("c.com", "/").spec(); FrameTreeNode* tiptop_child = root->child_at(0); FrameTreeNode* middle_child = root->child_at(0)->child_at(0); FrameTreeNode* lowest_child = root->child_at(0)->child_at(0)->child_at(0); // Check that b.com frame's location.ancestorOrigins contains the correct // origin for the parent. The origin should have been replicated as part of // the mojom::Renderer::CreateView message that created the parent's // RenderFrameProxy in b.com's process. int ancestor_origins_length = 0; EXPECT_TRUE(ExecuteScriptAndExtractInt( tiptop_child, "window.domAutomationController.send(location.ancestorOrigins.length);", &ancestor_origins_length)); EXPECT_EQ(1, ancestor_origins_length); std::string result; EXPECT_TRUE(ExecuteScriptAndExtractString( tiptop_child, "window.domAutomationController.send(location.ancestorOrigins[0]);", &result)); EXPECT_EQ(a_origin, result + "/"); // Check that c.com frame's location.ancestorOrigins contains the correct // origin for its two ancestors. The topmost parent origin should be // replicated as part of mojom::Renderer::CreateView, and the middle frame // (b.com's) origin should be replicated as part of // mojom::Renderer::CreateFrameProxy sent for b.com's frame in c.com's // process. EXPECT_TRUE(ExecuteScriptAndExtractInt( middle_child, "window.domAutomationController.send(location.ancestorOrigins.length);", &ancestor_origins_length)); EXPECT_EQ(2, ancestor_origins_length); EXPECT_TRUE(ExecuteScriptAndExtractString( middle_child, "window.domAutomationController.send(location.ancestorOrigins[0]);", &result)); EXPECT_EQ(b_origin, result + "/"); EXPECT_TRUE(ExecuteScriptAndExtractString( middle_child, "window.domAutomationController.send(location.ancestorOrigins[1]);", &result)); EXPECT_EQ(a_origin, result + "/"); // Check that the nested a.com frame's location.ancestorOrigins contains the // correct origin for its three ancestors. EXPECT_TRUE(ExecuteScriptAndExtractInt( lowest_child, "window.domAutomationController.send(location.ancestorOrigins.length);", &ancestor_origins_length)); EXPECT_EQ(3, ancestor_origins_length); EXPECT_TRUE(ExecuteScriptAndExtractString( lowest_child, "window.domAutomationController.send(location.ancestorOrigins[0]);", &result)); EXPECT_EQ(c_origin, result + "/"); EXPECT_TRUE(ExecuteScriptAndExtractString( lowest_child, "window.domAutomationController.send(location.ancestorOrigins[1]);", &result)); EXPECT_EQ(b_origin, result + "/"); EXPECT_TRUE(ExecuteScriptAndExtractString( lowest_child, "window.domAutomationController.send(location.ancestorOrigins[2]);", &result)); EXPECT_EQ(a_origin, result + "/"); } // Check that iframe sandbox flags are replicated correctly. IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, SandboxFlagsReplication) { GURL main_url(embedded_test_server()->GetURL("/sandboxed_frames.html")); EXPECT_TRUE(NavigateToURL(shell(), main_url)); // It is safe to obtain the root frame tree node here, as it doesn't change. FrameTreeNode* root = web_contents()->GetFrameTree()->root(); TestNavigationObserver observer(shell()->web_contents()); // Navigate the second (sandboxed) subframe to a cross-site page with a // subframe. GURL foo_url( embedded_test_server()->GetURL("foo.com", "/frame_tree/1-1.html")); NavigateFrameToURL(root->child_at(1), foo_url); EXPECT_TRUE(WaitForLoadStop(shell()->web_contents())); // We can't use a TestNavigationObserver to verify the URL here, // since the frame has children that may have clobbered it in the observer. EXPECT_EQ(foo_url, root->child_at(1)->current_url()); // Load cross-site page into subframe's subframe. ASSERT_EQ(2U, root->child_at(1)->child_count()); GURL bar_url(embedded_test_server()->GetURL("bar.com", "/title1.html")); NavigateFrameToURL(root->child_at(1)->child_at(0), bar_url); EXPECT_TRUE(observer.last_navigation_succeeded()); EXPECT_EQ(bar_url, observer.last_navigation_url()); // Opening a popup in the sandboxed foo.com iframe should fail. bool success = false; EXPECT_TRUE( ExecuteScriptAndExtractBool(root->child_at(1), "window.domAutomationController.send(" "!window.open('data:text/html,dataurl'));", &success)); EXPECT_TRUE(success); EXPECT_EQ(1u, Shell::windows().size()); // Opening a popup in a frame whose parent is sandboxed should also fail. // Here, bar.com frame's sandboxed parent frame is a remote frame in // bar.com's process. success = false; EXPECT_TRUE( ExecuteScriptAndExtractBool(root->child_at(1)->child_at(0), "window.domAutomationController.send(" "!window.open('data:text/html,dataurl'));", &success)); EXPECT_TRUE(success); EXPECT_EQ(1u, Shell::windows().size()); // Same, but now try the case where bar.com frame's sandboxed parent is a // local frame in bar.com's process. success = false; EXPECT_TRUE( ExecuteScriptAndExtractBool(root->child_at(2)->child_at(0), "window.domAutomationController.send(" "!window.open('data:text/html,dataurl'));", &success)); EXPECT_TRUE(success); EXPECT_EQ(1u, Shell::windows().size()); // Check that foo.com frame's location.ancestorOrigins contains the correct // origin for the parent, which should be unaffected by sandboxing. int ancestor_origins_length = 0; EXPECT_TRUE(ExecuteScriptAndExtractInt( root->child_at(1), "window.domAutomationController.send(location.ancestorOrigins.length);", &ancestor_origins_length)); EXPECT_EQ(1, ancestor_origins_length); std::string result; EXPECT_TRUE(ExecuteScriptAndExtractString( root->child_at(1), "window.domAutomationController.send(location.ancestorOrigins[0]);", &result)); EXPECT_EQ(result + "/", main_url.GetOrigin().spec()); // Now check location.ancestorOrigins for the bar.com frame. The middle frame // (foo.com's) origin should be unique, since that frame is sandboxed, and // the top frame should match |main_url|. FrameTreeNode* bottom_child = root->child_at(1)->child_at(0); EXPECT_TRUE(ExecuteScriptAndExtractInt( bottom_child, "window.domAutomationController.send(location.ancestorOrigins.length);", &ancestor_origins_length)); EXPECT_EQ(2, ancestor_origins_length); EXPECT_TRUE(ExecuteScriptAndExtractString( bottom_child, "window.domAutomationController.send(location.ancestorOrigins[0]);", &result)); EXPECT_EQ("null", result); EXPECT_TRUE(ExecuteScriptAndExtractString( bottom_child, "window.domAutomationController.send(location.ancestorOrigins[1]);", &result)); EXPECT_EQ(main_url.GetOrigin().spec(), result + "/"); } // Check that dynamic updates to iframe sandbox flags are propagated correctly. IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, DynamicSandboxFlags) { GURL main_url( embedded_test_server()->GetURL("/frame_tree/page_with_two_frames.html")); EXPECT_TRUE(NavigateToURL(shell(), main_url)); // It is safe to obtain the root frame tree node here, as it doesn't change. FrameTreeNode* root = web_contents()->GetFrameTree()->root(); TestNavigationObserver observer(shell()->web_contents()); ASSERT_EQ(2U, root->child_count()); // Make sure first frame starts out at the correct cross-site page. EXPECT_EQ(embedded_test_server()->GetURL("bar.com", "/title1.html"), root->child_at(0)->current_url()); // Navigate second frame to another cross-site page. GURL baz_url(embedded_test_server()->GetURL("baz.com", "/title1.html")); NavigateFrameToURL(root->child_at(1), baz_url); EXPECT_TRUE(observer.last_navigation_succeeded()); EXPECT_EQ(baz_url, observer.last_navigation_url()); // Both frames should not be sandboxed to start with. EXPECT_EQ(blink::WebSandboxFlags::None, root->child_at(0)->pending_sandbox_flags()); EXPECT_EQ(blink::WebSandboxFlags::None, root->child_at(0)->effective_sandbox_flags()); EXPECT_EQ(blink::WebSandboxFlags::None, root->child_at(1)->pending_sandbox_flags()); EXPECT_EQ(blink::WebSandboxFlags::None, root->child_at(1)->effective_sandbox_flags()); // Dynamically update sandbox flags for the first frame. EXPECT_TRUE(ExecuteScript( shell(), "document.querySelector('iframe').sandbox='allow-scripts';")); // Check that updated sandbox flags are propagated to browser process. // The new flags should be reflected in pending_sandbox_flags(), while // effective_sandbox_flags() should still reflect the old flags, because // sandbox flag updates take place only after navigations. "allow-scripts" // resets both SandboxFlags::Scripts and SandboxFlags::AutomaticFeatures bits // per blink::parseSandboxPolicy(). blink::WebSandboxFlags expected_flags = blink::WebSandboxFlags::All & ~blink::WebSandboxFlags::Scripts & ~blink::WebSandboxFlags::AutomaticFeatures; EXPECT_EQ(expected_flags, root->child_at(0)->pending_sandbox_flags()); EXPECT_EQ(blink::WebSandboxFlags::None, root->child_at(0)->effective_sandbox_flags()); // Navigate the first frame to a page on the same site. The new sandbox // flags should take effect. GURL bar_url( embedded_test_server()->GetURL("bar.com", "/frame_tree/2-4.html")); NavigateFrameToURL(root->child_at(0), bar_url); // (The new page has a subframe; wait for it to load as well.) ASSERT_TRUE(WaitForLoadStop(shell()->web_contents())); EXPECT_EQ(bar_url, root->child_at(0)->current_url()); ASSERT_EQ(1U, root->child_at(0)->child_count()); EXPECT_EQ( " Site A ------------ proxies for B C\n" " |--Site B ------- proxies for A C\n" " | +--Site B -- proxies for A C\n" " +--Site C ------- proxies for A B\n" "Where A = http://127.0.0.1/\n" " B = http://bar.com/\n" " C = http://baz.com/", DepictFrameTree(root)); // Confirm that the browser process has updated the frame's current sandbox // flags. EXPECT_EQ(expected_flags, root->child_at(0)->pending_sandbox_flags()); EXPECT_EQ(expected_flags, root->child_at(0)->effective_sandbox_flags()); // Opening a popup in the now-sandboxed frame should fail. bool success = false; EXPECT_TRUE(ExecuteScriptAndExtractBool( root->child_at(0), "window.domAutomationController.send(" " !window.open('data:text/html,dataurl'));", &success)); EXPECT_TRUE(success); EXPECT_EQ(1u, Shell::windows().size()); // Navigate the child of the now-sandboxed frame to a page on baz.com. The // child should inherit the latest sandbox flags from its parent frame, which // is currently a proxy in baz.com's renderer process. This checks that the // proxies of |root->child_at(0)| were also updated with the latest sandbox // flags. GURL baz_child_url(embedded_test_server()->GetURL("baz.com", "/title2.html")); NavigateFrameToURL(root->child_at(0)->child_at(0), baz_child_url); EXPECT_TRUE(observer.last_navigation_succeeded()); EXPECT_EQ(baz_child_url, observer.last_navigation_url()); EXPECT_EQ( " Site A ------------ proxies for B C\n" " |--Site B ------- proxies for A C\n" " | +--Site C -- proxies for A B\n" " +--Site C ------- proxies for A B\n" "Where A = http://127.0.0.1/\n" " B = http://bar.com/\n" " C = http://baz.com/", DepictFrameTree(root)); // Opening a popup in the child of a sandboxed frame should fail. success = false; EXPECT_TRUE(ExecuteScriptAndExtractBool( root->child_at(0)->child_at(0), "window.domAutomationController.send(" " !window.open('data:text/html,dataurl'));", &success)); EXPECT_TRUE(success); EXPECT_EQ(1u, Shell::windows().size()); // Child of a sandboxed frame should also be sandboxed on the browser side. EXPECT_EQ(expected_flags, root->child_at(0)->child_at(0)->effective_sandbox_flags()); } // Check that dynamic updates to iframe sandbox flags are propagated correctly. IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, DynamicSandboxFlagsRemoteToLocal) { GURL main_url( embedded_test_server()->GetURL("/frame_tree/page_with_two_frames.html")); EXPECT_TRUE(NavigateToURL(shell(), main_url)); // It is safe to obtain the root frame tree node here, as it doesn't change. FrameTreeNode* root = web_contents()->GetFrameTree()->root(); TestNavigationObserver observer(shell()->web_contents()); ASSERT_EQ(2U, root->child_count()); // Make sure the two frames starts out at correct URLs. EXPECT_EQ(embedded_test_server()->GetURL("bar.com", "/title1.html"), root->child_at(0)->current_url()); EXPECT_EQ(embedded_test_server()->GetURL("/title1.html"), root->child_at(1)->current_url()); // Update the second frame's sandbox flags. EXPECT_TRUE(ExecuteScript( shell(), "document.querySelectorAll('iframe')[1].sandbox='allow-scripts'")); // Check that the current sandbox flags are updated but the effective // sandbox flags are not. blink::WebSandboxFlags expected_flags = blink::WebSandboxFlags::All & ~blink::WebSandboxFlags::Scripts & ~blink::WebSandboxFlags::AutomaticFeatures; EXPECT_EQ(expected_flags, root->child_at(1)->pending_sandbox_flags()); EXPECT_EQ(blink::WebSandboxFlags::None, root->child_at(1)->effective_sandbox_flags()); // Navigate the second subframe to a page on bar.com. This will trigger a // remote-to-local frame swap in bar.com's process. GURL bar_url(embedded_test_server()->GetURL( "bar.com", "/frame_tree/page_with_one_frame.html")); NavigateFrameToURL(root->child_at(1), bar_url); EXPECT_EQ(bar_url, root->child_at(1)->current_url()); ASSERT_EQ(1U, root->child_at(1)->child_count()); // Confirm that the browser process has updated the current sandbox flags. EXPECT_EQ(expected_flags, root->child_at(1)->pending_sandbox_flags()); EXPECT_EQ(expected_flags, root->child_at(1)->effective_sandbox_flags()); // Opening a popup in the sandboxed second frame should fail. bool success = false; EXPECT_TRUE(ExecuteScriptAndExtractBool( root->child_at(1), "window.domAutomationController.send(" " !window.open('data:text/html,dataurl'));", &success)); EXPECT_TRUE(success); EXPECT_EQ(1u, Shell::windows().size()); // Make sure that the child frame inherits the sandbox flags of its // now-sandboxed parent frame. success = false; EXPECT_TRUE(ExecuteScriptAndExtractBool( root->child_at(1)->child_at(0), "window.domAutomationController.send(" " !window.open('data:text/html,dataurl'));", &success)); EXPECT_TRUE(success); EXPECT_EQ(1u, Shell::windows().size()); } // Check that dynamic updates to iframe sandbox flags are propagated correctly. IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, DynamicSandboxFlagsRendererInitiatedNavigation) { GURL main_url( embedded_test_server()->GetURL("/frame_tree/page_with_one_frame.html")); EXPECT_TRUE(NavigateToURL(shell(), main_url)); // It is safe to obtain the root frame tree node here, as it doesn't change. FrameTreeNode* root = web_contents()->GetFrameTree()->root(); TestNavigationObserver observer(shell()->web_contents()); ASSERT_EQ(1U, root->child_count()); // Make sure the frame starts out at the correct cross-site page. EXPECT_EQ(embedded_test_server()->GetURL("baz.com", "/title1.html"), root->child_at(0)->current_url()); // The frame should not be sandboxed to start with. EXPECT_EQ(blink::WebSandboxFlags::None, root->child_at(0)->pending_sandbox_flags()); EXPECT_EQ(blink::WebSandboxFlags::None, root->child_at(0)->effective_sandbox_flags()); // Dynamically update the frame's sandbox flags. EXPECT_TRUE(ExecuteScript( shell(), "document.querySelector('iframe').sandbox='allow-scripts';")); // Check that updated sandbox flags are propagated to browser process. // The new flags should be set in pending_sandbox_flags(), while // effective_sandbox_flags() should still reflect the old flags, because // sandbox flag updates take place only after navigations. "allow-scripts" // resets both SandboxFlags::Scripts and SandboxFlags::AutomaticFeatures bits // per blink::parseSandboxPolicy(). blink::WebSandboxFlags expected_flags = blink::WebSandboxFlags::All & ~blink::WebSandboxFlags::Scripts & ~blink::WebSandboxFlags::AutomaticFeatures; EXPECT_EQ(expected_flags, root->child_at(0)->pending_sandbox_flags()); EXPECT_EQ(blink::WebSandboxFlags::None, root->child_at(0)->effective_sandbox_flags()); // Perform a renderer-initiated same-site navigation in the first frame. The // new sandbox flags should take effect. TestFrameNavigationObserver frame_observer(root->child_at(0)); ASSERT_TRUE( ExecuteScript(root->child_at(0), "window.location.href='/title2.html'")); frame_observer.Wait(); EXPECT_EQ(embedded_test_server()->GetURL("baz.com", "/title2.html"), root->child_at(0)->current_url()); // Confirm that the browser process has updated the frame's current sandbox // flags. EXPECT_EQ(expected_flags, root->child_at(0)->pending_sandbox_flags()); EXPECT_EQ(expected_flags, root->child_at(0)->effective_sandbox_flags()); // Opening a popup in the now-sandboxed frame should fail. bool success = false; EXPECT_TRUE(ExecuteScriptAndExtractBool( root->child_at(0), "window.domAutomationController.send(" " !window.open('data:text/html,dataurl'));", &success)); EXPECT_TRUE(success); EXPECT_EQ(1u, Shell::windows().size()); } // Verify that when a new child frame is added, the proxies created for it in // other SiteInstances have correct sandbox flags and origin. // // A A A // / / \ / \ . // B -> B A -> B A // \ . // B // // The test checks sandbox flags and origin for the proxy added in step 2, by // checking whether the grandchild frame added in step 3 sees proper sandbox // flags and origin for its (remote) parent. This wasn't addressed when // https://crbug.com/423587 was fixed. // TODO(alexmos): Re-enable when https://crbug.com/610893 is fixed. IN_PROC_BROWSER_TEST_F( SitePerProcessBrowserTest, DISABLED_ProxiesForNewChildFramesHaveCorrectReplicationState) { GURL main_url( embedded_test_server()->GetURL("/frame_tree/page_with_one_frame.html")); EXPECT_TRUE(NavigateToURL(shell(), main_url)); // It is safe to obtain the root frame tree node here, as it doesn't change. FrameTreeNode* root = web_contents()->GetFrameTree()->root(); TestNavigationObserver observer(shell()->web_contents()); EXPECT_EQ( " Site A ------------ proxies for B\n" " +--Site B ------- proxies for A\n" "Where A = http://127.0.0.1/\n" " B = http://baz.com/", DepictFrameTree(root)); // In the root frame, add a new sandboxed local frame, which itself has a // child frame on baz.com. Wait for three RenderFrameHosts to be created: // the new sandboxed local frame, its child (while it's still local), and a // pending RFH when starting the cross-site navigation to baz.com. RenderFrameHostCreatedObserver frame_observer(shell()->web_contents(), 3); EXPECT_TRUE(ExecuteScript(root, "addFrame('/frame_tree/page_with_one_frame.html'," " 'allow-scripts allow-same-origin'))")); frame_observer.Wait(); // Wait for the cross-site navigation to baz.com in the grandchild to finish. FrameTreeNode* bottom_child = root->child_at(1)->child_at(0); TestFrameNavigationObserver navigation_observer(bottom_child); navigation_observer.Wait(); EXPECT_EQ( " Site A ------------ proxies for B\n" " |--Site B ------- proxies for A\n" " +--Site A ------- proxies for B\n" " +--Site B -- proxies for A\n" "Where A = http://127.0.0.1/\n" " B = http://baz.com/", DepictFrameTree(root)); // Use location.ancestorOrigins to check that the grandchild on baz.com sees // correct origin for its parent. int ancestor_origins_length = 0; EXPECT_TRUE(ExecuteScriptAndExtractInt( bottom_child, "window.domAutomationController.send(location.ancestorOrigins.length);", &ancestor_origins_length)); EXPECT_EQ(2, ancestor_origins_length); std::string parent_origin; EXPECT_TRUE(ExecuteScriptAndExtractString( bottom_child, "window.domAutomationController.send(location.ancestorOrigins[0]);", &parent_origin)); EXPECT_EQ(main_url.GetOrigin().spec(), parent_origin + "/"); // Check that the sandbox flags in the browser process are correct. // "allow-scripts" resets both WebSandboxFlags::Scripts and // WebSandboxFlags::AutomaticFeatures bits per blink::parseSandboxPolicy(). blink::WebSandboxFlags expected_flags = blink::WebSandboxFlags::All & ~blink::WebSandboxFlags::Scripts & ~blink::WebSandboxFlags::AutomaticFeatures & ~blink::WebSandboxFlags::Origin; EXPECT_EQ(expected_flags, root->child_at(1)->effective_sandbox_flags()); // The child of the sandboxed frame should've inherited sandbox flags, so it // should not be able to create popups. EXPECT_EQ(expected_flags, bottom_child->effective_sandbox_flags()); bool success = false; EXPECT_TRUE(ExecuteScriptAndExtractBool( bottom_child, "window.domAutomationController.send(" " !window.open('data:text/html,dataurl'));", &success)); EXPECT_TRUE(success); EXPECT_EQ(1u, Shell::windows().size()); } // Verify that a child frame can retrieve the name property set by its parent. IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, WindowNameReplication) { GURL main_url(embedded_test_server()->GetURL("/frame_tree/2-4.html")); EXPECT_TRUE(NavigateToURL(shell(), main_url)); // It is safe to obtain the root frame tree node here, as it doesn't change. FrameTreeNode* root = web_contents()->GetFrameTree()->root(); TestNavigationObserver observer(shell()->web_contents()); // Load cross-site page into iframe. GURL frame_url = embedded_test_server()->GetURL("foo.com", "/frame_tree/3-1.html"); NavigateFrameToURL(root->child_at(0), frame_url); EXPECT_TRUE(observer.last_navigation_succeeded()); EXPECT_EQ(frame_url, observer.last_navigation_url()); // Ensure that a new process is created for the subframe. EXPECT_NE(shell()->web_contents()->GetSiteInstance(), root->child_at(0)->current_frame_host()->GetSiteInstance()); // Check that the window.name seen by the frame matches the name attribute // specified by its parent in the iframe tag. std::string result; EXPECT_TRUE(ExecuteScriptAndExtractString( root->child_at(0), "window.domAutomationController.send(window.name);", &result)); EXPECT_EQ("3-1-name", result); } // Verify that dynamic updates to a frame's window.name propagate to the // frame's proxies, so that the latest frame names can be used in navigations. IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, DynamicWindowName) { GURL main_url(embedded_test_server()->GetURL("/frame_tree/2-4.html")); EXPECT_TRUE(NavigateToURL(shell(), main_url)); // It is safe to obtain the root frame tree node here, as it doesn't change. FrameTreeNode* root = web_contents()->GetFrameTree()->root(); TestNavigationObserver observer(shell()->web_contents()); // Load cross-site page into iframe. GURL frame_url = embedded_test_server()->GetURL("foo.com", "/frame_tree/3-1.html"); NavigateFrameToURL(root->child_at(0), frame_url); EXPECT_TRUE(observer.last_navigation_succeeded()); EXPECT_EQ(frame_url, observer.last_navigation_url()); // Browser process should know the child frame's original window.name // specified in the iframe element. EXPECT_EQ(root->child_at(0)->frame_name(), "3-1-name"); // Update the child frame's window.name. EXPECT_TRUE( ExecuteScript(root->child_at(0), "window.name = 'updated-name';")); // The change should propagate to the browser process. EXPECT_EQ(root->child_at(0)->frame_name(), "updated-name"); // The proxy in the parent process should also receive the updated name. // Check that it can reference the child frame by its new name. bool success = false; EXPECT_TRUE( ExecuteScriptAndExtractBool(shell(), "window.domAutomationController.send(" " frames['updated-name'] == frames[0]);", &success)); EXPECT_TRUE(success); // Issue a renderer-initiated navigation from the root frame to the child // frame using the frame's name. Make sure correct frame is navigated. // // TODO(alexmos): When blink::createWindow is refactored to handle // RemoteFrames, this should also be tested via window.open(url, frame_name) // and a more complicated frame hierarchy (https://crbug.com/463742) TestFrameNavigationObserver frame_observer(root->child_at(0)); GURL foo_url(embedded_test_server()->GetURL("foo.com", "/title1.html")); EXPECT_TRUE(ExecuteScript( shell(), base::StringPrintf("frames['updated-name'].location.href = '%s';", foo_url.spec().c_str()))); frame_observer.Wait(); EXPECT_EQ(foo_url, root->child_at(0)->current_url()); } // Verify that when a frame is navigated to a new origin, the origin update // propagates to the frame's proxies. IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, OriginUpdatesReachProxies) { GURL main_url( embedded_test_server()->GetURL("/frame_tree/page_with_two_frames.html")); EXPECT_TRUE(NavigateToURL(shell(), main_url)); // It is safe to obtain the root frame tree node here, as it doesn't change. FrameTreeNode* root = web_contents()->GetFrameTree()->root(); TestNavigationObserver observer(shell()->web_contents()); EXPECT_EQ( " Site A ------------ proxies for B\n" " |--Site B ------- proxies for A\n" " +--Site A ------- proxies for B\n" "Where A = http://127.0.0.1/\n" " B = http://bar.com/", DepictFrameTree(root)); // Navigate second subframe to a baz.com. This should send an origin update // to the frame's proxy in the bar.com (first frame's) process. GURL frame_url = embedded_test_server()->GetURL("baz.com", "/title2.html"); NavigateFrameToURL(root->child_at(1), frame_url); EXPECT_TRUE(observer.last_navigation_succeeded()); EXPECT_EQ(frame_url, observer.last_navigation_url()); // The first frame can't directly observe the second frame's origin with // JavaScript. Instead, try to navigate the second frame from the first // frame. This should fail with a console error message, which should // contain the second frame's updated origin (see blink::Frame::canNavigate). std::unique_ptr<ConsoleObserverDelegate> console_delegate( new ConsoleObserverDelegate( shell()->web_contents(), "Unsafe JavaScript attempt to initiate navigation*")); shell()->web_contents()->SetDelegate(console_delegate.get()); // frames[1] can't be used due to a bug where RemoteFrames are created out of // order (https://crbug.com/478792). Instead, target second frame by name. EXPECT_TRUE(ExecuteScript(root->child_at(0), "try { parent.frames['frame2'].location.href = " "'data:text/html,foo'; } catch (e) {}")); console_delegate->Wait(); std::string frame_origin = root->child_at(1)->current_origin().Serialize(); EXPECT_EQ(frame_origin + "/", frame_url.GetOrigin().spec()); EXPECT_TRUE( base::MatchPattern(console_delegate->message(), "*" + frame_origin + "*")) << "Error message does not contain the frame's latest origin (" << frame_origin << ")"; } // Ensure that navigating subframes in --site-per-process mode properly fires // the DidStopLoading event on WebContentsObserver. IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, CrossSiteDidStopLoading) { GURL main_url(embedded_test_server()->GetURL("/site_per_process_main.html")); NavigateToURL(shell(), main_url); // It is safe to obtain the root frame tree node here, as it doesn't change. FrameTreeNode* root = web_contents()->GetFrameTree()->root(); TestNavigationObserver observer(shell()->web_contents()); // Load same-site page into iframe. FrameTreeNode* child = root->child_at(0); GURL http_url(embedded_test_server()->GetURL("/title1.html")); NavigateFrameToURL(child, http_url); EXPECT_EQ(http_url, observer.last_navigation_url()); EXPECT_TRUE(observer.last_navigation_succeeded()); // Load cross-site page into iframe. TestNavigationObserver nav_observer(shell()->web_contents(), 1); GURL url = embedded_test_server()->GetURL("foo.com", "/title2.html"); NavigationController::LoadURLParams params(url); params.transition_type = ui::PAGE_TRANSITION_LINK; params.frame_tree_node_id = child->frame_tree_node_id(); child->navigator()->GetController()->LoadURLWithParams(params); nav_observer.Wait(); // Verify that the navigation succeeded and the expected URL was loaded. EXPECT_TRUE(observer.last_navigation_succeeded()); EXPECT_EQ(url, observer.last_navigation_url()); } // Ensure that the renderer does not crash when navigating a frame that has a // sibling RemoteFrame. See https://crbug.com/426953. IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, NavigateWithSiblingRemoteFrame) { GURL main_url( embedded_test_server()->GetURL("/frame_tree/page_with_two_frames.html")); NavigateToURL(shell(), main_url); // It is safe to obtain the root frame tree node here, as it doesn't change. FrameTreeNode* root = web_contents()->GetFrameTree()->root(); TestNavigationObserver observer(shell()->web_contents()); // Make sure the first frame is out of process. ASSERT_EQ(2U, root->child_count()); FrameTreeNode* node2 = root->child_at(0); EXPECT_NE(root->current_frame_host()->GetSiteInstance(), node2->current_frame_host()->GetSiteInstance()); // Make sure the second frame is in the parent's process. FrameTreeNode* node3 = root->child_at(1); EXPECT_EQ(root->current_frame_host()->GetSiteInstance(), node3->current_frame_host()->GetSiteInstance()); // Navigate the second iframe (node3) to a URL in its own process. GURL title_url = embedded_test_server()->GetURL("/title2.html"); NavigateFrameToURL(node3, title_url); EXPECT_TRUE(observer.last_navigation_succeeded()); EXPECT_EQ(title_url, observer.last_navigation_url()); EXPECT_EQ(root->current_frame_host()->GetSiteInstance(), node3->current_frame_host()->GetSiteInstance()); EXPECT_TRUE(node3->current_frame_host()->IsRenderFrameLive()); } // Ensure that the renderer does not crash when a local frame with a remote // parent frame is swapped from local to remote, then back to local again. // See https://crbug.com/585654. IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, NavigateSiblingsToSameProcess) { GURL main_url( embedded_test_server()->GetURL("/frame_tree/page_with_two_frames.html")); NavigateToURL(shell(), main_url); // It is safe to obtain the root frame tree node here, as it doesn't change. FrameTreeNode* root = web_contents()->GetFrameTree()->root(); FrameTreeNode* node2 = root->child_at(0); FrameTreeNode* node3 = root->child_at(1); // Navigate the second iframe to the same process as the first. GURL frame_url = embedded_test_server()->GetURL("bar.com", "/title1.html"); NavigateFrameToURL(node3, frame_url); // Verify that they are in the same process. EXPECT_EQ(node2->current_frame_host()->GetSiteInstance(), node3->current_frame_host()->GetSiteInstance()); EXPECT_NE(root->current_frame_host()->GetSiteInstance(), node3->current_frame_host()->GetSiteInstance()); // Navigate the first iframe into its parent's process. GURL title_url = embedded_test_server()->GetURL("/title2.html"); NavigateFrameToURL(node2, title_url); EXPECT_NE(node2->current_frame_host()->GetSiteInstance(), node3->current_frame_host()->GetSiteInstance()); // Return the first iframe to the same process as its sibling, and ensure // that it does not crash. NavigateFrameToURL(node2, frame_url); EXPECT_EQ(node2->current_frame_host()->GetSiteInstance(), node3->current_frame_host()->GetSiteInstance()); EXPECT_TRUE(node2->current_frame_host()->IsRenderFrameLive()); } // Verify that load events for iframe elements work when the child frame is // out-of-process. In such cases, the load event is forwarded from the child // frame to the parent frame via the browser process. IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, LoadEventForwarding) { // Load a page with a cross-site frame. The parent page has an onload // handler in the iframe element that appends "LOADED" to the document title. { GURL main_url( embedded_test_server()->GetURL("/frame_with_load_event.html")); base::string16 expected_title(base::UTF8ToUTF16("LOADED")); TitleWatcher title_watcher(shell()->web_contents(), expected_title); EXPECT_TRUE(NavigateToURL(shell(), main_url)); EXPECT_EQ(title_watcher.WaitAndGetTitle(), expected_title); } // It is safe to obtain the root frame tree node here, as it doesn't change. FrameTreeNode* root = web_contents()->GetFrameTree()->root(); // Load another cross-site page into the iframe and check that the load event // is fired. { GURL foo_url(embedded_test_server()->GetURL("foo.com", "/title1.html")); base::string16 expected_title(base::UTF8ToUTF16("LOADEDLOADED")); TitleWatcher title_watcher(shell()->web_contents(), expected_title); TestNavigationObserver observer(shell()->web_contents()); NavigateFrameToURL(root->child_at(0), foo_url); EXPECT_TRUE(observer.last_navigation_succeeded()); EXPECT_EQ(foo_url, observer.last_navigation_url()); EXPECT_EQ(title_watcher.WaitAndGetTitle(), expected_title); } } // Check that postMessage can be routed between cross-site iframes. IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, SubframePostMessage) { GURL main_url(embedded_test_server()->GetURL( "/frame_tree/page_with_post_message_frames.html")); EXPECT_TRUE(NavigateToURL(shell(), main_url)); // It is safe to obtain the root frame tree node here, as it doesn't change. FrameTreeNode* root = web_contents()->GetFrameTree()->root(); ASSERT_EQ(2U, root->child_count()); // Verify the frames start at correct URLs. First frame should be // same-site; second frame should be cross-site. GURL same_site_url(embedded_test_server()->GetURL("/post_message.html")); EXPECT_EQ(same_site_url, root->child_at(0)->current_url()); GURL foo_url(embedded_test_server()->GetURL("foo.com", "/post_message.html")); EXPECT_EQ(foo_url, root->child_at(1)->current_url()); EXPECT_NE(root->child_at(0)->current_frame_host()->GetSiteInstance(), root->child_at(1)->current_frame_host()->GetSiteInstance()); // Send a message from first, same-site frame to second, cross-site frame. // Expect the second frame to reply back to the first frame. PostMessageAndWaitForReply(root->child_at(0), "postToSibling('subframe-msg','subframe2')", "\"done-subframe1\""); // Send a postMessage from second, cross-site frame to its parent. Expect // parent to send a reply to the frame. base::string16 expected_title(base::ASCIIToUTF16("subframe-msg")); TitleWatcher title_watcher(shell()->web_contents(), expected_title); PostMessageAndWaitForReply(root->child_at(1), "postToParent('subframe-msg')", "\"done-subframe2\""); EXPECT_EQ(expected_title, title_watcher.WaitAndGetTitle()); // Verify the total number of received messages for each subframe. First // frame should have one message (reply from second frame). Second frame // should have two messages (message from first frame and reply from parent). // Parent should have one message (from second frame). EXPECT_EQ(1, GetReceivedMessages(root->child_at(0))); EXPECT_EQ(2, GetReceivedMessages(root->child_at(1))); EXPECT_EQ(1, GetReceivedMessages(root)); } // Check that renderer initiated navigations which commit a new RenderFrameHost // do not crash if the original RenderFrameHost was being covered by an // interstitial. See crbug.com/607964. IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, NavigateOpenerWithInterstitial) { EXPECT_TRUE(NavigateToURL( shell(), embedded_test_server()->GetURL("a.com", "/title1.html"))); // Open a popup and navigate it to bar.com. ShellAddedObserver new_shell_observer; EXPECT_TRUE(ExecuteScript(web_contents(), "window.open('about:blank');")); Shell* popup = new_shell_observer.GetShell(); EXPECT_TRUE(NavigateToURL(popup, embedded_test_server()->GetURL( "bar.com", "/navigate_opener.html"))); // Show an interstitial in the opener. TestInterstitialDelegate* delegate = new TestInterstitialDelegate; WebContentsImpl* opener_contents = static_cast<WebContentsImpl*>(web_contents()); GURL interstitial_url("http://interstitial"); InterstitialPageImpl* interstitial = new InterstitialPageImpl( opener_contents, static_cast<RenderWidgetHostDelegate*>(opener_contents), true, interstitial_url, delegate); interstitial->Show(); WaitForInterstitialAttach(opener_contents); // Now, navigate the opener cross-process using the popup while it still has // an interstitial. This should not crash. TestNavigationObserver navigation_observer(opener_contents); EXPECT_TRUE(ExecuteScript(popup, "navigateOpener();")); navigation_observer.Wait(); } // Check that postMessage can be sent from a subframe on a cross-process opener // tab, and that its event.source points to a valid proxy. IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, PostMessageWithSubframeOnOpenerChain) { GURL main_url(embedded_test_server()->GetURL( "a.com", "/frame_tree/page_with_post_message_frames.html")); EXPECT_TRUE(NavigateToURL(shell(), main_url)); // It is safe to obtain the root frame tree node here, as it doesn't change. FrameTreeNode* root = web_contents()->GetFrameTree()->root(); ASSERT_EQ(2U, root->child_count()); // Verify the initial state of the world. First frame should be same-site; // second frame should be cross-site. EXPECT_EQ( " Site A ------------ proxies for B\n" " |--Site A ------- proxies for B\n" " +--Site B ------- proxies for A\n" "Where A = http://a.com/\n" " B = http://foo.com/", DepictFrameTree(root)); // Open a popup from the first subframe (so that popup's window.opener points // to the subframe) and navigate it to bar.com. ShellAddedObserver new_shell_observer; EXPECT_TRUE(ExecuteScript(root->child_at(0), "openPopup('about:blank');")); Shell* popup = new_shell_observer.GetShell(); GURL popup_url( embedded_test_server()->GetURL("bar.com", "/post_message.html")); EXPECT_TRUE(NavigateToURL(popup, popup_url)); // From the popup, open another popup for baz.com. This will be used to // check that the whole opener chain is processed when creating proxies and // not just an immediate opener. ShellAddedObserver new_shell_observer2; EXPECT_TRUE(ExecuteScript(popup, "openPopup('about:blank');")); Shell* popup2 = new_shell_observer2.GetShell(); GURL popup2_url( embedded_test_server()->GetURL("baz.com", "/post_message.html")); EXPECT_TRUE(NavigateToURL(popup2, popup2_url)); // Ensure that we've created proxies for SiteInstances of both popups (C, D) // in the main window's frame tree. EXPECT_EQ( " Site A ------------ proxies for B C D\n" " |--Site A ------- proxies for B C D\n" " +--Site B ------- proxies for A C D\n" "Where A = http://a.com/\n" " B = http://foo.com/\n" " C = http://bar.com/\n" " D = http://baz.com/", DepictFrameTree(root)); // Check the first popup's frame tree as well. Note that it doesn't have a // proxy for foo.com, since foo.com can't reach the popup. It does have a // proxy for its opener a.com (which can reach it via the window.open // reference) and second popup (which can reach it via window.opener). FrameTreeNode* popup_root = static_cast<WebContentsImpl*>(popup->web_contents()) ->GetFrameTree() ->root(); EXPECT_EQ( " Site C ------------ proxies for A D\n" "Where A = http://a.com/\n" " C = http://bar.com/\n" " D = http://baz.com/", DepictFrameTree(popup_root)); // Send a message from first subframe on main page to the first popup and // wait for a reply back. The reply verifies that the proxy for the opener // tab's subframe is targeted properly. PostMessageAndWaitForReply(root->child_at(0), "postToPopup('subframe-msg')", "\"done-subframe1\""); // Send a postMessage from the popup to window.opener and ensure that it // reaches subframe1. This verifies that the subframe opener information // propagated to the popup's RenderFrame. Wait for subframe1 to send a reply // message to the popup. EXPECT_TRUE(ExecuteScript(popup, "window.name = 'popup';")); PostMessageAndWaitForReply(popup_root, "postToOpener('subframe-msg', '*')", "\"done-popup\""); // Second a postMessage from popup2 to window.opener.opener, which should // resolve to subframe1. This tests opener chains of length greater than 1. // As before, subframe1 will send a reply to popup2. FrameTreeNode* popup2_root = static_cast<WebContentsImpl*>(popup2->web_contents()) ->GetFrameTree() ->root(); EXPECT_TRUE(ExecuteScript(popup2, "window.name = 'popup2';")); PostMessageAndWaitForReply(popup2_root, "postToOpenerOfOpener('subframe-msg', '*')", "\"done-popup2\""); // Verify the total number of received messages for each subframe: // - 3 for first subframe (two from first popup, one from second popup) // - 2 for popup (both from first subframe) // - 1 for popup2 (reply from first subframe) // - 0 for other frames EXPECT_EQ(0, GetReceivedMessages(root)); EXPECT_EQ(3, GetReceivedMessages(root->child_at(0))); EXPECT_EQ(0, GetReceivedMessages(root->child_at(1))); EXPECT_EQ(2, GetReceivedMessages(popup_root)); EXPECT_EQ(1, GetReceivedMessages(popup2_root)); } // Check that parent.frames[num] references correct sibling frames when the // parent is remote. See https://crbug.com/478792. IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, IndexedFrameAccess) { // Start on a page with three same-site subframes. GURL main_url( embedded_test_server()->GetURL("a.com", "/frame_tree/top.html")); EXPECT_TRUE(NavigateToURL(shell(), main_url)); // It is safe to obtain the root frame tree node here, as it doesn't change. FrameTreeNode* root = web_contents()->GetFrameTree()->root(); ASSERT_EQ(3U, root->child_count()); FrameTreeNode* child0 = root->child_at(0); FrameTreeNode* child1 = root->child_at(1); FrameTreeNode* child2 = root->child_at(2); // Send each of the frames to a different site. Each new renderer will first // create proxies for the parent and two sibling subframes and then create // and insert the new RenderFrame into the frame tree. GURL b_url(embedded_test_server()->GetURL("b.com", "/post_message.html")); GURL c_url(embedded_test_server()->GetURL("c.com", "/post_message.html")); GURL d_url(embedded_test_server()->GetURL("d.com", "/post_message.html")); NavigateFrameToURL(child0, b_url); NavigateFrameToURL(child1, c_url); NavigateFrameToURL(child2, d_url); EXPECT_EQ( " Site A ------------ proxies for B C D\n" " |--Site B ------- proxies for A C D\n" " |--Site C ------- proxies for A B D\n" " +--Site D ------- proxies for A B C\n" "Where A = http://a.com/\n" " B = http://b.com/\n" " C = http://c.com/\n" " D = http://d.com/", DepictFrameTree(root)); // Check that each subframe sees itself at correct index in parent.frames. bool success = false; EXPECT_TRUE(ExecuteScriptAndExtractBool( child0, "window.domAutomationController.send(window === parent.frames[0]);", &success)); EXPECT_TRUE(success); success = false; EXPECT_TRUE(ExecuteScriptAndExtractBool( child1, "window.domAutomationController.send(window === parent.frames[1]);", &success)); EXPECT_TRUE(success); success = false; EXPECT_TRUE(ExecuteScriptAndExtractBool( child2, "window.domAutomationController.send(window === parent.frames[2]);", &success)); EXPECT_TRUE(success); // Send a postMessage from B to parent.frames[1], which should go to C, and // wait for reply. PostMessageAndWaitForReply(child0, "postToSibling('subframe-msg', 1)", "\"done-1-1-name\""); // Send a postMessage from C to parent.frames[2], which should go to D, and // wait for reply. PostMessageAndWaitForReply(child1, "postToSibling('subframe-msg', 2)", "\"done-1-2-name\""); // Verify the total number of received messages for each subframe. EXPECT_EQ(1, GetReceivedMessages(child0)); EXPECT_EQ(2, GetReceivedMessages(child1)); EXPECT_EQ(1, GetReceivedMessages(child2)); } #if defined(OS_WIN) // This test is flaky on Windows, see https://crbug.com/629419. #define MAYBE_RFPHDestruction DISABLED_RFPHDestruction #else #define MAYBE_RFPHDestruction RFPHDestruction #endif IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, MAYBE_RFPHDestruction) { GURL main_url(embedded_test_server()->GetURL("/site_per_process_main.html")); NavigateToURL(shell(), main_url); // It is safe to obtain the root frame tree node here, as it doesn't change. FrameTreeNode* root = web_contents()->GetFrameTree()->root(); TestNavigationObserver observer(shell()->web_contents()); // Load cross-site page into iframe. FrameTreeNode* child = root->child_at(0); GURL url = embedded_test_server()->GetURL("foo.com", "/title2.html"); NavigateFrameToURL(root->child_at(0), url); EXPECT_TRUE(observer.last_navigation_succeeded()); EXPECT_EQ(url, observer.last_navigation_url()); EXPECT_EQ( " Site A ------------ proxies for B\n" " |--Site B ------- proxies for A\n" " +--Site A ------- proxies for B\n" " |--Site A -- proxies for B\n" " +--Site A -- proxies for B\n" " +--Site A -- proxies for B\n" "Where A = http://127.0.0.1/\n" " B = http://foo.com/", DepictFrameTree(root)); // Load another cross-site page. url = embedded_test_server()->GetURL("bar.com", "/title3.html"); NavigateIframeToURL(shell()->web_contents(), "test", url); EXPECT_TRUE(observer.last_navigation_succeeded()); EXPECT_EQ(url, observer.last_navigation_url()); EXPECT_EQ( " Site A ------------ proxies for C\n" " |--Site C ------- proxies for A\n" " +--Site A ------- proxies for C\n" " |--Site A -- proxies for C\n" " +--Site A -- proxies for C\n" " +--Site A -- proxies for C\n" "Where A = http://127.0.0.1/\n" " C = http://bar.com/", DepictFrameTree(root)); // Navigate back to the parent's origin. RenderFrameDeletedObserver deleted_observer(child->current_frame_host()); url = embedded_test_server()->GetURL("/title1.html"); NavigateFrameToURL(child, url); EXPECT_EQ(url, observer.last_navigation_url()); EXPECT_TRUE(observer.last_navigation_succeeded()); // Wait for the old process to exit, to verify that the proxies go away. deleted_observer.WaitUntilDeleted(); EXPECT_EQ( " Site A\n" " |--Site A\n" " +--Site A\n" " |--Site A\n" " +--Site A\n" " +--Site A\n" "Where A = http://127.0.0.1/", DepictFrameTree(root)); } IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, OpenPopupWithRemoteParent) { GURL main_url( embedded_test_server()->GetURL("a.com", "/site_per_process_main.html")); NavigateToURL(shell(), main_url); // It is safe to obtain the root frame tree node here, as it doesn't change. FrameTreeNode* root = web_contents()->GetFrameTree()->root(); // Navigate first child cross-site. GURL frame_url(embedded_test_server()->GetURL("b.com", "/title1.html")); NavigateFrameToURL(root->child_at(0), frame_url); // Open a popup from the first child. Shell* new_shell = OpenPopup(root->child_at(0), GURL(url::kAboutBlankURL), ""); EXPECT_TRUE(new_shell); // Check that the popup's opener is correct on both the browser and renderer // sides. FrameTreeNode* popup_root = static_cast<WebContentsImpl*>(new_shell->web_contents()) ->GetFrameTree() ->root(); EXPECT_EQ(root->child_at(0), popup_root->opener()); std::string opener_url; EXPECT_TRUE(ExecuteScriptAndExtractString( popup_root, "window.domAutomationController.send(window.opener.location.href);", &opener_url)); EXPECT_EQ(frame_url.spec(), opener_url); // Now try the same with a cross-site popup and make sure it ends up in a new // process and with a correct opener. GURL popup_url(embedded_test_server()->GetURL("c.com", "/title2.html")); Shell* cross_site_popup = OpenPopup(root->child_at(0), popup_url, ""); EXPECT_TRUE(cross_site_popup); FrameTreeNode* cross_site_popup_root = static_cast<WebContentsImpl*>(cross_site_popup->web_contents()) ->GetFrameTree() ->root(); EXPECT_EQ(cross_site_popup_root->current_url(), popup_url); EXPECT_NE(shell()->web_contents()->GetSiteInstance(), cross_site_popup->web_contents()->GetSiteInstance()); EXPECT_NE(root->child_at(0)->current_frame_host()->GetSiteInstance(), cross_site_popup->web_contents()->GetSiteInstance()); EXPECT_EQ(root->child_at(0), cross_site_popup_root->opener()); // Ensure the popup's window.opener points to the right subframe. Note that // we can't check the opener's location as above since it's cross-origin. bool success = false; EXPECT_TRUE(ExecuteScriptAndExtractBool( cross_site_popup_root, "window.domAutomationController.send(" " window.opener === window.opener.top.frames[0]);", &success)); EXPECT_TRUE(success); } // Test that cross-process popups can't be navigated to disallowed URLs by // their opener. This ensures that proper URL validation is performed when // RenderFrameProxyHosts are navigated. See https://crbug.com/595339. IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, NavigatePopupToIllegalURL) { GURL main_url(embedded_test_server()->GetURL("a.com", "/title1.html")); EXPECT_TRUE(NavigateToURL(shell(), main_url)); // Open a cross-site popup. GURL popup_url(embedded_test_server()->GetURL("b.com", "/title2.html")); Shell* popup = OpenPopup(shell(), popup_url, "foo"); EXPECT_TRUE(popup); EXPECT_NE(popup->web_contents()->GetSiteInstance(), shell()->web_contents()->GetSiteInstance()); // From the opener, navigate the popup to a file:/// URL. This should be // disallowed and result in an about:blank navigation. GURL file_url("file:///"); NavigateNamedFrame(shell(), file_url, "foo"); EXPECT_TRUE(WaitForLoadStop(popup->web_contents())); EXPECT_EQ(GURL(url::kAboutBlankURL), popup->web_contents()->GetLastCommittedURL()); // Navigate popup back to a cross-site URL. EXPECT_TRUE(NavigateToURL(popup, popup_url)); EXPECT_NE(popup->web_contents()->GetSiteInstance(), shell()->web_contents()->GetSiteInstance()); // Now try the same test with a chrome:// URL. GURL chrome_url(std::string(kChromeUIScheme) + "://" + std::string(kChromeUIGpuHost)); NavigateNamedFrame(shell(), chrome_url, "foo"); EXPECT_TRUE(WaitForLoadStop(popup->web_contents())); EXPECT_EQ(GURL(url::kAboutBlankURL), popup->web_contents()->GetLastCommittedURL()); } // Verify that named frames are discoverable from their opener's ancestors. // See https://crbug.com/511474. IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, DiscoverNamedFrameFromAncestorOfOpener) { GURL main_url( embedded_test_server()->GetURL("a.com", "/site_per_process_main.html")); NavigateToURL(shell(), main_url); // It is safe to obtain the root frame tree node here, as it doesn't change. FrameTreeNode* root = web_contents()->GetFrameTree()->root(); // Navigate first child cross-site. GURL frame_url(embedded_test_server()->GetURL("b.com", "/title1.html")); NavigateFrameToURL(root->child_at(0), frame_url); // Open a popup named "foo" from the first child. Shell* foo_shell = OpenPopup(root->child_at(0), GURL(url::kAboutBlankURL), "foo"); EXPECT_TRUE(foo_shell); // Check that a proxy was created for the "foo" popup in a.com. FrameTreeNode* foo_root = static_cast<WebContentsImpl*>(foo_shell->web_contents()) ->GetFrameTree() ->root(); SiteInstance* site_instance_a = root->current_frame_host()->GetSiteInstance(); RenderFrameProxyHost* popup_rfph_for_a = foo_root->render_manager()->GetRenderFrameProxyHost(site_instance_a); EXPECT_TRUE(popup_rfph_for_a); // Verify that the main frame can find the "foo" popup by name. If // window.open targets the correct frame, the "foo" popup's current URL // should be updated to |named_frame_url|. GURL named_frame_url(embedded_test_server()->GetURL("c.com", "/title2.html")); NavigateNamedFrame(shell(), named_frame_url, "foo"); EXPECT_TRUE(WaitForLoadStop(foo_shell->web_contents())); EXPECT_EQ(named_frame_url, foo_root->current_url()); // Navigate the popup cross-site and ensure it's still reachable via // window.open from the main frame. GURL d_url(embedded_test_server()->GetURL("d.com", "/title3.html")); NavigateToURL(foo_shell, d_url); EXPECT_EQ(d_url, foo_root->current_url()); NavigateNamedFrame(shell(), named_frame_url, "foo"); EXPECT_TRUE(WaitForLoadStop(foo_shell->web_contents())); EXPECT_EQ(named_frame_url, foo_root->current_url()); } // Similar to DiscoverNamedFrameFromAncestorOfOpener, but check that if a // window is created without a name and acquires window.name later, it will // still be discoverable from its opener's ancestors. Also, instead of using // an opener's ancestor, this test uses a popup with same origin as that // ancestor. See https://crbug.com/511474. IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, DiscoverFrameAfterSettingWindowName) { GURL main_url( embedded_test_server()->GetURL("a.com", "/site_per_process_main.html")); NavigateToURL(shell(), main_url); // It is safe to obtain the root frame tree node here, as it doesn't change. FrameTreeNode* root = web_contents()->GetFrameTree()->root(); // Open a same-site popup from the main frame. GURL a_com_url(embedded_test_server()->GetURL("a.com", "/title3.html")); Shell* a_com_shell = OpenPopup(root->child_at(0), a_com_url, ""); EXPECT_TRUE(a_com_shell); // Navigate first child on main frame cross-site. GURL frame_url(embedded_test_server()->GetURL("b.com", "/title1.html")); NavigateFrameToURL(root->child_at(0), frame_url); // Open an unnamed popup from the first child frame. Shell* foo_shell = OpenPopup(root->child_at(0), GURL(url::kAboutBlankURL), ""); EXPECT_TRUE(foo_shell); // There should be no proxy created for the "foo" popup in a.com, since // there's no way for the two a.com frames to access it yet. FrameTreeNode* foo_root = static_cast<WebContentsImpl*>(foo_shell->web_contents()) ->GetFrameTree() ->root(); SiteInstance* site_instance_a = root->current_frame_host()->GetSiteInstance(); EXPECT_FALSE( foo_root->render_manager()->GetRenderFrameProxyHost(site_instance_a)); // Set window.name in the popup's frame. EXPECT_TRUE(ExecuteScript(foo_shell, "window.name = 'foo'")); // A proxy for the popup should now exist in a.com. EXPECT_TRUE( foo_root->render_manager()->GetRenderFrameProxyHost(site_instance_a)); // Verify that the a.com popup can now find the "foo" popup by name. GURL named_frame_url(embedded_test_server()->GetURL("c.com", "/title2.html")); NavigateNamedFrame(a_com_shell, named_frame_url, "foo"); EXPECT_TRUE(WaitForLoadStop(foo_shell->web_contents())); EXPECT_EQ(named_frame_url, foo_root->current_url()); } // Check that frame opener updates work with subframes. Set up a window with a // popup and update openers for the popup's main frame and subframe to // subframes on first window, as follows: // // foo +---- bar // / \ | / \ . // bar foo <-+ bar foo // ^ | // +--------------------+ // // The sites are carefully set up so that both opener updates are cross-process // but still allowed by Blink's navigation checks. IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, UpdateSubframeOpener) { GURL main_url = embedded_test_server()->GetURL( "foo.com", "/frame_tree/page_with_two_frames.html"); EXPECT_TRUE(NavigateToURL(shell(), main_url)); FrameTreeNode* root = web_contents()->GetFrameTree()->root(); EXPECT_EQ(2U, root->child_count()); // From the top frame, open a popup and navigate it to a cross-site page with // two subframes. Shell* popup_shell = OpenPopup(shell(), GURL(url::kAboutBlankURL), "popup"); EXPECT_TRUE(popup_shell); GURL popup_url(embedded_test_server()->GetURL( "bar.com", "/frame_tree/page_with_post_message_frames.html")); NavigateToURL(popup_shell, popup_url); FrameTreeNode* popup_root = static_cast<WebContentsImpl*>(popup_shell->web_contents()) ->GetFrameTree() ->root(); EXPECT_EQ(2U, popup_root->child_count()); // Popup's opener should point to main frame to start with. EXPECT_EQ(root, popup_root->opener()); // Update the popup's opener to the second subframe on the main page (which // is same-origin with the top frame, i.e., foo.com). bool success = false; EXPECT_TRUE(ExecuteScriptAndExtractBool( root->child_at(1), "window.domAutomationController.send(!!window.open('','popup'));", &success)); EXPECT_TRUE(success); // Check that updated opener propagated to the browser process and the // popup's bar.com process. EXPECT_EQ(root->child_at(1), popup_root->opener()); success = false; EXPECT_TRUE(ExecuteScriptAndExtractBool( popup_shell, "window.domAutomationController.send(" " window.opener === window.opener.parent.frames['frame2']);", &success)); EXPECT_TRUE(success); // Now update opener on the popup's second subframe (foo.com) to the main // page's first subframe (bar.com). success = false; EXPECT_TRUE(ExecuteScriptAndExtractBool( root->child_at(0), "window.domAutomationController.send(!!window.open('','subframe2'));", &success)); EXPECT_TRUE(success); // Check that updated opener propagated to the browser process and the // foo.com process. EXPECT_EQ(root->child_at(0), popup_root->child_at(1)->opener()); success = false; EXPECT_TRUE(ExecuteScriptAndExtractBool( popup_root->child_at(1), "window.domAutomationController.send(" " window.opener === window.opener.parent.frames['frame1']);", &success)); EXPECT_TRUE(success); } // Check that when a subframe navigates to a new SiteInstance, the new // SiteInstance will get a proxy for the opener of subframe's parent. I.e., // accessing parent.opener from the subframe should still work after a // cross-process navigation. IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, NavigatingSubframePreservesOpenerInParent) { GURL main_url = embedded_test_server()->GetURL("a.com", "/post_message.html"); EXPECT_TRUE(NavigateToURL(shell(), main_url)); FrameTreeNode* root = web_contents()->GetFrameTree()->root(); // Open a popup with a cross-site page that has a subframe. GURL popup_url(embedded_test_server()->GetURL( "b.com", "/cross_site_iframe_factory.html?b(b)")); Shell* popup_shell = OpenPopup(shell(), popup_url, "popup"); EXPECT_TRUE(popup_shell); FrameTreeNode* popup_root = static_cast<WebContentsImpl*>(popup_shell->web_contents()) ->GetFrameTree() ->root(); EXPECT_EQ(1U, popup_root->child_count()); // Check that the popup's opener is correct in the browser process. EXPECT_EQ(root, popup_root->opener()); // Navigate popup's subframe to another site. GURL frame_url(embedded_test_server()->GetURL("c.com", "/post_message.html")); NavigateFrameToURL(popup_root->child_at(0), frame_url); // Check that the new subframe process still sees correct opener for its // parent by sending a postMessage to subframe's parent.opener. bool success = false; EXPECT_TRUE(ExecuteScriptAndExtractBool( popup_root->child_at(0), "window.domAutomationController.send(!!parent.opener);", &success)); EXPECT_TRUE(success); base::string16 expected_title = base::ASCIIToUTF16("msg"); TitleWatcher title_watcher(shell()->web_contents(), expected_title); EXPECT_TRUE(ExecuteScriptAndExtractBool( popup_root->child_at(0), "window.domAutomationController.send(postToOpenerOfParent('msg','*'));", &success)); EXPECT_TRUE(success); EXPECT_EQ(expected_title, title_watcher.WaitAndGetTitle()); } // Check that if a subframe has an opener, that opener is preserved when the // subframe navigates cross-site. IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, NavigateSubframeWithOpener) { GURL main_url(embedded_test_server()->GetURL( "foo.com", "/frame_tree/page_with_two_frames.html")); EXPECT_TRUE(NavigateToURL(shell(), main_url)); FrameTreeNode* root = web_contents()->GetFrameTree()->root(); EXPECT_EQ( " Site A ------------ proxies for B\n" " |--Site B ------- proxies for A\n" " +--Site A ------- proxies for B\n" "Where A = http://foo.com/\n" " B = http://bar.com/", DepictFrameTree(root)); // Update the first (cross-site) subframe's opener to root frame. bool success = false; EXPECT_TRUE(ExecuteScriptAndExtractBool( root, "window.domAutomationController.send(!!window.open('','frame1'));", &success)); EXPECT_TRUE(success); // Check that updated opener propagated to the browser process and subframe's // process. EXPECT_EQ(root, root->child_at(0)->opener()); success = false; EXPECT_TRUE(ExecuteScriptAndExtractBool( root->child_at(0), "window.domAutomationController.send(window.opener === window.parent);", &success)); EXPECT_TRUE(success); // Navigate the subframe with opener to another site. GURL frame_url(embedded_test_server()->GetURL("baz.com", "/title1.html")); NavigateFrameToURL(root->child_at(0), frame_url); // Check that the subframe still sees correct opener in its new process. success = false; EXPECT_TRUE(ExecuteScriptAndExtractBool( root->child_at(0), "window.domAutomationController.send(window.opener === window.parent);", &success)); EXPECT_TRUE(success); // Navigate second subframe to a new site. Check that the proxy that's // created for the first subframe in the new SiteInstance has correct opener. GURL frame2_url(embedded_test_server()->GetURL("qux.com", "/title1.html")); NavigateFrameToURL(root->child_at(1), frame2_url); success = false; EXPECT_TRUE(ExecuteScriptAndExtractBool( root->child_at(1), "window.domAutomationController.send(" " parent.frames['frame1'].opener === parent);", &success)); EXPECT_TRUE(success); } // Check that if a subframe has an opener, that opener is preserved when a new // RenderFrameProxy is created for that subframe in another renderer process. // Similar to NavigateSubframeWithOpener, but this test verifies the subframe // opener plumbing for mojom::Renderer::CreateFrameProxy(), whereas // NavigateSubframeWithOpener targets mojom::Renderer::CreateFrame(). IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, NewRenderFrameProxyPreservesOpener) { GURL main_url( embedded_test_server()->GetURL("foo.com", "/post_message.html")); EXPECT_TRUE(NavigateToURL(shell(), main_url)); FrameTreeNode* root = web_contents()->GetFrameTree()->root(); // Open a popup with a cross-site page that has two subframes. GURL popup_url(embedded_test_server()->GetURL( "bar.com", "/frame_tree/page_with_post_message_frames.html")); Shell* popup_shell = OpenPopup(shell(), popup_url, "popup"); EXPECT_TRUE(popup_shell); FrameTreeNode* popup_root = static_cast<WebContentsImpl*>(popup_shell->web_contents()) ->GetFrameTree() ->root(); EXPECT_EQ( " Site A ------------ proxies for B\n" " |--Site A ------- proxies for B\n" " +--Site B ------- proxies for A\n" "Where A = http://bar.com/\n" " B = http://foo.com/", DepictFrameTree(popup_root)); // Update the popup's second subframe's opener to root frame. This is // allowed because that subframe is in the same foo.com SiteInstance as the // root frame. bool success = false; EXPECT_TRUE(ExecuteScriptAndExtractBool( root, "window.domAutomationController.send(!!window.open('','subframe2'));", &success)); EXPECT_TRUE(success); // Check that the opener update propagated to the browser process and bar.com // process. EXPECT_EQ(root, popup_root->child_at(1)->opener()); success = false; EXPECT_TRUE(ExecuteScriptAndExtractBool( popup_root->child_at(0), "window.domAutomationController.send(" " parent.frames['subframe2'].opener && " " parent.frames['subframe2'].opener === parent.opener);", &success)); EXPECT_TRUE(success); // Navigate the popup's first subframe to another site. GURL frame_url( embedded_test_server()->GetURL("baz.com", "/post_message.html")); NavigateFrameToURL(popup_root->child_at(0), frame_url); // Check that the second subframe's opener is still correct in the first // subframe's new process. Verify it both in JS and with a postMessage. success = false; EXPECT_TRUE(ExecuteScriptAndExtractBool( popup_root->child_at(0), "window.domAutomationController.send(" " parent.frames['subframe2'].opener && " " parent.frames['subframe2'].opener === parent.opener);", &success)); EXPECT_TRUE(success); base::string16 expected_title = base::ASCIIToUTF16("msg"); TitleWatcher title_watcher(shell()->web_contents(), expected_title); EXPECT_TRUE(ExecuteScriptAndExtractBool( popup_root->child_at(0), "window.domAutomationController.send(" " postToOpenerOfSibling('subframe2', 'msg', '*'));", &success)); EXPECT_TRUE(success); EXPECT_EQ(expected_title, title_watcher.WaitAndGetTitle()); } // Test for https://crbug.com/515302. Perform two navigations, A->B->A, and // drop the SwapOut ACK from the A->B navigation, so that the second B->A // navigation is initiated before the first page receives the SwapOut ACK. // Ensure that this doesn't crash and that the RVH(A) is not reused in that // case. IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, RenderViewHostIsNotReusedAfterDelayedSwapOutACK) { GURL a_url(embedded_test_server()->GetURL("a.com", "/title1.html")); NavigateToURL(shell(), a_url); FrameTreeNode* root = web_contents()->GetFrameTree()->root(); RenderFrameHostImpl* rfh = root->current_frame_host(); RenderViewHostImpl* rvh = rfh->render_view_host(); int rvh_routing_id = rvh->GetRoutingID(); SiteInstanceImpl* site_instance = rfh->GetSiteInstance(); RenderFrameDeletedObserver deleted_observer(rfh); // Install a BrowserMessageFilter to drop SwapOut ACK messages in A's // process. scoped_refptr<SwapoutACKMessageFilter> filter = new SwapoutACKMessageFilter(); rfh->GetProcess()->AddFilter(filter.get()); rfh->DisableSwapOutTimerForTesting(); // Navigate to B. This must wait for DidCommitProvisionalLoad and not // DidStopLoading, so that the SwapOut timer doesn't call OnSwappedOut and // destroy |rfh| and |rvh| before they are checked in the test. GURL b_url(embedded_test_server()->GetURL("b.com", "/title2.html")); TestFrameNavigationObserver commit_observer(root); shell()->LoadURL(b_url); commit_observer.WaitForCommit(); EXPECT_FALSE(deleted_observer.deleted()); // Since the SwapOut ACK for A->B is dropped, the first page's // RenderFrameHost should be pending deletion after the last navigation. EXPECT_FALSE(rfh->is_active()); // Wait for process A to exit so we can reinitialize it cleanly for the next // navigation. Since process A doesn't have any active views, it will // initiate shutdown via ChildProcessHostMsg_ShutdownRequest. After process // A shuts down, the |rfh| and |rvh| should get destroyed via // OnRenderProcessGone. // // Not waiting for process shutdown here could lead to the |rvh| being // reused, now that there is no notion of pending deletion RenderViewHosts. // This would also be fine; however, the race in https://crbug.com/535246 // still needs to be addressed and tested in that case. RenderProcessHostWatcher process_exit_observer( rvh->GetProcess(), RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT); process_exit_observer.Wait(); // Verify that the RVH and RFH for A were cleaned up. EXPECT_FALSE(root->frame_tree()->GetRenderViewHost(site_instance)); EXPECT_TRUE(deleted_observer.deleted()); // Start a navigation back to A and check that the RenderViewHost wasn't // reused. TestNavigationObserver navigation_observer(shell()->web_contents()); shell()->LoadURL(a_url); RenderViewHostImpl* pending_rvh = IsBrowserSideNavigationEnabled() ? root->render_manager()->speculative_frame_host()->render_view_host() : root->render_manager()->pending_render_view_host(); EXPECT_EQ(site_instance, pending_rvh->GetSiteInstance()); EXPECT_NE(rvh_routing_id, pending_rvh->GetRoutingID()); // Make sure the last navigation finishes without crashing. navigation_observer.Wait(); } // Test for https://crbug.com/591478, where navigating to a cross-site page with // a subframe on the old site caused a crash while trying to reuse the old // RenderViewHost. IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, ReusePendingDeleteRenderViewHostForSubframe) { GURL main_url(embedded_test_server()->GetURL("a.com", "/title1.html")); EXPECT_TRUE(NavigateToURL(shell(), main_url)); std::string script = "window.onunload = function() { " " var start = Date.now();" " while (Date.now() - start < 1000);" "}"; EXPECT_TRUE(ExecuteScript(shell(), script)); // Navigating cross-site with an iframe to the original site shouldn't crash. GURL second_url(embedded_test_server()->GetURL( "b.com", "/cross_site_iframe_factory.html?b(a)")); EXPECT_TRUE(NavigateToURL(shell(), second_url)); // If the subframe is created while the main frame is pending deletion, then // the RVH will be reused. The main frame should've been swapped with a // proxy despite being the last active frame in the progress (see // https://crbug.com/568836), and this proxy should also be reused by the new // page. // // TODO(creis, alexmos): Find a way to assert this that isn't flaky. For now, // the test is just likely (not certain) to catch regressions by crashing. } // Check that when a cross-process frame acquires focus, the old focused frame // loses focus and fires blur events. Starting on a page with a cross-site // subframe, simulate mouse clicks to switch focus from root frame to subframe // and then back to root frame. IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, CrossProcessFocusChangeFiresBlurEvents) { GURL main_url( embedded_test_server()->GetURL("a.com", "/page_with_input_field.html")); EXPECT_TRUE(NavigateToURL(shell(), main_url)); FrameTreeNode* root = web_contents()->GetFrameTree()->root(); EXPECT_EQ( " Site A ------------ proxies for B\n" " +--Site B ------- proxies for A\n" "Where A = http://a.com/\n" " B = http://b.com/", DepictFrameTree(root)); // Focus the main frame's text field. The return value "input-focus" // indicates that the focus event was fired correctly. std::string result; EXPECT_TRUE( ExecuteScriptAndExtractString(shell(), "focusInputField()", &result)); EXPECT_EQ(result, "input-focus"); // The main frame should be focused. EXPECT_EQ(root, root->frame_tree()->GetFocusedFrame()); DOMMessageQueue msg_queue; // Click on the cross-process subframe. SimulateMouseClick( root->child_at(0)->current_frame_host()->GetRenderWidgetHost(), 1, 1); // Check that the main frame lost focus and fired blur event on the input // text field. std::string status; while (msg_queue.WaitForMessage(&status)) { if (status == "\"input-blur\"") break; } // The subframe should now be focused. EXPECT_EQ(root->child_at(0), root->frame_tree()->GetFocusedFrame()); // Click on the root frame. SimulateMouseClick( shell()->web_contents()->GetRenderViewHost()->GetWidget(), 1, 1); // Check that the subframe lost focus and fired blur event on its // document's body. while (msg_queue.WaitForMessage(&status)) { if (status == "\"document-blur\"") break; } // The root frame should be focused again. EXPECT_EQ(root, root->frame_tree()->GetFocusedFrame()); } // Check that when a cross-process subframe is focused, its parent's // document.activeElement correctly returns the corresponding <iframe> element. // The test sets up an A-embed-B-embed-C page and shifts focus A->B->A->C, // checking document.activeElement after each change. IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, DocumentActiveElement) { GURL main_url(embedded_test_server()->GetURL( "a.com", "/cross_site_iframe_factory.html?a(b(c))")); EXPECT_TRUE(NavigateToURL(shell(), main_url)); FrameTreeNode* root = web_contents()->GetFrameTree()->root(); EXPECT_EQ( " Site A ------------ proxies for B C\n" " +--Site B ------- proxies for A C\n" " +--Site C -- proxies for A B\n" "Where A = http://a.com/\n" " B = http://b.com/\n" " C = http://c.com/", DepictFrameTree(root)); FrameTreeNode* child = root->child_at(0); FrameTreeNode* grandchild = root->child_at(0)->child_at(0); // The main frame should be focused to start with. EXPECT_EQ(root, root->frame_tree()->GetFocusedFrame()); // Focus the b.com frame. FocusFrame(child); EXPECT_EQ(child, root->frame_tree()->GetFocusedFrame()); // Helper function to check a property of document.activeElement in the // specified frame. auto verify_active_element_property = [](RenderFrameHost* rfh, const std::string& property, const std::string& expected_value) { std::string script = base::StringPrintf( "window.domAutomationController.send(document.activeElement.%s);", property.c_str()); std::string result; EXPECT_TRUE(ExecuteScriptAndExtractString(rfh, script, &result)); EXPECT_EQ(expected_value, base::ToLowerASCII(result)); }; // Verify that document.activeElement on main frame points to the <iframe> // element for the b.com frame. RenderFrameHost* root_rfh = root->current_frame_host(); verify_active_element_property(root_rfh, "tagName", "iframe"); verify_active_element_property(root_rfh, "src", child->current_url().spec()); // Focus the a.com main frame again. FocusFrame(root); EXPECT_EQ(root, root->frame_tree()->GetFocusedFrame()); // Main frame document's <body> should now be the active element. verify_active_element_property(root_rfh, "tagName", "body"); // Now shift focus from main frame to c.com frame. FocusFrame(grandchild); // Check document.activeElement in main frame. It should still point to // <iframe> for the b.com frame, since Blink computes the focused iframe // element by walking the parent chain of the focused frame until it hits the // current frame. This logic should still work with remote frames. verify_active_element_property(root_rfh, "tagName", "iframe"); verify_active_element_property(root_rfh, "src", child->current_url().spec()); // Check document.activeElement in b.com subframe. It should point to // <iframe> for the c.com frame. This is a tricky case where B needs to find // out that focus changed from one remote frame to another (A to C). RenderFrameHost* child_rfh = child->current_frame_host(); verify_active_element_property(child_rfh, "tagName", "iframe"); verify_active_element_property(child_rfh, "src", grandchild->current_url().spec()); } // Check that window.focus works for cross-process subframes. IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, SubframeWindowFocus) { GURL main_url(embedded_test_server()->GetURL( "a.com", "/cross_site_iframe_factory.html?a(b,c)")); EXPECT_TRUE(NavigateToURL(shell(), main_url)); FrameTreeNode* root = web_contents()->GetFrameTree()->root(); EXPECT_EQ( " Site A ------------ proxies for B C\n" " |--Site B ------- proxies for A C\n" " +--Site C ------- proxies for A B\n" "Where A = http://a.com/\n" " B = http://b.com/\n" " C = http://c.com/", DepictFrameTree(root)); FrameTreeNode* child1 = root->child_at(0); FrameTreeNode* child2 = root->child_at(1); // The main frame should be focused to start with. EXPECT_EQ(root, root->frame_tree()->GetFocusedFrame()); DOMMessageQueue msg_queue; // Register focus and blur events that will send messages when each frame's // window gets or loses focus. const char kSetupFocusEvents[] = "window.addEventListener('focus', function() {" " domAutomationController.setAutomationId(0);" " domAutomationController.send('%s-got-focus');" "});" "window.addEventListener('blur', function() {" " domAutomationController.setAutomationId(0);" " domAutomationController.send('%s-lost-focus');" "});"; std::string script = base::StringPrintf(kSetupFocusEvents, "main", "main"); EXPECT_TRUE(ExecuteScript(shell(), script)); script = base::StringPrintf(kSetupFocusEvents, "child1", "child1"); EXPECT_TRUE(ExecuteScript(child1, script)); script = base::StringPrintf(kSetupFocusEvents, "child2", "child2"); EXPECT_TRUE(ExecuteScript(child2, script)); // Execute window.focus on the B subframe from the A main frame. EXPECT_TRUE(ExecuteScript(root, "frames[0].focus()")); // Helper to wait for two specified messages to arrive on the specified // DOMMessageQueue, assuming that the two messages can arrive in any order. auto wait_for_two_messages = [](DOMMessageQueue* msg_queue, const std::string& msg1, const std::string& msg2) { bool msg1_received = false; bool msg2_received = false; std::string status; while (msg_queue->WaitForMessage(&status)) { if (status == msg1) msg1_received = true; if (status == msg2) msg2_received = true; if (msg1_received && msg2_received) break; } }; // Process A should fire a blur event, and process B should fire a focus // event. Wait for both events. wait_for_two_messages(&msg_queue, "\"main-lost-focus\"", "\"child1-got-focus\""); // The B subframe should now be focused in the browser process. EXPECT_EQ(child1, root->frame_tree()->GetFocusedFrame()); // Now, execute window.focus on the C subframe from A main frame. This // checks that we can shift focus from one remote frame to another. EXPECT_TRUE(ExecuteScript(root, "frames[1].focus()")); // Wait for the two subframes (B and C) to fire blur and focus events. wait_for_two_messages(&msg_queue, "\"child1-lost-focus\"", "\"child2-got-focus\""); // The C subframe should now be focused. EXPECT_EQ(child2, root->frame_tree()->GetFocusedFrame()); // window.focus the main frame from the C subframe. EXPECT_TRUE(ExecuteScript(child2, "parent.focus()")); // Wait for the C subframe to blur and main frame to focus. wait_for_two_messages(&msg_queue, "\"child2-lost-focus\"", "\"main-got-focus\""); // The main frame should now be focused. EXPECT_EQ(root, root->frame_tree()->GetFocusedFrame()); } // There are no cursors on Android. #if !defined(OS_ANDROID) class CursorMessageFilter : public content::BrowserMessageFilter { public: CursorMessageFilter() : content::BrowserMessageFilter(ViewMsgStart), message_loop_runner_(new content::MessageLoopRunner), last_set_cursor_routing_id_(MSG_ROUTING_NONE) {} bool OnMessageReceived(const IPC::Message& message) override { if (message.type() == ViewHostMsg_SetCursor::ID) { content::BrowserThread::PostTask( content::BrowserThread::UI, FROM_HERE, base::Bind(&CursorMessageFilter::OnSetCursor, this, message.routing_id())); } return false; } void OnSetCursor(int routing_id) { last_set_cursor_routing_id_ = routing_id; message_loop_runner_->Quit(); } int last_set_cursor_routing_id() const { return last_set_cursor_routing_id_; } void Wait() { last_set_cursor_routing_id_ = MSG_ROUTING_NONE; message_loop_runner_->Run(); } private: ~CursorMessageFilter() override {} scoped_refptr<content::MessageLoopRunner> message_loop_runner_; int last_set_cursor_routing_id_; DISALLOW_COPY_AND_ASSIGN(CursorMessageFilter); }; // Verify that we receive a mouse cursor update message when we mouse over // a text field contained in an out-of-process iframe. // Fails under TSan. http://crbug.com/545237 IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, DISABLED_CursorUpdateFromReceivedFromCrossSiteIframe) { GURL main_url(embedded_test_server()->GetURL( "/frame_tree/page_with_positioned_frame.html")); EXPECT_TRUE(NavigateToURL(shell(), main_url)); FrameTreeNode* root = web_contents()->GetFrameTree()->root(); FrameTreeNode* child_node = root->child_at(0); EXPECT_NE(shell()->web_contents()->GetSiteInstance(), child_node->current_frame_host()->GetSiteInstance()); scoped_refptr<CursorMessageFilter> filter = new CursorMessageFilter(); child_node->current_frame_host()->GetProcess()->AddFilter(filter.get()); // Send a MouseMove to the subframe. The frame contains text, and moving the // mouse over it should cause the renderer to send a mouse cursor update. blink::WebMouseEvent mouse_event; mouse_event.type = blink::WebInputEvent::MouseMove; mouse_event.x = 60; mouse_event.y = 60; RenderWidgetHost* rwh_child = root->child_at(0)->current_frame_host()->GetRenderWidgetHost(); RenderWidgetHostViewBase* root_view = static_cast<RenderWidgetHostViewBase*>( root->current_frame_host()->GetRenderWidgetHost()->GetView()); web_contents()->GetInputEventRouter()->RouteMouseEvent( root_view, &mouse_event, ui::LatencyInfo()); // CursorMessageFilter::Wait() implicitly tests whether we receive a // ViewHostMsg_SetCursor message from the renderer process, because it does // does not return otherwise. filter->Wait(); EXPECT_EQ(filter->last_set_cursor_routing_id(), rwh_child->GetRoutingID()); } #endif // Tests that we are using the correct RenderFrameProxy when navigating an // opener window. IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, OpenerSetLocation) { // Navigate the main window. GURL main_url(embedded_test_server()->GetURL("/title1.html")); EXPECT_TRUE(NavigateToURL(shell(), main_url)); EXPECT_EQ(shell()->web_contents()->GetLastCommittedURL(), main_url); // Load cross-site page into a new window. GURL cross_url = embedded_test_server()->GetURL("foo.com", "/title1.html"); Shell* popup = OpenPopup(shell(), cross_url, ""); EXPECT_EQ(popup->web_contents()->GetLastCommittedURL(), cross_url); // Use new window to navigate main window. std::string script = "window.opener.location.href = '" + cross_url.spec() + "'"; EXPECT_TRUE(ExecuteScript(popup, script)); EXPECT_TRUE(WaitForLoadStop(shell()->web_contents())); EXPECT_EQ(shell()->web_contents()->GetLastCommittedURL(), cross_url); } // Ensure that a cross-process subframe with a touch-handler can receive touch // events. #if defined(USE_AURA) // Browser process hit testing is not implemented on Android, and this test // requires Aura for RenderWidgetHostViewAura::OnTouchEvent(). // https://crbug.com/491334 IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, SubframeTouchEventRouting) { GURL main_url(embedded_test_server()->GetURL( "/frame_tree/page_with_positioned_nested_frames.html")); EXPECT_TRUE(NavigateToURL(shell(), main_url)); WebContentsImpl* contents = web_contents(); FrameTreeNode* root = contents->GetFrameTree()->root(); ASSERT_EQ(1U, root->child_count()); GURL frame_url( embedded_test_server()->GetURL("b.com", "/page_with_touch_handler.html")); NavigateFrameToURL(root->child_at(0), frame_url); // Synchronize with the child and parent renderers to guarantee that the // surface information required for event hit testing is ready. RenderWidgetHostViewBase* child_rwhv = static_cast<RenderWidgetHostViewBase*>( root->child_at(0)->current_frame_host()->GetView()); SurfaceHitTestReadyNotifier notifier( static_cast<RenderWidgetHostViewChildFrame*>(child_rwhv)); notifier.WaitForSurfaceReady(); // Simulate touch event to sub-frame. gfx::Point child_center(150, 150); auto* rwhv = static_cast<RenderWidgetHostViewAura*>( contents->GetRenderWidgetHostView()); ui::TouchEvent touch_event(ui::ET_TOUCH_PRESSED, child_center, 0, 0, ui::EventTimeForNow(), 30.f, 30.f, 0.f, 0.f); rwhv->OnTouchEvent(&touch_event); // Verify touch handler in subframe was invoked std::string result; EXPECT_TRUE(ExecuteScriptAndExtractString( root->child_at(0), "window.domAutomationController.send(getLastTouchEvent());", &result)); EXPECT_EQ("touchstart", result); } namespace { // Declared here to be close to the SubframeGestureEventRouting test. void OnSyntheticGestureCompleted(scoped_refptr<MessageLoopRunner> runner, SyntheticGesture::Result result) { EXPECT_EQ(SyntheticGesture::GESTURE_FINISHED, result); runner->Quit(); } } // namespace anonymous // Flaky under TSan. https://crbug.com/592320 #if defined(THREAD_SANITIZER) #define MAYBE_SubframeGestureEventRouting DISABLED_SubframeGestureEventRouting #else #define MAYBE_SubframeGestureEventRouting SubframeGestureEventRouting #endif IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, MAYBE_SubframeGestureEventRouting) { GURL main_url(embedded_test_server()->GetURL( "/frame_tree/page_with_positioned_nested_frames.html")); EXPECT_TRUE(NavigateToURL(shell(), main_url)); FrameTreeNode* root = web_contents()->GetFrameTree()->root(); ASSERT_EQ(1U, root->child_count()); GURL frame_url( embedded_test_server()->GetURL("b.com", "/page_with_click_handler.html")); NavigateFrameToURL(root->child_at(0), frame_url); auto* child_frame_host = root->child_at(0)->current_frame_host(); // Synchronize with the child and parent renderers to guarantee that the // surface information required for event hit testing is ready. RenderWidgetHostViewBase* child_rwhv = static_cast<RenderWidgetHostViewBase*>( child_frame_host->GetView()); SurfaceHitTestReadyNotifier notifier( static_cast<RenderWidgetHostViewChildFrame*>(child_rwhv)); notifier.WaitForSurfaceReady(); // There have been no GestureTaps sent yet. { std::string result; EXPECT_TRUE(ExecuteScriptAndExtractString( child_frame_host, "window.domAutomationController.send(getClickStatus());", &result)); EXPECT_EQ("0 clicks received", result); } // Simulate touch sequence to send GestureTap to sub-frame. SyntheticTapGestureParams params; params.gesture_source_type = SyntheticGestureParams::TOUCH_INPUT; gfx::Point center(150, 150); params.position = gfx::PointF(center.x(), center.y()); params.duration_ms = 100; std::unique_ptr<SyntheticTapGesture> gesture(new SyntheticTapGesture(params)); scoped_refptr<MessageLoopRunner> runner = new MessageLoopRunner(); RenderWidgetHostImpl* render_widget_host = root->current_frame_host()->GetRenderWidgetHost(); // TODO(wjmaclean): Convert the call to base::Bind() to a lambda someday. render_widget_host->QueueSyntheticGesture( std::move(gesture), base::Bind(OnSyntheticGestureCompleted, runner)); // We need to run the message loop while we wait for the synthetic gesture // to be processed; the callback registered above will get us out of the // message loop when that happens. runner->Run(); runner = nullptr; // Verify click handler in subframe was invoked { std::string result; EXPECT_TRUE(ExecuteScriptAndExtractString( child_frame_host, "window.domAutomationController.send(getClickStatus());", &result)); EXPECT_EQ("1 click received", result); } } namespace { // Defined here to be close to // SitePerProcessBrowserTest.InputEventRouterGestureTargetQueueTest. void SendTouchTapWithExpectedTarget( RenderWidgetHostViewBase* root_view, const gfx::Point& touch_point, RenderWidgetHostViewBase*& router_touch_target, const RenderWidgetHostViewBase* expected_target) { auto* root_view_aura = static_cast<RenderWidgetHostViewAura*>(root_view); ui::TouchEvent touch_event_pressed(ui::ET_TOUCH_PRESSED, touch_point, 0, 0, ui::EventTimeForNow(), 30.f, 30.f, 0.f, 0.f); root_view_aura->OnTouchEvent(&touch_event_pressed); EXPECT_EQ(expected_target, router_touch_target); ui::TouchEvent touch_event_released(ui::ET_TOUCH_RELEASED, touch_point, 0, 0, ui::EventTimeForNow(), 30.f, 30.f, 0.f, 0.f); root_view_aura->OnTouchEvent(&touch_event_released); EXPECT_EQ(nullptr, router_touch_target); } void SendGestureTapSequenceWithExpectedTarget( RenderWidgetHostViewBase* root_view, const gfx::Point& gesture_point, RenderWidgetHostViewBase*& router_gesture_target, const RenderWidgetHostViewBase* old_expected_target, const RenderWidgetHostViewBase* expected_target) { auto* root_view_aura = static_cast<RenderWidgetHostViewAura*>(root_view); ui::GestureEventDetails gesture_begin_details(ui::ET_GESTURE_BEGIN); gesture_begin_details.set_device_type( ui::GestureDeviceType::DEVICE_TOUCHSCREEN); ui::GestureEvent gesture_begin_event(gesture_point.x(), gesture_point.y(), 0, ui::EventTimeForNow(), gesture_begin_details); root_view_aura->OnGestureEvent(&gesture_begin_event); // We expect to still have the old gesture target in place for the // GestureFlingCancel that will be inserted before GestureTapDown. // Note: the GestureFlingCancel is inserted by RenderWidgetHostViewAura:: // OnGestureEvent() when it sees ui::ET_GESTURE_TAP_DOWN, so we don't // explicitly add it here. EXPECT_EQ(old_expected_target, router_gesture_target); ui::GestureEventDetails gesture_tap_down_details(ui::ET_GESTURE_TAP_DOWN); gesture_tap_down_details.set_device_type( ui::GestureDeviceType::DEVICE_TOUCHSCREEN); ui::GestureEvent gesture_tap_down_event(gesture_point.x(), gesture_point.y(), 0, ui::EventTimeForNow(), gesture_tap_down_details); root_view_aura->OnGestureEvent(&gesture_tap_down_event); EXPECT_EQ(expected_target, router_gesture_target); ui::GestureEventDetails gesture_show_press_details(ui::ET_GESTURE_SHOW_PRESS); gesture_show_press_details.set_device_type( ui::GestureDeviceType::DEVICE_TOUCHSCREEN); ui::GestureEvent gesture_show_press_event( gesture_point.x(), gesture_point.y(), 0, ui::EventTimeForNow(), gesture_show_press_details); root_view_aura->OnGestureEvent(&gesture_show_press_event); EXPECT_EQ(expected_target, router_gesture_target); ui::GestureEventDetails gesture_tap_details(ui::ET_GESTURE_TAP); gesture_tap_details.set_device_type( ui::GestureDeviceType::DEVICE_TOUCHSCREEN); gesture_tap_details.set_tap_count(1); ui::GestureEvent gesture_tap_event(gesture_point.x(), gesture_point.y(), 0, ui::EventTimeForNow(), gesture_tap_details); root_view_aura->OnGestureEvent(&gesture_tap_event); EXPECT_EQ(expected_target, router_gesture_target); ui::GestureEventDetails gesture_end_details(ui::ET_GESTURE_END); gesture_end_details.set_device_type( ui::GestureDeviceType::DEVICE_TOUCHSCREEN); ui::GestureEvent gesture_end_event(gesture_point.x(), gesture_point.y(), 0, ui::EventTimeForNow(), gesture_end_details); root_view_aura->OnGestureEvent(&gesture_end_event); EXPECT_EQ(expected_target, router_gesture_target); } void SendTouchpadPinchSequenceWithExpectedTarget( RenderWidgetHostViewBase* root_view, const gfx::Point& gesture_point, RenderWidgetHostViewBase*& router_touchpad_gesture_target, RenderWidgetHostViewBase* expected_target) { auto* root_view_aura = static_cast<RenderWidgetHostViewAura*>(root_view); ui::GestureEventDetails pinch_begin_details(ui::ET_GESTURE_PINCH_BEGIN); pinch_begin_details.set_device_type(ui::GestureDeviceType::DEVICE_TOUCHPAD); ui::GestureEvent pinch_begin(gesture_point.x(), gesture_point.y(), 0, ui::EventTimeForNow(), pinch_begin_details); root_view_aura->OnGestureEvent(&pinch_begin); EXPECT_EQ(expected_target, router_touchpad_gesture_target); ui::GestureEventDetails pinch_update_details(ui::ET_GESTURE_PINCH_UPDATE); pinch_update_details.set_device_type(ui::GestureDeviceType::DEVICE_TOUCHPAD); ui::GestureEvent pinch_update(gesture_point.x(), gesture_point.y(), 0, ui::EventTimeForNow(), pinch_update_details); root_view_aura->OnGestureEvent(&pinch_update); EXPECT_EQ(expected_target, router_touchpad_gesture_target); ui::GestureEventDetails pinch_end_details(ui::ET_GESTURE_PINCH_END); pinch_end_details.set_device_type(ui::GestureDeviceType::DEVICE_TOUCHPAD); ui::GestureEvent pinch_end(gesture_point.x(), gesture_point.y(), 0, ui::EventTimeForNow(), pinch_end_details); root_view_aura->OnGestureEvent(&pinch_end); EXPECT_EQ(expected_target, router_touchpad_gesture_target); } #if !defined(OS_WIN) // Sending touchpad fling events is not supported on Windows. void SendTouchpadFlingSequenceWithExpectedTarget( RenderWidgetHostViewBase* root_view, const gfx::Point& gesture_point, RenderWidgetHostViewBase*& router_touchpad_gesture_target, RenderWidgetHostViewBase* expected_target) { auto* root_view_aura = static_cast<RenderWidgetHostViewAura*>(root_view); ui::ScrollEvent fling_start(ui::ET_SCROLL_FLING_START, gesture_point, ui::EventTimeForNow(), 0, 1, 0, 1, 0, 1); root_view_aura->OnScrollEvent(&fling_start); EXPECT_EQ(expected_target, router_touchpad_gesture_target); ui::ScrollEvent fling_cancel(ui::ET_SCROLL_FLING_CANCEL, gesture_point, ui::EventTimeForNow(), 0, 1, 0, 1, 0, 1); root_view_aura->OnScrollEvent(&fling_cancel); EXPECT_EQ(expected_target, router_touchpad_gesture_target); } #endif } // namespace anonymous IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, InputEventRouterGestureTargetQueueTest) { GURL main_url(embedded_test_server()->GetURL( "/frame_tree/page_with_positioned_nested_frames.html")); EXPECT_TRUE(NavigateToURL(shell(), main_url)); WebContentsImpl* contents = web_contents(); FrameTreeNode* root = contents->GetFrameTree()->root(); ASSERT_EQ(1U, root->child_count()); GURL frame_url( embedded_test_server()->GetURL("b.com", "/page_with_click_handler.html")); NavigateFrameToURL(root->child_at(0), frame_url); auto* child_frame_host = root->child_at(0)->current_frame_host(); // Synchronize with the child and parent renderers to guarantee that the // surface information required for event hit testing is ready. auto* rwhv_child = static_cast<RenderWidgetHostViewBase*>(child_frame_host->GetView()); SurfaceHitTestReadyNotifier notifier( static_cast<RenderWidgetHostViewChildFrame*>(rwhv_child)); notifier.WaitForSurfaceReady(); // All touches & gestures are sent to the main frame's view, and should be // routed appropriately from there. auto* rwhv_parent = static_cast<RenderWidgetHostViewBase*>( contents->GetRenderWidgetHostView()); RenderWidgetHostInputEventRouter* router = contents->GetInputEventRouter(); EXPECT_TRUE(router->touchscreen_gesture_target_queue_.empty()); EXPECT_EQ(nullptr, router->touchscreen_gesture_target_.target); // Send touch sequence to main-frame. gfx::Point main_frame_point(25, 25); SendTouchTapWithExpectedTarget(rwhv_parent, main_frame_point, router->touch_target_.target, rwhv_parent); EXPECT_EQ(1LU, router->touchscreen_gesture_target_queue_.size()); EXPECT_EQ(nullptr, router->touchscreen_gesture_target_.target); // Send touch sequence to child. gfx::Point child_center(150, 150); SendTouchTapWithExpectedTarget(rwhv_parent, child_center, router->touch_target_.target, rwhv_child); EXPECT_EQ(2LU, router->touchscreen_gesture_target_queue_.size()); EXPECT_EQ(nullptr, router->touchscreen_gesture_target_.target); // Send another touch sequence to main frame. SendTouchTapWithExpectedTarget(rwhv_parent, main_frame_point, router->touch_target_.target, rwhv_parent); EXPECT_EQ(3LU, router->touchscreen_gesture_target_queue_.size()); EXPECT_EQ(nullptr, router->touchscreen_gesture_target_.target); // Send Gestures to clear GestureTargetQueue. // The first touch sequence should generate a GestureTapDown, sent to the // main frame. SendGestureTapSequenceWithExpectedTarget( rwhv_parent, main_frame_point, router->touchscreen_gesture_target_.target, nullptr, rwhv_parent); EXPECT_EQ(2LU, router->touchscreen_gesture_target_queue_.size()); // Note: rwhv_parent is the target used for GestureFlingCancel sent by // RenderWidgetHostViewAura::OnGestureEvent() at the start of the next gesture // sequence; the sequence itself goes to rwhv_child. EXPECT_EQ(rwhv_parent, router->touchscreen_gesture_target_.target); // The second touch sequence should generate a GestureTapDown, sent to the // child frame. SendGestureTapSequenceWithExpectedTarget( rwhv_parent, child_center, router->touchscreen_gesture_target_.target, rwhv_parent, rwhv_child); EXPECT_EQ(1LU, router->touchscreen_gesture_target_queue_.size()); EXPECT_EQ(rwhv_child, router->touchscreen_gesture_target_.target); // The third touch sequence should generate a GestureTapDown, sent to the // main frame. SendGestureTapSequenceWithExpectedTarget( rwhv_parent, main_frame_point, router->touchscreen_gesture_target_.target, rwhv_child, rwhv_parent); EXPECT_EQ(0LU, router->touchscreen_gesture_target_queue_.size()); EXPECT_EQ(rwhv_parent, router->touchscreen_gesture_target_.target); } IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, InputEventRouterTouchpadGestureTargetTest) { GURL main_url(embedded_test_server()->GetURL( "/frame_tree/page_with_positioned_nested_frames.html")); EXPECT_TRUE(NavigateToURL(shell(), main_url)); WebContentsImpl* contents = web_contents(); FrameTreeNode* root = contents->GetFrameTree()->root(); ASSERT_EQ(1U, root->child_count()); GURL frame_url( embedded_test_server()->GetURL("b.com", "/page_with_click_handler.html")); NavigateFrameToURL(root->child_at(0), frame_url); auto* child_frame_host = root->child_at(0)->current_frame_host(); // Synchronize with the child and parent renderers to guarantee that the // surface information required for event hit testing is ready. auto* rwhv_child = static_cast<RenderWidgetHostViewBase*>(child_frame_host->GetView()); SurfaceHitTestReadyNotifier notifier( static_cast<RenderWidgetHostViewChildFrame*>(rwhv_child)); notifier.WaitForSurfaceReady(); // All touches & gestures are sent to the main frame's view, and should be // routed appropriately from there. auto* rwhv_parent = static_cast<RenderWidgetHostViewBase*>( contents->GetRenderWidgetHostView()); RenderWidgetHostInputEventRouter* router = contents->GetInputEventRouter(); EXPECT_EQ(nullptr, router->touchpad_gesture_target_.target); gfx::Point main_frame_point(25, 25); gfx::Point child_center(150, 150); // Send touchpad pinch sequence to main-frame. SendTouchpadPinchSequenceWithExpectedTarget( rwhv_parent, main_frame_point, router->touchpad_gesture_target_.target, rwhv_parent); // Send touchpad pinch sequence to child. SendTouchpadPinchSequenceWithExpectedTarget( rwhv_parent, child_center, router->touchpad_gesture_target_.target, rwhv_child); // Send another touchpad pinch sequence to main frame. SendTouchpadPinchSequenceWithExpectedTarget( rwhv_parent, main_frame_point, router->touchpad_gesture_target_.target, rwhv_parent); #if !defined(OS_WIN) // Sending touchpad fling events is not supported on Windows. // Send touchpad fling sequence to main-frame. SendTouchpadFlingSequenceWithExpectedTarget( rwhv_parent, main_frame_point, router->touchpad_gesture_target_.target, rwhv_parent); // Send touchpad fling sequence to child. SendTouchpadFlingSequenceWithExpectedTarget( rwhv_parent, child_center, router->touchpad_gesture_target_.target, rwhv_child); // Send another touchpad fling sequence to main frame. SendTouchpadFlingSequenceWithExpectedTarget( rwhv_parent, main_frame_point, router->touchpad_gesture_target_.target, rwhv_parent); #endif } #endif // defined(USE_AURA) // A WebContentsDelegate to capture ContextMenu creation events. class ContextMenuObserverDelegate : public WebContentsDelegate { public: ContextMenuObserverDelegate() : context_menu_created_(false), message_loop_runner_(new MessageLoopRunner) {} ~ContextMenuObserverDelegate() override {} bool HandleContextMenu(const content::ContextMenuParams& params) override { context_menu_created_ = true; menu_params_ = params; message_loop_runner_->Quit(); return true; } ContextMenuParams getParams() { return menu_params_; } void Wait() { if (!context_menu_created_) message_loop_runner_->Run(); context_menu_created_ = false; } private: bool context_menu_created_; ContextMenuParams menu_params_; // The MessageLoopRunner used to spin the message loop. scoped_refptr<MessageLoopRunner> message_loop_runner_; DISALLOW_COPY_AND_ASSIGN(ContextMenuObserverDelegate); }; // Helper function to run the CreateContextMenuTest in either normal // or high DPI mode. void CreateContextMenuTestHelper( Shell* shell, net::test_server::EmbeddedTestServer* embedded_test_server) { GURL main_url(embedded_test_server->GetURL( "/frame_tree/page_with_positioned_frame.html")); EXPECT_TRUE(NavigateToURL(shell, main_url)); // It is safe to obtain the root frame tree node here, as it doesn't change. FrameTreeNode* root = static_cast<WebContentsImpl*>(shell->web_contents()) ->GetFrameTree() ->root(); ASSERT_EQ(1U, root->child_count()); FrameTreeNode* child_node = root->child_at(0); GURL site_url(embedded_test_server->GetURL("baz.com", "/title1.html")); EXPECT_EQ(site_url, child_node->current_url()); EXPECT_NE(shell->web_contents()->GetSiteInstance(), child_node->current_frame_host()->GetSiteInstance()); RenderWidgetHostViewBase* root_view = static_cast<RenderWidgetHostViewBase*>( root->current_frame_host()->GetRenderWidgetHost()->GetView()); RenderWidgetHostViewBase* rwhv_child = static_cast<RenderWidgetHostViewBase*>( child_node->current_frame_host()->GetRenderWidgetHost()->GetView()); // Ensure that the child process renderer is ready to have input events // routed to it. This happens when the browser process has received // updated compositor surfaces from both renderer processes. SurfaceHitTestReadyNotifier notifier( static_cast<RenderWidgetHostViewChildFrame*>(rwhv_child)); notifier.WaitForSurfaceReady(); // A WebContentsDelegate to listen for the ShowContextMenu message. ContextMenuObserverDelegate context_menu_delegate; shell->web_contents()->SetDelegate(&context_menu_delegate); RenderWidgetHostInputEventRouter* router = static_cast<WebContentsImpl*>(shell->web_contents()) ->GetInputEventRouter(); gfx::Point point(75, 75); // Target right-click event to child frame. blink::WebMouseEvent click_event; click_event.type = blink::WebInputEvent::MouseDown; click_event.button = blink::WebPointerProperties::Button::Right; click_event.x = point.x(); click_event.y = point.y(); click_event.clickCount = 1; router->RouteMouseEvent(root_view, &click_event, ui::LatencyInfo()); // We also need a MouseUp event, needed by Windows. click_event.type = blink::WebInputEvent::MouseUp; click_event.x = point.x(); click_event.y = point.y(); router->RouteMouseEvent(root_view, &click_event, ui::LatencyInfo()); context_menu_delegate.Wait(); ContextMenuParams params = context_menu_delegate.getParams(); EXPECT_EQ(point.x(), params.x); EXPECT_EQ(point.y(), params.y); } // Test that a mouse right-click to an out-of-process iframe causes a context // menu to be generated with the correct screen position. #if defined(OS_ANDROID) // Browser process hit testing is not implemented on Android. // https://crbug.com/491334 #define MAYBE_CreateContextMenuTest DISABLED_CreateContextMenuTest #else #define MAYBE_CreateContextMenuTest CreateContextMenuTest #endif IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, MAYBE_CreateContextMenuTest) { CreateContextMenuTestHelper(shell(), embedded_test_server()); } // Test that a mouse right-click to an out-of-process iframe causes a context // menu to be generated with the correct screen position on a screen with // non-default scale factor. #if defined(OS_ANDROID) || defined(OS_WIN) // Browser process hit testing is not implemented on Android. // https://crbug.com/491334 // Windows is disabled because of https://crbug.com/545547. #define MAYBE_HighDPICreateContextMenuTest DISABLED_HighDPICreateContextMenuTest #else #define MAYBE_HighDPICreateContextMenuTest HighDPICreateContextMenuTest #endif IN_PROC_BROWSER_TEST_F(SitePerProcessHighDPIBrowserTest, MAYBE_HighDPICreateContextMenuTest) { CreateContextMenuTestHelper(shell(), embedded_test_server()); } class ShowWidgetMessageFilter : public content::BrowserMessageFilter { public: ShowWidgetMessageFilter() #if defined(OS_MACOSX) || defined(OS_ANDROID) : content::BrowserMessageFilter(FrameMsgStart), #else : content::BrowserMessageFilter(ViewMsgStart), #endif message_loop_runner_(new content::MessageLoopRunner) { } bool OnMessageReceived(const IPC::Message& message) override { IPC_BEGIN_MESSAGE_MAP(ShowWidgetMessageFilter, message) #if defined(OS_MACOSX) || defined(OS_ANDROID) IPC_MESSAGE_HANDLER(FrameHostMsg_ShowPopup, OnShowPopup) #else IPC_MESSAGE_HANDLER(ViewHostMsg_ShowWidget, OnShowWidget) #endif IPC_END_MESSAGE_MAP() return false; } gfx::Rect last_initial_rect() const { return initial_rect_; } void Wait() { initial_rect_ = gfx::Rect(); message_loop_runner_->Run(); } void Reset() { initial_rect_ = gfx::Rect(); message_loop_runner_ = new content::MessageLoopRunner; } private: ~ShowWidgetMessageFilter() override {} void OnShowWidget(int route_id, const gfx::Rect& initial_rect) { content::BrowserThread::PostTask( content::BrowserThread::UI, FROM_HERE, base::Bind(&ShowWidgetMessageFilter::OnShowWidgetOnUI, this, route_id, initial_rect)); } #if defined(OS_MACOSX) || defined(OS_ANDROID) void OnShowPopup(const FrameHostMsg_ShowPopup_Params& params) { content::BrowserThread::PostTask( content::BrowserThread::UI, FROM_HERE, base::Bind(&ShowWidgetMessageFilter::OnShowWidgetOnUI, this, MSG_ROUTING_NONE, params.bounds)); } #endif void OnShowWidgetOnUI(int route_id, const gfx::Rect& initial_rect) { initial_rect_ = initial_rect; message_loop_runner_->Quit(); } scoped_refptr<content::MessageLoopRunner> message_loop_runner_; gfx::Rect initial_rect_; DISALLOW_COPY_AND_ASSIGN(ShowWidgetMessageFilter); }; // Test that clicking a select element in an out-of-process iframe creates // a popup menu in the correct position. #if defined(OS_ANDROID) // Surface-based hit testing and coordinate translation is not yet available // on Android. #define MAYBE_PopupMenuTest DISABLED_PopupMenuTest #else #define MAYBE_PopupMenuTest PopupMenuTest #endif IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, MAYBE_PopupMenuTest) { GURL main_url( embedded_test_server()->GetURL("/cross_site_iframe_factory.html?a(a)")); NavigateToURL(shell(), main_url); FrameTreeNode* root = web_contents()->GetFrameTree()->root(); #if !defined(OS_MACOSX) // Unused variable on Mac. RenderWidgetHostViewBase* rwhv_root = static_cast<RenderWidgetHostViewBase*>( root->current_frame_host()->GetRenderWidgetHost()->GetView()); #endif web_contents()->SendScreenRects(); content::TestNavigationObserver navigation_observer(shell()->web_contents()); FrameTreeNode* child_node = root->child_at(0); GURL site_url(embedded_test_server()->GetURL( "baz.com", "/site_isolation/page-with-select.html")); NavigateFrameToURL(child_node, site_url); navigation_observer.Wait(); RenderWidgetHostViewBase* rwhv_child = static_cast<RenderWidgetHostViewBase*>( child_node->current_frame_host()->GetRenderWidgetHost()->GetView()); EXPECT_NE(shell()->web_contents()->GetSiteInstance(), child_node->current_frame_host()->GetSiteInstance()); scoped_refptr<ShowWidgetMessageFilter> filter = new ShowWidgetMessageFilter(); child_node->current_frame_host()->GetProcess()->AddFilter(filter.get()); // Target left-click event to child frame. blink::WebMouseEvent click_event; click_event.type = blink::WebInputEvent::MouseDown; click_event.button = blink::WebPointerProperties::Button::Left; click_event.x = 15; click_event.y = 15; click_event.clickCount = 1; rwhv_child->ProcessMouseEvent(click_event, ui::LatencyInfo()); // Dismiss the popup. click_event.x = 1; click_event.y = 1; rwhv_child->ProcessMouseEvent(click_event, ui::LatencyInfo()); filter->Wait(); gfx::Rect popup_rect = filter->last_initial_rect(); #if defined(OS_MACOSX) // On Mac we receive the coordinates before they are transformed, so they // are still relative to the out-of-process iframe origin. EXPECT_EQ(popup_rect.x(), 9); EXPECT_EQ(popup_rect.y(), 9); #else EXPECT_EQ(popup_rect.x() - rwhv_root->GetViewBounds().x(), 354); EXPECT_EQ(popup_rect.y() - rwhv_root->GetViewBounds().y(), 94); #endif } // Test that clicking a select element in a nested out-of-process iframe creates // a popup menu in the correct position, even if the top-level page repositions // its out-of-process iframe. This verifies that screen positioning information // is propagating down the frame tree correctly. #if defined(OS_ANDROID) // Surface-based hit testing and coordinate translation is not yet avaiable on // Android. #define MAYBE_NestedPopupMenuTest DISABLED_NestedPopupMenuTest #else // Times out frequently. https://crbug.com/599730. #define MAYBE_NestedPopupMenuTest DISABLED_NestedPopupMenuTest #endif IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, MAYBE_NestedPopupMenuTest) { GURL main_url(embedded_test_server()->GetURL( "/cross_site_iframe_factory.html?a(b(c))")); NavigateToURL(shell(), main_url); FrameTreeNode* root = web_contents()->GetFrameTree()->root(); #if !defined(OS_MACOSX) // Undefined variable on Mac. RenderWidgetHostViewBase* rwhv_root = static_cast<RenderWidgetHostViewBase*>( root->current_frame_host()->GetRenderWidgetHost()->GetView()); #endif web_contents()->SendScreenRects(); // For clarity, we are labeling the frame tree nodes as: // - root_node // \-> b_node (out-of-process from root and c_node) // \-> c_node (out-of-process from root and b_node) content::TestNavigationObserver navigation_observer(shell()->web_contents()); FrameTreeNode* b_node = root->child_at(0); FrameTreeNode* c_node = b_node->child_at(0); GURL site_url(embedded_test_server()->GetURL( "baz.com", "/site_isolation/page-with-select.html")); NavigateFrameToURL(c_node, site_url); RenderWidgetHostViewBase* rwhv_c_node = static_cast<RenderWidgetHostViewBase*>( c_node->current_frame_host()->GetRenderWidgetHost()->GetView()); EXPECT_NE(shell()->web_contents()->GetSiteInstance(), c_node->current_frame_host()->GetSiteInstance()); scoped_refptr<ShowWidgetMessageFilter> filter = new ShowWidgetMessageFilter(); c_node->current_frame_host()->GetProcess()->AddFilter(filter.get()); // Target left-click event to child frame. blink::WebMouseEvent click_event; click_event.type = blink::WebInputEvent::MouseDown; click_event.button = blink::WebPointerProperties::Button::Left; click_event.x = 15; click_event.y = 15; click_event.clickCount = 1; rwhv_c_node->ProcessMouseEvent(click_event, ui::LatencyInfo()); // Prompt the WebContents to dismiss the popup by clicking elsewhere. click_event.x = 1; click_event.y = 1; rwhv_c_node->ProcessMouseEvent(click_event, ui::LatencyInfo()); filter->Wait(); gfx::Rect popup_rect = filter->last_initial_rect(); #if defined(OS_MACOSX) EXPECT_EQ(popup_rect.x(), 9); EXPECT_EQ(popup_rect.y(), 9); #else EXPECT_EQ(popup_rect.x() - rwhv_root->GetViewBounds().x(), 354); EXPECT_EQ(popup_rect.y() - rwhv_root->GetViewBounds().y(), 154); #endif // Save the screen rect for b_node. Since it updates asynchronously from // the script command that changes it, we need to wait for it to change // before attempting to create the popup widget again. gfx::Rect last_b_node_bounds_rect = b_node->current_frame_host()->GetView()->GetViewBounds(); std::string script = "var iframe = document.querySelector('iframe');" "iframe.style.position = 'absolute';" "iframe.style.left = 150;" "iframe.style.top = 150;"; EXPECT_TRUE(ExecuteScript(root, script)); filter->Reset(); // Busy loop to wait for b_node's screen rect to get updated. There // doesn't seem to be any better way to find out when this happens. while (last_b_node_bounds_rect.x() == b_node->current_frame_host()->GetView()->GetViewBounds().x() && last_b_node_bounds_rect.y() == b_node->current_frame_host()->GetView()->GetViewBounds().y()) { base::RunLoop run_loop; base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, run_loop.QuitClosure(), TestTimeouts::tiny_timeout()); run_loop.Run(); } click_event.button = blink::WebPointerProperties::Button::Left; click_event.x = 15; click_event.y = 15; click_event.clickCount = 1; rwhv_c_node->ProcessMouseEvent(click_event, ui::LatencyInfo()); click_event.x = 1; click_event.y = 1; rwhv_c_node->ProcessMouseEvent(click_event, ui::LatencyInfo()); filter->Wait(); popup_rect = filter->last_initial_rect(); #if defined(OS_MACOSX) EXPECT_EQ(popup_rect.x(), 9); EXPECT_EQ(popup_rect.y(), 9); #else EXPECT_EQ(popup_rect.x() - rwhv_root->GetViewBounds().x(), 203); EXPECT_EQ(popup_rect.y() - rwhv_root->GetViewBounds().y(), 248); #endif } // Test for https://crbug.com/526304, where a parent frame executes a // remote-to-local navigation on a child frame and immediately removes the same // child frame. This test exercises the path where the detach happens before // the provisional local frame is created. IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, NavigateProxyAndDetachBeforeProvisionalFrameCreation) { GURL main_url(embedded_test_server()->GetURL( "a.com", "/cross_site_iframe_factory.html?a(b,b)")); EXPECT_TRUE(NavigateToURL(shell(), main_url)); WebContents* contents = shell()->web_contents(); FrameTreeNode* root = static_cast<WebContentsImpl*>(contents)->GetFrameTree()->root(); EXPECT_EQ(2U, root->child_count()); // Navigate the first child frame to 'about:blank' (which is a // remote-to-local transition), and then detach it. FrameDeletedObserver observer(root->child_at(0)); std::string script = "var f = document.querySelector('iframe');" "f.contentWindow.location.href = 'about:blank';" "setTimeout(function() { document.body.removeChild(f); }, 0);"; EXPECT_TRUE(ExecuteScript(root, script)); observer.Wait(); EXPECT_EQ(1U, root->child_count()); // Make sure the main frame renderer does not crash and ignores the // navigation to the frame that's already been deleted. int child_count = 0; EXPECT_TRUE(ExecuteScriptAndExtractInt( root, "domAutomationController.send(frames.length)", &child_count)); EXPECT_EQ(1, child_count); } // Test for a variation of https://crbug.com/526304, where a child frame does a // remote-to-local navigation, and the parent frame removes that child frame // after the provisional local frame is created and starts to navigate, but // before it commits. IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, NavigateProxyAndDetachBeforeCommit) { GURL main_url(embedded_test_server()->GetURL( "a.com", "/cross_site_iframe_factory.html?a(b,b)")); EXPECT_TRUE(NavigateToURL(shell(), main_url)); WebContents* contents = shell()->web_contents(); FrameTreeNode* root = static_cast<WebContentsImpl*>(contents)->GetFrameTree()->root(); EXPECT_EQ(2U, root->child_count()); FrameTreeNode* child = root->child_at(0); // Start a remote-to-local navigation for the child, but don't wait for // commit. GURL same_site_url(embedded_test_server()->GetURL("a.com", "/title1.html")); NavigationController::LoadURLParams params(same_site_url); params.transition_type = ui::PAGE_TRANSITION_LINK; params.frame_tree_node_id = child->frame_tree_node_id(); child->navigator()->GetController()->LoadURLWithParams(params); // Tell parent to remove the first child. This should happen after the // previous navigation starts but before it commits. FrameDeletedObserver observer(child); EXPECT_TRUE(ExecuteScript( root, "document.body.removeChild(document.querySelector('iframe'));")); observer.Wait(); EXPECT_EQ(1U, root->child_count()); // Make sure the a.com renderer does not crash. int child_count = 0; EXPECT_TRUE(ExecuteScriptAndExtractInt( root, "domAutomationController.send(frames.length)", &child_count)); EXPECT_EQ(1, child_count); } // Similar to NavigateProxyAndDetachBeforeCommit, but uses a synchronous // navigation to about:blank and the parent removes the child frame in a load // event handler for the subframe. IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, NavigateAboutBlankAndDetach) { GURL main_url( embedded_test_server()->GetURL("a.com", "/remove_frame_on_load.html")); EXPECT_TRUE(NavigateToURL(shell(), main_url)); WebContents* contents = shell()->web_contents(); FrameTreeNode* root = static_cast<WebContentsImpl*>(contents)->GetFrameTree()->root(); EXPECT_EQ(1U, root->child_count()); FrameTreeNode* child = root->child_at(0); EXPECT_NE(shell()->web_contents()->GetSiteInstance(), child->current_frame_host()->GetSiteInstance()); // Navigate the child frame to "about:blank" from the parent document. TestNavigationObserver observer(shell()->web_contents()); EXPECT_TRUE(ExecuteScript( root, base::StringPrintf("f.src = '%s'", url::kAboutBlankURL))); observer.Wait(); // Make sure the a.com renderer does not crash and the frame is removed. int child_count = 0; EXPECT_TRUE(ExecuteScriptAndExtractInt( root, "domAutomationController.send(frames.length)", &child_count)); EXPECT_EQ(0, child_count); } // Test for https://crbug.com/568670. In A-embed-B, simultaneously have B // create a new (local) child frame, and have A detach B's proxy. The child // frame creation sends an IPC to create a new proxy in A's process, and if // that IPC arrives after the detach, the new frame's parent (a proxy) won't be // available, and this shouldn't cause RenderFrameProxy::CreateFrameProxy to // crash. IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, RaceBetweenCreateChildFrameAndDetachParentProxy) { GURL main_url(embedded_test_server()->GetURL( "a.com", "/cross_site_iframe_factory.html?a(b)")); EXPECT_TRUE(NavigateToURL(shell(), main_url)); WebContents* contents = shell()->web_contents(); FrameTreeNode* root = static_cast<WebContentsImpl*>(contents)->GetFrameTree()->root(); // Simulate subframe B creating a new child frame in parallel to main frame A // detaching subframe B. We can't use ExecuteScript in both A and B to do // this simultaneously, as that won't guarantee the timing that we want. // Instead, tell A to detach B and then send a fake proxy creation IPC to A // that would've come from create-child-frame code in B. Prepare parameters // for that IPC ahead of the detach, while B's FrameTreeNode still exists. SiteInstance* site_instance_a = root->current_frame_host()->GetSiteInstance(); RenderProcessHost* process_a = root->render_manager()->current_frame_host()->GetProcess(); int new_routing_id = process_a->GetNextRoutingID(); int view_routing_id = root->frame_tree()->GetRenderViewHost(site_instance_a)->GetRoutingID(); int parent_routing_id = root->child_at(0)->render_manager()->GetProxyToParent()->GetRoutingID(); // Tell main frame A to delete its subframe B. FrameDeletedObserver observer(root->child_at(0)); EXPECT_TRUE(ExecuteScript( root, "document.body.removeChild(document.querySelector('iframe'));")); // Send the message to create a proxy for B's new child frame in A. This // used to crash, as parent_routing_id refers to a proxy that doesn't exist // anymore. process_a->GetRendererInterface()->CreateFrameProxy( new_routing_id, view_routing_id, MSG_ROUTING_NONE, parent_routing_id, FrameReplicationState()); // Ensure the subframe is detached in the browser process. observer.Wait(); EXPECT_EQ(0U, root->child_count()); // Make sure process A did not crash. int child_count = 0; EXPECT_TRUE(ExecuteScriptAndExtractInt( root, "domAutomationController.send(frames.length)", &child_count)); EXPECT_EQ(0, child_count); } // This test ensures that the RenderFrame isn't leaked in the renderer process // if a pending cross-process navigation is cancelled. The test works by trying // to create a new RenderFrame with the same routing id. If there is an // entry with the same routing ID, a CHECK is hit and the process crashes. IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, SubframePendingAndBackToSameSiteInstance) { GURL main_url(embedded_test_server()->GetURL( "a.com", "/cross_site_iframe_factory.html?a(b)")); NavigateToURL(shell(), main_url); // Capture the FrameTreeNode this test will be navigating. FrameTreeNode* node = web_contents()->GetFrameTree()->root()->child_at(0); EXPECT_TRUE(node); EXPECT_NE(node->current_frame_host()->GetSiteInstance(), node->parent()->current_frame_host()->GetSiteInstance()); // Navigate to the site of the parent, but to a page that will not commit. GURL same_site_url(embedded_test_server()->GetURL("a.com", "/title1.html")); NavigationStallDelegate stall_delegate(same_site_url); ResourceDispatcherHost::Get()->SetDelegate(&stall_delegate); { NavigationController::LoadURLParams params(same_site_url); params.transition_type = ui::PAGE_TRANSITION_LINK; params.frame_tree_node_id = node->frame_tree_node_id(); node->navigator()->GetController()->LoadURLWithParams(params); } // Grab the routing id of the pending RenderFrameHost and set up a process // observer to ensure there is no crash when a new RenderFrame creation is // attempted. RenderProcessHost* process = IsBrowserSideNavigationEnabled() ? node->render_manager()->speculative_frame_host()->GetProcess() : node->render_manager()->pending_frame_host()->GetProcess(); RenderProcessHostWatcher watcher( process, RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT); int frame_routing_id = IsBrowserSideNavigationEnabled() ? node->render_manager()->speculative_frame_host()->GetRoutingID() : node->render_manager()->pending_frame_host()->GetRoutingID(); int proxy_routing_id = node->render_manager()->GetProxyToParent()->GetRoutingID(); // Now go to c.com so the navigation to a.com is cancelled and send an IPC // to create a new RenderFrame with the routing id of the previously pending // one. NavigateFrameToURL(node, embedded_test_server()->GetURL("c.com", "/title2.html")); { mojom::CreateFrameParamsPtr params = mojom::CreateFrameParams::New(); params->routing_id = frame_routing_id; params->proxy_routing_id = proxy_routing_id; params->opener_routing_id = IPC::mojom::kRoutingIdNone; params->parent_routing_id = shell()->web_contents()->GetMainFrame()->GetRoutingID(); params->previous_sibling_routing_id = IPC::mojom::kRoutingIdNone; params->widget_params = mojom::CreateFrameWidgetParams::New(); params->widget_params->routing_id = IPC::mojom::kRoutingIdNone; params->widget_params->hidden = true; params->replication_state.name = "name"; params->replication_state.unique_name = "name"; process->GetRendererInterface()->CreateFrame(std::move(params)); } // The test must wait for the process to exit, but if there is no leak, the // RenderFrame will be properly created and there will be no crash. // Therefore, navigate the main frame to completely different site, which // will cause the original process to exit cleanly. EXPECT_TRUE(NavigateToURL( shell(), embedded_test_server()->GetURL("d.com", "/title3.html"))); watcher.Wait(); EXPECT_TRUE(watcher.did_exit_normally()); ResourceDispatcherHost::Get()->SetDelegate(nullptr); } // This test ensures that the RenderFrame isn't leaked in the renderer process // when a remote parent detaches a child frame. The test works by trying // to create a new RenderFrame with the same routing id. If there is an // entry with the same routing ID, a CHECK is hit and the process crashes. IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, ParentDetachRemoteChild) { GURL main_url(embedded_test_server()->GetURL( "a.com", "/cross_site_iframe_factory.html?a(b,b)")); NavigateToURL(shell(), main_url); WebContentsImpl* contents = web_contents(); EXPECT_EQ(2U, contents->GetFrameTree()->root()->child_count()); // Capture the FrameTreeNode this test will be navigating. FrameTreeNode* node = contents->GetFrameTree()->root()->child_at(0); EXPECT_TRUE(node); EXPECT_NE(node->current_frame_host()->GetSiteInstance(), node->parent()->current_frame_host()->GetSiteInstance()); // Grab the routing id of the first child RenderFrameHost and set up a process // observer to ensure there is no crash when a new RenderFrame creation is // attempted. RenderProcessHost* process = node->current_frame_host()->GetProcess(); RenderProcessHostWatcher watcher( process, RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT); int frame_routing_id = node->current_frame_host()->GetRoutingID(); int widget_routing_id = node->current_frame_host()->GetRenderWidgetHost()->GetRoutingID(); int parent_routing_id = node->parent()->render_manager()->GetRoutingIdForSiteInstance( node->current_frame_host()->GetSiteInstance()); // Have the parent frame remove the child frame from its DOM. This should // result in the child RenderFrame being deleted in the remote process. EXPECT_TRUE(ExecuteScript(contents, "document.body.removeChild(" "document.querySelectorAll('iframe')[0])")); EXPECT_EQ(1U, contents->GetFrameTree()->root()->child_count()); { mojom::CreateFrameParamsPtr params = mojom::CreateFrameParams::New(); params->routing_id = frame_routing_id; params->proxy_routing_id = IPC::mojom::kRoutingIdNone; params->opener_routing_id = IPC::mojom::kRoutingIdNone; params->parent_routing_id = parent_routing_id; params->previous_sibling_routing_id = IPC::mojom::kRoutingIdNone; params->widget_params = mojom::CreateFrameWidgetParams::New(); params->widget_params->routing_id = widget_routing_id; params->widget_params->hidden = true; params->replication_state.name = "name"; params->replication_state.unique_name = "name"; process->GetRendererInterface()->CreateFrame(std::move(params)); } // The test must wait for the process to exit, but if there is no leak, the // RenderFrame will be properly created and there will be no crash. // Therefore, navigate the remaining subframe to completely different site, // which will cause the original process to exit cleanly. NavigateFrameToURL(contents->GetFrameTree()->root()->child_at(0), embedded_test_server()->GetURL("d.com", "/title3.html")); watcher.Wait(); EXPECT_TRUE(watcher.did_exit_normally()); } IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, VisibilityChanged) { GURL main_url( embedded_test_server()->GetURL("a.com", "/page_with_iframe.html")); EXPECT_TRUE(NavigateToURL(shell(), main_url)); EXPECT_EQ(shell()->web_contents()->GetLastCommittedURL(), main_url); GURL cross_site_url = embedded_test_server()->GetURL("oopif.com", "/title1.html"); FrameTreeNode* root = web_contents()->GetFrameTree()->root(); TestNavigationObserver observer(shell()->web_contents()); NavigateFrameToURL(root->child_at(0), cross_site_url); EXPECT_EQ(cross_site_url, observer.last_navigation_url()); EXPECT_TRUE(observer.last_navigation_succeeded()); RenderWidgetHostImpl* render_widget_host = root->child_at(0)->current_frame_host()->GetRenderWidgetHost(); EXPECT_FALSE(render_widget_host->is_hidden()); std::string show_script = "document.querySelector('iframe').style.visibility = 'visible';"; std::string hide_script = "document.querySelector('iframe').style.visibility = 'hidden';"; // Verify that hiding leads to a notification from RenderWidgetHost. RenderWidgetHostVisibilityObserver hide_observer( root->child_at(0)->current_frame_host()->GetRenderWidgetHost(), false); EXPECT_TRUE(ExecuteScript(shell(), hide_script)); EXPECT_TRUE(hide_observer.WaitUntilSatisfied()); // Verify showing leads to a notification as well. RenderWidgetHostVisibilityObserver show_observer( root->child_at(0)->current_frame_host()->GetRenderWidgetHost(), true); EXPECT_TRUE(ExecuteScript(shell(), show_script)); EXPECT_TRUE(show_observer.WaitUntilSatisfied()); } // Verify that sandbox flags inheritance works across multiple levels of // frames. See https://crbug.com/576845. IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, SandboxFlagsInheritance) { GURL main_url(embedded_test_server()->GetURL( "a.com", "/cross_site_iframe_factory.html?a(a)")); NavigateToURL(shell(), main_url); // It is safe to obtain the root frame tree node here, as it doesn't change. FrameTreeNode* root = web_contents()->GetFrameTree()->root(); // Set sandbox flags for child frame. EXPECT_TRUE(ExecuteScript( root, "document.querySelector('iframe').sandbox = 'allow-scripts';")); // Calculate expected flags. Note that "allow-scripts" resets both // WebSandboxFlags::Scripts and WebSandboxFlags::AutomaticFeatures bits per // blink::parseSandboxPolicy(). blink::WebSandboxFlags expected_flags = blink::WebSandboxFlags::All & ~blink::WebSandboxFlags::Scripts & ~blink::WebSandboxFlags::AutomaticFeatures; EXPECT_EQ(expected_flags, root->child_at(0)->pending_sandbox_flags()); EXPECT_EQ(blink::WebSandboxFlags::None, root->child_at(0)->effective_sandbox_flags()); // Navigate child frame so that the sandbox flags take effect. Use a page // with three levels of frames and make sure all frames properly inherit // sandbox flags. GURL frame_url(embedded_test_server()->GetURL( "b.com", "/cross_site_iframe_factory.html?b(c(d))")); NavigateFrameToURL(root->child_at(0), frame_url); // Wait for subframes to load as well. ASSERT_TRUE(WaitForLoadStop(shell()->web_contents())); // Check each new frame's sandbox flags on the browser process side. FrameTreeNode* b_child = root->child_at(0); FrameTreeNode* c_child = b_child->child_at(0); FrameTreeNode* d_child = c_child->child_at(0); EXPECT_EQ(expected_flags, b_child->effective_sandbox_flags()); EXPECT_EQ(expected_flags, c_child->effective_sandbox_flags()); EXPECT_EQ(expected_flags, d_child->effective_sandbox_flags()); // Check whether each frame is sandboxed on the renderer side, by seeing if // each frame's origin is unique ("null"). EXPECT_EQ("null", GetDocumentOrigin(b_child)); EXPECT_EQ("null", GetDocumentOrigin(c_child)); EXPECT_EQ("null", GetDocumentOrigin(d_child)); } // Check that sandbox flags are not inherited before they take effect. Create // a child frame, update its sandbox flags but don't navigate the frame, and // ensure that a new cross-site grandchild frame doesn't inherit the new flags // (which shouldn't have taken effect). IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, SandboxFlagsNotInheritedBeforeNavigation) { GURL main_url(embedded_test_server()->GetURL( "a.com", "/cross_site_iframe_factory.html?a(a)")); NavigateToURL(shell(), main_url); // It is safe to obtain the root frame tree node here, as it doesn't change. FrameTreeNode* root = web_contents()->GetFrameTree()->root(); // Set sandbox flags for child frame. EXPECT_TRUE(ExecuteScript( root, "document.querySelector('iframe').sandbox = 'allow-scripts';")); // These flags should be pending but not take effect, since there's been no // navigation. blink::WebSandboxFlags expected_flags = blink::WebSandboxFlags::All & ~blink::WebSandboxFlags::Scripts & ~blink::WebSandboxFlags::AutomaticFeatures; FrameTreeNode* child = root->child_at(0); EXPECT_EQ(expected_flags, child->pending_sandbox_flags()); EXPECT_EQ(blink::WebSandboxFlags::None, child->effective_sandbox_flags()); // Add a new grandchild frame and navigate it cross-site. RenderFrameHostCreatedObserver frame_observer(shell()->web_contents(), 1); EXPECT_TRUE(ExecuteScript( child, "document.body.appendChild(document.createElement('iframe'));")); frame_observer.Wait(); FrameTreeNode* grandchild = child->child_at(0); GURL frame_url(embedded_test_server()->GetURL("b.com", "/title1.html")); TestFrameNavigationObserver navigation_observer(grandchild); NavigateFrameToURL(grandchild, frame_url); navigation_observer.Wait(); // Since the update flags haven't yet taken effect in its parent, this // grandchild frame should not be sandboxed. EXPECT_EQ(blink::WebSandboxFlags::None, grandchild->pending_sandbox_flags()); EXPECT_EQ(blink::WebSandboxFlags::None, grandchild->effective_sandbox_flags()); // Check that the grandchild frame isn't sandboxed on the renderer side. If // sandboxed, its origin would be unique ("null"). EXPECT_EQ(frame_url.GetOrigin().spec(), GetDocumentOrigin(grandchild) + "/"); } // Verify that popups opened from sandboxed frames inherit sandbox flags from // their opener, and that they keep these inherited flags after being navigated // cross-site. See https://crbug.com/483584. IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, NewPopupInheritsSandboxFlagsFromOpener) { GURL main_url(embedded_test_server()->GetURL( "a.com", "/cross_site_iframe_factory.html?a(a)")); EXPECT_TRUE(NavigateToURL(shell(), main_url)); // It is safe to obtain the root frame tree node here, as it doesn't change. FrameTreeNode* root = web_contents()->GetFrameTree()->root(); // Set sandbox flags for child frame. EXPECT_TRUE(ExecuteScript(root, "document.querySelector('iframe').sandbox = " " 'allow-scripts allow-popups';")); // Calculate expected flags. Note that "allow-scripts" resets both // WebSandboxFlags::Scripts and WebSandboxFlags::AutomaticFeatures bits per // blink::parseSandboxPolicy(). blink::WebSandboxFlags expected_flags = blink::WebSandboxFlags::All & ~blink::WebSandboxFlags::Scripts & ~blink::WebSandboxFlags::AutomaticFeatures & ~blink::WebSandboxFlags::Popups; EXPECT_EQ(expected_flags, root->child_at(0)->pending_sandbox_flags()); // Navigate child frame cross-site. The sandbox flags should take effect. GURL frame_url(embedded_test_server()->GetURL("b.com", "/title1.html")); TestFrameNavigationObserver frame_observer(root->child_at(0)); NavigateFrameToURL(root->child_at(0), frame_url); frame_observer.Wait(); EXPECT_EQ(expected_flags, root->child_at(0)->effective_sandbox_flags()); // Verify that they've also taken effect on the renderer side. The sandboxed // frame's origin should be unique. EXPECT_EQ("null", GetDocumentOrigin(root->child_at(0))); // Open a popup named "foo" from the sandboxed child frame. Shell* foo_shell = OpenPopup(root->child_at(0), GURL(url::kAboutBlankURL), "foo"); EXPECT_TRUE(foo_shell); FrameTreeNode* foo_root = static_cast<WebContentsImpl*>(foo_shell->web_contents()) ->GetFrameTree() ->root(); // Check that the sandbox flags for new popup are correct in the browser // process. EXPECT_EQ(expected_flags, foo_root->effective_sandbox_flags()); // The popup's origin should be unique, since it's sandboxed. EXPECT_EQ("null", GetDocumentOrigin(foo_root)); // Navigate the popup cross-site. This should keep the unique origin and the // inherited sandbox flags. GURL c_url(embedded_test_server()->GetURL("c.com", "/title1.html")); TestFrameNavigationObserver popup_observer(foo_root); EXPECT_TRUE( ExecuteScript(foo_root, "location.href = '" + c_url.spec() + "';")); popup_observer.Wait(); EXPECT_EQ(c_url, foo_shell->web_contents()->GetLastCommittedURL()); // Confirm that the popup is still sandboxed, both on browser and renderer // sides. EXPECT_EQ(expected_flags, foo_root->effective_sandbox_flags()); EXPECT_EQ("null", GetDocumentOrigin(foo_root)); } // Verify that popups opened from frames sandboxed with the // "allow-popups-to-escape-sandbox" directive do *not* inherit sandbox flags // from their opener. IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, OpenUnsandboxedPopupFromSandboxedFrame) { GURL main_url(embedded_test_server()->GetURL( "a.com", "/cross_site_iframe_factory.html?a(a)")); EXPECT_TRUE(NavigateToURL(shell(), main_url)); // It is safe to obtain the root frame tree node here, as it doesn't change. FrameTreeNode* root = web_contents()->GetFrameTree()->root(); // Set sandbox flags for child frame, specifying that popups opened from it // should not be sandboxed. EXPECT_TRUE(ExecuteScript( root, "document.querySelector('iframe').sandbox = " " 'allow-scripts allow-popups allow-popups-to-escape-sandbox';")); // Set expected flags for the child frame. Note that "allow-scripts" resets // both WebSandboxFlags::Scripts and WebSandboxFlags::AutomaticFeatures bits // per blink::parseSandboxPolicy(). blink::WebSandboxFlags expected_flags = blink::WebSandboxFlags::All & ~blink::WebSandboxFlags::Scripts & ~blink::WebSandboxFlags::AutomaticFeatures & ~blink::WebSandboxFlags::Popups & ~blink::WebSandboxFlags::PropagatesToAuxiliaryBrowsingContexts; EXPECT_EQ(expected_flags, root->child_at(0)->pending_sandbox_flags()); // Navigate child frame cross-site. The sandbox flags should take effect. GURL frame_url(embedded_test_server()->GetURL("b.com", "/title1.html")); TestFrameNavigationObserver frame_observer(root->child_at(0)); NavigateFrameToURL(root->child_at(0), frame_url); frame_observer.Wait(); EXPECT_EQ(expected_flags, root->child_at(0)->effective_sandbox_flags()); // Open a cross-site popup named "foo" from the child frame. GURL b_url(embedded_test_server()->GetURL("c.com", "/title1.html")); Shell* foo_shell = OpenPopup(root->child_at(0), b_url, "foo"); EXPECT_TRUE(foo_shell); FrameTreeNode* foo_root = static_cast<WebContentsImpl*>(foo_shell->web_contents()) ->GetFrameTree() ->root(); // Check that the sandbox flags for new popup are correct in the browser // process. They should not have been inherited. EXPECT_EQ(blink::WebSandboxFlags::None, foo_root->effective_sandbox_flags()); // The popup's origin should match |b_url|, since it's not sandboxed. std::string popup_origin; EXPECT_TRUE(ExecuteScriptAndExtractString( foo_root, "domAutomationController.send(document.origin)", &popup_origin)); EXPECT_EQ(b_url.GetOrigin().spec(), popup_origin + "/"); } // Tests that the WebContents is notified when passive mixed content is // displayed in an OOPIF. The test ignores cert errors so that an HTTPS // iframe can be loaded from a site other than localhost (the // EmbeddedTestServer serves a certificate that is valid for localhost). // This test crashes on Windows under Dr. Memory, see https://crbug.com/600942. #if defined(OS_WIN) #define MAYBE_PassiveMixedContentInIframe DISABLED_PassiveMixedContentInIframe #else #define MAYBE_PassiveMixedContentInIframe PassiveMixedContentInIframe #endif IN_PROC_BROWSER_TEST_F(SitePerProcessIgnoreCertErrorsBrowserTest, MAYBE_PassiveMixedContentInIframe) { net::EmbeddedTestServer https_server(net::EmbeddedTestServer::TYPE_HTTPS); https_server.ServeFilesFromSourceDirectory("content/test/data"); ASSERT_TRUE(https_server.Start()); SetupCrossSiteRedirector(&https_server); WebContentsImpl* web_contents = static_cast<WebContentsImpl*>(shell()->web_contents()); GURL iframe_url( https_server.GetURL("/mixed-content/basic-passive-in-iframe.html")); EXPECT_TRUE(NavigateToURL(shell(), iframe_url)); NavigationEntry* entry = web_contents->GetController().GetVisibleEntry(); EXPECT_TRUE(!!(entry->GetSSL().content_status & SSLStatus::DISPLAYED_INSECURE_CONTENT)); // When the subframe navigates, the WebContents should still be marked // as having displayed insecure content. GURL navigate_url(https_server.GetURL("/title1.html")); FrameTreeNode* root = web_contents->GetFrameTree()->root(); NavigateFrameToURL(root->child_at(0), navigate_url); entry = web_contents->GetController().GetVisibleEntry(); EXPECT_TRUE(!!(entry->GetSSL().content_status & SSLStatus::DISPLAYED_INSECURE_CONTENT)); // When the main frame navigates, it should no longer be marked as // displaying insecure content. EXPECT_TRUE( NavigateToURL(shell(), https_server.GetURL("b.com", "/title1.html"))); entry = web_contents->GetController().GetVisibleEntry(); EXPECT_FALSE(!!(entry->GetSSL().content_status & SSLStatus::DISPLAYED_INSECURE_CONTENT)); } // Tests that, when a parent frame is set to strictly block mixed // content via Content Security Policy, child OOPIFs cannot display // mixed content. IN_PROC_BROWSER_TEST_F(SitePerProcessIgnoreCertErrorsBrowserTest, PassiveMixedContentInIframeWithStrictBlocking) { net::EmbeddedTestServer https_server(net::EmbeddedTestServer::TYPE_HTTPS); https_server.ServeFilesFromSourceDirectory("content/test/data"); ASSERT_TRUE(https_server.Start()); SetupCrossSiteRedirector(&https_server); WebContentsImpl* web_contents = static_cast<WebContentsImpl*>(shell()->web_contents()); GURL iframe_url_with_strict_blocking(https_server.GetURL( "/mixed-content/basic-passive-in-iframe-with-strict-blocking.html")); EXPECT_TRUE(NavigateToURL(shell(), iframe_url_with_strict_blocking)); NavigationEntry* entry = web_contents->GetController().GetVisibleEntry(); EXPECT_FALSE(!!(entry->GetSSL().content_status & SSLStatus::DISPLAYED_INSECURE_CONTENT)); FrameTreeNode* root = web_contents->GetFrameTree()->root(); EXPECT_EQ(blink::kBlockAllMixedContent, root->current_replication_state().insecure_request_policy); EXPECT_EQ( blink::kBlockAllMixedContent, root->child_at(0)->current_replication_state().insecure_request_policy); // When the subframe navigates, it should still be marked as enforcing // strict mixed content. GURL navigate_url(https_server.GetURL("/title1.html")); NavigateFrameToURL(root->child_at(0), navigate_url); EXPECT_EQ(blink::kBlockAllMixedContent, root->current_replication_state().insecure_request_policy); EXPECT_EQ( blink::kBlockAllMixedContent, root->child_at(0)->current_replication_state().insecure_request_policy); // When the main frame navigates, it should no longer be marked as // enforcing strict mixed content. EXPECT_TRUE( NavigateToURL(shell(), https_server.GetURL("b.com", "/title1.html"))); EXPECT_EQ(blink::kLeaveInsecureRequestsAlone, root->current_replication_state().insecure_request_policy); } // Tests that, when a parent frame is set to upgrade insecure requests // via Content Security Policy, child OOPIFs will upgrade as well. IN_PROC_BROWSER_TEST_F(SitePerProcessIgnoreCertErrorsBrowserTest, PassiveMixedContentInIframeWithUpgrade) { net::EmbeddedTestServer https_server(net::EmbeddedTestServer::TYPE_HTTPS); https_server.ServeFilesFromSourceDirectory("content/test/data"); ASSERT_TRUE(https_server.Start()); SetupCrossSiteRedirector(&https_server); WebContentsImpl* web_contents = static_cast<WebContentsImpl*>(shell()->web_contents()); GURL iframe_url_with_upgrade(https_server.GetURL( "/mixed-content/basic-passive-in-iframe-with-upgrade.html")); EXPECT_TRUE(NavigateToURL(shell(), iframe_url_with_upgrade)); NavigationEntry* entry = web_contents->GetController().GetVisibleEntry(); EXPECT_FALSE(!!(entry->GetSSL().content_status & SSLStatus::DISPLAYED_INSECURE_CONTENT)); FrameTreeNode* root = web_contents->GetFrameTree()->root(); EXPECT_EQ(blink::kUpgradeInsecureRequests, root->current_replication_state().insecure_request_policy); EXPECT_EQ( blink::kUpgradeInsecureRequests, root->child_at(0)->current_replication_state().insecure_request_policy); // When the subframe navigates, it should still be marked as upgrading // insecure requests. GURL navigate_url(https_server.GetURL("/title1.html")); NavigateFrameToURL(root->child_at(0), navigate_url); EXPECT_EQ(blink::kUpgradeInsecureRequests, root->current_replication_state().insecure_request_policy); EXPECT_EQ( blink::kUpgradeInsecureRequests, root->child_at(0)->current_replication_state().insecure_request_policy); // When the main frame navigates, it should no longer be marked as // upgrading insecure requests. EXPECT_TRUE( NavigateToURL(shell(), https_server.GetURL("b.com", "/title1.html"))); EXPECT_EQ(blink::kLeaveInsecureRequestsAlone, root->current_replication_state().insecure_request_policy); } // Tests that active mixed content is blocked in an OOPIF. The test // ignores cert errors so that an HTTPS iframe can be loaded from a site // other than localhost (the EmbeddedTestServer serves a certificate // that is valid for localhost). IN_PROC_BROWSER_TEST_F(SitePerProcessIgnoreCertErrorsBrowserTest, ActiveMixedContentInIframe) { net::EmbeddedTestServer https_server(net::EmbeddedTestServer::TYPE_HTTPS); https_server.ServeFilesFromSourceDirectory("content/test/data"); ASSERT_TRUE(https_server.Start()); SetupCrossSiteRedirector(&https_server); GURL iframe_url( https_server.GetURL("/mixed-content/basic-active-in-iframe.html")); EXPECT_TRUE(NavigateToURL(shell(), iframe_url)); FrameTreeNode* root = web_contents()->GetFrameTree()->root(); ASSERT_EQ(1U, root->child_count()); FrameTreeNode* mixed_child = root->child_at(0)->child_at(0); ASSERT_TRUE(mixed_child); // The child iframe attempted to create a mixed iframe; this should // have been blocked, so the mixed iframe should not have committed a // load. EXPECT_FALSE(mixed_child->has_committed_real_load()); } // Test that subresources with certificate errors get reported to the // browser. That is, if https://example.test frames https://a.com which // loads an image with certificate errors, the browser should be // notified about the subresource with certificate errors and downgrade // the UI appropriately. IN_PROC_BROWSER_TEST_F(SitePerProcessIgnoreCertErrorsBrowserTest, SubresourceWithCertificateErrors) { net::EmbeddedTestServer https_server(net::EmbeddedTestServer::TYPE_HTTPS); https_server.ServeFilesFromSourceDirectory("content/test/data"); ASSERT_TRUE(https_server.Start()); SetupCrossSiteRedirector(&https_server); GURL url(https_server.GetURL( "example.test", "/mixed-content/non-redundant-cert-error-in-iframe.html")); EXPECT_TRUE(NavigateToURL(shell(), url)); NavigationEntry* entry = shell()->web_contents()->GetController().GetLastCommittedEntry(); ASSERT_TRUE(entry); // The main page was loaded with certificate errors. EXPECT_TRUE(net::IsCertStatusError(entry->GetSSL().cert_status)); // The image that the iframe loaded had certificate errors also, so // the page should be marked as having displayed subresources with // cert errors. EXPECT_TRUE(!!(entry->GetSSL().content_status & SSLStatus::DISPLAYED_CONTENT_WITH_CERT_ERRORS)); } // Test setting a cross-origin iframe to display: none. IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, CrossSiteIframeDisplayNone) { GURL main_url(embedded_test_server()->GetURL( "a.com", "/cross_site_iframe_factory.html?a(b)")); NavigateToURL(shell(), main_url); FrameTreeNode* root = web_contents()->GetFrameTree()->root(); RenderWidgetHost* root_render_widget_host = root->current_frame_host()->GetRenderWidgetHost(); // Set the iframe to display: none. EXPECT_TRUE(ExecuteScript( shell(), "document.querySelector('iframe').style.display = 'none'")); // Waits until pending frames are done. std::unique_ptr<MainThreadFrameObserver> observer( new MainThreadFrameObserver(root_render_widget_host)); observer->Wait(); // Force the renderer to generate a new frame. EXPECT_TRUE( ExecuteScript(shell(), "document.body.style.background = 'black'")); // Waits for the next frame. observer->Wait(); } // Test that a cross-origin iframe can be blocked by X-Frame-Options and CSP // frame-ancestors. IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, CrossSiteIframeBlockedByXFrameOptionsOrCSP) { GURL main_url(embedded_test_server()->GetURL( "a.com", "/cross_site_iframe_factory.html?a(a)")); NavigateToURL(shell(), main_url); FrameTreeNode* root = web_contents()->GetFrameTree()->root(); // Add a load event handler for the iframe element. EXPECT_TRUE(ExecuteScript(shell(), "document.querySelector('iframe').onload = " " function() { document.title = 'loaded'; };")); GURL blocked_urls[] = { embedded_test_server()->GetURL("b.com", "/frame-ancestors-none.html"), embedded_test_server()->GetURL("b.com", "/x-frame-options-deny.html") }; for (size_t i = 0; i < arraysize(blocked_urls); ++i) { EXPECT_TRUE(ExecuteScript(shell(), "document.title = 'not loaded';")); base::string16 expected_title(base::UTF8ToUTF16("loaded")); TitleWatcher title_watcher(shell()->web_contents(), expected_title); // Navigate the subframe to a blocked URL. TestNavigationObserver load_observer(shell()->web_contents()); EXPECT_TRUE(ExecuteScript(shell(), "frames[0].location.href = '" + blocked_urls[i].spec() + "';")); load_observer.Wait(); // The blocked frame's origin should become unique. EXPECT_EQ("null", root->child_at(0)->current_origin().Serialize()); // Ensure that we don't use the blocked URL as the blocked frame's last // committed URL (see https://crbug.com/622385). EXPECT_NE(root->child_at(0)->current_frame_host()->GetLastCommittedURL(), blocked_urls[i]); // The blocked frame should still fire a load event in its parent's process. EXPECT_EQ(expected_title, title_watcher.WaitAndGetTitle()); // Check that the current RenderFrameHost has stopped loading. EXPECT_FALSE(root->child_at(0)->current_frame_host()->is_loading()); // The blocked navigation should behave like an empty 200 response. Make // sure that the frame's document.title is empty: this double-checks both // that the blocked URL's contents wasn't loaded, and that the old page // isn't active anymore (both of these pages have non-empty titles). std::string frame_title; EXPECT_TRUE(ExecuteScriptAndExtractString( root->child_at(0), "domAutomationController.send(document.title)", &frame_title)); EXPECT_EQ("", frame_title); // Navigate the subframe to another cross-origin page and ensure that this // navigation succeeds. Use a renderer-initiated navigation to test the // transfer logic, which used to have some issues with this. GURL c_url(embedded_test_server()->GetURL("c.com", "/title1.html")); EXPECT_TRUE(NavigateIframeToURL(shell()->web_contents(), "child-0", c_url)); EXPECT_EQ(c_url, root->child_at(0)->current_url()); // When a page gets blocked due to XFO or CSP, it is sandboxed with the // SandboxOrigin flag (i.e., its origin is set to be unique) to ensure that // the blocked page is seen as cross-origin. However, those flags shouldn't // affect future navigations for a frame. Verify this for the above // navigation. EXPECT_EQ(c_url.GetOrigin().spec(), root->child_at(0)->current_origin().Serialize() + "/"); EXPECT_EQ(blink::WebSandboxFlags::None, root->child_at(0)->effective_sandbox_flags()); } } // Test that a cross-origin frame's navigation can be blocked by CSP frame-src. // In this version of a test, CSP comes from HTTP headers. IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, CrossSiteIframeBlockedByParentCSPFromHeaders) { GURL main_url( embedded_test_server()->GetURL("a.com", "/frame-src-self-and-b.html")); EXPECT_TRUE(NavigateToURL(shell(), main_url)); FrameTreeNode* root = web_contents()->GetFrameTree()->root(); // Sanity-check that the test page has the expected shape for testing. GURL old_subframe_url( embedded_test_server()->GetURL("b.com", "/title2.html")); EXPECT_FALSE(root->child_at(0)->HasSameOrigin(*root)); EXPECT_EQ(old_subframe_url, root->child_at(0)->current_url()); const std::vector<ContentSecurityPolicyHeader>& root_csp = root->current_replication_state().accumulated_csp_headers; EXPECT_EQ(1u, root_csp.size()); EXPECT_EQ("frame-src 'self' http://b.com:*", root_csp[0].header_value); // Monitor subframe's load events via main frame's title. EXPECT_TRUE(ExecuteScript(shell(), "document.querySelector('iframe').onload = " " function() { document.title = 'loaded'; };")); EXPECT_TRUE(ExecuteScript(shell(), "document.title = 'not loaded';")); base::string16 expected_title(base::UTF8ToUTF16("loaded")); TitleWatcher title_watcher(shell()->web_contents(), expected_title); // Try to navigate the subframe to a blocked URL. TestNavigationObserver load_observer(shell()->web_contents()); GURL blocked_url = embedded_test_server()->GetURL("c.com", "/title3.html"); EXPECT_TRUE(ExecuteScript(root->child_at(0), "window.location.href = '" + blocked_url.spec() + "';")); // The blocked frame should still fire a load event in its parent's process. EXPECT_EQ(expected_title, title_watcher.WaitAndGetTitle()); // Check that the current RenderFrameHost has stopped loading. if (root->child_at(0)->current_frame_host()->is_loading()) { ADD_FAILURE() << "Blocked RenderFrameHost shouldn't be loading anything"; load_observer.Wait(); } // The blocked frame should stay at the old location. EXPECT_EQ(old_subframe_url, root->child_at(0)->current_url()); // The blocked frame should keep the old title. std::string frame_title; EXPECT_TRUE(ExecuteScriptAndExtractString( root->child_at(0), "domAutomationController.send(document.title)", &frame_title)); EXPECT_EQ("Title Of Awesomeness", frame_title); // Navigate to a URL without CSP. EXPECT_TRUE(NavigateToURL( shell(), embedded_test_server()->GetURL("a.com", "/title1.html"))); // Verify that the frame's CSP got correctly reset to an empty set. EXPECT_EQ(0u, root->current_replication_state().accumulated_csp_headers.size()); } // Test that a cross-origin frame's navigation can be blocked by CSP frame-src. // In this version of a test, CSP comes from a <meta> element added after the // page has already loaded. IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, CrossSiteIframeBlockedByParentCSPFromMeta) { GURL main_url(embedded_test_server()->GetURL( "a.com", "/cross_site_iframe_factory.html?a(a)")); EXPECT_TRUE(NavigateToURL(shell(), main_url)); FrameTreeNode* root = web_contents()->GetFrameTree()->root(); // Navigate the subframe to a location we will disallow in the future. GURL old_subframe_url( embedded_test_server()->GetURL("b.com", "/title2.html")); NavigateFrameToURL(root->child_at(0), old_subframe_url); // Add frame-src CSP via a new <meta> element. EXPECT_TRUE(ExecuteScript( shell(), "var meta = document.createElement('meta');" "meta.httpEquiv = 'Content-Security-Policy';" "meta.content = 'frame-src https://a.com:*';" "document.getElementsByTagName('head')[0].appendChild(meta);")); // Sanity-check that the test page has the expected shape for testing. // (the CSP should not have an effect on the already loaded frames). EXPECT_FALSE(root->child_at(0)->HasSameOrigin(*root)); EXPECT_EQ(old_subframe_url, root->child_at(0)->current_url()); const std::vector<ContentSecurityPolicyHeader>& root_csp = root->current_replication_state().accumulated_csp_headers; EXPECT_EQ(1u, root_csp.size()); EXPECT_EQ("frame-src https://a.com:*", root_csp[0].header_value); // Monitor subframe's load events via main frame's title. EXPECT_TRUE(ExecuteScript(shell(), "document.querySelector('iframe').onload = " " function() { document.title = 'loaded'; };")); EXPECT_TRUE(ExecuteScript(shell(), "document.title = 'not loaded';")); base::string16 expected_title(base::UTF8ToUTF16("loaded")); TitleWatcher title_watcher(shell()->web_contents(), expected_title); // Try to navigate the subframe to a blocked URL. TestNavigationObserver load_observer2(shell()->web_contents()); GURL blocked_url = embedded_test_server()->GetURL("c.com", "/title3.html"); EXPECT_TRUE(ExecuteScript(root->child_at(0), "window.location.href = '" + blocked_url.spec() + "';")); // The blocked frame should still fire a load event in its parent's process. EXPECT_EQ(expected_title, title_watcher.WaitAndGetTitle()); // Check that the current RenderFrameHost has stopped loading. if (root->child_at(0)->current_frame_host()->is_loading()) { ADD_FAILURE() << "Blocked RenderFrameHost shouldn't be loading anything"; load_observer2.Wait(); } // The blocked frame should stay at the old location. EXPECT_EQ(old_subframe_url, root->child_at(0)->current_url()); // The blocked frame should keep the old title. std::string frame_title; EXPECT_TRUE(ExecuteScriptAndExtractString( root->child_at(0), "domAutomationController.send(document.title)", &frame_title)); EXPECT_EQ("Title Of Awesomeness", frame_title); } // Test that a cross-origin frame's navigation can be blocked by CSP frame-src. // In this version of a test, CSP is inherited by srcdoc iframe from a parent // that declared CSP via HTTP headers. Cross-origin frame navigating to a // blocked location is a child of the srcdoc iframe. IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, CrossSiteIframeBlockedByCSPInheritedBySrcDocParent) { GURL main_url( embedded_test_server()->GetURL("a.com", "/frame-src-self-and-b.html")); EXPECT_TRUE(NavigateToURL(shell(), main_url)); FrameTreeNode* root = web_contents()->GetFrameTree()->root(); FrameTreeNode* srcdoc_frame = root->child_at(1); EXPECT_TRUE(srcdoc_frame != nullptr); FrameTreeNode* navigating_frame = srcdoc_frame->child_at(0); EXPECT_TRUE(navigating_frame != nullptr); // Sanity-check that the test page has the expected shape for testing. // (the CSP should not have an effect on the already loaded frames). GURL old_subframe_url( embedded_test_server()->GetURL("b.com", "/title2.html")); EXPECT_TRUE(srcdoc_frame->HasSameOrigin(*root)); EXPECT_FALSE(srcdoc_frame->HasSameOrigin(*navigating_frame)); EXPECT_EQ(old_subframe_url, navigating_frame->current_url()); const std::vector<ContentSecurityPolicyHeader>& srcdoc_csp = srcdoc_frame->current_replication_state().accumulated_csp_headers; EXPECT_EQ(1u, srcdoc_csp.size()); EXPECT_EQ("frame-src 'self' http://b.com:*", srcdoc_csp[0].header_value); // Monitor navigating_frame's load events via srcdoc_frame posting // a message to the parent frame. EXPECT_TRUE( ExecuteScript(root, "window.addEventListener('message', function(event) {" " document.title = event.data;" "});")); EXPECT_TRUE(ExecuteScript( srcdoc_frame, "document.querySelector('iframe').onload = " " function() { window.top.postMessage('loaded', '*'); };")); EXPECT_TRUE(ExecuteScript(shell(), "document.title = 'not loaded';")); base::string16 expected_title(base::UTF8ToUTF16("loaded")); TitleWatcher title_watcher(shell()->web_contents(), expected_title); // Try to navigate the subframe to a blocked URL. TestNavigationObserver load_observer2(shell()->web_contents()); GURL blocked_url = embedded_test_server()->GetURL("c.com", "/title3.html"); EXPECT_TRUE(ExecuteScript(navigating_frame, "window.location.href = '" + blocked_url.spec() + "';")); // The blocked frame should still fire a load event in its parent's process. EXPECT_EQ(expected_title, title_watcher.WaitAndGetTitle()); // Check that the current RenderFrameHost has stopped loading. if (navigating_frame->current_frame_host()->is_loading()) { ADD_FAILURE() << "Blocked RenderFrameHost shouldn't be loading anything"; load_observer2.Wait(); } // The blocked frame should stay at the old location. EXPECT_EQ(old_subframe_url, navigating_frame->current_url()); // The blocked frame should keep the old title. std::string frame_title; EXPECT_TRUE(ExecuteScriptAndExtractString( navigating_frame, "domAutomationController.send(document.title)", &frame_title)); EXPECT_EQ("Title Of Awesomeness", frame_title); // Navigate the subframe to a URL without CSP. NavigateFrameToURL(srcdoc_frame, embedded_test_server()->GetURL("a.com", "/title1.html")); // Verify that the frame's CSP got correctly reset to an empty set. EXPECT_EQ( 0u, srcdoc_frame->current_replication_state().accumulated_csp_headers.size()); } IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, ScreenCoordinates) { GURL main_url(embedded_test_server()->GetURL( "a.com", "/cross_site_iframe_factory.html?a(b)")); NavigateToURL(shell(), main_url); FrameTreeNode* root = web_contents()->GetFrameTree()->root(); FrameTreeNode* child = root->child_at(0); const char* properties[] = {"screenX", "screenY", "outerWidth", "outerHeight"}; for (const char* property : properties) { std::string script = "window.domAutomationController.send(window."; script += property; script += ");"; int root_value = 1; int child_value = 2; EXPECT_TRUE(ExecuteScriptAndExtractInt(root, script.c_str(), &root_value)); EXPECT_TRUE( ExecuteScriptAndExtractInt(child, script.c_str(), &child_value)); EXPECT_EQ(root_value, child_value); } } // Tests that the swapped out state on RenderViewHost is properly reset when // the main frame is navigated to the same SiteInstance as one of its child // frames. IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, NavigateMainFrameToChildSite) { GURL main_url(embedded_test_server()->GetURL( "a.com", "/cross_site_iframe_factory.html?a(b)")); EXPECT_TRUE(NavigateToURL(shell(), main_url)); WebContentsImpl* contents = web_contents(); FrameTreeNode* root = contents->GetFrameTree()->root(); EXPECT_EQ(1U, root->child_count()); // Ensure the RenderViewHost for the SiteInstance of the child is considered // in swapped out state. RenderViewHostImpl* rvh = contents->GetFrameTree()->GetRenderViewHost( root->child_at(0)->current_frame_host()->GetSiteInstance()); EXPECT_TRUE(rvh->is_swapped_out_); // Have the child frame navigate its parent to its SiteInstance. GURL b_url(embedded_test_server()->GetURL("b.com", "/title1.html")); std::string script = base::StringPrintf( "window.domAutomationController.send(" "parent.location = '%s');", b_url.spec().c_str()); TestFrameNavigationObserver frame_observer(root); EXPECT_TRUE(ExecuteScript(root->child_at(0), script)); frame_observer.Wait(); EXPECT_EQ(b_url, root->current_url()); // Verify that the same RenderViewHost is preserved and that it is no longer // in swapped out state. EXPECT_EQ(rvh, contents->GetFrameTree()->GetRenderViewHost( root->current_frame_host()->GetSiteInstance())); EXPECT_FALSE(rvh->is_swapped_out_); } // Helper class to wait for a ChildProcessHostMsg_ShutdownRequest message to // arrive. class ShutdownRequestMessageFilter : public BrowserMessageFilter { public: ShutdownRequestMessageFilter() : BrowserMessageFilter(ChildProcessMsgStart), message_loop_runner_(new MessageLoopRunner) {} bool OnMessageReceived(const IPC::Message& message) override { if (message.type() == ChildProcessHostMsg_ShutdownRequest::ID) { content::BrowserThread::PostTask( content::BrowserThread::UI, FROM_HERE, base::Bind(&ShutdownRequestMessageFilter::OnShutdownRequest, this)); } return false; } void OnShutdownRequest() { message_loop_runner_->Quit(); } void Wait() { message_loop_runner_->Run(); } private: ~ShutdownRequestMessageFilter() override {} scoped_refptr<MessageLoopRunner> message_loop_runner_; DISALLOW_COPY_AND_ASSIGN(ShutdownRequestMessageFilter); }; // Test for https://crbug.com/568836. From an A-embed-B page, navigate the // subframe from B to A. This cleans up the process for B, but the test delays // the browser side from killing the B process right away. This allows the // B process to process two ViewMsg_Close messages sent to the subframe's // RenderWidget and to the RenderView, in that order. In the bug, the latter // crashed while detaching the subframe's LocalFrame (triggered as part of // closing the RenderView), because this tried to access the subframe's // WebFrameWidget (from RenderFrameImpl::didChangeSelection), which had already // been cleared by the former. IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, CloseSubframeWidgetAndViewOnProcessExit) { GURL main_url(embedded_test_server()->GetURL( "a.com", "/cross_site_iframe_factory.html?a(b)")); EXPECT_TRUE(NavigateToURL(shell(), main_url)); FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents()) ->GetFrameTree() ->root(); // "Select all" in the subframe. The bug only happens if there's a selection // change, which triggers the path through didChangeSelection. root->child_at(0)->current_frame_host()->Send(new InputMsg_SelectAll( root->child_at(0)->current_frame_host()->GetRoutingID())); // Prevent b.com process from terminating right away once the subframe // navigates away from b.com below. This is necessary so that the renderer // process has time to process the closings of RenderWidget and RenderView, // which is where the original bug was triggered. Incrementing worker // RefCount will cause RenderProcessHostImpl::Cleanup to forego process // termination. RenderProcessHost* subframe_process = root->child_at(0)->current_frame_host()->GetProcess(); subframe_process->IncrementSharedWorkerRefCount(); // Navigate the subframe away from b.com. Since this is the last active // frame in the b.com process, this causes the RenderWidget and RenderView to // be closed. If this succeeds without crashing, the renderer will release // the process and send a ChildProcessHostMsg_ShutdownRequest to the browser // process to ask whether it's ok to terminate. Thus, wait for this message // to ensure that the RenderView and widget were closed without crashing. scoped_refptr<ShutdownRequestMessageFilter> filter = new ShutdownRequestMessageFilter(); subframe_process->AddFilter(filter.get()); NavigateFrameToURL(root->child_at(0), embedded_test_server()->GetURL("a.com", "/title1.html")); filter->Wait(); // TODO(alexmos): Navigating the subframe back to b.com at this point would // trigger the race in https://crbug.com/535246, where the browser process // tries to reuse the b.com process thinking it's still initialized, whereas // the process has actually been destroyed by the renderer (but the browser // process hasn't heard the OnChannelError yet). This race will need to be // fixed. subframe_process->DecrementSharedWorkerRefCount(); } // Tests that an input event targeted to a out-of-process iframe correctly // triggers a user interaction notification for WebContentsObservers. // This is used for browser features such as download request limiting and // launching multiple external protocol handlers, which can block repeated // actions from a page when a user is not interacting with the page. IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, UserInteractionForChildFrameTest) { GURL main_url(embedded_test_server()->GetURL( "a.com", "/cross_site_iframe_factory.html?a(b)")); EXPECT_TRUE(NavigateToURL(shell(), main_url)); UserInteractionObserver observer(web_contents()); // Target an event to the child frame's RenderWidgetHostView. FrameTreeNode* root = web_contents()->GetFrameTree()->root(); SimulateMouseClick( root->child_at(0)->current_frame_host()->GetRenderWidgetHost(), 5, 5); EXPECT_TRUE(observer.WasUserInteractionReceived()); // Target an event to the main frame. observer.Reset(); SimulateMouseClick(root->current_frame_host()->GetRenderWidgetHost(), 1, 1); EXPECT_TRUE(observer.WasUserInteractionReceived()); } // Ensures that navigating to data: URLs present in session history will // correctly commit the navigation in the same process as the parent frame. // See https://crbug.com/606996. IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, NavigateSubframeToDataUrlInSessionHistory) { GURL main_url(embedded_test_server()->GetURL( "a.com", "/cross_site_iframe_factory.html?a(b,b)")); EXPECT_TRUE(NavigateToURL(shell(), main_url)); FrameTreeNode* root = web_contents()->GetFrameTree()->root(); EXPECT_EQ(2U, root->child_count()); EXPECT_EQ( " Site A ------------ proxies for B\n" " |--Site B ------- proxies for A\n" " +--Site B ------- proxies for A\n" "Where A = http://a.com/\n" " B = http://b.com/", DepictFrameTree(root)); TestNavigationObserver observer(shell()->web_contents()); FrameTreeNode* child = root->child_at(0); // Navigate iframe to a data URL, which will commit in a new SiteInstance. GURL data_url("data:text/html,dataurl"); NavigateFrameToURL(child, data_url); EXPECT_TRUE(observer.last_navigation_succeeded()); EXPECT_EQ(data_url, observer.last_navigation_url()); scoped_refptr<SiteInstanceImpl> orig_site_instance = child->current_frame_host()->GetSiteInstance(); EXPECT_NE(root->current_frame_host()->GetSiteInstance(), orig_site_instance); // Navigate it to another cross-site url. GURL cross_site_url(embedded_test_server()->GetURL("c.com", "/title1.html")); NavigateFrameToURL(child, cross_site_url); EXPECT_TRUE(observer.last_navigation_succeeded()); EXPECT_EQ(cross_site_url, observer.last_navigation_url()); EXPECT_EQ(3, web_contents()->GetController().GetEntryCount()); EXPECT_NE(orig_site_instance, child->current_frame_host()->GetSiteInstance()); // Go back and ensure the data: URL committed in the same SiteInstance as the // original navigation. EXPECT_TRUE(web_contents()->GetController().CanGoBack()); TestFrameNavigationObserver frame_observer(child); web_contents()->GetController().GoBack(); frame_observer.WaitForCommit(); EXPECT_EQ(orig_site_instance, child->current_frame_host()->GetSiteInstance()); } // Ensures that navigating to about:blank URLs present in session history will // correctly commit the navigation in the same process as the one used for // the original navigation. IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, NavigateSubframeToAboutBlankInSessionHistory) { GURL main_url(embedded_test_server()->GetURL( "a.com", "/cross_site_iframe_factory.html?a(b,b)")); EXPECT_TRUE(NavigateToURL(shell(), main_url)); FrameTreeNode* root = web_contents()->GetFrameTree()->root(); EXPECT_EQ(2U, root->child_count()); EXPECT_EQ( " Site A ------------ proxies for B\n" " |--Site B ------- proxies for A\n" " +--Site B ------- proxies for A\n" "Where A = http://a.com/\n" " B = http://b.com/", DepictFrameTree(root)); TestNavigationObserver observer(shell()->web_contents()); FrameTreeNode* child = root->child_at(0); // Navigate iframe to about:blank, which will commit in a new SiteInstance. GURL about_blank_url("about:blank"); NavigateFrameToURL(child, about_blank_url); EXPECT_TRUE(observer.last_navigation_succeeded()); EXPECT_EQ(about_blank_url, observer.last_navigation_url()); scoped_refptr<SiteInstanceImpl> orig_site_instance = child->current_frame_host()->GetSiteInstance(); EXPECT_NE(root->current_frame_host()->GetSiteInstance(), orig_site_instance); // Navigate it to another cross-site url. GURL cross_site_url(embedded_test_server()->GetURL("c.com", "/title1.html")); NavigateFrameToURL(child, cross_site_url); EXPECT_TRUE(observer.last_navigation_succeeded()); EXPECT_EQ(cross_site_url, observer.last_navigation_url()); EXPECT_EQ(3, web_contents()->GetController().GetEntryCount()); EXPECT_NE(orig_site_instance, child->current_frame_host()->GetSiteInstance()); // Go back and ensure the about:blank URL committed in the same SiteInstance // as the original navigation. EXPECT_TRUE(web_contents()->GetController().CanGoBack()); TestFrameNavigationObserver frame_observer(child); web_contents()->GetController().GoBack(); frame_observer.WaitForCommit(); EXPECT_EQ(orig_site_instance, child->current_frame_host()->GetSiteInstance()); } // Tests that there are no crashes if a subframe is detached in its unload // handler. See https://crbug.com/590054. IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, DetachInUnloadHandler) { GURL main_url(embedded_test_server()->GetURL( "a.com", "/cross_site_iframe_factory.html?a(b(b))")); NavigateToURL(shell(), main_url); FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents()) ->GetFrameTree() ->root(); EXPECT_EQ( " Site A ------------ proxies for B\n" " +--Site B ------- proxies for A\n" " +--Site B -- proxies for A\n" "Where A = http://a.com/\n" " B = http://b.com/", DepictFrameTree(root)); int child_count = 0; EXPECT_TRUE(ExecuteScriptAndExtractInt( root->child_at(0), "window.domAutomationController.send(frames.length);", &child_count)); EXPECT_EQ(1, child_count); RenderFrameDeletedObserver deleted_observer( root->child_at(0)->child_at(0)->current_frame_host()); // Add an unload handler to the grandchild that causes it to be synchronously // detached, then navigate it. EXPECT_TRUE(ExecuteScript( root->child_at(0)->child_at(0), "window.onunload=function(e){\n" " window.parent.document.getElementById('child-0').remove();\n" "};\n")); std::string script = std::string("window.document.getElementById('child-0').src = \"") + embedded_test_server() ->GetURL("c.com", "/cross_site_iframe_factory.html?c") .spec() + "\""; EXPECT_TRUE(ExecuteScript(root->child_at(0), script.c_str())); deleted_observer.WaitUntilDeleted(); EXPECT_TRUE(ExecuteScriptAndExtractInt( root->child_at(0), "window.domAutomationController.send(frames.length);", &child_count)); EXPECT_EQ(0, child_count); EXPECT_EQ( " Site A ------------ proxies for B\n" " +--Site B ------- proxies for A\n" "Where A = http://a.com/\n" " B = http://b.com/", DepictFrameTree(root)); } // Helper filter class to wait for a ShowView or ShowWidget message, record the // routing ID from the message, and then drop the message. class PendingWidgetMessageFilter : public BrowserMessageFilter { public: PendingWidgetMessageFilter() : BrowserMessageFilter(ViewMsgStart), routing_id_(MSG_ROUTING_NONE), message_loop_runner_(new MessageLoopRunner) {} bool OnMessageReceived(const IPC::Message& message) override { bool handled = true; IPC_BEGIN_MESSAGE_MAP(PendingWidgetMessageFilter, message) IPC_MESSAGE_HANDLER(ViewHostMsg_ShowView, OnShowView) IPC_MESSAGE_HANDLER(ViewHostMsg_ShowWidget, OnShowWidget) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() return handled; } void Wait() { message_loop_runner_->Run(); } int routing_id() { return routing_id_; } private: ~PendingWidgetMessageFilter() override {} void OnShowView(int routing_id, WindowOpenDisposition disposition, const gfx::Rect& initial_rect, bool user_gesture) { content::BrowserThread::PostTask( content::BrowserThread::UI, FROM_HERE, base::Bind(&PendingWidgetMessageFilter::OnReceivedRoutingIDOnUI, this, routing_id)); } void OnShowWidget(int routing_id, const gfx::Rect& initial_rect) { content::BrowserThread::PostTask( content::BrowserThread::UI, FROM_HERE, base::Bind(&PendingWidgetMessageFilter::OnReceivedRoutingIDOnUI, this, routing_id)); } void OnReceivedRoutingIDOnUI(int routing_id) { routing_id_ = routing_id; message_loop_runner_->Quit(); } int routing_id_; scoped_refptr<MessageLoopRunner> message_loop_runner_; DISALLOW_COPY_AND_ASSIGN(PendingWidgetMessageFilter); }; // Test for https://crbug.com/612276. Simultaneously open two new windows from // two subframes in different processes, where each subframe process's next // routing ID is the same. Make sure that both windows are created properly. // // Each new window requires two IPCs to first create it (handled by // CreateNewWindow) and then show it (ShowCreatedWindow). In the bug, both // CreateNewWindow calls arrived before the ShowCreatedWindow calls, resulting // in the two pending windows colliding in the pending WebContents map, which // used to be keyed only by routing_id. IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, TwoSubframesCreatePopupsSimultaneously) { GURL main_url(embedded_test_server()->GetURL( "a.com", "/cross_site_iframe_factory.html?a(b,c)")); EXPECT_TRUE(NavigateToURL(shell(), main_url)); FrameTreeNode* root = web_contents()->GetFrameTree()->root(); FrameTreeNode* child1 = root->child_at(0); FrameTreeNode* child2 = root->child_at(1); RenderProcessHost* process1 = child1->current_frame_host()->GetProcess(); RenderProcessHost* process2 = child2->current_frame_host()->GetProcess(); // Call window.open simultaneously in both subframes to create two popups. // Wait for and then drop both ViewHostMsg_ShowView messages. This will // ensure that both CreateNewWindow calls happen before either // ShowCreatedWindow call. scoped_refptr<PendingWidgetMessageFilter> filter1 = new PendingWidgetMessageFilter(); process1->AddFilter(filter1.get()); EXPECT_TRUE(ExecuteScript(child1, "window.open();")); filter1->Wait(); scoped_refptr<PendingWidgetMessageFilter> filter2 = new PendingWidgetMessageFilter(); process2->AddFilter(filter2.get()); EXPECT_TRUE(ExecuteScript(child2, "window.open();")); filter2->Wait(); // At this point, we should have two pending WebContents. EXPECT_TRUE(base::ContainsKey( web_contents()->pending_contents_, std::make_pair(process1->GetID(), filter1->routing_id()))); EXPECT_TRUE(base::ContainsKey( web_contents()->pending_contents_, std::make_pair(process2->GetID(), filter2->routing_id()))); // Both subframes were set up in the same way, so the next routing ID for the // new popup windows should match up (this led to the collision in the // pending contents map in the original bug). EXPECT_EQ(filter1->routing_id(), filter2->routing_id()); // Now, simulate that both ShowView messages arrive by showing both of the // pending WebContents. web_contents()->ShowCreatedWindow(process1->GetID(), filter1->routing_id(), WindowOpenDisposition::NEW_FOREGROUND_TAB, gfx::Rect(), true); web_contents()->ShowCreatedWindow(process2->GetID(), filter2->routing_id(), WindowOpenDisposition::NEW_FOREGROUND_TAB, gfx::Rect(), true); // Verify that both shells were properly created. EXPECT_EQ(3u, Shell::windows().size()); } // Test for https://crbug.com/612276. Similar to // TwoSubframesOpenWindowsSimultaneously, but use popup menu widgets instead of // windows. // // The plumbing that this test is verifying is not utilized on Mac/Android, // where popup menus don't create a popup RenderWidget, but rather they trigger // a FrameHostMsg_ShowPopup to ask the browser to build and display the actual // popup using native controls. #if !defined(OS_MACOSX) && !defined(OS_ANDROID) IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, TwoSubframesCreatePopupMenuWidgetsSimultaneously) { GURL main_url(embedded_test_server()->GetURL( "a.com", "/cross_site_iframe_factory.html?a(b,c)")); EXPECT_TRUE(NavigateToURL(shell(), main_url)); FrameTreeNode* root = web_contents()->GetFrameTree()->root(); FrameTreeNode* child1 = root->child_at(0); FrameTreeNode* child2 = root->child_at(1); RenderProcessHost* process1 = child1->current_frame_host()->GetProcess(); RenderProcessHost* process2 = child2->current_frame_host()->GetProcess(); // Navigate both subframes to a page with a <select> element. NavigateFrameToURL(child1, embedded_test_server()->GetURL( "b.com", "/site_isolation/page-with-select.html")); NavigateFrameToURL(child2, embedded_test_server()->GetURL( "c.com", "/site_isolation/page-with-select.html")); // Open both <select> menus by focusing each item and sending a space key // at the focused node. This creates a popup widget in both processes. // Wait for and then drop the ViewHostMsg_ShowWidget messages, so that both // widgets are left in pending-but-not-shown state. NativeWebKeyboardEvent event; event.text[0] = ' '; event.timeStampSeconds = 100; event.type = blink::WebKeyboardEvent::Char; scoped_refptr<PendingWidgetMessageFilter> filter1 = new PendingWidgetMessageFilter(); process1->AddFilter(filter1.get()); EXPECT_TRUE(ExecuteScript(child1, "focusSelectMenu();")); child1->current_frame_host()->GetRenderWidgetHost()->ForwardKeyboardEvent( event); filter1->Wait(); scoped_refptr<PendingWidgetMessageFilter> filter2 = new PendingWidgetMessageFilter(); process2->AddFilter(filter2.get()); EXPECT_TRUE(ExecuteScript(child2, "focusSelectMenu();")); child2->current_frame_host()->GetRenderWidgetHost()->ForwardKeyboardEvent( event); filter2->Wait(); // At this point, we should have two pending widgets. EXPECT_TRUE(base::ContainsKey( web_contents()->pending_widget_views_, std::make_pair(process1->GetID(), filter1->routing_id()))); EXPECT_TRUE(base::ContainsKey( web_contents()->pending_widget_views_, std::make_pair(process2->GetID(), filter2->routing_id()))); // Both subframes were set up in the same way, so the next routing ID for the // new popup widgets should match up (this led to the collision in the // pending widgets map in the original bug). EXPECT_EQ(filter1->routing_id(), filter2->routing_id()); // Now simulate both widgets being shown. web_contents()->ShowCreatedWidget(process1->GetID(), filter1->routing_id(), false, gfx::Rect()); web_contents()->ShowCreatedWidget(process2->GetID(), filter2->routing_id(), false, gfx::Rect()); EXPECT_FALSE(base::ContainsKey( web_contents()->pending_widget_views_, std::make_pair(process1->GetID(), filter1->routing_id()))); EXPECT_FALSE(base::ContainsKey( web_contents()->pending_widget_views_, std::make_pair(process2->GetID(), filter2->routing_id()))); } #endif // Check that out-of-process frames correctly calculate their ability to enter // fullscreen. A frame is allowed enter fullscreen if the allowFullscreen // attribute is present in all of its ancestor <iframe> elements. For OOPIF, // when a parent frame changes this attribute, the change is replicated to the // child frame and its proxies. // // The test checks the following cases: // // 1. Static attribute (<iframe allowfullscreen>) // 2. Attribute injected dynamically via JavaScript // 3. Multiple levels of nesting (A-embed-B-embed-C) // 4. Cross-site subframe navigation IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, AllowFullscreen) { // Load a page with a cross-site <iframe allowFullscreen>. GURL url_1(embedded_test_server()->GetURL( "a.com", "/page_with_allowfullscreen_frame.html")); EXPECT_TRUE(NavigateToURL(shell(), url_1)); WebContentsImpl* contents = web_contents(); FrameTreeNode* root = contents->GetFrameTree()->root(); // Helper to check if a frame is allowed to go fullscreen on the renderer // side. auto is_fullscreen_allowed = [](FrameTreeNode* ftn) { bool fullscreen_allowed = false; EXPECT_TRUE(ExecuteScriptAndExtractBool( ftn, "window.domAutomationController.send(document.webkitFullscreenEnabled)", &fullscreen_allowed)); return fullscreen_allowed; }; EXPECT_TRUE(is_fullscreen_allowed(root)); EXPECT_TRUE(is_fullscreen_allowed(root->child_at(0))); EXPECT_TRUE(root->child_at(0)->frame_owner_properties().allow_fullscreen); // Now navigate to a page with two <iframe>'s, both without allowFullscreen. GURL url_2(embedded_test_server()->GetURL( "a.com", "/cross_site_iframe_factory.html?a(b,c)")); EXPECT_TRUE(NavigateToURL(shell(), url_2)); EXPECT_FALSE(root->child_at(0)->frame_owner_properties().allow_fullscreen); EXPECT_FALSE(root->child_at(1)->frame_owner_properties().allow_fullscreen); EXPECT_TRUE(is_fullscreen_allowed(root)); EXPECT_FALSE(is_fullscreen_allowed(root->child_at(0))); EXPECT_FALSE(is_fullscreen_allowed(root->child_at(1))); // Dynamically enable fullscreen for first subframe and check that the // fullscreen property was updated on the FrameTreeNode. EXPECT_TRUE(ExecuteScript( root, "document.getElementById('child-0').allowFullscreen='true'")); EXPECT_TRUE(root->child_at(0)->frame_owner_properties().allow_fullscreen); // Check that the first subframe is now allowed to go fullscreen. Other // frames shouldn't be affected. EXPECT_TRUE(is_fullscreen_allowed(root)); EXPECT_TRUE(is_fullscreen_allowed(root->child_at(0))); EXPECT_FALSE(is_fullscreen_allowed(root->child_at(1))); // Now navigate to a page with two levels of nesting. GURL url_3(embedded_test_server()->GetURL( "a.com", "/cross_site_iframe_factory.html?a(b(c))")); EXPECT_TRUE(NavigateToURL(shell(), url_3)); EXPECT_TRUE(is_fullscreen_allowed(root)); EXPECT_FALSE(is_fullscreen_allowed(root->child_at(0))); EXPECT_FALSE(is_fullscreen_allowed(root->child_at(0)->child_at(0))); // Dynamically enable fullscreen for bottom subframe. EXPECT_TRUE(ExecuteScript( root->child_at(0), "document.getElementById('child-0').allowFullscreen='true'")); // This still shouldn't allow the bottom child to go fullscreen, since the // top frame hasn't allowed fullscreen for the middle frame. EXPECT_TRUE(is_fullscreen_allowed(root)); EXPECT_FALSE(is_fullscreen_allowed(root->child_at(0))); EXPECT_FALSE(is_fullscreen_allowed(root->child_at(0)->child_at(0))); // Now allow fullscreen for the middle frame. EXPECT_TRUE(ExecuteScript( root, "document.getElementById('child-0').allowFullscreen='true'")); // All frames should be allowed to go fullscreen now. EXPECT_TRUE(is_fullscreen_allowed(root)); EXPECT_TRUE(is_fullscreen_allowed(root->child_at(0))); EXPECT_TRUE(is_fullscreen_allowed(root->child_at(0)->child_at(0))); // Cross-site navigation should preserve the fullscreen flags. NavigateFrameToURL(root->child_at(0)->child_at(0), embedded_test_server()->GetURL("d.com", "/title1.html")); EXPECT_TRUE(is_fullscreen_allowed(root->child_at(0)->child_at(0))); } // Test for https://crbug.com/615575. It ensures that file chooser triggered // by a document in an out-of-process subframe works properly. IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, FileChooserInSubframe) { EXPECT_TRUE(NavigateToURL(shell(), embedded_test_server()->GetURL( "a.com", "/cross_site_iframe_factory.html?a(b)"))); FrameTreeNode* root = web_contents()->GetFrameTree()->root(); GURL url(embedded_test_server()->GetURL("b.com", "/file_input.html")); NavigateFrameToURL(root->child_at(0), url); // Use FileChooserDelegate to avoid showing the actual dialog and to respond // back to the renderer process with predefined file. base::FilePath file; EXPECT_TRUE(PathService::Get(base::DIR_TEMP, &file)); file = file.AppendASCII("bar"); std::unique_ptr<FileChooserDelegate> delegate(new FileChooserDelegate(file)); shell()->web_contents()->SetDelegate(delegate.get()); EXPECT_TRUE(ExecuteScript(root->child_at(0), "document.getElementById('fileinput').click();")); EXPECT_TRUE(delegate->file_chosen()); // Also, extract the file from the renderer process to ensure that the // response made it over successfully and the proper filename is set. std::string file_name; EXPECT_TRUE(ExecuteScriptAndExtractString( root->child_at(0), "window.domAutomationController.send(" "document.getElementById('fileinput').files[0].name);", &file_name)); EXPECT_EQ("bar", file_name); } // Tests that an out-of-process iframe receives the visibilitychange event. IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, VisibilityChange) { GURL main_url(embedded_test_server()->GetURL( "a.com", "/cross_site_iframe_factory.html?a(b)")); NavigateToURL(shell(), main_url); FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents()) ->GetFrameTree() ->root(); EXPECT_EQ( " Site A ------------ proxies for B\n" " +--Site B ------- proxies for A\n" "Where A = http://a.com/\n" " B = http://b.com/", DepictFrameTree(root)); EXPECT_TRUE(ExecuteScript( root->child_at(0)->current_frame_host(), "var event_fired = 0;\n" "document.addEventListener('visibilitychange',\n" " function() { event_fired++; });\n")); shell()->web_contents()->WasHidden(); int event_fired = 0; EXPECT_TRUE(ExecuteScriptAndExtractInt( root->child_at(0)->current_frame_host(), "window.domAutomationController.send(event_fired);", &event_fired)); EXPECT_EQ(1, event_fired); shell()->web_contents()->WasShown(); EXPECT_TRUE(ExecuteScriptAndExtractInt( root->child_at(0)->current_frame_host(), "window.domAutomationController.send(event_fired);", &event_fired)); EXPECT_EQ(2, event_fired); } #if defined(USE_AURA) class SitePerProcessGestureBrowserTest : public SitePerProcessBrowserTest { public: SitePerProcessGestureBrowserTest() {} // This functions simulates a sequence of events that are typical of a // gesture pinch at |position|. We need this since machinery in the event // codepath will require GesturePinch* to be enclosed in // GestureScrollBegin/End, and since RenderWidgetHostInputEventRouter needs // both the preceding touch events, as well as GestureTapDown, in order to // correctly target the subsequent gesture event stream. The minimum stream // required to trigger the correct behaviours is represented here, but could // be expanded to include additional events such as one or more // GestureScrollUpdate and GesturePinchUpdate events. void SendPinchBeginEndSequence(RenderWidgetHostViewAura* rwhva, const gfx::Point& position) { DCHECK(rwhva); // Use full version of constructor with radius, angle and force since it // will crash in the renderer otherwise. ui::TouchEvent touch_pressed(ui::ET_TOUCH_PRESSED, position, 0, 0, ui::EventTimeForNow(), 1.f, 1.f, 0.f, 1.f); rwhva->OnTouchEvent(&touch_pressed); ui::TouchEvent touch_released(ui::ET_TOUCH_RELEASED, position, 0, 0, ui::EventTimeForNow(), 1.f, 1.f, 0.f, 1.f); rwhva->OnTouchEvent(&touch_released); ui::GestureEventDetails gesture_tap_down_details(ui::ET_GESTURE_TAP_DOWN); gesture_tap_down_details.set_device_type( ui::GestureDeviceType::DEVICE_TOUCHSCREEN); ui::GestureEvent gesture_tap_down(position.x(), position.y(), 0, ui::EventTimeForNow(), gesture_tap_down_details); rwhva->OnGestureEvent(&gesture_tap_down); ui::GestureEventDetails gesture_scroll_begin_details( ui::ET_GESTURE_SCROLL_BEGIN); gesture_scroll_begin_details.set_device_type( ui::GestureDeviceType::DEVICE_TOUCHSCREEN); ui::GestureEvent gesture_scroll_begin(position.x(), position.y(), 0, ui::EventTimeForNow(), gesture_scroll_begin_details); rwhva->OnGestureEvent(&gesture_scroll_begin); ui::GestureEventDetails gesture_pinch_begin_details( ui::ET_GESTURE_PINCH_BEGIN); gesture_pinch_begin_details.set_device_type( ui::GestureDeviceType::DEVICE_TOUCHSCREEN); ui::GestureEvent gesture_pinch_begin(position.x(), position.y(), 0, ui::EventTimeForNow(), gesture_pinch_begin_details); rwhva->OnGestureEvent(&gesture_pinch_begin); ui::GestureEventDetails gesture_pinch_end_details(ui::ET_GESTURE_PINCH_END); gesture_pinch_end_details.set_device_type( ui::GestureDeviceType::DEVICE_TOUCHSCREEN); ui::GestureEvent gesture_pinch_end(position.x(), position.y(), 0, ui::EventTimeForNow(), gesture_pinch_end_details); rwhva->OnGestureEvent(&gesture_pinch_end); ui::GestureEventDetails gesture_scroll_end_details( ui::ET_GESTURE_SCROLL_END); gesture_scroll_end_details.set_device_type( ui::GestureDeviceType::DEVICE_TOUCHSCREEN); ui::GestureEvent gesture_scroll_end(position.x(), position.y(), 0, ui::EventTimeForNow(), gesture_scroll_end_details); rwhva->OnGestureEvent(&gesture_scroll_end); } void SetupRootAndChild() { GURL main_url(embedded_test_server()->GetURL( "a.com", "/cross_site_iframe_factory.html?a(b)")); NavigateToURL(shell(), main_url); FrameTreeNode* root_node = static_cast<WebContentsImpl*>(shell()->web_contents()) ->GetFrameTree() ->root(); FrameTreeNode* child_node = root_node->child_at(0); rwhv_child_ = static_cast<RenderWidgetHostViewBase*>( child_node->current_frame_host()->GetRenderWidgetHost()->GetView()); rwhva_root_ = static_cast<RenderWidgetHostViewAura*>( shell()->web_contents()->GetRenderWidgetHostView()); SurfaceHitTestReadyNotifier notifier( static_cast<RenderWidgetHostViewChildFrame*>(rwhv_child_)); notifier.WaitForSurfaceReady(); rwhi_child_ = child_node->current_frame_host()->GetRenderWidgetHost(); rwhi_root_ = root_node->current_frame_host()->GetRenderWidgetHost(); } protected: RenderWidgetHostViewBase* rwhv_child_; RenderWidgetHostViewAura* rwhva_root_; RenderWidgetHostImpl* rwhi_child_; RenderWidgetHostImpl* rwhi_root_; private: DISALLOW_COPY_AND_ASSIGN(SitePerProcessGestureBrowserTest); }; IN_PROC_BROWSER_TEST_F(SitePerProcessGestureBrowserTest, SubframeGesturePinchGoesToMainFrame) { SetupRootAndChild(); TestInputEventObserver root_frame_monitor(rwhi_root_); TestInputEventObserver child_frame_monitor(rwhi_child_); // Need child rect in main frame coords. gfx::Rect bounds = rwhv_child_->GetViewBounds(); bounds.Offset(gfx::Point() - rwhva_root_->GetViewBounds().origin()); SendPinchBeginEndSequence(rwhva_root_, bounds.CenterPoint()); // Verify root-RWHI gets GSB/GPB/GPE/GSE. EXPECT_TRUE(root_frame_monitor.EventWasReceived()); EXPECT_EQ(blink::WebInputEvent::GestureScrollBegin, root_frame_monitor.events_received()[0]); EXPECT_EQ(blink::WebInputEvent::GesturePinchBegin, root_frame_monitor.events_received()[1]); EXPECT_EQ(blink::WebInputEvent::GesturePinchEnd, root_frame_monitor.events_received()[2]); EXPECT_EQ(blink::WebInputEvent::GestureScrollEnd, root_frame_monitor.events_received()[3]); // Verify child-RWHI gets TS/TE, GTD/GSB/GSE. EXPECT_TRUE(child_frame_monitor.EventWasReceived()); EXPECT_EQ(blink::WebInputEvent::TouchStart, child_frame_monitor.events_received()[0]); EXPECT_EQ(blink::WebInputEvent::TouchEnd, child_frame_monitor.events_received()[1]); EXPECT_EQ(blink::WebInputEvent::GestureTapDown, child_frame_monitor.events_received()[2]); EXPECT_EQ(blink::WebInputEvent::GestureScrollBegin, child_frame_monitor.events_received()[3]); EXPECT_EQ(blink::WebInputEvent::GestureScrollEnd, child_frame_monitor.events_received()[4]); } IN_PROC_BROWSER_TEST_F(SitePerProcessGestureBrowserTest, MainframeGesturePinchGoesToMainFrame) { SetupRootAndChild(); TestInputEventObserver root_frame_monitor(rwhi_root_); TestInputEventObserver child_frame_monitor(rwhi_child_); // Need child rect in main frame coords. gfx::Rect bounds = rwhv_child_->GetViewBounds(); bounds.Offset(gfx::Point() - rwhva_root_->GetViewBounds().origin()); gfx::Point main_frame_point(bounds.origin()); main_frame_point += gfx::Vector2d(-5, -5); SendPinchBeginEndSequence(rwhva_root_, main_frame_point); // Verify root-RWHI gets TS/TE/GTD/GSB/GPB/GPE/GSE. EXPECT_TRUE(root_frame_monitor.EventWasReceived()); EXPECT_EQ(blink::WebInputEvent::TouchStart, root_frame_monitor.events_received()[0]); EXPECT_EQ(blink::WebInputEvent::TouchEnd, root_frame_monitor.events_received()[1]); EXPECT_EQ(blink::WebInputEvent::GestureTapDown, root_frame_monitor.events_received()[2]); EXPECT_EQ(blink::WebInputEvent::GestureScrollBegin, root_frame_monitor.events_received()[3]); EXPECT_EQ(blink::WebInputEvent::GesturePinchBegin, root_frame_monitor.events_received()[4]); EXPECT_EQ(blink::WebInputEvent::GesturePinchEnd, root_frame_monitor.events_received()[5]); EXPECT_EQ(blink::WebInputEvent::GestureScrollEnd, root_frame_monitor.events_received()[6]); // Verify child-RWHI gets no events. EXPECT_FALSE(child_frame_monitor.EventWasReceived()); } #endif // Test that the pending RenderFrameHost is canceled and destroyed when its // process dies. Previously, reusing a top-level pending RFH which // is not live was hitting a CHECK in CreateRenderView due to having neither a // main frame routing ID nor a proxy routing ID. See https://crbug.com/627400 // for more details. IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, PendingRFHIsCanceledWhenItsProcessDies) { GURL main_url(embedded_test_server()->GetURL("a.com", "/title1.html")); EXPECT_TRUE(NavigateToURL(shell(), main_url)); FrameTreeNode* root = web_contents()->GetFrameTree()->root(); // Open a popup at b.com. GURL popup_url(embedded_test_server()->GetURL("b.com", "/title1.html")); Shell* popup_shell = OpenPopup(root, popup_url, "foo"); EXPECT_TRUE(popup_shell); // The RenderViewHost for b.com in the main tab should not be active. SiteInstance* b_instance = popup_shell->web_contents()->GetSiteInstance(); RenderViewHostImpl* rvh = web_contents()->GetFrameTree()->GetRenderViewHost(b_instance); EXPECT_FALSE(rvh->is_active()); // Navigate main tab to a b.com URL that will not commit. GURL stall_url(embedded_test_server()->GetURL("b.com", "/title2.html")); TestNavigationManager delayer(shell()->web_contents(), stall_url); shell()->LoadURL(stall_url); EXPECT_TRUE(delayer.WaitForRequestStart()); // The pending RFH should be in the same process as the popup. RenderFrameHostImpl* pending_rfh = IsBrowserSideNavigationEnabled() ? root->render_manager()->speculative_frame_host() : root->render_manager()->pending_frame_host(); RenderProcessHost* pending_process = pending_rfh->GetProcess(); EXPECT_EQ(pending_process, popup_shell->web_contents()->GetMainFrame()->GetProcess()); // Kill the b.com process, currently in use by the pending RenderFrameHost // and the popup. RenderProcessHostWatcher crash_observer( pending_process, RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT); EXPECT_TRUE(pending_process->Shutdown(0, false)); crash_observer.Wait(); // The pending RFH should have been canceled and destroyed, so that it won't // be reused while it's not live in the next navigation. { RenderFrameHostImpl* pending_rfh = IsBrowserSideNavigationEnabled() ? root->render_manager()->speculative_frame_host() : root->render_manager()->pending_frame_host(); EXPECT_FALSE(pending_rfh); } // Navigate main tab to b.com again. This should not crash. GURL b_url(embedded_test_server()->GetURL("b.com", "/title3.html")); EXPECT_TRUE(NavigateToURL(shell(), b_url)); // The b.com RVH in the main tab should become active. EXPECT_TRUE(rvh->is_active()); } // Test that killing a pending RenderFrameHost's process doesn't leave its // RenderViewHost confused whether it's active or not for future navigations // that try to reuse it. See https://crbug.com/627893 for more details. // Similar to the test above for https://crbug.com/627400, except the popup is // navigated after pending RFH's process is killed, rather than the main tab. IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, RenderViewHostKeepsSwappedOutStateIfPendingRFHDies) { GURL main_url(embedded_test_server()->GetURL("a.com", "/title1.html")); EXPECT_TRUE(NavigateToURL(shell(), main_url)); FrameTreeNode* root = web_contents()->GetFrameTree()->root(); // Open a popup at b.com. GURL popup_url(embedded_test_server()->GetURL("b.com", "/title1.html")); Shell* popup_shell = OpenPopup(root, popup_url, "foo"); EXPECT_TRUE(popup_shell); // The RenderViewHost for b.com in the main tab should not be active. SiteInstance* b_instance = popup_shell->web_contents()->GetSiteInstance(); RenderViewHostImpl* rvh = web_contents()->GetFrameTree()->GetRenderViewHost(b_instance); EXPECT_FALSE(rvh->is_active()); // Navigate main tab to a b.com URL that will not commit. GURL stall_url(embedded_test_server()->GetURL("b.com", "/title2.html")); TestNavigationManager delayer(shell()->web_contents(), stall_url); shell()->LoadURL(stall_url); EXPECT_TRUE(delayer.WaitForRequestStart()); // Kill the b.com process, currently in use by the pending RenderFrameHost // and the popup. RenderProcessHost* pending_process = popup_shell->web_contents()->GetMainFrame()->GetProcess(); RenderProcessHostWatcher crash_observer( pending_process, RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT); EXPECT_TRUE(pending_process->Shutdown(0, false)); crash_observer.Wait(); // Since the navigation above didn't commit, the b.com RenderViewHost in the // main tab should still not be active. EXPECT_FALSE(rvh->is_active()); // Navigate popup to b.com to recreate the b.com process. When creating // opener proxies, |rvh| should be reused as a swapped out RVH. In // https://crbug.com/627893, recreating the opener RenderView was hitting a // CHECK(params.swapped_out) in the renderer process, since its // RenderViewHost was brought into an active state by the navigation to // |stall_url| above, even though it never committed. GURL b_url(embedded_test_server()->GetURL("b.com", "/title3.html")); EXPECT_TRUE(NavigateToURL(popup_shell, b_url)); EXPECT_FALSE(rvh->is_active()); } // Test that a crashed subframe can be successfully navigated to the site it // was on before crashing. See https://crbug.com/634368. IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, NavigateCrashedSubframeToSameSite) { GURL main_url(embedded_test_server()->GetURL( "a.com", "/cross_site_iframe_factory.html?a(b)")); EXPECT_TRUE(NavigateToURL(shell(), main_url)); FrameTreeNode* root = web_contents()->GetFrameTree()->root(); FrameTreeNode* child = root->child_at(0); // Set up a postMessage handler in the main frame for later use. EXPECT_TRUE(ExecuteScript( root->current_frame_host(), "window.addEventListener('message'," " function(e) { document.title = e.data; });")); // Crash the subframe process. RenderProcessHost* child_process = child->current_frame_host()->GetProcess(); RenderProcessHostWatcher crash_observer( child_process, RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT); child_process->Shutdown(0, false); crash_observer.Wait(); EXPECT_FALSE(child->current_frame_host()->IsRenderFrameLive()); // When the subframe dies, its RenderWidgetHostView should be cleared and // reset in the CrossProcessFrameConnector. EXPECT_FALSE(child->current_frame_host()->GetView()); RenderFrameProxyHost* proxy_to_parent = child->render_manager()->GetProxyToParent(); EXPECT_FALSE( proxy_to_parent->cross_process_frame_connector()->get_view_for_testing()); // Navigate the subframe to the same site it was on before crashing. This // should reuse the subframe's current RenderFrameHost and reinitialize the // RenderFrame in a new process. NavigateFrameToURL(child, embedded_test_server()->GetURL("b.com", "/title1.html")); EXPECT_TRUE(child->current_frame_host()->IsRenderFrameLive()); // The RenderWidgetHostView for the child should be recreated and set to be // used in the CrossProcessFrameConnector. Without this, the frame won't be // rendered properly. EXPECT_TRUE(child->current_frame_host()->GetView()); EXPECT_EQ( child->current_frame_host()->GetView(), proxy_to_parent->cross_process_frame_connector()->get_view_for_testing()); // Send a postMessage from the child to its parent. This verifies that the // parent's proxy in the child's SiteInstance was also restored. base::string16 expected_title(base::UTF8ToUTF16("I am alive!")); TitleWatcher title_watcher(shell()->web_contents(), expected_title); EXPECT_TRUE(ExecuteScript(child->current_frame_host(), "parent.postMessage('I am alive!', '*');")); EXPECT_EQ(expected_title, title_watcher.WaitAndGetTitle()); } // Test that session history length and offset are replicated to all renderer // processes in a FrameTree. This allows each renderer to see correct values // for history.length, and to check the offset validity properly for // navigations initiated via history.go(). See https:/crbug.com/501116. IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, SessionHistoryReplication) { GURL main_url(embedded_test_server()->GetURL( "a.com", "/cross_site_iframe_factory.html?a(a,a)")); EXPECT_TRUE(NavigateToURL(shell(), main_url)); FrameTreeNode* root = web_contents()->GetFrameTree()->root(); FrameTreeNode* child1 = root->child_at(0); FrameTreeNode* child2 = root->child_at(1); GURL child_first_url(child1->current_url()); EXPECT_EQ(child1->current_url(), child2->current_url()); // Helper to retrieve the history length from a given frame. auto history_length = [](FrameTreeNode* ftn) { int history_length = -1; EXPECT_TRUE(ExecuteScriptAndExtractInt( ftn->current_frame_host(), "window.domAutomationController.send(history.length);", &history_length)); return history_length; }; // All frames should see a history length of 1 to start with. EXPECT_EQ(1, history_length(root)); EXPECT_EQ(1, history_length(child1)); EXPECT_EQ(1, history_length(child2)); // Navigate first child cross-site. This increases history length to 2. NavigateFrameToURL(child1, embedded_test_server()->GetURL("b.com", "/title1.html")); EXPECT_EQ(2, history_length(root)); EXPECT_EQ(2, history_length(child1)); EXPECT_EQ(2, history_length(child2)); // Navigate second child same-site. GURL child2_last_url(embedded_test_server()->GetURL("a.com", "/title2.html")); NavigateFrameToURL(child2, child2_last_url); EXPECT_EQ(3, history_length(root)); EXPECT_EQ(3, history_length(child1)); EXPECT_EQ(3, history_length(child2)); // Navigate first child same-site to another b.com URL. GURL child1_last_url(embedded_test_server()->GetURL("b.com", "/title3.html")); NavigateFrameToURL(child1, child1_last_url); EXPECT_EQ(4, history_length(root)); EXPECT_EQ(4, history_length(child1)); EXPECT_EQ(4, history_length(child2)); // Go back three entries using the history API from the main frame. This // checks that both history length and offset are not stale in a.com, as // otherwise this navigation might be dropped by Blink. EXPECT_TRUE(ExecuteScript(root, "history.go(-3);")); EXPECT_TRUE(WaitForLoadStop(shell()->web_contents())); EXPECT_EQ(main_url, root->current_url()); EXPECT_EQ(child_first_url, child1->current_url()); EXPECT_EQ(child_first_url, child2->current_url()); // Now go forward three entries from the child1 frame and check that the // history length and offset are not stale in b.com. EXPECT_TRUE(ExecuteScript(child1, "history.go(3);")); EXPECT_TRUE(WaitForLoadStop(shell()->web_contents())); EXPECT_EQ(main_url, root->current_url()); EXPECT_EQ(child1_last_url, child1->current_url()); EXPECT_EQ(child2_last_url, child2->current_url()); } // A BrowserMessageFilter that drops FrameHostMsg_OnDispatchLoad messages. class DispatchLoadMessageFilter : public BrowserMessageFilter { public: DispatchLoadMessageFilter() : BrowserMessageFilter(FrameMsgStart) {} protected: ~DispatchLoadMessageFilter() override {} private: // BrowserMessageFilter: bool OnMessageReceived(const IPC::Message& message) override { return message.type() == FrameHostMsg_DispatchLoad::ID; } DISALLOW_COPY_AND_ASSIGN(DispatchLoadMessageFilter); }; // Test that the renderer isn't killed when a frame generates a load event just // after becoming pending deletion. See https://crbug.com/636513. IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, LoadEventForwardingWhilePendingDeletion) { GURL main_url(embedded_test_server()->GetURL( "a.com", "/cross_site_iframe_factory.html?a(a)")); EXPECT_TRUE(NavigateToURL(shell(), main_url)); FrameTreeNode* root = web_contents()->GetFrameTree()->root(); FrameTreeNode* child = root->child_at(0); // Open a popup in the b.com process for later use. GURL popup_url(embedded_test_server()->GetURL("b.com", "/title1.html")); Shell* popup_shell = OpenPopup(root, popup_url, "foo"); EXPECT_TRUE(popup_shell); // Install a filter to drop DispatchLoad messages from b.com. scoped_refptr<DispatchLoadMessageFilter> filter = new DispatchLoadMessageFilter(); RenderProcessHost* b_process = popup_shell->web_contents()->GetMainFrame()->GetProcess(); b_process->AddFilter(filter.get()); // Navigate subframe to b.com. Wait for commit but not full load. GURL b_url(embedded_test_server()->GetURL("b.com", "/title2.html")); { TestFrameNavigationObserver commit_observer(child); EXPECT_TRUE( ExecuteScript(child, "location.href = '" + b_url.spec() + "';")); commit_observer.WaitForCommit(); } RenderFrameHostImpl* child_rfh = child->current_frame_host(); child_rfh->DisableSwapOutTimerForTesting(); // At this point, the subframe should have a proxy in its parent's // SiteInstance, a.com. EXPECT_TRUE(child->render_manager()->GetProxyToParent()); // Now, go back to a.com in the subframe and wait for commit. { TestFrameNavigationObserver commit_observer(child); web_contents()->GetController().GoBack(); commit_observer.WaitForCommit(); } // At this point, the subframe's old RFH for b.com should be pending // deletion, and the subframe's proxy in a.com should've been cleared. EXPECT_FALSE(child_rfh->is_active()); EXPECT_FALSE(child->render_manager()->GetProxyToParent()); // Simulate that the load event is dispatched from |child_rfh| just after // it's become pending deletion. child_rfh->OnDispatchLoad(); // In the bug, OnDispatchLoad killed the b.com renderer. Ensure that this is // not the case. Note that the process kill doesn't happen immediately, so // IsRenderFrameLive() can't be checked here (yet). Instead, check that // JavaScript can still execute in b.com using the popup. EXPECT_TRUE(ExecuteScript(popup_shell->web_contents(), "true")); } // Tests that trying to navigate in the unload handler doesn't crash the // browser. IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, NavigateInUnloadHandler) { GURL main_url(embedded_test_server()->GetURL( "a.com", "/cross_site_iframe_factory.html?a(b(b))")); NavigateToURL(shell(), main_url); FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents()) ->GetFrameTree() ->root(); EXPECT_EQ( " Site A ------------ proxies for B\n" " +--Site B ------- proxies for A\n" " +--Site B -- proxies for A\n" "Where A = http://a.com/\n" " B = http://b.com/", DepictFrameTree(root)); int child_count = 0; EXPECT_TRUE(ExecuteScriptAndExtractInt( root->child_at(0)->current_frame_host(), "window.domAutomationController.send(frames.length);", &child_count)); EXPECT_EQ(1, child_count); // Add an unload handler to B's subframe. EXPECT_TRUE( ExecuteScript(root->child_at(0)->child_at(0)->current_frame_host(), "window.onunload=function(e){\n" " window.location = '#navigate';\n" "};\n")); // Navigate B's subframe to a cross-site C. std::string script = std::string("window.document.getElementById('child-0').src = \"") + embedded_test_server() ->GetURL("c.com", "/cross_site_iframe_factory.html") .spec() + "\""; EXPECT_TRUE( ExecuteScript(root->child_at(0)->current_frame_host(), script.c_str())); // Wait until B's subframe RenderFrameHost is destroyed. RenderFrameDeletedObserver deleted_observer( root->child_at(0)->child_at(0)->current_frame_host()); deleted_observer.WaitUntilDeleted(); // Check that C's subframe is alive and the navigation in the unload handler // was ignored. EXPECT_TRUE(ExecuteScriptAndExtractInt( root->child_at(0)->child_at(0)->current_frame_host(), "window.domAutomationController.send(frames.length);", &child_count)); EXPECT_EQ(0, child_count); EXPECT_EQ( " Site A ------------ proxies for B C\n" " +--Site B ------- proxies for A C\n" " +--Site C -- proxies for A B\n" "Where A = http://a.com/\n" " B = http://b.com/\n" " C = http://c.com/", DepictFrameTree(root)); } IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, RFHTransfersWhilePendingDeletion) { GURL main_url(embedded_test_server()->GetURL("a.com", "/title1.html")); NavigateToURL(shell(), main_url); FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents()) ->GetFrameTree() ->root(); // Start a cross-process navigation and wait until the response is received. GURL cross_site_url_1 = embedded_test_server()->GetURL("b.com", "/title1.html"); TestNavigationManager cross_site_manager(shell()->web_contents(), cross_site_url_1); shell()->web_contents()->GetController().LoadURL( cross_site_url_1, Referrer(), ui::PAGE_TRANSITION_LINK, std::string()); EXPECT_TRUE(cross_site_manager.WaitForResponse()); // Start a renderer-initiated navigation to a cross-process url and make sure // the navigation will be blocked before being transferred. GURL cross_site_url_2 = embedded_test_server()->GetURL("c.com", "/title1.html"); TestNavigationManager transfer_manager(shell()->web_contents(), cross_site_url_2); EXPECT_TRUE(ExecuteScript( root, "location.href = '" + cross_site_url_2.spec() + "';")); EXPECT_TRUE(transfer_manager.WaitForResponse()); // Now have the cross-process navigation commit and mark the current RFH as // pending deletion. cross_site_manager.WaitForNavigationFinished(); // Resume the navigation in the previous RFH that has just been marked as // pending deletion. We should not crash. transfer_manager.WaitForNavigationFinished(); } class NavigationHandleWatcher : public WebContentsObserver { public: NavigationHandleWatcher(WebContents* web_contents) : WebContentsObserver(web_contents) {} void DidStartNavigation(NavigationHandle* navigation_handle) override { DCHECK_EQ(GURL("http://b.com/"), navigation_handle->GetStartingSiteInstance()->GetSiteURL()); } }; // Verifies that the SiteInstance of a NavigationHandle correctly identifies the // RenderFrameHost that started the navigation (and not the destination RFH). IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, NavigationHandleSiteInstance) { // Navigate to a page with a cross-site iframe. GURL main_url(embedded_test_server()->GetURL( "a.com", "/cross_site_iframe_factory.html?a(b)")); EXPECT_TRUE(NavigateToURL(shell(), main_url)); // Navigate the iframe cross-site. NavigationHandleWatcher watcher(shell()->web_contents()); TestNavigationObserver load_observer(shell()->web_contents()); GURL frame_url = embedded_test_server()->GetURL("c.com", "/title1.html"); EXPECT_TRUE(ExecuteScript( shell()->web_contents(), "window.frames[0].location = \"" + frame_url.spec() + "\";")); load_observer.Wait(); } // Test that when canceling a pending RenderFrameHost in the middle of a // redirect, and then killing the corresponding RenderView's renderer process, // the RenderViewHost isn't reused in an improper state later. Previously this // led to a crash in CreateRenderView when recreating the RenderView due to a // stale main frame routing ID. See https://crbug.com/627400. IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, ReuseNonLiveRenderViewHostAfterCancelPending) { GURL a_url(embedded_test_server()->GetURL("a.com", "/title1.html")); GURL b_url(embedded_test_server()->GetURL("b.com", "/title2.html")); GURL c_url(embedded_test_server()->GetURL("c.com", "/title3.html")); EXPECT_TRUE(NavigateToURL(shell(), a_url)); // Open a popup and navigate it to b.com. Shell* popup = OpenPopup(shell(), a_url, "popup"); EXPECT_TRUE(NavigateToURL(popup, b_url)); // Open a second popup and navigate it to b.com, which redirects to c.com. // The navigation to b.com will create a pending RenderFrameHost, which will // be canceled during the redirect to c.com. Note that NavigateToURL will // return false because the committed URL won't match the requested URL due // to the redirect. Shell* popup2 = OpenPopup(shell(), a_url, "popup2"); TestNavigationObserver observer(popup2->web_contents()); GURL redirect_url(embedded_test_server()->GetURL( "b.com", "/server-redirect?" + c_url.spec())); EXPECT_FALSE(NavigateToURL(popup2, redirect_url)); EXPECT_EQ(c_url, observer.last_navigation_url()); EXPECT_TRUE(observer.last_navigation_succeeded()); // Kill the b.com process (which currently hosts a RenderFrameProxy that // replaced the pending RenderFrame in |popup2|, as well as the RenderFrame // for |popup|). RenderProcessHost* b_process = popup->web_contents()->GetMainFrame()->GetProcess(); RenderProcessHostWatcher crash_observer( b_process, RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT); b_process->Shutdown(0, false); crash_observer.Wait(); // Navigate the second popup to b.com. This used to crash when creating the // RenderView, because it reused the RenderViewHost created by the canceled // navigation to b.com, and that RenderViewHost had a stale main frame // routing ID and active state. EXPECT_TRUE(NavigateToURL(popup2, b_url)); } // Check that after a pending RFH is canceled and replaced with a proxy (which // reuses the canceled RFH's RenderViewHost), navigating to a main frame in the // same site as the canceled RFH doesn't lead to a renderer crash. The steps // here are similar to ReuseNonLiveRenderViewHostAfterCancelPending, but don't // involve crashing the renderer. See https://crbug.com/651980. IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, RecreateMainFrameAfterCancelPending) { GURL a_url(embedded_test_server()->GetURL("a.com", "/title1.html")); GURL b_url(embedded_test_server()->GetURL("b.com", "/title2.html")); GURL c_url(embedded_test_server()->GetURL("c.com", "/title3.html")); EXPECT_TRUE(NavigateToURL(shell(), a_url)); // Open a popup and navigate it to b.com. Shell* popup = OpenPopup(shell(), a_url, "popup"); EXPECT_TRUE(NavigateToURL(popup, b_url)); // Open a second popup and navigate it to b.com, which redirects to c.com. // The navigation to b.com will create a pending RenderFrameHost, which will // be canceled during the redirect to c.com. Note that NavigateToURL will // return false because the committed URL won't match the requested URL due // to the redirect. Shell* popup2 = OpenPopup(shell(), a_url, "popup2"); TestNavigationObserver observer(popup2->web_contents()); GURL redirect_url(embedded_test_server()->GetURL( "b.com", "/server-redirect?" + c_url.spec())); EXPECT_FALSE(NavigateToURL(popup2, redirect_url)); EXPECT_EQ(c_url, observer.last_navigation_url()); EXPECT_TRUE(observer.last_navigation_succeeded()); // Navigate the second popup to b.com. This used to crash the b.com renderer // because it failed to delete the canceled RFH's RenderFrame, so this caused // it to try to create a frame widget which already existed. EXPECT_TRUE(NavigateToURL(popup2, b_url)); } // Check that when a pending RFH is canceled and a proxy needs to be created in // its place, the proxy is properly initialized on the renderer side. See // https://crbug.com/653746. IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, CommunicateWithProxyAfterCancelPending) { GURL a_url(embedded_test_server()->GetURL("a.com", "/title1.html")); GURL b_url(embedded_test_server()->GetURL("b.com", "/title2.html")); GURL c_url(embedded_test_server()->GetURL("c.com", "/title3.html")); EXPECT_TRUE(NavigateToURL(shell(), a_url)); // Open a popup and navigate it to b.com. Shell* popup = OpenPopup(shell(), a_url, "popup"); EXPECT_TRUE(NavigateToURL(popup, b_url)); // Open a second popup and navigate it to b.com, which redirects to c.com. // The navigation to b.com will create a pending RenderFrameHost, which will // be canceled during the redirect to c.com. Note that NavigateToURL will // return false because the committed URL won't match the requested URL due // to the redirect. Shell* popup2 = OpenPopup(shell(), a_url, "popup2"); TestNavigationObserver observer(popup2->web_contents()); GURL redirect_url(embedded_test_server()->GetURL( "b.com", "/server-redirect?" + c_url.spec())); EXPECT_FALSE(NavigateToURL(popup2, redirect_url)); EXPECT_EQ(c_url, observer.last_navigation_url()); EXPECT_TRUE(observer.last_navigation_succeeded()); // Because b.com has other active frames (namely, the frame in |popup|), // there should be a proxy created for the canceled RFH, and it should be // live. SiteInstance* b_instance = popup->web_contents()->GetSiteInstance(); FrameTreeNode* popup2_root = static_cast<WebContentsImpl*>(popup2->web_contents()) ->GetFrameTree() ->root(); RenderFrameProxyHost* proxy = popup2_root->render_manager()->GetRenderFrameProxyHost(b_instance); EXPECT_TRUE(proxy); EXPECT_TRUE(proxy->is_render_frame_proxy_live()); // Add a postMessage listener in |popup2| (currently at a c.com URL). EXPECT_TRUE( ExecuteScript(popup2, "window.addEventListener('message', function(event) {\n" " document.title=event.data;\n" "});")); // Check that a postMessage can be sent via |proxy| above. This needs to be // done from the b.com process. |popup| is currently in b.com, but it can't // reach the window reference for |popup2| due to a security restriction in // Blink. So, navigate the main tab to b.com and then send a postMessage to // |popup2|. This is allowed since the main tab is |popup2|'s opener. EXPECT_TRUE(NavigateToURL(shell(), b_url)); base::string16 expected_title(base::UTF8ToUTF16("foo")); TitleWatcher title_watcher(popup2->web_contents(), expected_title); EXPECT_TRUE(ExecuteScript( shell(), "window.open('','popup2').postMessage('foo', '*');")); EXPECT_EQ(expected_title, title_watcher.WaitAndGetTitle()); } } // namespace content
[ "support@opentext.com" ]
support@opentext.com
b6bffbfe2445bffa701726b6119ae5a75e417769
20d24e22ee83a56de04010308918f71afa088b2b
/AlgNT_7/AlgNT_7/main.cpp
f033ec4e336ef96fc4151fb8a0fac94bfc5818c1
[]
no_license
ileasile/ANT_algorithms
2068f4c13db554296c4dba6e6261cf15b6b62fe9
3b45487aa174e809119924ee2a77ee86aa63484a
refs/heads/master
2021-01-20T12:06:51.665753
2017-04-20T05:53:39
2017-04-20T05:53:39
81,721,784
0
0
null
null
null
null
UTF-8
C++
false
false
4,616
cpp
#include <iostream> #include <cstdlib> #include <ctime> #include <string> #include <sstream> #include <NTL/ZZ_pXFactoring.h> #include <NTL/GF2XFactoring.h> using namespace NTL; using namespace std; void zz_px_test() { cout << "===== ZZ_PX test =====\n"; ZZ modulus(17); cout << "Modulus is " << modulus<< "\n"; ZZ_p::init(modulus); ZZ_pX p1, p2; string p1s("[2323 2323 12 30 33 0 2 11]"); string p2s("[13 15 8 177 31]"); stringstream io; //input io << p1s << " " << p2s; io >> p1 >> p2; //output std::cout << "P1 = " << p1 << "\nP2 = " << p2 << "\n"; //multiplication auto mlt = p1 * p2; std::cout << "P1 * P2 = " << mlt << "\n"; //division auto quo = p1 / p2; auto rem = p1 % p2; std::cout << "P1 / P2 = (" << quo << ", " << rem << ")\n"; std::cout << "Division check: P2 * Q + R = " << p2 * quo + rem << " (should be " << p1 << ")\n"; //Euclid algorithm ZZ_pX gcd; GCD(gcd, p1, p2); std::cout << "Euclid algorithm: (P1, P2) = " << gcd << "\n"; //Extended Euclid algorithm ZZ_pX u, v; XGCD(gcd, u, v, p1, p2); std::cout << "Ext. Euclid algorithm: (P1, P2) = " << gcd << " = " << "P1 * " << u << " + P2 * " << v << "\n"; //derivative of P1 ZZ_pX dp1; diff(dp1, p1); dp1.normalize(); std::cout << "d(P1)/dx = " << dp1 << "\n"; //P1(a) ZZ_p a(2); auto b = eval(p1, a); std::cout << "P1(" << a << ") = " << b << "\n"; //factorization of P1. //first make P1 monic auto ec = p1[deg(p1)]; auto p1_monic = p1 / ec; //then factor monic polynomial Vec< Pair< ZZ_pX, long > > factors; CanZass(factors, p1_monic); cout << "Factorization of P1: " << ec << " * " << factors << "\n"; //test for irreducibility cout << "Is P1 irreducible: " << DetIrredTest(p1) << "\n"; cout << "Is P2 irreducible: " << DetIrredTest(p2) << "\n"; //using ZZ_pXModulus. Using p1_monic as modulus ZZ_pXModulus F(p1_monic); auto res = ZZ_pX(1); int num_poly = 10; for (int i = 0; i < num_poly; ++i) { ZZ_pX p; BuildIrred(p, 6); MulMod(res, res, p, F); } cout << "Result of multiplication of several polynomials: " << res << "\n"; //modular compozition ZZ_pX p; BuildIrred(p, 9); cout << "P = " << p << "\n"; auto x = CompMod(p1, p2, p); cout << "P1(P2) mod P: " << x << "\n"; } GF2 eval(const GF2X & p, GF2 a) { if (IsZero(a)) return GF2(0); return GF2(weight(p)%2); } void gf2x_test() { cout << "===== GF2X test =====\n"; GF2X p1, p2; string p1s("[1 0 1 1 0 0 1 1]"); string p2s("[1 0 0 0 1]"); stringstream io; //input io << p1s << " " << p2s; io >> p1 >> p2; //output std::cout << "P1 = " << p1 << "\nP2 = " << p2 << "\n"; //multiplication auto mlt = p1 * p2; std::cout << "P1 * P2 = " << mlt << "\n"; //division auto quo = p1 / p2; auto rem = p1 % p2; std::cout << "P1 / P2 = (" << quo << ", " << rem << ")\n"; std::cout << "Division check: P2 * Q + R = " << p2 * quo + rem << " (should be " << p1 << ")\n"; //Euclid algorithm GF2X gcd; GCD(gcd, p1, p2); std::cout << "Euclid algorithm: (P1, P2) = " << gcd << "\n"; //Extended Euclid algorithm GF2X u, v; XGCD(gcd, u, v, p1, p2); std::cout << "Ext. Euclid algorithm: (P1, P2) = " << gcd << " = " << "P1 * " << u << " + P2 * " << v << "\n"; //derivative of P1 GF2X dp1; diff(dp1, p1); dp1.normalize(); std::cout << "d(P1)/dx = " << dp1 << "\n"; //P1(a), P2(a) GF2 a(1); auto b = eval(p1, a); std::cout << "P1(" << a << ") = " << b << "\n"; b = eval(p2, a); std::cout << "P2(" << a << ") = " << b << "\n"; //factorization of P1. //first make P1 monic auto ec = p1[deg(p1)]; auto p1_monic = p1 / ec; //then factor monic polynomial Vec< Pair< GF2X, long > > factors; CanZass(factors, p1_monic); cout << "Factorization of P1: " << ec << " * " << factors << "\n"; //test for irreducibility cout << "Is P1 irreducible: " << IterIrredTest(p1) << "\n"; cout << "Is P2 irreducible: " << IterIrredTest(p2) << "\n"; //using GF2XModulus. Using p1_monic as modulus GF2XModulus F(p1_monic); auto res = GF2X(1); int num_poly = 10; for (int i = 0; i < num_poly; ++i) { GF2X p; BuildIrred(p, 6); MulMod(res, res, p, F); } cout << "Result of multiplication of several polynomials: " << res << "\n"; //modular compozition GF2X p; BuildIrred(p, 9); cout << "P = " << p << "\n"; auto x = CompMod(p1, p2, p); cout <<"P1(P2) mod P: " << x << "\n"; } int main() { cout << "\nOriginal notation is used:\n"; cout << "P = [a0 a1 a2 ... an] means P(x) = a0 + a1*x + a2*x^2 + ... + an*x^n\n"; cout << "[[P1 n1] [P2 n2] ... [Pk nk]] means P1^n1 * P2^n2 * ... * Pk^nk\n\n"; zz_px_test(); cout << "\n"; gf2x_test(); //system("pause"); return 0; }
[ "leopardile@yandex.ru" ]
leopardile@yandex.ru
319c28e110f9c97d662fef508d9afc8faf3e6e40
879681c994f1ca9c8d2c905a4e5064997ad25a27
/root-2.3.0/run/tutorials/multiphase/twoPhaseEulerFoam/RAS/bubbleColumn/50/pMean
3bce07dbf3f54ca33e4b6df443a73f5f774ffb76
[]
no_license
MizuhaWatanabe/OpenFOAM-2.3.0-with-Ubuntu
3828272d989d45fb020e83f8426b849e75560c62
daeb870be81275e8a81f5cbac4ca1906a9bc69c0
refs/heads/master
2020-05-17T16:36:41.848261
2015-04-18T09:29:48
2015-04-18T09:29:48
34,159,882
1
0
null
null
null
null
UTF-8
C++
false
false
15,706
/*--------------------------------*- C++ -*----------------------------------*\ | ========= | | | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | | \\ / O peration | Version: 2.3.0 | | \\ / A nd | Web: www.OpenFOAM.org | | \\/ M anipulation | | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class volScalarField; location "50"; object pMean; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [1 -1 -2 0 0 0 0]; internalField nonuniform List<scalar> 1875 ( 107114 107108 107092 107078 107066 107058 107053 107051 107051 107051 107050 107049 107048 107045 107042 107040 107038 107037 107040 107046 107055 107069 107086 107104 107112 106933 106924 106911 106899 106891 106886 106884 106884 106885 106886 106886 106885 106884 106881 106878 106875 106872 106871 106871 106874 106881 106890 106903 106918 106929 106805 106800 106793 106787 106782 106779 106777 106777 106777 106777 106776 106776 106774 106773 106771 106770 106769 106769 106770 106772 106776 106781 106787 106794 106800 106684 106680 106675 106670 106666 106663 106660 106659 106658 106658 106658 106657 106657 106656 106656 106656 106656 106656 106658 106660 106665 106669 106675 106680 106684 106579 106575 106572 106568 106565 106562 106559 106558 106557 106557 106557 106557 106558 106558 106558 106559 106560 106560 106562 106565 106568 106572 106576 106580 106582 106475 106472 106469 106466 106463 106460 106458 106457 106457 106457 106457 106458 106459 106460 106461 106461 106462 106463 106465 106467 106470 106474 106477 106480 106482 106372 106369 106368 106366 106363 106361 106359 106358 106357 106358 106358 106359 106360 106361 106362 106363 106364 106365 106367 106369 106372 106374 106377 106379 106380 106268 106265 106264 106263 106261 106259 106257 106256 106255 106255 106254 106255 106255 106256 106257 106258 106259 106261 106262 106264 106267 106269 106272 106273 106274 106163 106161 106160 106159 106158 106156 106154 106152 106151 106149 106148 106148 106148 106148 106149 106150 106151 106153 106154 106157 106159 106161 106163 106164 106165 106056 106054 106054 106053 106052 106050 106048 106046 106044 106042 106040 106039 106039 106038 106039 106039 106040 106042 106043 106045 106048 106050 106052 106053 106054 105947 105946 105945 105944 105943 105942 105940 105938 105936 105934 105932 105930 105929 105928 105928 105929 105930 105931 105932 105934 105936 105938 105940 105941 105942 105837 105836 105835 105834 105833 105832 105831 105829 105827 105825 105822 105820 105819 105818 105819 105819 105820 105821 105823 105825 105826 105828 105829 105830 105831 105727 105726 105725 105724 105723 105722 105721 105719 105718 105716 105714 105712 105711 105710 105711 105712 105713 105714 105715 105717 105718 105720 105721 105722 105723 105618 105616 105615 105614 105614 105613 105612 105610 105609 105607 105606 105605 105604 105604 105604 105605 105607 105608 105609 105610 105611 105613 105615 105616 105617 105509 105508 105507 105506 105505 105505 105504 105503 105502 105500 105499 105498 105498 105498 105499 105500 105501 105502 105503 105504 105505 105507 105509 105510 105511 105403 105402 105401 105400 105399 105398 105398 105397 105396 105395 105394 105393 105393 105393 105394 105395 105396 105397 105398 105399 105400 105402 105403 105404 105405 105297 105297 105296 105294 105293 105293 105292 105291 105291 105289 105288 105287 105287 105287 105288 105290 105291 105292 105293 105294 105295 105297 105298 105299 105300 105192 105192 105191 105190 105188 105187 105186 105185 105184 105183 105181 105180 105180 105181 105182 105184 105186 105187 105189 105190 105191 105192 105193 105194 105195 105087 105086 105086 105084 105083 105081 105080 105078 105077 105075 105074 105074 105074 105075 105076 105078 105080 105082 105083 105085 105086 105087 105088 105089 105090 104982 104982 104981 104979 104978 104976 104975 104973 104971 104970 104969 104968 104968 104969 104971 104972 104974 104976 104978 104979 104981 104982 104983 104984 104985 104878 104877 104877 104876 104874 104873 104871 104870 104869 104867 104866 104865 104865 104865 104866 104867 104869 104870 104872 104873 104874 104876 104877 104878 104879 104775 104774 104774 104773 104772 104770 104769 104768 104767 104766 104765 104763 104762 104762 104762 104763 104764 104765 104766 104768 104769 104770 104771 104772 104774 104672 104672 104671 104671 104670 104669 104668 104667 104666 104664 104663 104661 104660 104659 104659 104659 104660 104661 104662 104663 104664 104665 104667 104667 104669 104569 104569 104569 104568 104567 104566 104565 104564 104563 104561 104560 104558 104557 104556 104555 104555 104556 104557 104558 104559 104560 104561 104562 104563 104564 104465 104465 104465 104464 104463 104462 104461 104460 104458 104457 104455 104453 104452 104451 104450 104451 104451 104452 104453 104455 104456 104457 104458 104459 104460 104359 104359 104359 104358 104357 104356 104355 104354 104352 104351 104349 104348 104346 104346 104345 104345 104346 104348 104349 104350 104352 104353 104354 104355 104356 104253 104252 104252 104251 104250 104249 104248 104247 104245 104244 104242 104241 104240 104240 104240 104241 104242 104243 104245 104247 104248 104249 104250 104251 104251 104146 104145 104145 104144 104143 104142 104141 104140 104138 104137 104136 104135 104134 104134 104135 104136 104137 104139 104141 104142 104144 104145 104146 104146 104147 104039 104038 104038 104037 104036 104035 104034 104033 104032 104031 104030 104029 104029 104029 104029 104031 104032 104034 104036 104037 104039 104040 104041 104041 104042 103933 103932 103931 103931 103930 103929 103928 103927 103926 103925 103924 103923 103923 103923 103924 103926 103927 103929 103930 103932 103933 103934 103936 103936 103936 103827 103826 103826 103825 103824 103823 103822 103821 103821 103820 103819 103819 103819 103819 103820 103821 103822 103824 103825 103827 103828 103829 103830 103831 103831 103723 103722 103721 103720 103719 103718 103718 103717 103716 103716 103715 103715 103715 103715 103716 103717 103718 103719 103720 103722 103723 103724 103725 103726 103726 103618 103617 103617 103616 103615 103614 103614 103613 103612 103612 103612 103611 103611 103611 103612 103612 103613 103614 103615 103617 103618 103619 103620 103621 103621 103514 103513 103513 103512 103512 103511 103510 103509 103509 103508 103508 103507 103507 103507 103508 103508 103509 103510 103510 103512 103513 103514 103515 103515 103516 103411 103410 103409 103409 103408 103407 103407 103406 103405 103404 103404 103403 103403 103403 103403 103403 103404 103405 103406 103407 103408 103409 103409 103410 103410 103307 103306 103306 103305 103305 103304 103303 103302 103301 103300 103299 103299 103298 103298 103299 103299 103300 103300 103301 103302 103303 103303 103304 103305 103305 103202 103202 103202 103201 103200 103200 103199 103198 103196 103195 103194 103194 103194 103194 103194 103194 103195 103196 103196 103197 103198 103199 103199 103200 103200 103098 103097 103097 103096 103095 103094 103094 103092 103091 103090 103089 103089 103088 103088 103089 103089 103090 103091 103092 103093 103093 103094 103095 103095 103095 102992 102992 102991 102991 102990 102989 102988 102987 102986 102985 102984 102983 102983 102983 102984 102984 102985 102986 102987 102988 102989 102989 102990 102990 102990 102887 102887 102886 102886 102885 102884 102883 102882 102881 102880 102879 102878 102878 102878 102879 102880 102881 102882 102882 102883 102884 102884 102885 102885 102886 102782 102782 102781 102781 102780 102779 102778 102777 102776 102775 102775 102774 102774 102774 102774 102775 102776 102777 102778 102779 102779 102780 102780 102781 102781 102677 102677 102677 102676 102676 102675 102674 102673 102672 102671 102671 102670 102670 102670 102670 102671 102671 102672 102673 102674 102675 102675 102676 102676 102676 102573 102573 102572 102572 102571 102571 102570 102569 102568 102567 102567 102566 102566 102565 102566 102566 102567 102567 102568 102569 102570 102570 102571 102571 102572 102468 102468 102468 102467 102467 102466 102465 102465 102464 102463 102463 102462 102461 102461 102461 102461 102462 102462 102463 102464 102465 102466 102466 102467 102467 102363 102363 102363 102363 102362 102362 102361 102360 102359 102359 102358 102358 102357 102357 102357 102357 102357 102358 102359 102359 102360 102361 102362 102362 102362 102258 102258 102258 102257 102257 102256 102256 102255 102254 102254 102253 102253 102253 102252 102252 102253 102253 102253 102254 102255 102255 102256 102257 102257 102258 102153 102153 102152 102152 102152 102151 102150 102150 102149 102149 102148 102148 102148 102148 102148 102148 102148 102149 102150 102150 102151 102152 102152 102152 102153 102048 102048 102047 102047 102046 102046 102045 102045 102044 102044 102044 102044 102043 102043 102043 102044 102044 102045 102045 102046 102046 102047 102048 102048 102049 101944 101943 101943 101942 101942 101941 101940 101940 101940 101940 101939 101939 101939 101939 101939 101939 101940 101940 101941 101942 101942 101943 101943 101944 101944 101839 101838 101838 101837 101837 101836 101836 101836 101835 101835 101835 101835 101834 101834 101835 101835 101835 101836 101836 101837 101838 101838 101839 101839 101840 101734 101734 101733 101733 101732 101732 101731 101731 101730 101730 101730 101730 101730 101730 101730 101730 101731 101732 101732 101733 101734 101734 101735 101735 101736 101630 101629 101629 101628 101627 101627 101626 101626 101626 101625 101625 101625 101625 101625 101625 101626 101627 101628 101629 101629 101630 101630 101631 101631 101632 101526 101525 101524 101524 101523 101523 101522 101521 101521 101521 101520 101520 101520 101520 101521 101522 101523 101524 101524 101525 101526 101526 101527 101527 101527 101422 101421 101421 101420 101420 101419 101419 101418 101417 101417 101416 101416 101416 101416 101417 101418 101419 101420 101421 101421 101422 101422 101423 101423 101424 101319 101318 101318 101318 101317 101317 101316 101315 101315 101314 101314 101313 101313 101314 101314 101315 101316 101317 101318 101318 101319 101319 101319 101320 101320 101217 101216 101216 101215 101215 101214 101214 101213 101213 101212 101212 101211 101211 101211 101212 101213 101213 101214 101215 101215 101216 101216 101217 101217 101217 101115 101114 101114 101113 101113 101112 101112 101111 101111 101110 101109 101109 101109 101109 101109 101110 101110 101111 101112 101112 101113 101113 101114 101114 101115 101013 101013 101012 101012 101012 101011 101010 101010 101009 101008 101008 101007 101007 101007 101007 101007 101008 101008 101009 101010 101011 101011 101012 101012 101013 100913 100912 100912 100911 100911 100910 100910 100909 100908 100907 100906 100906 100905 100905 100905 100905 100906 100906 100907 100908 100909 100909 100910 100910 100911 100812 100812 100812 100811 100811 100810 100809 100808 100807 100807 100806 100805 100805 100805 100805 100805 100805 100806 100806 100807 100808 100808 100809 100809 100810 100712 100712 100711 100711 100711 100710 100709 100708 100708 100707 100706 100706 100705 100705 100705 100705 100706 100706 100707 100708 100708 100709 100709 100709 100711 100613 100612 100612 100611 100611 100610 100610 100609 100608 100607 100607 100606 100606 100606 100606 100606 100607 100607 100608 100609 100609 100610 100610 100611 100612 100514 100513 100512 100512 100512 100511 100511 100510 100509 100508 100508 100508 100507 100507 100508 100508 100508 100509 100510 100511 100511 100512 100512 100513 100514 100415 100414 100414 100414 100413 100413 100413 100412 100412 100411 100411 100411 100411 100411 100411 100411 100411 100412 100412 100413 100414 100414 100415 100415 100417 100319 100318 100318 100317 100317 100317 100317 100317 100317 100316 100316 100316 100316 100316 100316 100316 100316 100316 100317 100317 100318 100318 100319 100319 100320 100222 100221 100221 100221 100221 100221 100222 100222 100222 100222 100222 100222 100222 100222 100222 100221 100221 100221 100221 100221 100221 100221 100222 100221 100223 100123 100123 100124 100125 100125 100125 100125 100125 100125 100125 100125 100125 100124 100124 100124 100123 100123 100122 100122 100122 100122 100122 100122 100121 100121 100033 100035 100037 100037 100037 100036 100036 100036 100036 100036 100036 100036 100036 100036 100036 100036 100035 100035 100035 100035 100035 100035 100034 100033 100031 100004 100005 100005 100006 100006 100006 100005 100005 100005 100005 100005 100005 100005 100005 100005 100005 100005 100005 100005 100005 100005 100005 100005 100005 100003 100001 100001 100001 100001 100001 100001 100001 100001 100001 100001 100001 100001 100001 100001 100001 100001 100001 100001 100001 100001 100001 100001 100001 100001 100001 100001 100001 100001 100001 100001 100001 100001 100001 100001 100001 100001 100001 100001 100001 100001 100001 100001 100001 100001 100001 100001 100001 100001 100001 100001 100001 100001 100001 100001 100001 100001 100001 100001 100001 100001 100001 100001 100001 100001 100001 100001 100001 100001 100001 100001 100001 100001 100001 100001 100001 100000 100000 100000 100000 100000 100000 100000 100000 100000 100000 100000 100000 100000 100000 100000 100000 100000 100000 100000 100000 100000 100000 100000 100000 100000 100000 100000 100000 100000 100000 100000 100000 100000 100000 100000 100000 100000 100000 100000 100000 100000 100000 100000 100000 100000 100000 100000 100000 100000 100000 100000 100000 100000 100000 100000 100000 100000 100000 100000 100000 100000 100000 100000 100000 100000 100000 100000 100000 100000 100000 100000 100000 100000 100000 100000 ) ; boundaryField { inlet { type calculated; value nonuniform List<scalar> 25 ( 107122 107116 107100 107086 107075 107067 107062 107060 107060 107060 107060 107059 107057 107055 107052 107049 107047 107047 107049 107055 107064 107077 107094 107112 107120 ) ; } outlet { type calculated; value uniform 100000; } walls { type calculated; value nonuniform List<scalar> 150 ( 107114 106933 106805 106684 106579 106475 106372 106268 106163 106056 105947 105837 105727 105618 105509 105403 105297 105192 105087 104982 104878 104775 104672 104569 104465 104359 104253 104146 104039 103933 103827 103723 103618 103514 103411 103307 103202 103098 102992 102887 102782 102677 102573 102468 102363 102258 102153 102048 101944 101839 101734 101630 101526 101422 101319 101217 101115 101013 100913 100812 100712 100613 100514 100415 100319 100222 100123 100033 100004 100001 100001 100001 100000 100000 100000 107112 106929 106800 106684 106582 106482 106380 106274 106165 106054 105942 105831 105723 105617 105511 105405 105300 105195 105090 104985 104879 104774 104669 104564 104460 104356 104251 104147 104042 103936 103831 103726 103621 103516 103410 103305 103200 103095 102990 102886 102781 102676 102572 102467 102362 102258 102153 102049 101944 101840 101736 101632 101527 101424 101320 101217 101115 101013 100911 100810 100711 100612 100514 100417 100320 100223 100121 100031 100003 100001 100001 100001 100000 100000 100000 ) ; } defaultFaces { type empty; } } // ************************************************************************* //
[ "mizuha.watanabe@gmail.com" ]
mizuha.watanabe@gmail.com
f9b5c67f14f6cd4111dd50cc926e406e42055af4
4897b9d75d851a81606d19a0e046b32eb16aa1bd
/contest/3/339/A.cpp
266a2659960ec813af935895bc5cda4f6afeb9b9
[]
no_license
tiankonguse/leetcode-solutions
0b5e3a5b3f7063374e9543b5f516e9cecee0ad1f
a36269c861bd5797fe3835fc179a19559fac8655
refs/heads/master
2023-09-04T11:01:00.787559
2023-09-03T04:26:25
2023-09-03T04:26:25
33,770,209
83
38
null
2020-05-12T15:13:59
2015-04-11T09:31:39
C++
UTF-8
C++
false
false
619
cpp
// #include <bits/stdc++.h> #include "base.h" using namespace std; typedef long long ll; class Solution { public: int findTheLongestBalancedSubstring(string s) { int ans = 0; int preZero = 0; int preOne = 0; int state = 0; for (auto c : s) { if (c == '0') { if (state == 1) { preZero = 0; preOne = 0; state = 0; } preZero++; } else { if (state == 0) { state = 1; } preOne++; ans = max(ans, min(preZero, preOne) * 2); } } return ans; } };
[ "i@tiankonguse.com" ]
i@tiankonguse.com
c84a2fea30cb1d39266cd8178b97d270f4c6e69b
804cc6764d90fdd7424fa435126c7fe581111562
/Kernel/Interrupts/IRQController.cpp
9650ca42bd64475488c7cdd5bb96edfd332e146f
[ "BSD-2-Clause" ]
permissive
NukeWilliams/prana-os
96abeed02f33f87c74dd066a5fa7b2d501cb2c62
c56c230d3001a48c342361733dc634a5afaf35f9
refs/heads/master
2023-06-17T18:39:22.394466
2021-07-02T13:37:47
2021-07-02T13:37:47
358,167,671
1
0
null
null
null
null
UTF-8
C++
false
false
1,366
cpp
// includes #include <Kernel/Arch/x86/CPU.h> #include <Kernel/Debug.h> #include <Kernel/Interrupts/IRQHandler.h> #include <Kernel/Interrupts/InterruptManagement.h> namespace Kernel { IRQHandler::IRQHandler(u8 irq) : GenericInterruptHandler(irq) , m_responsible_irq_controller(InterruptManagement::the().get_responsible_irq_controller(irq)) { disable_irq(); } IRQHandler::~IRQHandler() { } bool IRQHandler::eoi() { dbgln_if(IRQ_DEBUG, "EOI IRQ {}", interrupt_number()); if (!m_shared_with_others) { VERIFY(!m_responsible_irq_controller.is_null()); m_responsible_irq_controller->eoi(*this); return true; } return false; } void IRQHandler::enable_irq() { dbgln_if(IRQ_DEBUG, "Enable IRQ {}", interrupt_number()); if (!is_registered()) register_interrupt_handler(); m_enabled = true; if (!m_shared_with_others) m_responsible_irq_controller->enable(*this); } void IRQHandler::disable_irq() { dbgln_if(IRQ_DEBUG, "Disable IRQ {}", interrupt_number()); m_enabled = false; if (!m_shared_with_others) m_responsible_irq_controller->disable(*this); } void IRQHandler::change_irq_number(u8 irq) { InterruptDisabler disabler; change_interrupt_number(irq); m_responsible_irq_controller = InterruptManagement::the().get_responsible_irq_controller(irq); } }
[ "krisna.pranav@gmail.com" ]
krisna.pranav@gmail.com
01362f15d738e0e6c90690918b64666dad86d956
b6fbcca571d9505e1670240b665bb6176c018227
/src/mhoauth-refresh_loop.c++
13b1d2c864eb815f5126dcfa969f204a03e80122
[]
no_license
palmer-dabbelt/mhng
e3265521dd5c344e6e03ab21cbf18d50df1772a7
fe4016edfa0a9210cecb130379138b8c2041a3b3
refs/heads/master
2023-05-27T04:07:02.280190
2023-05-10T19:19:03
2023-05-10T19:19:03
4,741,488
1
0
null
2021-02-03T05:32:32
2012-06-21T16:32:18
C++
UTF-8
C++
false
false
1,065
/* Copyright (C) 2019 Palmer Dabbelt <palmerdabbelt@google.com> */ /* SPDX-License-Identifier: GPL-2.0+ OR Apache-2.0 OR BSD-3-Clause */ #include <libmhng/args.h++> #include <libmhoauth/pkce.h++> #include <iomanip> #include <thread> int main(int argc, const char **argv) { auto args = mhng::args::parse_account(argc, argv); auto account = args->mbox()->account(args->account()); while (true) { std::cerr << "Refreshing oauth2 token for " << account->name() << "\n"; auto expired_at = std::chrono::system_clock::to_time_t(account->access_token().expires_at()); std::cerr << " from " << std::put_time(std::gmtime(&expired_at), "%c %Z") << "\n"; auto ref = account->refresh(); auto expires_at = std::chrono::system_clock::to_time_t(ref.expires_at()); std::cerr << " to " << std::put_time(std::gmtime(&expires_at), "%c %Z") << "\n"; /* FIXME: Hopefully these last for an hour... */ std::this_thread::sleep_until(ref.expires_at() - std::chrono::minutes(10)); } return 0; }
[ "palmerdabbelt@google.com" ]
palmerdabbelt@google.com
3339e832a9c913c04305e4239b730d602e404ee9
38030e497b6e172cb926ebce4d25019175713bbd
/Medium/Merge K sorted lists.cpp
9e82a4d9f6034f104de3a9455f1652326fccbafb
[]
no_license
KushRohra/GFG_Codes
7e6126434360bd0e376ce13be7e855c380b88d24
54e2b0affeaac3406aa052c28cfebcefc6492f90
refs/heads/master
2021-03-26T00:37:05.871686
2020-12-27T12:51:53
2020-12-27T12:51:53
247,659,010
0
0
null
null
null
null
UTF-8
C++
false
false
1,910
cpp
// { Driver Code Starts // C++ program to merge k sorted arrays of size n each #include <bits/stdc++.h> using namespace std; // A Linked List node struct Node { int data; Node* next; Node(int x){ data = x; next = NULL; } }; Node* mergeKLists(Node* arr[], int N); /* Function to print nodes in a given linked list */ void printList(Node* node) { while (node != NULL) { printf("%d ", node->data); node = node->next; } cout<<endl; } // Driver program to test above functions int main() { int t; cin>>t; while(t--) { int N; cin>>N; struct Node *arr[N]; for(int j=0;j<N;j++) { int n; cin>>n; int x; cin>>x; arr[j]=new Node(x); Node *curr = arr[j]; n--; for(int i=0;i<n;i++) { cin>>x; Node *temp = new Node(x); curr->next =temp; curr=temp; } } Node *res = mergeKLists(arr,N); printList(res); } return 0; } // } Driver Code Ends /*Linked list Node structure struct Node { int data; Node* next; Node(int x){ data = x; next = NULL; } }; */ /* arr[] is an array of pointers to heads of linked lists and N is size of arr[] */ Node *merge(Node *h1, Node *h2) { Node *head=NULL; if(h1==NULL) return h2; if(h2==NULL) return h1; if(h1->data<=h2->data) { head=h1; head->next=merge(h1->next, h2); } else { head=h2; head->next=merge(h1, h2->next); } return head; } Node * mergeKLists(Node *arr[], int N) { int last=N-1; while(last!=0) { int i=0, j=last; while(i<j) { arr[i]=merge(arr[i], arr[j]); i++; j--; if(i>=j) last=j; } } return arr[0]; }
[ "iec2017024@iiita.ac.in" ]
iec2017024@iiita.ac.in
b398a4e4852d71f5bb699494bba0a46a8a5f405f
49f15e237696d1c166c727fad9c8923d33497494
/codeforces/432.cpp
a5caeebd1c5283fc6c786c8ed00d88e92e319aed
[]
no_license
gauravkr123/Codes
280284a3c7cdab2454a8da267c0622b40707e32b
c0295cfbad7794a25c1d4cf85ef8d4d13da8f2c6
refs/heads/master
2020-03-22T17:29:24.819064
2017-12-14T17:59:33
2017-12-14T17:59:33
140,398,111
2
0
null
2018-07-10T08:01:38
2018-07-10T08:01:38
null
UTF-8
C++
false
false
255
cpp
#include<bits/stdc++.h> using namespace std; int main() { int n,k; cin>>n>>k; int a[n]; int counter=0; for(int i=0;i<n;i++) { cin>>a[i]; if(a[i]+k<=5) counter++; } cout<<counter/3<<endl; return 0; }
[ "vedicpartap1999@gmail.com" ]
vedicpartap1999@gmail.com
7781c7edabe93da0a8a835a8f604b597b4c5c1f8
e3d917181ee947fe596df4b66e1bdc066e9f9e02
/windowsbuild/MSVC2022/vtkm/v1.9.0/include/vtkm-1.9/vtkm/cont/arg/TypeCheckTagArrayOut.h
f694b4c11dc838b616142e9bb360c431b079a468
[ "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ]
permissive
visit-dav/visit-deps
d1be0023fa4c91c02589e5d87ab4e48c99145bb5
d779eb48a12e667c3b759cedd3732053d7676abf
refs/heads/master
2023-08-08T15:30:28.412508
2023-07-31T22:34:52
2023-07-31T22:34:52
174,021,407
2
3
NOASSERTION
2023-07-06T16:07:22
2019-03-05T21:12:14
C++
UTF-8
C++
false
false
1,755
h
//============================================================================ // Copyright (c) Kitware, Inc. // All rights reserved. // See LICENSE.txt for details. // // This software is distributed WITHOUT ANY WARRANTY; without even // the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR // PURPOSE. See the above copyright notice for more information. //============================================================================ #ifndef vtk_m_cont_arg_TypeCheckTagArrayOut_h #define vtk_m_cont_arg_TypeCheckTagArrayOut_h #include <vtkm/cont/arg/TypeCheck.h> #include <vtkm/List.h> #include <vtkm/cont/ArrayHandle.h> #include <vtkm/internal/ArrayPortalHelpers.h> namespace vtkm { namespace cont { namespace arg { /// The Array type check passes for any object that behaves like an /// `ArrayHandle` class and can be passed to the ArrayOut transport. /// struct TypeCheckTagArrayOut { }; namespace detail { template <typename ArrayType, bool IsArrayHandle = vtkm::cont::internal::ArrayHandleCheck<ArrayType>::type::value> struct IsArrayHandleOut; template <typename ArrayType> struct IsArrayHandleOut<ArrayType, true> { static constexpr bool value = (vtkm::internal::PortalSupportsGets<typename ArrayType::ReadPortalType>::value && vtkm::internal::PortalSupportsSets<typename ArrayType::WritePortalType>::value); }; template <typename ArrayType> struct IsArrayHandleOut<ArrayType, false> { static constexpr bool value = false; }; } // namespace detail template <typename ArrayType> struct TypeCheck<TypeCheckTagArrayOut, ArrayType> { static constexpr bool value = detail::IsArrayHandleOut<ArrayType>::value; }; } } } // namespace vtkm::cont::arg #endif //vtk_m_cont_arg_TypeCheckTagArray_h
[ "noreply@github.com" ]
noreply@github.com
8b9a33bd819651167363c35aa4a361537528c13a
c414d144924798766a8e64d1b6b1f2c4f038584b
/Editor/Editor/Door.h
f062e724f48d9f6a0ef38b3a90a3d0ae93eb0eb7
[]
no_license
Luoman/GameTools
80f378a9c0af0e36e82d30be0ba8868eaf6c93f0
597af2227da8111827f629c1a8922cb271355449
refs/heads/master
2021-01-01T15:35:20.145428
2013-05-20T12:13:54
2013-05-20T12:13:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
394
h
#ifndef DOOR_H #define DOOR_H #include <iostream> #include <string> class Door { private: char m_cLocalization; std::string m_sState; public: Door(); Door(char loc, const std::string &state); ~Door(); char &getLocalization(); const std::string &getState() const; void setLocalization(char loc); void setState(const std::string &type); }; #endif /* DOOR_H */
[ "romuald.scharre@gmail.com" ]
romuald.scharre@gmail.com
3db8c03b12eedca71c9f9ab59262706876d0fcb8
6ee55fde0bbe04141ed311b172fa834ec117fa57
/src/control.cc
958667212ef6ecb336585f0e4551c130c5825d1d
[ "Apache-2.0" ]
permissive
icaropires/embedded-temperature-on-off
36de8a8d3130c3236c27d2db0ca0dec167c2d80e
a5669acd930375b44afff69badacaf32bf8539be
refs/heads/main
2023-01-19T11:00:47.853860
2020-11-24T19:41:27
2020-11-24T19:52:50
302,998,206
1
0
null
null
null
null
UTF-8
C++
false
false
6,332
cc
#include "control.h" Control::Control(const std::string &sensor_ti_addr, const std::string &sensor_tr_addr, const std::string &sensor_te_addr, uint8_t display_monitor_addr, uint8_t cooler_addr, uint8_t resistor_addr, const std::string& csv_file) : sensor_ti(sensor_ti_addr), sensor_tr(sensor_tr_addr), sensor_te(sensor_te_addr), display_monitor(display_monitor_addr), cooler(cooler_addr), resistor(resistor_addr), ui(current_ti, current_tr, current_te, mutex_ti, mutex_tr, mutex_te), do_stop(false), has_started(false), csv_file(csv_file) { } void Control::stop() { do_stop = true; ui.stop(); cv_general.notify_all(); cv_csv.notify_all(); s_csv_file.close(); usleep(5e5); // Let threads finish display_monitor.clear(); cooler.turn_off(); resistor.turn_off(); } void Control::start() { create_csv(); hysteresis = ask_hysteresis(); bool use_potentiometer = ask_use_potentiometer(); has_started = true; std::thread t_te(&Control::update_te_loop, this); std::thread t_ti_tr(&Control::update_ti_tr_loop, this, use_potentiometer); std::thread t_ui (&UI::start, std::ref(ui), !use_potentiometer); std::thread t_display(&Control::update_display_loop, this); std::thread t_csv_file(&Control::update_csv_loop, this); std::thread t_apply(&Control::apply_loop, this); t_te.join(); t_ti_tr.join(); t_ui.join(); t_display.join(); t_csv_file.join(); t_apply.join(); } bool Control::ask_use_potentiometer() const { std::string str_potentiometer; std::cout << "Use potentiometer (yes)? Or give inputs using keyboard? (no)" << std::endl; std::getline(std::cin, str_potentiometer); if (str_potentiometer == "yes") { return true; } return false; } float Control::ask_hysteresis() const { float result = -1; while (result == -1) { try { std::string str_hysteresis; std::cout << "Which value use for hysteresis?" << std::endl; std::getline(std::cin, str_hysteresis); result = std::stof(str_hysteresis); } catch(std::invalid_argument&) { std::cout << "Invalid value! Try again." << std::endl << std::endl; } } return result; } void Control::schedule() { /* Meant to be called every 500ms */ /* Same period for applying control and updating temperature */ if (!has_started) { return; } unsigned int save_csv_period = 4; // Save every 2s save_csv_counter++; if (save_csv_counter == save_csv_period) { cv_csv.notify_one(); save_csv_counter = 0; } ui.print_out(); cv_general.notify_all(); // Start updating all temperatures at same time } void Control::update_display_loop() { std::unique_lock<std::mutex> lock_display(mutex_display); float ti_aux = -1, te_aux = -1, tr_aux = -1; while (!do_stop) { { std::lock_guard<std::mutex> lock_ti(mutex_ti); ti_aux = current_ti; } { std::lock_guard<std::mutex> lock_tr(mutex_tr); tr_aux = current_tr; } { std::lock_guard<std::mutex> lock_te(mutex_te); te_aux = current_te; } display_monitor.print_temps(ti_aux, tr_aux, te_aux); cv_general.wait(lock_display); } } void Control::update_te_loop() { std::unique_lock<std::mutex> lock_te(mutex_te); while (!do_stop) { try { current_te = sensor_te.get_next(); } catch (std::runtime_error& e) { std::cerr << "Error when getting data: " << e.what() << std::endl; } cv_general.wait(lock_te); } } void Control::update_ti_tr_loop(bool update_tr) { std::unique_lock<std::mutex> lock_uart(mutex_uart); while (!do_stop) { try { { std::lock_guard<std::mutex> lock_ti(mutex_ti); current_ti = sensor_ti.get_next(); } if (update_tr) { std::lock_guard<std::mutex> lock_tr(mutex_tr); current_tr = sensor_tr.get_next(); } } catch (std::runtime_error& e) { std::cerr << "Error when getting data: " << e.what() << std::endl; } cv_general.wait(lock_uart); } } std::string Control::get_datetime_csv() { time_t t = time(nullptr); struct tm tm = *localtime(&t); char datetime[20]; // Ex: 2020-09-22,19:52:31 strftime(datetime, sizeof(tm), "%F,%T", &tm); return std::string(datetime); } void Control::create_csv() { s_csv_file.open(csv_file, std::ios::out | std::ios::trunc); s_csv_file << "date,time,temperatura interna,temperatura externa,temperatura de referência" << std::endl; } void Control::update_csv_loop() { /* Open the file just once (on create_csv()) to make it faster */ std::unique_lock<std::mutex> lock(mutex_csv); float ti_aux = -1, te_aux = -1, tr_aux = -1; while (!do_stop) { { std::lock_guard<std::mutex> lock_ti(mutex_ti); ti_aux = current_ti; } { std::lock_guard<std::mutex> lock_tr(mutex_tr); tr_aux = current_tr; } { std::lock_guard<std::mutex> lock_te(mutex_te); te_aux = current_te; } std::string datetime = get_datetime_csv(); s_csv_file << std::fixed << std::setprecision(2) << std::setfill('0') << datetime << ',' << ti_aux << ',' << te_aux << ',' << tr_aux << std::endl; cv_csv.wait(lock); } } void Control::apply_loop() { std::unique_lock<std::mutex> lock_apply(mutex_apply); while (!do_stop) { float tr_aux = -1, ti_aux = -1; { std::lock_guard<std::mutex> lock_tr(mutex_tr); tr_aux = current_tr; } { std::lock_guard<std::mutex> lock_ti(mutex_ti); ti_aux = current_ti; } float upper = tr_aux + hysteresis / 2; float lower = tr_aux - hysteresis / 2; if (ti_aux < lower) { cooler.turn_off(); resistor.turn_on(); } else if(ti_aux > upper) { cooler.turn_on(); resistor.turn_off(); } cv_general.wait(lock_apply); } }
[ "icaropsa@gmail.com" ]
icaropsa@gmail.com
88f0cd8df8331ff3d3a3cbd24b5bc0544e155d2d
1ac4a89c27e6eb0ab5b6c7ae06c52cd3e526d90b
/vikr-source/src/scene/components/mesh_component.cpp
75d858ce9c08f58e773b4f0edb9223ceee26cf78
[ "MIT" ]
permissive
lm165678/Vikr
e54d3cc6130238eb59d78f2813d3cda1a6440ef5
9ac78f9f47a2222dfd40700fcc48e88d898c086b
refs/heads/master
2023-03-22T14:49:38.921733
2017-02-27T06:45:43
2017-02-27T06:45:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
361
cpp
// // Copyright (c) Mario Garcia, Under the MIT License. // #include <vikr/scene/components/mesh_component.hpp> #include <vikr/scene/scene_node.hpp> #include <vikr/renderer/command/mesh_command.hpp> namespace vikr { MeshComponent::MeshComponent() : SceneComponent(vikr_COMPONENT_MESH) { } vvoid MeshComponent::Update() { cmd.m_mesh = mesh; } } // vikr
[ "alexander.garcia18@yahoo.com" ]
alexander.garcia18@yahoo.com
7675974c576725092e26fe6d670e1b6abba36ff6
475850f09ea39d11814f3c9f6e301df2fd62c76e
/leetcode/081_Search in Rotated Sorted Array II.cpp
9d2849cd1d10babf4e8b48ececd53d6002445259
[]
no_license
njuHan/OJcodes
fed59759b4b954a123cdc423d8c36addd7252d41
1adc57f0850f3f0031ba8d62e974ab3842da5c2d
refs/heads/master
2021-01-25T14:22:21.728203
2019-06-16T05:11:55
2019-06-16T05:11:55
123,686,571
16
1
null
null
null
null
UTF-8
C++
false
false
1,947
cpp
#include<iostream> #include<cstdio> #include<vector> #include<queue> #include<stack> #include<string> #include<unordered_map> #include<unordered_set> #include<set> #include<list> using namespace std; /* 272 / 275 test cases passed. Input: [1,1,3,1] 3 Output: false Expected: true error : minidx = 0 class Solution { public: bool search(vector<int>& nums, int target) { int lo = 0, hi = nums.size()-1, minidx=0, maxidx=0; while (lo<hi) { int mid = lo + (hi - lo) / 2; if (nums[mid] > nums[hi]) lo = mid + 1; else if (nums[mid] < nums[hi]) hi = mid; else hi--; } minidx = lo; maxidx = (lo + nums.size() - 1) % nums.size(); if (target<nums[minidx] || target>nums[maxidx]) return false; if (target >= nums[0]) return bSearch(0, maxidx + 1, nums, target); else return bSearch(maxidx, nums.size(), nums, target); } bool bSearch(int x, int y, vector<int>& nums, int target) { while (x<y) { int mid = x + (y - x) / 2; if (nums[mid] == target) return true; if (nums[mid] < target) x = mid+1; else y = mid; } return false; } }; */ // https://leetcode.com/problems/search-in-rotated-sorted-array-ii/discuss/28218/My-8ms-C++-solution-(o(logn)-on-average-o(n)-worst-case) class Solution { public: bool search(vector<int>& nums, int target) { if (nums.size() == 0) return false; int lo = 0, hi = nums.size()-1; while (lo < hi) { int mid = lo + (hi - lo) / 2; if (nums[mid] == target) return true; if (nums[lo] < nums[mid]) { if (nums[lo] <= target && target < nums[mid]) hi = mid - 1; else lo = mid + 1; } else if (nums[mid] < nums[hi]) { if (nums[mid] < target && target <= nums[hi]) lo = mid + 1; else hi = mid - 1; } else { if (nums[lo] == nums[mid]) lo++; if (nums[hi] == nums[mid]) hi--; } } return nums[lo] == target; } }; int main() { Solution solu; vector<int> vec = { 2,5,6,0,0,1,2 }; solu.search(vec, 0); return 0; }
[ "463808243@qq.com" ]
463808243@qq.com
41f141a0e5c3e22bc84d2e5da2a472df80b42e47
d0fb46aecc3b69983e7f6244331a81dff42d9595
/dt-oc-info/src/model/GetOcListedCompanyRequest.cc
6cdf355d852e964acee0acbdef1661be7bfc82b5
[ "Apache-2.0" ]
permissive
aliyun/aliyun-openapi-cpp-sdk
3d8d051d44ad00753a429817dd03957614c0c66a
e862bd03c844bcb7ccaa90571bceaa2802c7f135
refs/heads/master
2023-08-29T11:54:00.525102
2023-08-29T03:32:48
2023-08-29T03:32:48
115,379,460
104
82
NOASSERTION
2023-09-14T06:13:33
2017-12-26T02:53:27
C++
UTF-8
C++
false
false
1,737
cc
/* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <alibabacloud/dt-oc-info/model/GetOcListedCompanyRequest.h> using AlibabaCloud::Dt_oc_info::Model::GetOcListedCompanyRequest; GetOcListedCompanyRequest::GetOcListedCompanyRequest() : RpcServiceRequest("dt-oc-info", "2022-08-29", "GetOcListedCompany") { setMethod(HttpRequest::Method::Post); } GetOcListedCompanyRequest::~GetOcListedCompanyRequest() {} int GetOcListedCompanyRequest::getPageNo() const { return pageNo_; } void GetOcListedCompanyRequest::setPageNo(int pageNo) { pageNo_ = pageNo; setBodyParameter(std::string("PageNo"), std::to_string(pageNo)); } int GetOcListedCompanyRequest::getPageSize() const { return pageSize_; } void GetOcListedCompanyRequest::setPageSize(int pageSize) { pageSize_ = pageSize; setBodyParameter(std::string("PageSize"), std::to_string(pageSize)); } std::string GetOcListedCompanyRequest::getSearchKey() const { return searchKey_; } void GetOcListedCompanyRequest::setSearchKey(const std::string &searchKey) { searchKey_ = searchKey; setBodyParameter(std::string("SearchKey"), searchKey); }
[ "sdk-team@alibabacloud.com" ]
sdk-team@alibabacloud.com
166ab75002b34edb0d2b05cd0bea89882b80bcfe
cde9dc97b0fc3df945e2500a4b21deb9caf994cf
/ilwiscore/source/geos/include/geos/geom/GeometryCollection.inl
4f08103cf967096ded06e30327107715f9e66b2f
[]
no_license
MartinSchouwenburg/ilwisobjects
7bbe06a9c097472dea0496522465f59701782351
ad59176c1eb79d56089abc009ea1622958d78fe4
refs/heads/main
2023-05-10T13:46:05.864706
2021-06-14T08:56:55
2021-06-14T08:56:55
373,075,845
0
0
null
null
null
null
UTF-8
C++
false
false
1,151
inl
/********************************************************************** * * GEOS - Geometry Engine Open Source * http://geos.osgeo.org * * Copyright (C) 2006 Refractions Research Inc. * * This is free software; you can redistribute and/or modify it under * the terms of the GNU Lesser General Public Licence as published * by the Free Software Foundation. * See the COPYING file for more information. * ********************************************************************** * * Last port: geom/GeometryCollection.java rev. 1.41 * **********************************************************************/ #ifndef GEOS_GEOMETRYCOLLECTION_INL #define GEOS_GEOMETRYCOLLECTION_INL #include <geos/geom/GeometryCollection.h> #include <vector> namespace geos { namespace geom { // geos::geom INLINE GeometryCollection::const_iterator GeometryCollection::begin() const { return geometries->begin(); } INLINE GeometryCollection::const_iterator GeometryCollection::end() const { return geometries->end(); } } // namespace geos::geom } // namespace geos #endif // GEOS_GEOMETRYCOLLECTION_INL
[ "m.l.schouwenburg@utwente.nl" ]
m.l.schouwenburg@utwente.nl
35df8616b33bfd39c9caefe73c77b913c68b71ce
cbad8d2d2ce87a15d82dd2a2463c9ceb9b7b910a
/Secur32Wrapper/KerberosException.h
ad224550edff28eb655bb18f4712b40b311c88c9
[ "MIT" ]
permissive
webstorage119/KerberosSkeleton
0c82d54fb898fa4a0200bbca57546d19b117d6da
058334719d0599ff768fcf64e5302cc2ffc91c0a
refs/heads/master
2022-04-07T15:21:15.936619
2019-12-17T13:28:41
2019-12-17T13:28:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,190
h
#pragma once #include <exception> #include <string> namespace KerbException { class KerberosException : public std::exception { public: enum ErrorType { NOT_IMPLEMENTED, FAILED_LSACONNECTUNTRUSTED, FAILED_LSALOOKUPAUTHENTICATIONPACKAGE, FAILED_LSACALLAUTHENTICATIONPACKAGE, FAILED_LSALOGONUSER, FAILED_LOADINDSECUR32, FAILED_LOADINDSECUR32FUNCTIONS, INVALID_PROTOCOLSTATUS, INVALID_RETURNBUFFER, INVALID_SPN_DATA, INVALID_SECUR32WRAPPER_INSATNCE }; explicit KerberosException(ErrorType errorType, const std::string &s) : m_errorType(errorType), m_what(s) {} virtual ~KerberosException() throw() {} const char *what() const throw() { return (m_what.c_str()); } const std::string &GetWhat() const { return m_what; } void SetWhat(const std::string &s) { m_what = s; } ErrorType GetErrorType() const { return m_errorType; } void SetErrorType(ErrorType errorType) { m_errorType = errorType; } private: ErrorType m_errorType; std::string m_what; }; }
[ "danchuk47@gmail.com" ]
danchuk47@gmail.com
9ea0010f72a3cae2a77cb5b079e22d10594adfd0
9808a681923e717fc36bba6c46f90820f7b12815
/src/h/SpielBrett.h
47680c25463697f52eaebb3d95c05ff0c9e8d7ec
[]
no_license
grany/distanz
e7e327991e9a2ab0e10ff6c595b95407ef0614d9
7542be38be7992ecef32cd05da58b0b4bf4f15a1
refs/heads/master
2021-01-20T12:06:32.357295
2017-01-20T19:03:40
2017-01-20T19:03:40
34,206,388
0
0
null
null
null
null
ISO-8859-1
C++
false
false
1,679
h
#ifndef SPIELBRETT_H #define SPIELBRETT_H /** * class SpielBrett * Das Spielfeld besteht aus einem 8x8 großen Feld. Jedes der 64 Felder besitzt eine eigene ID, welche bei Bewegungen und oder Besetzung abgefragt wird. Mithilfe von Pointern werden die Spielfiguren, je nach Spielzug, auf die Felder verwiesen. Die 2 Teams (Schwarz & Weiß) stehen sich auf dem Spielfeld gegenüber. Damit sind, egal zu welchem Zeitpunkt des Spielverlaufs, immer insgesamt 8 Figuren und damit 4 pro Team auf dem Feld. */ #include "Feld.h" #include "Team.h" class Team; class SpielBrett { private: static const short int dimmension = 8; //Dimension Feld** Brett=nullptr; Team *schwarz=nullptr, *weis=nullptr; //weiß void initBrett(); /** initBrett() * Erzeugt das 8x8 großes Feld. * */ public: SpielBrett (); /** SpielBrett() * Beinhaltet die Startaufstellung. * */ SpielBrett (const SpielBrett &sb); /** SpielBrett (const SpielBrett &sb) * Verweißt auf die Pointer, der einzelnen Spielsteine. * */ ~SpielBrett ( ); /** ~SpielBrett * Destruktor des Spiels * */ Team* getWeis() const; //Weiß (Wenn erforderlich auf Groß/-Kleinschreibung achten von Initialisierungen) /** getWeis() * Kennzeichnet die weißen Steine. * * @return weiß */ Team* getSchwarz() const; /**getSchwarz() * Kennzeichnet die schwarzen Steine. * * @return schwarz */ Feld* getFeld(int x, int y) const; /** getFeld(int x, int y) * verhindert, falsche Angaben der Positionen. * *@param [int] x, y Koordinaten des Feldes *@return nullptr */ }; #endif // SPIELBRETT_H
[ "toxxxsys@gmail.com" ]
toxxxsys@gmail.com
5792fa6b73d763bada2e2f43642e8eee4461bd53
30bdd8ab897e056f0fb2f9937dcf2f608c1fd06a
/scrape/data/Tokitsukaze and Discard Items/Lumos_Maxima_A.cpp
41a7a8204aa2ef6c7ef456f409fe3630896d3565
[]
no_license
thegamer1907/Code_Analysis
0a2bb97a9fb5faf01d983c223d9715eb419b7519
48079e399321b585efc8a2c6a84c25e2e7a22a61
refs/heads/master
2020-05-27T01:20:55.921937
2019-11-20T11:15:11
2019-11-20T11:15:11
188,403,594
2
1
null
null
null
null
UTF-8
C++
false
false
2,752
cpp
/*----------------by syr----------------*/ /* iii ii rBQBBBBBBE BBR iBBBBQBBL XBBBBBBQBBBBB iBBQJ 7BBB BBsSBBr BBQ i cBBB rBBU iBBw BBBQi HBBi KBBi BBH BB5 iBBB isL wBB5 GBB iBBi 6BB iBBB BBQ BQB BBD QBBi BBB BQB iQBi 1BBv sBBg wBBB QBB iBBB 7BBBBBBBBBi BBR wBBBBBBBBBBBBB irvi ii ii i i iii i5U BBB BB7 1BB iPBBBBBKBBR JBR1 rQBO BR UBQP iBBQi 7BBBGs7sXBBBi QBBr gBBE rBB BB2BB7HBZQBB QBBi sBQ BBB iBBB SQBBR BBBB cBQ gBQ BBg BBB KBBi MBBH BBB BBs iBBv iBBi QBBBL BBR pBB iBB pBB BBB iBBBB iBB BBL KBB MBB BBBR BBB JBBi DBR iBQ BBL GBB 7BBBB2 PBBH BBBi BQr DBB iBB BQBXwgBBP BB7 1BBB BBQ7 1BB BBc BBB 2BBBBw BB EBBS QBBi HBa iBB BB7 */ #include<bits/stdc++.h> using namespace std; #define PH push #define MP make_pair #define PB push_back #define fst first #define snd second #define FOR(i, x, y) for(int i = (x); i < (y); ++i) #define REP(i, x, y) for(int i = (x); i <= (y); ++i) #define x0 x0123456789 #define y0 y0123456789 #define x1 x1234567890 #define y1 y1234567890 #define x2 x2345678901 #define y2 y2345678901 typedef double db; typedef long long ll; typedef long double ldb; typedef unsigned long long ull; typedef pair<int, int> pii; typedef pair<ll, ll> pll; const int INF = 1e9 + 7; const int maxn = 1e5 + 5; int ans; ll n, m, k; ll a[maxn]; set<ll> s; int count(ll curl, ll curr){ int ret = 0; for(set<ll>::iterator it = s.begin(); it != s.end() && (*it) >= curl && (*it) <= curr; ++ret, ++it); return ret; } void erase(ll curl, ll curr){ for(; s.size() && (*s.begin()) >= curl && (*s.begin()) <= curr; s.erase(s.begin())); return; } int main(){ scanf("%lld%lld%lld", &n, &m, &k); FOR(i, 0, m) scanf("%lld", a + i), s.insert(a[i]); ll curl = 1, curr = k; while(s.size()){ int res = count(curl, curr); //printf("%lld %lld %d\n", curl, curr, res); if(res > 0){ ++ans; erase(curl, curr); curr += res; } else{ ll fir = *s.begin(); ll cnt = (fir - curr) / k; //printf("cnt = %lld\n", cnt); curl += (cnt + 1) * k; curr += (cnt + 1) * k; if(curr - k >= fir){ curr -= k; curl -= k; } } } printf("%d\n", ans); return 0; }
[ "harshitagar1907@gmail.com" ]
harshitagar1907@gmail.com
7b430ac269e1634631bbfab75adeaf444ae28160
002c86ddefed192b460266c80f3e38fce41916c1
/modules/arm_plugin/src/transformations/convert_interpolate_v0_to_v4.cpp
a52d003985899d2b5740af2199fa8b4c49cb61d1
[ "Apache-2.0" ]
permissive
dhruvsheth-ai/openvino_contrib
c244ebeadc22321f10167fe3472c8139a087ef87
7cdf572d26c7ac8bbfa33c6db7691cce54c1380f
refs/heads/master
2023-03-01T18:50:20.563337
2021-02-13T06:11:34
2021-02-13T06:11:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,883
cpp
//***************************************************************************** // Copyright (C) 2020-2021 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. //***************************************************************************** #include "transformations/convert_interpolate_v0_to_v4.hpp" #include "ngraph/op/interpolate.hpp" #include "ngraph/op/constant.hpp" #include "ngraph/rt_info.hpp" using namespace std; using namespace ArmPlugin; pass::ConvertInterpolateV0toV4::ConvertInterpolateV0toV4() { register_matcher( std::make_shared<ngraph::pattern::Matcher>( std::make_shared<ngraph::op::v0::Interpolate>( ngraph::pattern::any_input(), ngraph::pattern::any_input(), ngraph::op::v0::InterpolateAttrs{}), "ConvertInterpolateV0toV4"), [](ngraph::pattern::Matcher& m) { auto interpolationV0 = std::dynamic_pointer_cast<ngraph::op::v0::Interpolate>(m.get_match_root()); if (!interpolationV0) { return false; } auto& inp_shape = interpolationV0->get_input_shape(0); auto& out_shape = interpolationV0->get_output_shape(0); auto attrsV0 = interpolationV0->get_attrs(); std::vector<float> scales; for (std::size_t i = 0; i < inp_shape.size(); ++i) { scales.emplace_back(static_cast<float>(inp_shape.at(i))/out_shape.at(i)); } auto scalesConstant = ngraph::op::Constant::create( ngraph::element::f32, {scales.size()}, scales); auto axisConstant = ngraph::op::Constant::create( ngraph::element::i64, {attrsV0.axes.size()}, std::vector<std::size_t>{attrsV0.axes.begin(), attrsV0.axes.end()}); ngraph::op::v4::Interpolate::InterpolateAttrs attrsV4; if (attrsV0.mode == "nearest") { attrsV4.mode = ngraph::op::v4::Interpolate::InterpolateMode::nearest; } else if (attrsV0.mode == "linear") { attrsV4.mode = ngraph::op::v4::Interpolate::InterpolateMode::linear; } else if (attrsV0.mode == "cubic") { attrsV4.mode = ngraph::op::v4::Interpolate::InterpolateMode::cubic; } else if (attrsV0.mode == "linear_onnx") { attrsV4.mode = ngraph::op::v4::Interpolate::InterpolateMode::linear_onnx; } else { return false; } attrsV4.shape_calculation_mode = ngraph::op::v4::Interpolate::ShapeCalcMode::sizes; attrsV4.pads_begin = attrsV0.pads_begin; attrsV4.pads_end = attrsV0.pads_end; if (attrsV0.align_corners) { attrsV4.coordinate_transformation_mode = ngraph::op::v4::Interpolate::CoordinateTransformMode::align_corners; } auto interpolateV4 = std::make_shared<ngraph::op::v4::Interpolate>( interpolationV0->input_value(0), interpolationV0->input_value(1), scalesConstant, axisConstant, attrsV4); interpolateV4->set_friendly_name(interpolationV0->get_friendly_name() + ".V4"); ngraph::copy_runtime_info(interpolationV0, interpolateV4); ngraph::replace_node(interpolationV0, interpolateV4); return true; }); }
[ "noreply@github.com" ]
noreply@github.com
8851ea57c0de767416b135218fe395ef77ab15c8
cf3ef2cb7cbce88fb28b184d05f1286a17c6a09a
/ns-3.19/src/internet/model/icmpv4.cc
a78f7e8ce735ecb9e0ab18cfcc61f3b8361b362a
[]
no_license
G8XSU/ns3-pmipv6
4d318e39a799e2cfa8f8b8948972494d0d4ad559
cde2da6d2476eaa5ed49580494e2788f62ddb71e
refs/heads/master
2016-09-05T18:13:23.367968
2014-05-06T12:56:14
2014-05-06T12:56:14
19,178,140
6
6
null
null
null
null
UTF-8
C++
false
false
11,089
cc
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2008 INRIA * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Mathieu Lacage <mathieu.lacage@sophia.inria.fr> */ #include "icmpv4.h" #include "ns3/packet.h" #include "ns3/log.h" NS_LOG_COMPONENT_DEFINE ("Icmpv4Header"); namespace ns3 { /******************************************************** * Icmpv4Header ********************************************************/ NS_OBJECT_ENSURE_REGISTERED (Icmpv4Header) ; TypeId Icmpv4Header::GetTypeId (void) { static TypeId tid = TypeId ("ns3::Icmpv4Header") .SetParent<Header> () .AddConstructor<Icmpv4Header> () ; return tid; } Icmpv4Header::Icmpv4Header () : m_type (0), m_code (0), m_calcChecksum (false) { NS_LOG_FUNCTION (this); } Icmpv4Header::~Icmpv4Header () { NS_LOG_FUNCTION (this); } void Icmpv4Header::EnableChecksum (void) { NS_LOG_FUNCTION (this); m_calcChecksum = true; } TypeId Icmpv4Header::GetInstanceTypeId (void) const { NS_LOG_FUNCTION (this); return GetTypeId (); } uint32_t Icmpv4Header::GetSerializedSize (void) const { NS_LOG_FUNCTION (this); return 4; } void Icmpv4Header::Serialize (Buffer::Iterator start) const { NS_LOG_FUNCTION (this << &start); Buffer::Iterator i = start; i.WriteU8 (m_type); i.WriteU8 (m_code); i.WriteHtonU16 (0); if (m_calcChecksum) { i = start; uint16_t checksum = i.CalculateIpChecksum (i.GetSize ()); i = start; i.Next (2); i.WriteU16 (checksum); } } uint32_t Icmpv4Header::Deserialize (Buffer::Iterator start) { NS_LOG_FUNCTION (this << &start); m_type = start.ReadU8 (); m_code = start.ReadU8 (); start.Next (2); // uint16_t checksum = start.ReadNtohU16 (); return 4; } void Icmpv4Header::Print (std::ostream &os) const { NS_LOG_FUNCTION (this << &os); os << "type=" << (uint32_t)m_type << ", code=" << (uint32_t)m_code; } void Icmpv4Header::SetType (uint8_t type) { NS_LOG_FUNCTION (this << static_cast<uint32_t> (type)); m_type = type; } void Icmpv4Header::SetCode (uint8_t code) { NS_LOG_FUNCTION (this << static_cast<uint32_t> (code)); m_code = code; } uint8_t Icmpv4Header::GetType (void) const { NS_LOG_FUNCTION (this); return m_type; } uint8_t Icmpv4Header::GetCode (void) const { NS_LOG_FUNCTION (this); return m_code; } /******************************************************** * Icmpv4Echo ********************************************************/ NS_OBJECT_ENSURE_REGISTERED (Icmpv4Echo) ; void Icmpv4Echo::SetIdentifier (uint16_t id) { NS_LOG_FUNCTION (this << id); m_identifier = id; } void Icmpv4Echo::SetSequenceNumber (uint16_t seq) { NS_LOG_FUNCTION (this << seq); m_sequence = seq; } void Icmpv4Echo::SetData (Ptr<const Packet> data) { NS_LOG_FUNCTION (this << *data); uint32_t size = data->GetSize (); // // All kinds of optimizations are possible, but let's not get carried away // since this is probably a very uncommon thing in the big picture. // // N.B. Zero is a legal size for the alloc below even though a hardcoded zero // would result in warning. // if (size != m_dataSize) { delete [] m_data; m_data = new uint8_t[size]; m_dataSize = size; } data->CopyData (m_data, size); } uint16_t Icmpv4Echo::GetIdentifier (void) const { NS_LOG_FUNCTION (this); return m_identifier; } uint16_t Icmpv4Echo::GetSequenceNumber (void) const { NS_LOG_FUNCTION (this); return m_sequence; } uint32_t Icmpv4Echo::GetDataSize (void) const { NS_LOG_FUNCTION (this); return m_dataSize; } uint32_t Icmpv4Echo::GetData (uint8_t payload[]) const { NS_LOG_FUNCTION (this << payload); memcpy (payload, m_data, m_dataSize); return m_dataSize; } TypeId Icmpv4Echo::GetTypeId (void) { static TypeId tid = TypeId ("ns3::Icmpv4Echo") .SetParent<Header> () .AddConstructor<Icmpv4Echo> () ; return tid; } Icmpv4Echo::Icmpv4Echo () : m_identifier (0), m_sequence (0), m_dataSize (0) { NS_LOG_FUNCTION (this); // // After construction, m_data is always valid until destruction. This is true // even if m_dataSize is zero. // m_data = new uint8_t[m_dataSize]; } Icmpv4Echo::~Icmpv4Echo () { NS_LOG_FUNCTION (this); delete [] m_data; m_data = 0; m_dataSize = 0; } TypeId Icmpv4Echo::GetInstanceTypeId (void) const { NS_LOG_FUNCTION (this); return GetTypeId (); } uint32_t Icmpv4Echo::GetSerializedSize (void) const { NS_LOG_FUNCTION (this); return 4 + m_dataSize; } void Icmpv4Echo::Serialize (Buffer::Iterator start) const { NS_LOG_FUNCTION (this << &start); start.WriteHtonU16 (m_identifier); start.WriteHtonU16 (m_sequence); start.Write (m_data, m_dataSize); } uint32_t Icmpv4Echo::Deserialize (Buffer::Iterator start) { NS_LOG_FUNCTION (this << &start); m_identifier = start.ReadNtohU16 (); m_sequence = start.ReadNtohU16 (); NS_ASSERT (start.GetSize () >= 4); uint32_t size = start.GetSize () - 4; if (size != m_dataSize) { delete [] m_data; m_data = new uint8_t[size]; m_dataSize = size; } start.Read (m_data, m_dataSize); return m_dataSize; } void Icmpv4Echo::Print (std::ostream &os) const { NS_LOG_FUNCTION (this << &os); os << "identifier=" << m_identifier << ", sequence=" << m_sequence; } /******************************************************** * Icmpv4DestinationUnreachable ********************************************************/ NS_OBJECT_ENSURE_REGISTERED (Icmpv4DestinationUnreachable) ; TypeId Icmpv4DestinationUnreachable::GetTypeId (void) { static TypeId tid = TypeId ("ns3::Icmpv4DestinationUnreachable") .SetParent<Header> () .AddConstructor<Icmpv4DestinationUnreachable> () ; return tid; } Icmpv4DestinationUnreachable::Icmpv4DestinationUnreachable () { NS_LOG_FUNCTION (this); // make sure that thing is initialized to get initialized bytes // when the ip payload's size is smaller than 8 bytes. for (uint8_t j = 0; j < 8; j++) { m_data[j] = 0; } } void Icmpv4DestinationUnreachable::SetNextHopMtu (uint16_t mtu) { NS_LOG_FUNCTION (this << mtu); m_nextHopMtu = mtu; } uint16_t Icmpv4DestinationUnreachable::GetNextHopMtu (void) const { NS_LOG_FUNCTION (this); return m_nextHopMtu; } void Icmpv4DestinationUnreachable::SetData (Ptr<const Packet> data) { NS_LOG_FUNCTION (this << *data); data->CopyData (m_data, 8); } void Icmpv4DestinationUnreachable::SetHeader (Ipv4Header header) { NS_LOG_FUNCTION (this << header); m_header = header; } void Icmpv4DestinationUnreachable::GetData (uint8_t payload[8]) const { NS_LOG_FUNCTION (this << payload); memcpy (payload, m_data, 8); } Ipv4Header Icmpv4DestinationUnreachable::GetHeader (void) const { NS_LOG_FUNCTION (this); return m_header; } Icmpv4DestinationUnreachable::~Icmpv4DestinationUnreachable () { } TypeId Icmpv4DestinationUnreachable::GetInstanceTypeId (void) const { NS_LOG_FUNCTION (this); return GetTypeId (); } uint32_t Icmpv4DestinationUnreachable::GetSerializedSize (void) const { NS_LOG_FUNCTION (this); return 4 + m_header.GetSerializedSize () + 8; } void Icmpv4DestinationUnreachable::Serialize (Buffer::Iterator start) const { NS_LOG_FUNCTION (this << &start); start.WriteU16 (0); start.WriteHtonU16 (m_nextHopMtu); uint32_t size = m_header.GetSerializedSize (); m_header.Serialize (start); start.Next (size); start.Write (m_data, 8); } uint32_t Icmpv4DestinationUnreachable::Deserialize (Buffer::Iterator start) { NS_LOG_FUNCTION (this << &start); Buffer::Iterator i = start; i.Next (2); m_nextHopMtu = i.ReadNtohU16 (); uint32_t read = m_header.Deserialize (i); i.Next (read); for (uint8_t j = 0; j < 8; j++) { m_data[j] = i.ReadU8 (); } return i.GetDistanceFrom (start); } void Icmpv4DestinationUnreachable::Print (std::ostream &os) const { NS_LOG_FUNCTION (this << &os); m_header.Print (os); os << " org data="; for (uint8_t i = 0; i < 8; i++) { os << (uint32_t) m_data[i]; if (i != 8) { os << " "; } } } /******************************************************** * Icmpv4TimeExceeded ********************************************************/ NS_OBJECT_ENSURE_REGISTERED (Icmpv4TimeExceeded) ; TypeId Icmpv4TimeExceeded::GetTypeId (void) { static TypeId tid = TypeId ("ns3::Icmpv4TimeExceeded") .SetParent<Header> () .AddConstructor<Icmpv4TimeExceeded> () ; return tid; } Icmpv4TimeExceeded::Icmpv4TimeExceeded () { NS_LOG_FUNCTION (this); // make sure that thing is initialized to get initialized bytes // when the ip payload's size is smaller than 8 bytes. for (uint8_t j = 0; j < 8; j++) { m_data[j] = 0; } } void Icmpv4TimeExceeded::SetData (Ptr<const Packet> data) { NS_LOG_FUNCTION (this << *data); data->CopyData (m_data, 8); } void Icmpv4TimeExceeded::SetHeader (Ipv4Header header) { NS_LOG_FUNCTION (this << header); m_header = header; } void Icmpv4TimeExceeded::GetData (uint8_t payload[8]) const { NS_LOG_FUNCTION (this << payload); memcpy (payload, m_data, 8); } Ipv4Header Icmpv4TimeExceeded::GetHeader (void) const { NS_LOG_FUNCTION (this); return m_header; } Icmpv4TimeExceeded::~Icmpv4TimeExceeded () { NS_LOG_FUNCTION (this); } TypeId Icmpv4TimeExceeded::GetInstanceTypeId (void) const { NS_LOG_FUNCTION (this); return GetTypeId (); } uint32_t Icmpv4TimeExceeded::GetSerializedSize (void) const { NS_LOG_FUNCTION (this); return 4 + m_header.GetSerializedSize () + 8; } void Icmpv4TimeExceeded::Serialize (Buffer::Iterator start) const { NS_LOG_FUNCTION (this << &start); start.WriteU32 (0); uint32_t size = m_header.GetSerializedSize (); m_header.Serialize (start); start.Next (size); start.Write (m_data, 8); } uint32_t Icmpv4TimeExceeded::Deserialize (Buffer::Iterator start) { NS_LOG_FUNCTION (this << &start); Buffer::Iterator i = start; i.Next (4); uint32_t read = m_header.Deserialize (i); i.Next (read); for (uint8_t j = 0; j < 8; j++) { m_data[j] = i.ReadU8 (); } return i.GetDistanceFrom (start); } void Icmpv4TimeExceeded::Print (std::ostream &os) const { NS_LOG_FUNCTION (this << &os); m_header.Print (os); os << " org data="; for (uint8_t i = 0; i < 8; i++) { os << (uint32_t) m_data[i]; if (i != 8) { os << " "; } } } } // namespace ns3
[ "g8x000@gmail.com" ]
g8x000@gmail.com
0bf4ce17f1cd6310ee32b7cc866e8c681b773529
78918391a7809832dc486f68b90455c72e95cdda
/boost_lib/boost/function_types/detail/synthesize_impl/arity30_1.hpp
fa5c8ac2ee34871a44a56aa8ed906cec65b39835
[ "BSL-1.0", "MIT" ]
permissive
kyx0r/FA_Patcher
50681e3e8bb04745bba44a71b5fd04e1004c3845
3f539686955249004b4483001a9e49e63c4856ff
refs/heads/master
2022-03-28T10:03:28.419352
2020-01-02T09:16:30
2020-01-02T09:16:30
141,066,396
2
0
null
null
null
null
UTF-8
C++
false
false
36,050
hpp
// (C) Copyright Tobias Schwinger // // Use modification and distribution are subject to the boost Software License, // Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt). //------------------------------------------------------------------------------ // no include guards, this file is intended for multiple inclusion // input: BOOST_FT_syntax type macro to use // input: BOOST_FT_cc empty or cc specifier // input: BOOST_FT_ell empty or "..." // input: BOOST_FT_cv empty or cv qualifiers // input: BOOST_FT_flags single decimal integer encoding the flags // output: BOOST_FT_n number of component types (arity+1) // output: BOOST_FT_arity current arity // output: BOOST_FT_type macro that expands to the type // output: BOOST_FT_tplargs(p) template arguments with given prefix // output: BOOST_FT_params(p) parameters with given prefix # include <boost/function_types/detail/synthesize_impl/arity20_1.hpp> # define BOOST_FT_make_type(flags,cc,arity) BOOST_FT_make_type_impl(flags,cc,arity) # define BOOST_FT_make_type_impl(flags,cc,arity) make_type_ ## flags ## _ ## cc ## _ ## arity template< typename R, typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20 > struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,21) { typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20 BOOST_FT_ell) BOOST_FT_cv ; }; template< > struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 22 > { template<typename S> struct synthesize_impl_i { private: typedef typename mpl::begin<S> ::type iter_0; typedef typename mpl::next< iter_0 > ::type iter_1; typedef typename mpl::next< iter_1 > ::type iter_2; typedef typename mpl::next< iter_2 > ::type iter_3; typedef typename mpl::next< iter_3 > ::type iter_4; typedef typename mpl::next< iter_4 > ::type iter_5; typedef typename mpl::next< iter_5 > ::type iter_6; typedef typename mpl::next< iter_6 > ::type iter_7; typedef typename mpl::next< iter_7 > ::type iter_8; typedef typename mpl::next< iter_8 > ::type iter_9; typedef typename mpl::next< iter_9 > ::type iter_10; typedef typename mpl::next< iter_10 > ::type iter_11; typedef typename mpl::next< iter_11 > ::type iter_12; typedef typename mpl::next< iter_12 > ::type iter_13; typedef typename mpl::next< iter_13 > ::type iter_14; typedef typename mpl::next< iter_14 > ::type iter_15; typedef typename mpl::next< iter_15 > ::type iter_16; typedef typename mpl::next< iter_16 > ::type iter_17; typedef typename mpl::next< iter_17 > ::type iter_18; typedef typename mpl::next< iter_18 > ::type iter_19; typedef typename mpl::next< iter_19 > ::type iter_20; typedef typename mpl::next< iter_20 > ::type iter_21; public: typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,21) < typename mpl::deref< iter_0 > ::type , typename detail::cv_traits< typename mpl::deref< iter_1 > ::type > ::type , typename mpl::deref< iter_2 > ::type , typename mpl::deref< iter_3 > ::type , typename mpl::deref< iter_4 > ::type , typename mpl::deref< iter_5 > ::type , typename mpl::deref< iter_6 > ::type , typename mpl::deref< iter_7 > ::type , typename mpl::deref< iter_8 > ::type , typename mpl::deref< iter_9 > ::type , typename mpl::deref< iter_10 > ::type , typename mpl::deref< iter_11 > ::type , typename mpl::deref< iter_12 > ::type , typename mpl::deref< iter_13 > ::type , typename mpl::deref< iter_14 > ::type , typename mpl::deref< iter_15 > ::type , typename mpl::deref< iter_16 > ::type , typename mpl::deref< iter_17 > ::type , typename mpl::deref< iter_18 > ::type , typename mpl::deref< iter_19 > ::type , typename mpl::deref< iter_20 > ::type , typename mpl::deref< iter_21 > ::type > ::type type; }; }; template< typename R, typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21 > struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,22) { typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21 BOOST_FT_ell) BOOST_FT_cv ; }; template< > struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 23 > { template<typename S> struct synthesize_impl_i { private: typedef typename mpl::begin<S> ::type iter_0; typedef typename mpl::next< iter_0 > ::type iter_1; typedef typename mpl::next< iter_1 > ::type iter_2; typedef typename mpl::next< iter_2 > ::type iter_3; typedef typename mpl::next< iter_3 > ::type iter_4; typedef typename mpl::next< iter_4 > ::type iter_5; typedef typename mpl::next< iter_5 > ::type iter_6; typedef typename mpl::next< iter_6 > ::type iter_7; typedef typename mpl::next< iter_7 > ::type iter_8; typedef typename mpl::next< iter_8 > ::type iter_9; typedef typename mpl::next< iter_9 > ::type iter_10; typedef typename mpl::next< iter_10 > ::type iter_11; typedef typename mpl::next< iter_11 > ::type iter_12; typedef typename mpl::next< iter_12 > ::type iter_13; typedef typename mpl::next< iter_13 > ::type iter_14; typedef typename mpl::next< iter_14 > ::type iter_15; typedef typename mpl::next< iter_15 > ::type iter_16; typedef typename mpl::next< iter_16 > ::type iter_17; typedef typename mpl::next< iter_17 > ::type iter_18; typedef typename mpl::next< iter_18 > ::type iter_19; typedef typename mpl::next< iter_19 > ::type iter_20; typedef typename mpl::next< iter_20 > ::type iter_21; typedef typename mpl::next< iter_21 > ::type iter_22; public: typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,22) < typename mpl::deref< iter_0 > ::type , typename detail::cv_traits< typename mpl::deref< iter_1 > ::type > ::type , typename mpl::deref< iter_2 > ::type , typename mpl::deref< iter_3 > ::type , typename mpl::deref< iter_4 > ::type , typename mpl::deref< iter_5 > ::type , typename mpl::deref< iter_6 > ::type , typename mpl::deref< iter_7 > ::type , typename mpl::deref< iter_8 > ::type , typename mpl::deref< iter_9 > ::type , typename mpl::deref< iter_10 > ::type , typename mpl::deref< iter_11 > ::type , typename mpl::deref< iter_12 > ::type , typename mpl::deref< iter_13 > ::type , typename mpl::deref< iter_14 > ::type , typename mpl::deref< iter_15 > ::type , typename mpl::deref< iter_16 > ::type , typename mpl::deref< iter_17 > ::type , typename mpl::deref< iter_18 > ::type , typename mpl::deref< iter_19 > ::type , typename mpl::deref< iter_20 > ::type , typename mpl::deref< iter_21 > ::type , typename mpl::deref< iter_22 > ::type > ::type type; }; }; template< typename R, typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22 > struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,23) { typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22 BOOST_FT_ell) BOOST_FT_cv ; }; template< > struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 24 > { template<typename S> struct synthesize_impl_i { private: typedef typename mpl::begin<S> ::type iter_0; typedef typename mpl::next< iter_0 > ::type iter_1; typedef typename mpl::next< iter_1 > ::type iter_2; typedef typename mpl::next< iter_2 > ::type iter_3; typedef typename mpl::next< iter_3 > ::type iter_4; typedef typename mpl::next< iter_4 > ::type iter_5; typedef typename mpl::next< iter_5 > ::type iter_6; typedef typename mpl::next< iter_6 > ::type iter_7; typedef typename mpl::next< iter_7 > ::type iter_8; typedef typename mpl::next< iter_8 > ::type iter_9; typedef typename mpl::next< iter_9 > ::type iter_10; typedef typename mpl::next< iter_10 > ::type iter_11; typedef typename mpl::next< iter_11 > ::type iter_12; typedef typename mpl::next< iter_12 > ::type iter_13; typedef typename mpl::next< iter_13 > ::type iter_14; typedef typename mpl::next< iter_14 > ::type iter_15; typedef typename mpl::next< iter_15 > ::type iter_16; typedef typename mpl::next< iter_16 > ::type iter_17; typedef typename mpl::next< iter_17 > ::type iter_18; typedef typename mpl::next< iter_18 > ::type iter_19; typedef typename mpl::next< iter_19 > ::type iter_20; typedef typename mpl::next< iter_20 > ::type iter_21; typedef typename mpl::next< iter_21 > ::type iter_22; typedef typename mpl::next< iter_22 > ::type iter_23; public: typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,23) < typename mpl::deref< iter_0 > ::type , typename detail::cv_traits< typename mpl::deref< iter_1 > ::type > ::type , typename mpl::deref< iter_2 > ::type , typename mpl::deref< iter_3 > ::type , typename mpl::deref< iter_4 > ::type , typename mpl::deref< iter_5 > ::type , typename mpl::deref< iter_6 > ::type , typename mpl::deref< iter_7 > ::type , typename mpl::deref< iter_8 > ::type , typename mpl::deref< iter_9 > ::type , typename mpl::deref< iter_10 > ::type , typename mpl::deref< iter_11 > ::type , typename mpl::deref< iter_12 > ::type , typename mpl::deref< iter_13 > ::type , typename mpl::deref< iter_14 > ::type , typename mpl::deref< iter_15 > ::type , typename mpl::deref< iter_16 > ::type , typename mpl::deref< iter_17 > ::type , typename mpl::deref< iter_18 > ::type , typename mpl::deref< iter_19 > ::type , typename mpl::deref< iter_20 > ::type , typename mpl::deref< iter_21 > ::type , typename mpl::deref< iter_22 > ::type , typename mpl::deref< iter_23 > ::type > ::type type; }; }; template< typename R, typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23 > struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,24) { typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23 BOOST_FT_ell) BOOST_FT_cv ; }; template< > struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 25 > { template<typename S> struct synthesize_impl_i { private: typedef typename mpl::begin<S> ::type iter_0; typedef typename mpl::next< iter_0 > ::type iter_1; typedef typename mpl::next< iter_1 > ::type iter_2; typedef typename mpl::next< iter_2 > ::type iter_3; typedef typename mpl::next< iter_3 > ::type iter_4; typedef typename mpl::next< iter_4 > ::type iter_5; typedef typename mpl::next< iter_5 > ::type iter_6; typedef typename mpl::next< iter_6 > ::type iter_7; typedef typename mpl::next< iter_7 > ::type iter_8; typedef typename mpl::next< iter_8 > ::type iter_9; typedef typename mpl::next< iter_9 > ::type iter_10; typedef typename mpl::next< iter_10 > ::type iter_11; typedef typename mpl::next< iter_11 > ::type iter_12; typedef typename mpl::next< iter_12 > ::type iter_13; typedef typename mpl::next< iter_13 > ::type iter_14; typedef typename mpl::next< iter_14 > ::type iter_15; typedef typename mpl::next< iter_15 > ::type iter_16; typedef typename mpl::next< iter_16 > ::type iter_17; typedef typename mpl::next< iter_17 > ::type iter_18; typedef typename mpl::next< iter_18 > ::type iter_19; typedef typename mpl::next< iter_19 > ::type iter_20; typedef typename mpl::next< iter_20 > ::type iter_21; typedef typename mpl::next< iter_21 > ::type iter_22; typedef typename mpl::next< iter_22 > ::type iter_23; typedef typename mpl::next< iter_23 > ::type iter_24; public: typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,24) < typename mpl::deref< iter_0 > ::type , typename detail::cv_traits< typename mpl::deref< iter_1 > ::type > ::type , typename mpl::deref< iter_2 > ::type , typename mpl::deref< iter_3 > ::type , typename mpl::deref< iter_4 > ::type , typename mpl::deref< iter_5 > ::type , typename mpl::deref< iter_6 > ::type , typename mpl::deref< iter_7 > ::type , typename mpl::deref< iter_8 > ::type , typename mpl::deref< iter_9 > ::type , typename mpl::deref< iter_10 > ::type , typename mpl::deref< iter_11 > ::type , typename mpl::deref< iter_12 > ::type , typename mpl::deref< iter_13 > ::type , typename mpl::deref< iter_14 > ::type , typename mpl::deref< iter_15 > ::type , typename mpl::deref< iter_16 > ::type , typename mpl::deref< iter_17 > ::type , typename mpl::deref< iter_18 > ::type , typename mpl::deref< iter_19 > ::type , typename mpl::deref< iter_20 > ::type , typename mpl::deref< iter_21 > ::type , typename mpl::deref< iter_22 > ::type , typename mpl::deref< iter_23 > ::type , typename mpl::deref< iter_24 > ::type > ::type type; }; }; template< typename R, typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24 > struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,25) { typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24 BOOST_FT_ell) BOOST_FT_cv ; }; template< > struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 26 > { template<typename S> struct synthesize_impl_i { private: typedef typename mpl::begin<S> ::type iter_0; typedef typename mpl::next< iter_0 > ::type iter_1; typedef typename mpl::next< iter_1 > ::type iter_2; typedef typename mpl::next< iter_2 > ::type iter_3; typedef typename mpl::next< iter_3 > ::type iter_4; typedef typename mpl::next< iter_4 > ::type iter_5; typedef typename mpl::next< iter_5 > ::type iter_6; typedef typename mpl::next< iter_6 > ::type iter_7; typedef typename mpl::next< iter_7 > ::type iter_8; typedef typename mpl::next< iter_8 > ::type iter_9; typedef typename mpl::next< iter_9 > ::type iter_10; typedef typename mpl::next< iter_10 > ::type iter_11; typedef typename mpl::next< iter_11 > ::type iter_12; typedef typename mpl::next< iter_12 > ::type iter_13; typedef typename mpl::next< iter_13 > ::type iter_14; typedef typename mpl::next< iter_14 > ::type iter_15; typedef typename mpl::next< iter_15 > ::type iter_16; typedef typename mpl::next< iter_16 > ::type iter_17; typedef typename mpl::next< iter_17 > ::type iter_18; typedef typename mpl::next< iter_18 > ::type iter_19; typedef typename mpl::next< iter_19 > ::type iter_20; typedef typename mpl::next< iter_20 > ::type iter_21; typedef typename mpl::next< iter_21 > ::type iter_22; typedef typename mpl::next< iter_22 > ::type iter_23; typedef typename mpl::next< iter_23 > ::type iter_24; typedef typename mpl::next< iter_24 > ::type iter_25; public: typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,25) < typename mpl::deref< iter_0 > ::type , typename detail::cv_traits< typename mpl::deref< iter_1 > ::type > ::type , typename mpl::deref< iter_2 > ::type , typename mpl::deref< iter_3 > ::type , typename mpl::deref< iter_4 > ::type , typename mpl::deref< iter_5 > ::type , typename mpl::deref< iter_6 > ::type , typename mpl::deref< iter_7 > ::type , typename mpl::deref< iter_8 > ::type , typename mpl::deref< iter_9 > ::type , typename mpl::deref< iter_10 > ::type , typename mpl::deref< iter_11 > ::type , typename mpl::deref< iter_12 > ::type , typename mpl::deref< iter_13 > ::type , typename mpl::deref< iter_14 > ::type , typename mpl::deref< iter_15 > ::type , typename mpl::deref< iter_16 > ::type , typename mpl::deref< iter_17 > ::type , typename mpl::deref< iter_18 > ::type , typename mpl::deref< iter_19 > ::type , typename mpl::deref< iter_20 > ::type , typename mpl::deref< iter_21 > ::type , typename mpl::deref< iter_22 > ::type , typename mpl::deref< iter_23 > ::type , typename mpl::deref< iter_24 > ::type , typename mpl::deref< iter_25 > ::type > ::type type; }; }; template< typename R, typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25 > struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,26) { typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25 BOOST_FT_ell) BOOST_FT_cv ; }; template< > struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 27 > { template<typename S> struct synthesize_impl_i { private: typedef typename mpl::begin<S> ::type iter_0; typedef typename mpl::next< iter_0 > ::type iter_1; typedef typename mpl::next< iter_1 > ::type iter_2; typedef typename mpl::next< iter_2 > ::type iter_3; typedef typename mpl::next< iter_3 > ::type iter_4; typedef typename mpl::next< iter_4 > ::type iter_5; typedef typename mpl::next< iter_5 > ::type iter_6; typedef typename mpl::next< iter_6 > ::type iter_7; typedef typename mpl::next< iter_7 > ::type iter_8; typedef typename mpl::next< iter_8 > ::type iter_9; typedef typename mpl::next< iter_9 > ::type iter_10; typedef typename mpl::next< iter_10 > ::type iter_11; typedef typename mpl::next< iter_11 > ::type iter_12; typedef typename mpl::next< iter_12 > ::type iter_13; typedef typename mpl::next< iter_13 > ::type iter_14; typedef typename mpl::next< iter_14 > ::type iter_15; typedef typename mpl::next< iter_15 > ::type iter_16; typedef typename mpl::next< iter_16 > ::type iter_17; typedef typename mpl::next< iter_17 > ::type iter_18; typedef typename mpl::next< iter_18 > ::type iter_19; typedef typename mpl::next< iter_19 > ::type iter_20; typedef typename mpl::next< iter_20 > ::type iter_21; typedef typename mpl::next< iter_21 > ::type iter_22; typedef typename mpl::next< iter_22 > ::type iter_23; typedef typename mpl::next< iter_23 > ::type iter_24; typedef typename mpl::next< iter_24 > ::type iter_25; typedef typename mpl::next< iter_25 > ::type iter_26; public: typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,26) < typename mpl::deref< iter_0 > ::type , typename detail::cv_traits< typename mpl::deref< iter_1 > ::type > ::type , typename mpl::deref< iter_2 > ::type , typename mpl::deref< iter_3 > ::type , typename mpl::deref< iter_4 > ::type , typename mpl::deref< iter_5 > ::type , typename mpl::deref< iter_6 > ::type , typename mpl::deref< iter_7 > ::type , typename mpl::deref< iter_8 > ::type , typename mpl::deref< iter_9 > ::type , typename mpl::deref< iter_10 > ::type , typename mpl::deref< iter_11 > ::type , typename mpl::deref< iter_12 > ::type , typename mpl::deref< iter_13 > ::type , typename mpl::deref< iter_14 > ::type , typename mpl::deref< iter_15 > ::type , typename mpl::deref< iter_16 > ::type , typename mpl::deref< iter_17 > ::type , typename mpl::deref< iter_18 > ::type , typename mpl::deref< iter_19 > ::type , typename mpl::deref< iter_20 > ::type , typename mpl::deref< iter_21 > ::type , typename mpl::deref< iter_22 > ::type , typename mpl::deref< iter_23 > ::type , typename mpl::deref< iter_24 > ::type , typename mpl::deref< iter_25 > ::type , typename mpl::deref< iter_26 > ::type > ::type type; }; }; template< typename R, typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26 > struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,27) { typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26 BOOST_FT_ell) BOOST_FT_cv ; }; template< > struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 28 > { template<typename S> struct synthesize_impl_i { private: typedef typename mpl::begin<S> ::type iter_0; typedef typename mpl::next< iter_0 > ::type iter_1; typedef typename mpl::next< iter_1 > ::type iter_2; typedef typename mpl::next< iter_2 > ::type iter_3; typedef typename mpl::next< iter_3 > ::type iter_4; typedef typename mpl::next< iter_4 > ::type iter_5; typedef typename mpl::next< iter_5 > ::type iter_6; typedef typename mpl::next< iter_6 > ::type iter_7; typedef typename mpl::next< iter_7 > ::type iter_8; typedef typename mpl::next< iter_8 > ::type iter_9; typedef typename mpl::next< iter_9 > ::type iter_10; typedef typename mpl::next< iter_10 > ::type iter_11; typedef typename mpl::next< iter_11 > ::type iter_12; typedef typename mpl::next< iter_12 > ::type iter_13; typedef typename mpl::next< iter_13 > ::type iter_14; typedef typename mpl::next< iter_14 > ::type iter_15; typedef typename mpl::next< iter_15 > ::type iter_16; typedef typename mpl::next< iter_16 > ::type iter_17; typedef typename mpl::next< iter_17 > ::type iter_18; typedef typename mpl::next< iter_18 > ::type iter_19; typedef typename mpl::next< iter_19 > ::type iter_20; typedef typename mpl::next< iter_20 > ::type iter_21; typedef typename mpl::next< iter_21 > ::type iter_22; typedef typename mpl::next< iter_22 > ::type iter_23; typedef typename mpl::next< iter_23 > ::type iter_24; typedef typename mpl::next< iter_24 > ::type iter_25; typedef typename mpl::next< iter_25 > ::type iter_26; typedef typename mpl::next< iter_26 > ::type iter_27; public: typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,27) < typename mpl::deref< iter_0 > ::type , typename detail::cv_traits< typename mpl::deref< iter_1 > ::type > ::type , typename mpl::deref< iter_2 > ::type , typename mpl::deref< iter_3 > ::type , typename mpl::deref< iter_4 > ::type , typename mpl::deref< iter_5 > ::type , typename mpl::deref< iter_6 > ::type , typename mpl::deref< iter_7 > ::type , typename mpl::deref< iter_8 > ::type , typename mpl::deref< iter_9 > ::type , typename mpl::deref< iter_10 > ::type , typename mpl::deref< iter_11 > ::type , typename mpl::deref< iter_12 > ::type , typename mpl::deref< iter_13 > ::type , typename mpl::deref< iter_14 > ::type , typename mpl::deref< iter_15 > ::type , typename mpl::deref< iter_16 > ::type , typename mpl::deref< iter_17 > ::type , typename mpl::deref< iter_18 > ::type , typename mpl::deref< iter_19 > ::type , typename mpl::deref< iter_20 > ::type , typename mpl::deref< iter_21 > ::type , typename mpl::deref< iter_22 > ::type , typename mpl::deref< iter_23 > ::type , typename mpl::deref< iter_24 > ::type , typename mpl::deref< iter_25 > ::type , typename mpl::deref< iter_26 > ::type , typename mpl::deref< iter_27 > ::type > ::type type; }; }; template< typename R, typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27 > struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,28) { typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27 BOOST_FT_ell) BOOST_FT_cv ; }; template< > struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 29 > { template<typename S> struct synthesize_impl_i { private: typedef typename mpl::begin<S> ::type iter_0; typedef typename mpl::next< iter_0 > ::type iter_1; typedef typename mpl::next< iter_1 > ::type iter_2; typedef typename mpl::next< iter_2 > ::type iter_3; typedef typename mpl::next< iter_3 > ::type iter_4; typedef typename mpl::next< iter_4 > ::type iter_5; typedef typename mpl::next< iter_5 > ::type iter_6; typedef typename mpl::next< iter_6 > ::type iter_7; typedef typename mpl::next< iter_7 > ::type iter_8; typedef typename mpl::next< iter_8 > ::type iter_9; typedef typename mpl::next< iter_9 > ::type iter_10; typedef typename mpl::next< iter_10 > ::type iter_11; typedef typename mpl::next< iter_11 > ::type iter_12; typedef typename mpl::next< iter_12 > ::type iter_13; typedef typename mpl::next< iter_13 > ::type iter_14; typedef typename mpl::next< iter_14 > ::type iter_15; typedef typename mpl::next< iter_15 > ::type iter_16; typedef typename mpl::next< iter_16 > ::type iter_17; typedef typename mpl::next< iter_17 > ::type iter_18; typedef typename mpl::next< iter_18 > ::type iter_19; typedef typename mpl::next< iter_19 > ::type iter_20; typedef typename mpl::next< iter_20 > ::type iter_21; typedef typename mpl::next< iter_21 > ::type iter_22; typedef typename mpl::next< iter_22 > ::type iter_23; typedef typename mpl::next< iter_23 > ::type iter_24; typedef typename mpl::next< iter_24 > ::type iter_25; typedef typename mpl::next< iter_25 > ::type iter_26; typedef typename mpl::next< iter_26 > ::type iter_27; typedef typename mpl::next< iter_27 > ::type iter_28; public: typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,28) < typename mpl::deref< iter_0 > ::type , typename detail::cv_traits< typename mpl::deref< iter_1 > ::type > ::type , typename mpl::deref< iter_2 > ::type , typename mpl::deref< iter_3 > ::type , typename mpl::deref< iter_4 > ::type , typename mpl::deref< iter_5 > ::type , typename mpl::deref< iter_6 > ::type , typename mpl::deref< iter_7 > ::type , typename mpl::deref< iter_8 > ::type , typename mpl::deref< iter_9 > ::type , typename mpl::deref< iter_10 > ::type , typename mpl::deref< iter_11 > ::type , typename mpl::deref< iter_12 > ::type , typename mpl::deref< iter_13 > ::type , typename mpl::deref< iter_14 > ::type , typename mpl::deref< iter_15 > ::type , typename mpl::deref< iter_16 > ::type , typename mpl::deref< iter_17 > ::type , typename mpl::deref< iter_18 > ::type , typename mpl::deref< iter_19 > ::type , typename mpl::deref< iter_20 > ::type , typename mpl::deref< iter_21 > ::type , typename mpl::deref< iter_22 > ::type , typename mpl::deref< iter_23 > ::type , typename mpl::deref< iter_24 > ::type , typename mpl::deref< iter_25 > ::type , typename mpl::deref< iter_26 > ::type , typename mpl::deref< iter_27 > ::type , typename mpl::deref< iter_28 > ::type > ::type type; }; }; template< typename R, typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28 > struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,29) { typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28 BOOST_FT_ell) BOOST_FT_cv ; }; template< > struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 30 > { template<typename S> struct synthesize_impl_i { private: typedef typename mpl::begin<S> ::type iter_0; typedef typename mpl::next< iter_0 > ::type iter_1; typedef typename mpl::next< iter_1 > ::type iter_2; typedef typename mpl::next< iter_2 > ::type iter_3; typedef typename mpl::next< iter_3 > ::type iter_4; typedef typename mpl::next< iter_4 > ::type iter_5; typedef typename mpl::next< iter_5 > ::type iter_6; typedef typename mpl::next< iter_6 > ::type iter_7; typedef typename mpl::next< iter_7 > ::type iter_8; typedef typename mpl::next< iter_8 > ::type iter_9; typedef typename mpl::next< iter_9 > ::type iter_10; typedef typename mpl::next< iter_10 > ::type iter_11; typedef typename mpl::next< iter_11 > ::type iter_12; typedef typename mpl::next< iter_12 > ::type iter_13; typedef typename mpl::next< iter_13 > ::type iter_14; typedef typename mpl::next< iter_14 > ::type iter_15; typedef typename mpl::next< iter_15 > ::type iter_16; typedef typename mpl::next< iter_16 > ::type iter_17; typedef typename mpl::next< iter_17 > ::type iter_18; typedef typename mpl::next< iter_18 > ::type iter_19; typedef typename mpl::next< iter_19 > ::type iter_20; typedef typename mpl::next< iter_20 > ::type iter_21; typedef typename mpl::next< iter_21 > ::type iter_22; typedef typename mpl::next< iter_22 > ::type iter_23; typedef typename mpl::next< iter_23 > ::type iter_24; typedef typename mpl::next< iter_24 > ::type iter_25; typedef typename mpl::next< iter_25 > ::type iter_26; typedef typename mpl::next< iter_26 > ::type iter_27; typedef typename mpl::next< iter_27 > ::type iter_28; typedef typename mpl::next< iter_28 > ::type iter_29; public: typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,29) < typename mpl::deref< iter_0 > ::type , typename detail::cv_traits< typename mpl::deref< iter_1 > ::type > ::type , typename mpl::deref< iter_2 > ::type , typename mpl::deref< iter_3 > ::type , typename mpl::deref< iter_4 > ::type , typename mpl::deref< iter_5 > ::type , typename mpl::deref< iter_6 > ::type , typename mpl::deref< iter_7 > ::type , typename mpl::deref< iter_8 > ::type , typename mpl::deref< iter_9 > ::type , typename mpl::deref< iter_10 > ::type , typename mpl::deref< iter_11 > ::type , typename mpl::deref< iter_12 > ::type , typename mpl::deref< iter_13 > ::type , typename mpl::deref< iter_14 > ::type , typename mpl::deref< iter_15 > ::type , typename mpl::deref< iter_16 > ::type , typename mpl::deref< iter_17 > ::type , typename mpl::deref< iter_18 > ::type , typename mpl::deref< iter_19 > ::type , typename mpl::deref< iter_20 > ::type , typename mpl::deref< iter_21 > ::type , typename mpl::deref< iter_22 > ::type , typename mpl::deref< iter_23 > ::type , typename mpl::deref< iter_24 > ::type , typename mpl::deref< iter_25 > ::type , typename mpl::deref< iter_26 > ::type , typename mpl::deref< iter_27 > ::type , typename mpl::deref< iter_28 > ::type , typename mpl::deref< iter_29 > ::type > ::type type; }; }; template< typename R, typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29 > struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,30) { typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29 BOOST_FT_ell) BOOST_FT_cv ; }; template< > struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 31 > { template<typename S> struct synthesize_impl_i { private: typedef typename mpl::begin<S> ::type iter_0; typedef typename mpl::next< iter_0 > ::type iter_1; typedef typename mpl::next< iter_1 > ::type iter_2; typedef typename mpl::next< iter_2 > ::type iter_3; typedef typename mpl::next< iter_3 > ::type iter_4; typedef typename mpl::next< iter_4 > ::type iter_5; typedef typename mpl::next< iter_5 > ::type iter_6; typedef typename mpl::next< iter_6 > ::type iter_7; typedef typename mpl::next< iter_7 > ::type iter_8; typedef typename mpl::next< iter_8 > ::type iter_9; typedef typename mpl::next< iter_9 > ::type iter_10; typedef typename mpl::next< iter_10 > ::type iter_11; typedef typename mpl::next< iter_11 > ::type iter_12; typedef typename mpl::next< iter_12 > ::type iter_13; typedef typename mpl::next< iter_13 > ::type iter_14; typedef typename mpl::next< iter_14 > ::type iter_15; typedef typename mpl::next< iter_15 > ::type iter_16; typedef typename mpl::next< iter_16 > ::type iter_17; typedef typename mpl::next< iter_17 > ::type iter_18; typedef typename mpl::next< iter_18 > ::type iter_19; typedef typename mpl::next< iter_19 > ::type iter_20; typedef typename mpl::next< iter_20 > ::type iter_21; typedef typename mpl::next< iter_21 > ::type iter_22; typedef typename mpl::next< iter_22 > ::type iter_23; typedef typename mpl::next< iter_23 > ::type iter_24; typedef typename mpl::next< iter_24 > ::type iter_25; typedef typename mpl::next< iter_25 > ::type iter_26; typedef typename mpl::next< iter_26 > ::type iter_27; typedef typename mpl::next< iter_27 > ::type iter_28; typedef typename mpl::next< iter_28 > ::type iter_29; typedef typename mpl::next< iter_29 > ::type iter_30; public: typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,30) < typename mpl::deref< iter_0 > ::type , typename detail::cv_traits< typename mpl::deref< iter_1 > ::type > ::type , typename mpl::deref< iter_2 > ::type , typename mpl::deref< iter_3 > ::type , typename mpl::deref< iter_4 > ::type , typename mpl::deref< iter_5 > ::type , typename mpl::deref< iter_6 > ::type , typename mpl::deref< iter_7 > ::type , typename mpl::deref< iter_8 > ::type , typename mpl::deref< iter_9 > ::type , typename mpl::deref< iter_10 > ::type , typename mpl::deref< iter_11 > ::type , typename mpl::deref< iter_12 > ::type , typename mpl::deref< iter_13 > ::type , typename mpl::deref< iter_14 > ::type , typename mpl::deref< iter_15 > ::type , typename mpl::deref< iter_16 > ::type , typename mpl::deref< iter_17 > ::type , typename mpl::deref< iter_18 > ::type , typename mpl::deref< iter_19 > ::type , typename mpl::deref< iter_20 > ::type , typename mpl::deref< iter_21 > ::type , typename mpl::deref< iter_22 > ::type , typename mpl::deref< iter_23 > ::type , typename mpl::deref< iter_24 > ::type , typename mpl::deref< iter_25 > ::type , typename mpl::deref< iter_26 > ::type , typename mpl::deref< iter_27 > ::type , typename mpl::deref< iter_28 > ::type , typename mpl::deref< iter_29 > ::type , typename mpl::deref< iter_30 > ::type > ::type type; }; }; # undef BOOST_FT_make_type # undef BOOST_FT_make_type_impl
[ "k.melekhin@gmail.com" ]
k.melekhin@gmail.com
37215ce819dade01c292c7bde8e5c57c0b6e89a3
eeb26071325267cef3c8df6e67195b9bcbc60bf7
/Solution/Engine/CUI_TreeView.h
1ed4cf03b212f9608bd0aced2ee5d8cfdff64794
[]
no_license
nian0601/CubeEngine
0fccc98978b94ba66a5692064feb999c7d5dee25
4d581e748f8af0b559b3cc978a26b7dace8662e5
refs/heads/master
2021-06-25T04:37:14.050485
2019-06-27T19:45:55
2019-06-27T19:45:55
100,294,390
0
0
null
null
null
null
UTF-8
C++
false
false
427
h
#pragma once #include "CUI_VBox.h" class CUI_Button; class CE_OldFont; class CUI_TreeView : public CUI_VBox { public: CUI_TreeView(const CE_String& aString); void PrepareLayout(); void DeleteAllChildren() override; void DeleteChildren(int aStartIndex); void SetExpanded(bool aStatus); private: void UpdateSelfSize(CUI_Widget* aChildWidget); void OnToggleViewClick(); CUI_Button* myButton; bool myIsExpanded; };
[ "anderssonniklas@outlook.com" ]
anderssonniklas@outlook.com
1ded5cf1db73ed5eff7b5897d04b2af32f5de592
afdba41376845125205964dd92a66bee17e16dec
/Constitution/src/TimedContainer.cpp
3e822ed9f3c306635384892797e25db881ffc6f3
[]
no_license
Chhavi17/OOPS-and-Data-Structures
2aeb101743ad756d77676e55f67e10d70aa04c32
25aedf4796a1365f171251123fc931c7c191aaa1
refs/heads/master
2020-03-10T10:37:16.840738
2018-04-13T09:05:19
2018-04-13T09:05:19
129,337,000
0
0
null
null
null
null
UTF-8
C++
false
false
1,410
cpp
#include "TimedContainer.h" #include <chrono> #include "Word.h" using namespace std; using namespace std::chrono; /***** Modify this file as needed. *****/ TimedContainer::TimedContainer() {} TimedContainer::~TimedContainer() {} long TimedContainer::get_elapsed_time() const { return elapsed_time; } void TimedContainer::reset_elapsed_time() { elapsed_time = 0; } void TimedContainer::increment_elapsed_time(long elapsed) { elapsed_time += elapsed; } Word *TimedContainer::timed_insert(const string text) { // Start the timer. steady_clock::time_point start_time = steady_clock::now(); // Do the insertion. Word *word = insert(text); // Compute the elapsed time in microseconds // and increment the total elapsed time. steady_clock::time_point end_time = steady_clock::now(); increment_elapsed_time(duration_cast<microseconds>(end_time - start_time).count()); return word; } Word *TimedContainer::timed_search(const string text) { // Start the timer. steady_clock::time_point start_time = steady_clock::now(); // Do the search. Word *word = search(text); // Compute the elapsed time in microseconds // and increment the total elapsed time. steady_clock::time_point end_time = steady_clock::now(); long elapsed = duration_cast<microseconds>(end_time - start_time).count(); increment_elapsed_time(elapsed); return word; }
[ "chhavi@Chhavis-MacBook-Pro.local" ]
chhavi@Chhavis-MacBook-Pro.local
2ddda63537360ad3b3c04120a19d7e5341cd3c1c
10e25b7a8d540d198729668e60b4fc17cacc5ce6
/files/2018s2/mamarracho.cpp
bb20c906daab6fd416aee48457bf9d31b00e3f36
[]
no_license
unqpgc/unqpgc.github.io
2452ec8dca591ba340f86f07669d1c2bfb46f3b0
8df676b3cb80315797d57915cc5a143392f42790
refs/heads/master
2023-08-18T17:41:29.483719
2023-08-16T17:56:40
2023-08-16T17:56:40
100,538,338
0
0
null
null
null
null
UTF-8
C++
false
false
29,702
cpp
#include <iostream> #include <fstream> #include <cstdlib> #include <sstream> #include <vector> #include <map> #include <cassert> #include <cstring> using namespace std; // Helper functions typedef signed long long int i64; typedef unsigned long long int u64; void fail(const string& msg) { cerr << "*** Mamarracho ***" << endl; cerr << msg << endl; exit(1); } void usage(const string& program) { cerr << "Usage:" << endl; cerr << " " << program; cerr << " input.mam Run program." << endl; cerr << " " << program; cerr << " -p input.mam Print program." << endl; exit(1); } string int_to_string(int n) { ostringstream s; s << n; return s.str(); } string i64_to_string(i64 n) { ostringstream s; s << n; return s.str(); } string u64_to_string(u64 n) { ostringstream s; s << n; return s.str(); } string char_to_string(char c) { char s[2]; s[0] = c; s[1] = '\0'; return string(s); } // Instructions typedef string Reg; typedef string Label; typedef int Opcode; const Opcode OP_label = 1; const Opcode OP_mov_reg = 2; const Opcode OP_mov_int = 3; const Opcode OP_mov_label = 4; const Opcode OP_alloc = 5; const Opcode OP_load = 6; const Opcode OP_store = 7; const Opcode OP_print_char = 8; const Opcode OP_print = 9; const Opcode OP_jump = 10; const Opcode OP_jump_eq = 11; const Opcode OP_jump_lt = 12; const Opcode OP_add = 13; const Opcode OP_sub = 14; const Opcode OP_mul = 15; const Opcode OP_div = 16; const Opcode OP_mod = 17; const Opcode OP_call = 18; const Opcode OP_icall = 19; const Opcode OP_return = 20; const Opcode OPCODE_MIN = OP_label; const Opcode OPCODE_MAX = OP_return; string opcode_name(Opcode op) { switch (op) { case OP_label: return "label"; case OP_mov_reg: return "mov_reg"; case OP_mov_int: return "mov_int"; case OP_mov_label: return "mov_label"; case OP_alloc: return "alloc"; case OP_load: return "load"; case OP_store: return "store"; case OP_print_char: return "print_char"; case OP_print: return "print"; case OP_jump: return "jump"; case OP_jump_eq: return "jump_eq"; case OP_jump_lt: return "jump_lt"; case OP_add: return "add"; case OP_sub: return "sub"; case OP_mul: return "mul"; case OP_div: return "div"; case OP_mod: return "mod"; case OP_call: return "call"; case OP_icall: return "icall"; case OP_return: return "return"; default: fail("Opcode name not implemented for " + int_to_string(op)); return ""; } } string opcode_paramTypes(Opcode op) { switch (op) { case OP_label: return "l"; case OP_mov_reg: return "rr"; case OP_mov_int: return "ri"; case OP_mov_label: return "rl"; case OP_alloc: return "ru"; case OP_load: return "rru"; case OP_store: return "rur"; case OP_print_char: return "r"; case OP_print: return "r"; case OP_jump: return "l"; case OP_jump_eq: return "rrl"; case OP_jump_lt: return "rrl"; case OP_add: return "rrr"; case OP_sub: return "rrr"; case OP_mul: return "rrr"; case OP_div: return "rrr"; case OP_mod: return "rrr"; case OP_call: return "l"; case OP_icall: return "r"; case OP_return: return ""; default: fail("Opcode paramTypes not implemented for " + opcode_name(op)); return ""; } } class Instruction { public: Instruction(Opcode op); Opcode opcode() const; const Reg& regParam(int i) const; i64 i64Param(int i) const; u64 u64Param(int i) const; const Label& labelParam(int i) const; int numRegParams() const; int numI64Params() const; int numU64Params() const; int numLabelParams() const; void addRegParam(Reg reg); void addI64Param(i64 x); void addU64Param(u64 x); void addLabelParam(Label label); private: Opcode _op; vector<Reg> _regParams; vector<i64> _i64Params; vector<i64> _u64Params; vector<Label> _labelParams; }; Instruction::Instruction(Opcode op) : _op(op) { } Opcode Instruction::opcode() const { return _op; } const Reg& Instruction::regParam(int i) const { return _regParams[i]; } i64 Instruction::i64Param(int i) const { return _i64Params[i]; } u64 Instruction::u64Param(int i) const { return _u64Params[i]; } const Label& Instruction::labelParam(int i) const { return _labelParams[i]; } int Instruction::numRegParams() const { return _regParams.size(); } int Instruction::numI64Params() const { return _i64Params.size(); } int Instruction::numU64Params() const { return _u64Params.size(); } int Instruction::numLabelParams() const { return _labelParams.size(); } void Instruction::addRegParam(Reg reg) { _regParams.push_back(reg); } void Instruction::addI64Param(i64 x) { _i64Params.push_back(x); } void Instruction::addU64Param(u64 x) { _u64Params.push_back(x); } void Instruction::addLabelParam(Label label) { _labelParams.push_back(label); } ostream& operator<<(ostream& os, const Instruction& instr) { if (instr.opcode() == OP_label) { os << instr.labelParam(0) << ":"; } else { string paramTypes = opcode_paramTypes(instr.opcode()); os << opcode_name(instr.opcode()) << "("; int pr = 0; int pi = 0; int pu = 0; int pl = 0; for (unsigned int i = 0; i < paramTypes.size(); i++) { char paramType = paramTypes[i]; if (i > 0) { os << ", "; } switch (paramType) { case 'r': os << "$" << instr.regParam(pr++); break; case 'i': os << instr.i64Param(pi++); break; case 'u': os << instr.u64Param(pu++); break; case 'l': os << instr.labelParam(pl++); break; default: assert(false); } } os << ")"; } return os; } // Program class Program { public: Program(); void addInstruction(Instruction instruction); const Instruction& instruction(int i) const; u64 size() const; u64 labelLocation(const Label& label) const; void lint(); private: vector<Instruction> _instructions; map<Label, u64> _labels; void _fail(const string& msg) const; }; Program::Program() { } void Program::addInstruction(Instruction instruction) { if (instruction.opcode() == OP_label) { Label label = instruction.labelParam(0); u64 position = _instructions.size(); if (_labels.find(label) != _labels.end()) { _fail("Repeated label \"" + label + "\"."); } _labels[label] = position; } _instructions.push_back(instruction); } u64 Program::size() const { return _instructions.size(); } const Instruction& Program::instruction(int i) const { return _instructions[i]; } u64 Program::labelLocation(const Label& label) const { if (_labels.find(label) == _labels.end()) { _fail("Undefined label \"" + label + "\"."); } return _labels.at(label); } void Program::lint() { // Check that all referenced labels exist for (u64 i = 0; i < size(); i++) { const Instruction& instr = instruction(i); for (int j = 0; j < instr.numLabelParams(); j++) { Label label = instr.labelParam(j); if (_labels.find(label) == _labels.end()) { _fail("Undefined label \"" + label + "\"."); } } } } void Program::_fail(const string& msg) const { fail("Semantic error.\n" + msg); } ostream& operator<<(ostream& os, const Program& p) { for (u64 i = 0; i < p.size(); i++) { os << p.instruction(i) << endl; } return os; } // Reader class Reader { public: Reader(const string& filename); ~Reader(); Program readProgram(); private: istream& _is; string _filename; int _row; int _col; bool _isPrintable(char c); bool _isAlpha(char c); bool _isDigit(char c); bool _isIdent(char c); bool _isWhitespace(char c); void _match(char expected, const string& errmsg); string _currentChar(); string _readName(); string _readDigits(); string _readIdentifier(); Reg _readRegister(); Label _readLabel(); i64 _readI64(); u64 _readU64(); Instruction _readInstruction(); Instruction _readInstrParams(Opcode op, const string& paramTypes); void _skipComment(); void _skipWhitespaceAndComments(); bool _eof(); void _fail(const string& msg); }; Reader::Reader(const string& filename) : _is(*new ifstream(filename.c_str())), _filename(filename), _row(1), _col(1) { if (!_is.good()) { fail("File \"" + filename + "\" does not exist."); } } Reader::~Reader() { delete &_is; } Program Reader::readProgram() { Program program; while (true) { _skipWhitespaceAndComments(); if (!_is.good()) { break; } program.addInstruction(_readInstruction()); } program.lint(); return program; } bool Reader::_isPrintable(char c) { return 32 <= c && c <= 127; } bool Reader::_isAlpha(char c) { return ('A' <= c && c <= 'Z') || ('a' <= c && c <= 'z') || c == '_'; } bool Reader::_isDigit(char c) { return '0' <= c && c <= '9'; } bool Reader::_isIdent(char c) { return _isAlpha(c) || _isDigit(c); } bool Reader::_isWhitespace(char c) { return c == ' ' || c == '\t' || c == '\r' || c == '\n'; } void Reader::_match(char expected, const string& errmsg) { _skipWhitespaceAndComments(); if (_is.good() && _is.peek() == expected) { _is.get(); _col++; } else { _fail(errmsg); } } string Reader::_currentChar() { if (_is.good() && _isPrintable(_is.peek())) { return "'" + char_to_string(_is.peek()) + "'"; } else if (_is.good()) { return "chr(" + int_to_string(_is.peek()) + ")"; } else { return "end of file"; } } string Reader::_readName() { string id = ""; while (_is.good() && _isIdent(_is.peek())) { id += _is.get(); _col++; } return id; } string Reader::_readDigits() { string id = ""; while (_is.good() && _isDigit(_is.peek())) { id += _is.get(); _col++; } return id; } string Reader::_readIdentifier() { _skipWhitespaceAndComments(); if (!_is.good() || !_isAlpha(_is.peek())) { _fail( "Expected an identifier, " "but found " + _currentChar() + ".\n" "Identifiers should be of the form [_A-Za-z][_A-Za-z0-9]*." ); } return _readName(); } Reg Reader::_readRegister() { _skipWhitespaceAndComments(); if (!_is.good() || (_is.peek() != '$' && _is.peek() != '@')) { _fail( "Expected a register, " "but found " + _currentChar() + ".\n" "Registers should be of the form [@$][_A-Za-z0-9]+." ); } char sigil = _is.get(); _col++; return char_to_string(sigil) + _readName(); } Label Reader::_readLabel() { return _readIdentifier(); } i64 Reader::_readI64() { _skipWhitespaceAndComments(); string sign = ""; if (_is.good() && _is.peek() == '-') { sign = "-"; _is.get(); _col++; } if (!_is.good() || !_isDigit(_is.peek())) { _fail( "Expected a signed integer, " "but found " + _currentChar() + "." ); } string digits = sign + _readDigits(); i64 x; stringstream(digits) >> x; if (i64_to_string(x) != digits) { _fail( "Invalid signed integer constant \"" + digits + "\".\n" "Signed integers should be in the range -2^63..2^63-1." ); } return x; } u64 Reader::_readU64() { _skipWhitespaceAndComments(); if (!_is.good() || !_isDigit(_is.peek())) { _fail( "Expected an unsigned integer, " "but found " + _currentChar() + "." ); } string digits = _readDigits(); u64 x; stringstream(digits) >> x; if (u64_to_string(x) != digits) { _fail( "Invalid unsigned integer constant \"" + digits + "\".\n" "Unsigned integers should be in the range 0..2^64-1." ); } return x; } Instruction Reader::_readInstruction() { string id = _readIdentifier(); if (_is.good() && _is.peek() == ':') { Instruction instruction(OP_label); _is.get(); _col++; instruction.addLabelParam(id); return instruction; } for (Opcode op = OPCODE_MIN; op <= OPCODE_MAX; ++op) { if (id == opcode_name(op)) { return _readInstrParams(op, opcode_paramTypes(op)); } } _fail("Invalid instruction: \"" + id + "\"."); return Instruction(OPCODE_MIN); } Instruction Reader::_readInstrParams(Opcode op, const string& paramTypes) { Instruction instruction(op); bool with_parens = false; _skipWhitespaceAndComments(); if (_is.good() && _is.peek() == '(') { with_parens = true; _is.get(); _col++; } for (unsigned int i = 0; i < paramTypes.size(); i++) { char paramType = paramTypes[i]; if (i > 0) { _match(',', "Expected separator ','.\n" "Note: " + opcode_name(op) + " takes " + int_to_string(paramTypes.size()) + " arguments." ); } switch (paramType) { case 'r': instruction.addRegParam(_readRegister()); break; case 'i': instruction.addI64Param(_readI64()); break; case 'u': instruction.addU64Param(_readU64()); break; case 'l': instruction.addLabelParam(_readLabel()); break; default: assert(false); } } if (with_parens) { _match(')', "Expected closing ')'."); } return instruction; } void Reader::_skipComment() { while (_is.good() && _is.peek() != '\n') { _is.get(); _col++; } } void Reader::_skipWhitespaceAndComments() { while (_is.good()) { if (_is.peek() == '\n') { _row++; _col = 1; _is.get(); } else if (_isWhitespace(_is.peek())) { _is.get(); _col++; } else if (_is.peek() == '%') { _skipComment(); } else { break; } } } bool Reader::_eof() { _skipWhitespaceAndComments(); return !_is.good(); } void Reader::_fail(const string& msg) { fail( "Syntax error near \"" + _filename + "\"" + " (line " + int_to_string(_row) + "," + " column " + int_to_string(_col) + ").\n" + msg ); } // Virtual machine typedef enum { VInt, VPtr, VLoc, } ValueTag; class Value { public: Value(); Value(ValueTag tag, i64 vint); ValueTag tag() const; i64 vi64() const; u64 vu64() const; private: ValueTag _tag; i64 _vint; }; Value::Value() : _tag(VInt), _vint(0) { } Value::Value(ValueTag tag, i64 vint) : _tag(tag), _vint(vint) { } ValueTag Value::tag() const { return _tag; } i64 Value::vi64() const { return _vint; } u64 Value::vu64() const { return (u64)_vint; } ostream& operator<<(ostream& os, Value v) { switch (v.tag()) { case VInt: os << v.vi64(); break; case VPtr: os << "VPtr(" << v.vu64() << ")"; break; case VLoc: os << "VLoc(" << v.vu64() << ")"; break; } return os; } typedef vector<Value> Cell; typedef map<Reg, Value> Env; class VM { public: VM(const Program& program); void run(); ~VM(); private: const Program& _program; Env* _local_env; Env _global_env; vector<Cell> _memory; vector<u64> _call_stack; vector<Env*> _dump; u64 _ip; Value& _env(const Reg& r); void _step(); void _check_int(const Reg& r, const string& errmsg); void _fail(const string& msg); void _mov_reg(const Reg& r1, const Reg& r22); void _mov_int(const Reg& r, i64 n); void _mov_label(const Reg& r, const Label& l); void _alloc(const Reg& r, u64 n); void _load(const Reg& r1, const Reg& r2, u64 i); void _store(const Reg& r1, u64 i, const Reg& r2); void _print_char(const Reg& r); void _print(const Reg& r); void _jump(const Label& l); void _jump_eq(const Reg& r1, const Reg& r2, const Label& l); void _jump_lt(const Reg& r1, const Reg& r2, const Label& l); void _add(const Reg& r1, const Reg& r2, const Reg& r3); void _sub(const Reg& r1, const Reg& r2, const Reg& r3); void _mul(const Reg& r1, const Reg& r2, const Reg& r3); void _div(const Reg& r1, const Reg& r2, const Reg& r3); void _mod(const Reg& r1, const Reg& r2, const Reg& r3); void _call_loc(u64 loc); void _call(const Label& l); void _icall(const Reg& r); void _return(); }; VM::VM(const Program& program) : _program(program), _ip(0) { _local_env = new Env(); } void VM::run() { while (_ip < _program.size()) { _step(); } } VM::~VM() { for (int i = 0; i < _dump.size(); i++) { delete _dump[i]; } delete _local_env; } void VM::_step() { if (_ip >= _program.size()) { _fail("Program terminated."); } Instruction instr = _program.instruction(_ip++); switch (instr.opcode()) { case OP_label: /* Nop */ break; case OP_mov_reg: _mov_reg(instr.regParam(0), instr.regParam(1)); break; case OP_mov_int: _mov_int(instr.regParam(0), instr.i64Param(0)); break; case OP_mov_label: _mov_label(instr.regParam(0), instr.labelParam(0)); break; case OP_alloc: _alloc(instr.regParam(0), instr.u64Param(0)); break; case OP_load: _load(instr.regParam(0), instr.regParam(1), instr.u64Param(0)); break; case OP_store: _store(instr.regParam(0), instr.u64Param(0), instr.regParam(1)); break; case OP_print_char: _print_char(instr.regParam(0)); break; case OP_print: _print(instr.regParam(0)); break; case OP_jump: _jump(instr.labelParam(0)); break; case OP_jump_eq: _jump_eq(instr.regParam(0), instr.regParam(1), instr.labelParam(0)); break; case OP_jump_lt: _jump_lt(instr.regParam(0), instr.regParam(1), instr.labelParam(0)); break; case OP_add: _add(instr.regParam(0), instr.regParam(1), instr.regParam(2)); break; case OP_sub: _sub(instr.regParam(0), instr.regParam(1), instr.regParam(2)); break; case OP_mul: _mul(instr.regParam(0), instr.regParam(1), instr.regParam(2)); break; case OP_div: _div(instr.regParam(0), instr.regParam(1), instr.regParam(2)); break; case OP_mod: _mod(instr.regParam(0), instr.regParam(1), instr.regParam(2)); break; case OP_call: _call(instr.labelParam(0)); break; case OP_icall: _icall(instr.regParam(0)); break; case OP_return: _return(); break; default: _fail("Opcode \"" + opcode_name(instr.opcode()) + "\" not implemented.\n"); } } Value& VM::_env(const Reg& r) { assert(r[0] == '@' || r[0] == '$'); if (r[0] == '@') { return _global_env[r]; } else if (r[0] == '$') { return (*_local_env)[r]; } } void VM::_mov_reg(const Reg& r1, const Reg& r2) { _env(r1) = _env(r2); } void VM::_mov_int(const Reg& r, i64 n) { _env(r) = Value(VInt, n); } void VM::_mov_label(const Reg& r, const Label& l) { _env(r) = Value(VLoc, _program.labelLocation(l)); } void VM::_alloc(const Reg& r, u64 n) { u64 p = _memory.size(); _env(r) = Value(VPtr, p); _memory.push_back(Cell(n, Value())); } void VM::_load(const Reg& r1, const Reg& r2, u64 i) { Value vr2 = _env(r2); if (vr2.tag() != VPtr) { _fail("load: Value is not a pointer."); } Cell& cell = _memory[vr2.vu64()]; if (i >= cell.size()) { _fail("load: Index out of bounds."); } _env(r1) = cell[i]; } void VM::_store(const Reg& r1, u64 i, const Reg& r2) { Value vr1 = _env(r1); if (vr1.tag() != VPtr) { _fail("store: Value is not a pointer."); } Cell& cell = _memory[vr1.vu64()]; if (i >= cell.size()) { _fail("store: Index out of bounds."); } cell[i] = _env(r2); } void VM::_print_char(const Reg& r) { Value v = _env(r); cout << ((unsigned char)v.vi64()); } void VM::_print(const Reg& r) { cout << _env(r); } void VM::_jump(const Label& l) { _ip = _program.labelLocation(l); } void VM::_jump_eq(const Reg& r1, const Reg& r2, const Label& l) { _check_int(r1, "jump_eq: First argument is not an integer."); _check_int(r2, "jump_eq: Second argument is not an integer."); if (_env(r1).vi64() == _env(r2).vi64()) { _jump(l); } } void VM::_jump_lt(const Reg& r1, const Reg& r2, const Label& l) { _check_int(r1, "jump_lt: First argument is not an integer."); _check_int(r2, "jump_lt: Second argument is not an integer."); if (_env(r1).vi64() < _env(r2).vi64()) { _jump(l); } } void VM::_add(const Reg& r1, const Reg& r2, const Reg& r3) { _check_int(r2, "add: Second argument is not an integer."); _check_int(r3, "add: Third argument is not an integer."); i64 a = _env(r2).vi64(); i64 b = _env(r3).vi64(); _env(r1) = Value(VInt, a + b); } void VM::_sub(const Reg& r1, const Reg& r2, const Reg& r3) { _check_int(r2, "sub: Second argument is not an integer."); _check_int(r3, "sub: Third argument is not an integer."); i64 a = _env(r2).vi64(); i64 b = _env(r3).vi64(); _env(r1) = Value(VInt, a - b); } void VM::_mul(const Reg& r1, const Reg& r2, const Reg& r3) { _check_int(r2, "mul: Second argument is not an integer."); _check_int(r3, "mul: Third argument is not an integer."); i64 a = _env(r2).vi64(); i64 b = _env(r3).vi64(); _env(r1) = Value(VInt, a * b); } void VM::_div(const Reg& r1, const Reg& r2, const Reg& r3) { _check_int(r2, "div: Second argument is not an integer."); _check_int(r3, "div: Third argument is not an integer."); i64 a = _env(r2).vi64(); i64 b = _env(r3).vi64(); if (b == 0) { _fail("div: Zero division."); } _env(r1) = Value(VInt, a / b); } void VM::_mod(const Reg& r1, const Reg& r2, const Reg& r3) { _check_int(r2, "mod: Second argument is not an integer."); _check_int(r3, "mod: Third argument is not an integer."); i64 a = _env(r2).vi64(); i64 b = _env(r3).vi64(); if (b == 0) { _fail("mod: Zero division."); } _env(r1) = Value(VInt, a % b); } void VM::_call_loc(u64 loc) { _call_stack.push_back(_ip); _dump.push_back(_local_env); _local_env = new Env(); _ip = loc; } void VM::_call(const Label& l) { _call_loc(_program.labelLocation(l)); } void VM::_icall(const Reg& r) { Value v = _env(r); if (v.tag() != VLoc) { _fail("icall: Value is not a location."); } _call_loc(v.vu64()); } void VM::_return() { if (_call_stack.size() == 0 || _dump.size() == 0) { _fail("return: Empty stack."); } _ip = _call_stack.back(); delete _local_env; _local_env = _dump.back(); _call_stack.pop_back(); _dump.pop_back(); } void VM::_check_int(const Reg& r, const string& errmsg) { Value v = _env(r); if (v.tag() != VInt) { _fail(errmsg); } } void VM::_fail(const string& msg) { fail("Runtime error.\n" + msg); } // Main int main(int argc, char** argv) { bool option_print_program = false; string filename = ""; for (int i = 1; i < argc; i++) { if (!strcmp(argv[i], "-p")) { option_print_program = true; } else { filename = argv[i]; } } if (filename == "") { usage(argv[0]); } Reader reader(filename); Program program = reader.readProgram(); if (option_print_program) { cout << program; exit(0); } else { // Run program VM vm(program); vm.run(); } return 0; }
[ "foones@gmail.com" ]
foones@gmail.com
031b613ecbc0a7f9a56aba419b2716de274ff565
0757032a90e634df8fecbf4687cbf30eb60b5092
/src/libtfhe/numeric-functions.cpp
c4eada9292cbf074c1df22cde62359abde87c91f
[ "MIT", "GPL-1.0-or-later", "Apache-2.0" ]
permissive
A-Pisani/MK-TFHE
b28ab4847177d9b5a39fe317dfd2bbd536429fc9
76d7e658af4bc2343210d4549d07d2743d56a313
refs/heads/master
2023-07-15T15:49:04.024892
2021-08-29T09:32:47
2021-08-29T09:32:47
372,584,100
1
0
Apache-2.0
2021-08-29T15:41:37
2021-05-31T17:34:39
C++
UTF-8
C++
false
false
3,087
cpp
#include <cstdlib> #include <iostream> #include <random> #include <cassert> #include <limits.h> #include <tfhe_core.h> #include <numeric_functions.h> using namespace std; default_random_engine generator; uniform_int_distribution<Torus32> uniformTorus32_distrib(INT32_MIN, INT32_MAX); uniform_int_distribution<int32_t> uniformInt_distrib(INT_MIN, INT_MAX); /** sets the seed of the random number generator to the given values */ EXPORT void tfhe_random_generator_setSeed(uint32_t* values, int32_t size) { seed_seq seeds(values, values+size); generator.seed(seeds); } // Gaussian sample centered in message, with standard deviation sigma EXPORT Torus32 gaussian32(Torus32 message, double sigma){ //Attention: all the implementation will use the stdev instead of the gaussian fourier param normal_distribution<double> distribution(0.,sigma); //TODO: can we create a global distrib of param 1 and multiply by sigma? double err = distribution(generator); return message + dtot32(err); } // from double to Torus32 EXPORT Torus32 dtot32(double d) { return int32_t(int64_t((d - int64_t(d))*_two32)); } // from Torus32 to double EXPORT double t32tod(Torus32 x) { return double(x)/_two32_double; } // Used to approximate the phase to the nearest message possible in the message space // The constant Msize will indicate on which message space we are working (how many messages possible) // // "travailler sur 63 bits au lieu de 64, car dans nos cas pratiques, c'est plus précis" EXPORT Torus32 approxPhase(Torus32 phase, int32_t Msize){ uint64_t interv = ((UINT64_C(1)<<63)/Msize)*2; // width of each intervall uint64_t half_interval = interv/2; // begin of the first intervall uint64_t phase64 = (uint64_t(phase)<<32) + half_interval; //floor to the nearest multiples of interv phase64 -= phase64%interv; //rescale to torus32 return int32_t(phase64>>32); } // Used to approximate the phase to the nearest message possible in the message space // The constant Msize will indicate on which message space we are working (how many messages possible) // // "travailler sur 63 bits au lieu de 64, car dans nos cas pratiques, c'est plus précis" EXPORT int32_t modSwitchFromTorus32(Torus32 phase, int32_t Msize){ uint64_t interv = ((UINT64_C(1)<<63)/Msize)*2; // width of each intervall uint64_t half_interval = interv/2; // begin of the first intervall uint64_t phase64 = (uint64_t(phase)<<32) + half_interval; //floor to the nearest multiples of interv return phase64/interv; } // Used to approximate the phase to the nearest message possible in the message space // The constant Msize will indicate on which message space we are working (how many messages possible) // // "travailler sur 63 bits au lieu de 64, car dans nos cas pratiques, c'est plus précis" EXPORT Torus32 modSwitchToTorus32(int32_t mu, int32_t Msize){ uint64_t interv = ((UINT64_C(1)<<63)/Msize)*2; // width of each intervall uint64_t phase64 = mu*interv; //floor to the nearest multiples of interv return phase64>>32; }
[ "ilaria.chillotti@uvsq.fr" ]
ilaria.chillotti@uvsq.fr
397f0975eed1533bf1533afb78ba6b5450c2e09e
a841ed0dbf9c9b20496f67626fc7455f0b3553ef
/Baekjoon Online Judge/10815.cpp
7a0457d87ace408ff2accce9752388967ae76d62
[]
no_license
lkoiescg2031/APSS
8a8e9c38c93bac4e629af64cff63c0eba0626748
74ed82d96728a686c89bab871287ced020bd2ae4
refs/heads/master
2021-06-13T16:29:30.960443
2021-03-20T01:37:08
2021-03-20T01:37:08
148,625,706
6
0
null
null
null
null
UTF-8
C++
false
false
563
cpp
#include <cstdio> #include <algorithm> using namespace std; int n, m, arr[500000], k; int find(int start, int end, int key) { if (start <= end) { int mid = (start + end) / 2; if (arr[mid] == key) return 1; else if (arr[mid] > key) return find(start, mid - 1, key); else return find(mid + 1, end, key); } return 0; } int main() { scanf("%d", &n); for (int i = 0; i < n; i++) scanf("%d", &arr[i]); sort(arr, arr + n); scanf("%d", &m); for (int i = 0; i < m; i++) { scanf("%d", &k); printf("%d ", find(0, n, k)); } return 0; }
[ "lkoiescg2031@naver.com" ]
lkoiescg2031@naver.com
b88a326bc0038c620e70b555997737fcb8bd049f
ed2a0ba2cb4139a110226e4e45aa99f22aec7851
/city.h
3d8dade64ff9b628791ca9eb86ff51ced748dca9
[]
no_license
TingyunLiu/SolvingTSP_with_Simulated_Annealing
4c8027ac6b41fdf2009fa14cc319ceafe041aa71
eae3861fec8f6ca2689ad060f4284ddd29634faa
refs/heads/master
2021-07-25T20:15:14.779730
2017-11-06T03:23:09
2017-11-06T03:23:09
109,642,722
0
0
null
null
null
null
UTF-8
C++
false
false
581
h
#include <iostream> #include <string> #include <map> #include <vector> #include <queue> using namespace std; //******************************************************************************************************************** // Class City is to store city information, including city name and x,y-coordinates //******************************************************************************************************************** class City { public: string name; int x; int y; City(string name, int x, int y) { this->name = name; this->x = x; this->y = y; }; };
[ "liutingyun120808@gmail.com" ]
liutingyun120808@gmail.com
1699a8c4fc0fda89e7e6b79a07ecde7790953ea6
fe2836176ca940977734312801f647c12e32a297
/CodeChef/Beginner/TEMPLELA.cpp
454ad14c39c7e165291410b4ea41de671a46a90a
[]
no_license
henrybear327/Sandbox
ef26d96bc5cbcdc1ce04bf507e19212ca3ceb064
d77627dd713035ab89c755a515da95ecb1b1121b
refs/heads/master
2022-12-25T16:11:03.363028
2022-12-10T21:08:41
2022-12-10T21:08:41
53,817,848
2
0
null
null
null
null
UTF-8
C++
false
false
775
cpp
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef pair<int, int> ii; void solve() { int n; scanf("%d", &n); int inp[n], rev[n]; for (int i = 0; i < n; i++) { scanf("%d", &inp[i]); rev[i] = inp[i]; } reverse(rev, rev + n); bool ok = true; if (n % 2 == 0) ok = false; if (inp[0] != 1 || inp[n - 1] != 1) ok = false; for (int i = 1; i < n / 2; i++) if (inp[i] - inp[i - 1] != 1) ok = false; for (int i = n / 2 + 1; i < n; i++) if (inp[i] - inp[i - 1] != -1) ok = false; printf("%s\n", ok ? "yes" : "no"); } int main() { int ncase; scanf("%d", &ncase); while (ncase--) { solve(); } return 0; }
[ "henrybear327@gmail.com" ]
henrybear327@gmail.com
4279ce4a2d8af792353e8533f02b5ed174db04b8
3b9af3c3fa58cb3d4032214e133ef37e7c4d013b
/my_path_server/src/my_path_client.cpp
20231f39ed12830ca4aeb0382b7c9c7f3f908605
[]
no_license
dsb86/ros_packages
be7d2334068c1a16144992bbf711cf33ce9fddbe
2bc28dfc92c6f543e4f97c20afe995ecd8a6c636
refs/heads/master
2021-01-20T01:30:14.512914
2016-05-06T02:40:23
2016-05-06T02:40:23
50,958,549
1
0
null
null
null
null
UTF-8
C++
false
false
3,040
cpp
//path_client: // illustrates how to send a request to the path_service service #include <ros/ros.h> #include <example_ros_service/PathSrv.h> // this message type is defined in the current package #include <iostream> #include <string> #include <nav_msgs/Path.h> #include <geometry_msgs/Pose.h> #include <geometry_msgs/PoseStamped.h> using namespace std; geometry_msgs::Quaternion convertPlanarPhi2Quaternion(double phi) { geometry_msgs::Quaternion quaternion; quaternion.x = 0.0; quaternion.y = 0.0; quaternion.z = sin(phi / 2.0); quaternion.w = cos(phi / 2.0); return quaternion; } int main(int argc, char **argv) { ros::init(argc, argv, "path_client"); ros::NodeHandle n; ros::ServiceClient client = n.serviceClient<example_ros_service::PathSrv>("path_service"); geometry_msgs::Quaternion quat; while (!client.exists()) { ROS_INFO("waiting for service..."); ros::Duration(1.0).sleep(); } ROS_INFO("connected client to service"); example_ros_service::PathSrv path_srv; //create some path points...this should be done by some intelligent algorithm, but we'll hard-code it here geometry_msgs::PoseStamped pose_stamped; geometry_msgs::Pose pose; pose.position.x = 0.0; // say desired x-coord is 1 pose.position.y = 0.0; pose.position.z = 0.0; // let's hope so! pose.orientation.x = 0.0; //always, for motion in horizontal plane pose.orientation.y = 0.0; // ditto pose.orientation.z = 0.0; // implies oriented at yaw=0, i.e. along x axis pose.orientation.w = 1.0; //sum of squares of all components of unit quaternion is 1 pose_stamped.pose = pose; path_srv.request.nav_path.poses.push_back(pose_stamped); // some more poses... quat = convertPlanarPhi2Quaternion(0); // get a quaternion corresponding to this heading pose_stamped.pose.orientation = quat; pose_stamped.pose.position.x=3; pose_stamped.pose.position.y=0.0; path_srv.request.nav_path.poses.push_back(pose_stamped); pose_stamped.pose.position.x=8.0; pose_stamped.pose.position.y=5.0; path_srv.request.nav_path.poses.push_back(pose_stamped); pose_stamped.pose.position.x=4.0; pose_stamped.pose.position.y=7.0; path_srv.request.nav_path.poses.push_back(pose_stamped); pose_stamped.pose.position.x=3.0; pose_stamped.pose.position.y=7.0; path_srv.request.nav_path.poses.push_back(pose_stamped); pose_stamped.pose.position.x=3.0; pose_stamped.pose.position.y=12.0; path_srv.request.nav_path.poses.push_back(pose_stamped); pose_stamped.pose.position.x=0.0; pose_stamped.pose.position.y=12.0; path_srv.request.nav_path.poses.push_back(pose_stamped); /* quat = convertPlanarPhi2Quaternion(3.14); pose_stamped.pose.orientation = quat; //desired position is not updated...just the desired heading path_srv.request.nav_path.poses.push_back(pose_stamped); */ client.call(path_srv); return 0; }
[ "dsb86@case.edu" ]
dsb86@case.edu
3218b878c98fea8e3be178dc2b484cac92af1b2b
520647be9af9b8b4f5ed9f32e53c8fec1407ef8b
/challenge/jun2020/day30.cpp
d950e4e3963ca601acf26ff66894c2b02a295f51
[]
no_license
gxyau/leetcode
0419453affec44a6520859f6a6f07701d204b14d
61e966ab3d6182c9d10a8f8f9aabf2717ea4c23e
refs/heads/master
2021-06-27T00:39:33.544665
2020-09-20T21:15:32
2020-09-20T21:15:32
149,101,979
0
0
null
2020-09-20T21:15:33
2018-09-17T09:34:17
C++
UTF-8
C++
false
false
4,876
cpp
// Day 30, Word Search II #include<iostream> #include<stack> #include<string> #include<unordered_set> #include<vector> using std::cout; using std::endl; using std::string; using std::vector; struct TrieNode { TrieNode* children[26] = {nullptr}; bool end = false; string word; }; class SolutionDay30 { private: TrieNode* root = nullptr; void search_grid(int i, int j, TrieNode* ptr, std::unordered_set<string>& found, vector<vector<int>> visited, vector<vector<char>>& grid) { cout << "Position: " << i << ", " << j << endl; // Index out of bound if (i < 0 || i >= grid.size() || j < 0 || j >= grid[0].size() || visited[i][j] == 1) return; // Move pointer to current character cout << "Character: " << grid[i][j] << endl; visited[i][j] = 1; ptr = ptr->children[grid[i][j]-'a']; // No such word in our word list if (ptr == nullptr) return; // If this is the end of a word in our word list cout << "Is a word? " << ptr->end << endl; if (ptr->end) { cout << "Found word: " << ptr->word << endl; found.insert(ptr->word); } // Recursive call search_grid(i-1, j, ptr, found, visited, grid); search_grid(i+1, j, ptr, found, visited, grid); search_grid(i, j-1, ptr, found, visited, grid); search_grid(i, j+1, ptr, found, visited, grid); } public: vector<string> findWords(vector<vector<char>>& board, vector<string>& words) { int m = board.size(), n = board[0].size(); vector<vector<int>> visited; std::unordered_set<string> found; vector<string> answer; // Inserting words into prefix tree TrieNode* ptr; root = new TrieNode(); for (string word : words) { cout << "Inserting " << word << " into prefix tree." << endl; ptr = root; for (char c : word) { cout << "Character: " << c << endl; if (ptr->children[c-'a'] == nullptr) ptr->children[c-'a'] = new TrieNode(); ptr = ptr->children[c-'a']; } ptr->end = true; ptr->word = word; } cout << endl; // Searching the grid for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { cout << "Starting at position: " << i << ", " << j << endl; cout << "Starting character: " << board[i][j] << endl; visited = vector<vector<int>>(m, vector<int>(n)); ptr = root; search_grid(i, j, ptr, found, visited, board); cout << endl; } } // Return final result answer.assign(found.begin(), found.end()); return answer; } }; int main() { SolutionDay30 sol; vector<vector<char>> board; vector<string> words, answer; // Test case 1 board = {{'o','a','a','n'},{'e','t','a','e'},{'i','h','k','r'},{'i','f','l','v'}}; words = {"oath","pea","eat","rain"}; answer.clear(); // Print board cout << "The board looks like:" << endl; for (auto vec : board) { for (auto x : vec) { cout << x << " "; } cout << endl << endl; } // Print words cout << "Words to search for: "; for (string word : words) cout << word << " "; cout << endl << endl; answer = sol.findWords(board, words); cout << "Found: "; for (string word : answer) cout << word << " "; cout << endl << endl; // Test case 2 board = {{'a','b'},{'c','d'}}; words = {"cdba"}; answer.clear(); // Print board cout << "The board looks like:" << endl; for (auto vec : board) { for (auto x : vec) { cout << x << " "; } cout << endl << endl; } // Print words cout << "Words to search for: "; for (string word : words) cout << word << " "; cout << endl << endl; answer = sol.findWords(board, words); cout << "Found: "; for (string word : answer) cout << word << " "; cout << endl << endl; // Test case 3 board = {{'a','b'},{'c','d'}}; words = {"ab","cb","ad","bd","ac","ca","da","bc","db","adcb","dabc","abb","acb"}; answer.clear(); // Print board cout << "The board looks like:" << endl; for (auto vec : board) { for (auto x : vec) { cout << x << " "; } cout << endl << endl; } // Print words cout << "Words to search for: "; for (string word : words) cout << word << " "; cout << endl << endl; answer = sol.findWords(board, words); cout << "Found: "; for (string word : answer) cout << word << " "; cout << endl << endl; // Compile successful return 0; }
[ "GuoXian.Yau@gmail.com" ]
GuoXian.Yau@gmail.com
ad7f44008afd0cd726ba78533bac571cfd7bb4e7
aa85d0e5cb166680e4264ec9750a8b1d4128fc84
/CS1 and 1080C/Projects/LargePrimeFactor/main.cpp
32bcc039aaaa9f761cf8576200a42d95fba37188
[]
no_license
kavanamw/Data-Structures
78b8e04fa7be6352654ef71e1c69a96e133a406e
7645d0bb4dcc6e6dabe6829311e33d4200d21f14
refs/heads/master
2021-07-17T12:30:13.924987
2017-10-24T18:34:09
2017-10-24T18:34:09
104,476,601
0
0
null
null
null
null
UTF-8
C++
false
false
553
cpp
#include <iostream> #include <stdio.h> #include <cmath> using namespace std; void PrimeFactor(double Num) { cout << Num << endl; while(fmod(Num, 2) == 0) { printf("%d ", 2); cout << "Here"; Num = Num/2; } for(double i = 3.0;i <= sqrt(Num);i+=2) { while(fmod(Num, i) == 0) { printf("%d ", i); Num = Num/i; } } if(Num > 2) { printf("%d ", Num); } } int main() { double Num = 600851475143; PrimeFactor(Num); return 0; }
[ "kavanamw@mail.uc.edu" ]
kavanamw@mail.uc.edu
6344190278a732c0cfb97e41b0e280d5f6602523
dc2656823dcdf9df818402b1e539ea7741663a14
/542_01矩阵.cpp
09ac902b6c99ecbe79b1a438deb8ea5d217b9f7a
[]
no_license
Husaimawx/MyLeetcode
e1dab1191516188a204e9b7868cd129a0b1b4112
eeb6dc934ad2b76b1aca79b43b9da494126c2aca
refs/heads/main
2023-07-29T00:13:14.419480
2021-09-19T05:54:34
2021-09-19T05:54:34
408,043,526
0
0
null
null
null
null
UTF-8
C++
false
false
1,123
cpp
#include <vector> #include <iostream> using namespace std; #define INF 1234567890 class Solution { public: vector<vector<int> > updateMatrix(vector<vector<int> >& mat) { int m = mat.size(); int n = mat[0].size(); vector<vector<int> > dp(m , vector<int>(n, INF)); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (mat[i][j] == 0) { dp[i][j] = 0; } else { if (i > 0) dp[i][j] = min (dp[i][j], dp[i-1][j] + 1); if (j > 0) dp[i][j] = min (dp[i][j], dp[i][j-1] + 1); } } } for (int i = m - 1; i >= 0; i--) { for (int j = n - 1; j >= 0; j--) { if (mat[i][j] != 0) { if (i < m-1) dp[i][j] = min (dp[i][j], dp[i+1][j] + 1); if (j < n-1) dp[i][j] = min (dp[i][j], dp[i][j+1] + 1); } } } return dp; } };
[ "mwx18@mails.tsinghua.edu.cn" ]
mwx18@mails.tsinghua.edu.cn
971eeae8f88896d5a32baba1fb0cb5496ac32291
31f5cddb9885fc03b5c05fba5f9727b2f775cf47
/editor/Qt/5.12.3/clang_64/lib/QtGui.framework/Versions/5/Headers/5.12.3/QtGui/qpa/qplatformintegration.h
1179daeb323ace63509ffbb5c1b8077da93b5037
[ "MIT" ]
permissive
timi-liuliang/echo
2935a34b80b598eeb2c2039d686a15d42907d6f7
d6e40d83c86431a819c6ef4ebb0f930c1b4d0f24
refs/heads/master
2023-08-17T05:35:08.104918
2023-08-11T18:10:35
2023-08-11T18:10:35
124,620,874
822
102
MIT
2021-06-11T14:29:03
2018-03-10T04:07:35
C++
UTF-8
C++
false
false
7,427
h
/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the QtGui module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 3 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL3 included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 3 requirements ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 2.0 or (at your option) the GNU General ** Public license version 3 or any later version approved by the KDE Free ** Qt Foundation. The licenses are as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-2.0.html and ** https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QPLATFORMINTEGRATION_H #define QPLATFORMINTEGRATION_H // // W A R N I N G // ------------- // // This file is part of the QPA API and is not meant to be used // in applications. Usage of this API may make your code // source and binary incompatible with future versions of Qt. // #include <QtGui/qtguiglobal.h> #include <QtGui/qwindowdefs.h> #include <qpa/qplatformscreen.h> #include <QtGui/qsurfaceformat.h> #include <QtGui/qopenglcontext.h> QT_BEGIN_NAMESPACE class QPlatformWindow; class QWindow; class QPlatformBackingStore; class QPlatformFontDatabase; class QPlatformClipboard; class QPlatformNativeInterface; class QPlatformDrag; class QPlatformOpenGLContext; class QGuiGLFormat; class QAbstractEventDispatcher; class QPlatformInputContext; class QPlatformAccessibility; class QPlatformTheme; class QPlatformDialogHelper; class QPlatformSharedGraphicsCache; class QPlatformServices; class QPlatformSessionManager; class QKeyEvent; class QPlatformOffscreenSurface; class QOffscreenSurface; class QPlatformVulkanInstance; class QVulkanInstance; class Q_GUI_EXPORT QPlatformIntegration { public: enum Capability { ThreadedPixmaps = 1, OpenGL, ThreadedOpenGL, SharedGraphicsCache, BufferQueueingOpenGL, WindowMasks, MultipleWindows, ApplicationState, ForeignWindows, NonFullScreenWindows, NativeWidgets, WindowManagement, WindowActivation, // whether requestActivate is supported SyncState, RasterGLSurface, AllGLFunctionsQueryable, ApplicationIcon, SwitchableWidgetComposition, TopStackedNativeChildWindows }; virtual ~QPlatformIntegration() { } virtual bool hasCapability(Capability cap) const; virtual QPlatformPixmap *createPlatformPixmap(QPlatformPixmap::PixelType type) const; virtual QPlatformWindow *createPlatformWindow(QWindow *window) const = 0; virtual QPlatformWindow *createForeignWindow(QWindow *, WId) const { return 0; } virtual QPlatformBackingStore *createPlatformBackingStore(QWindow *window) const = 0; #ifndef QT_NO_OPENGL virtual QPlatformOpenGLContext *createPlatformOpenGLContext(QOpenGLContext *context) const; #endif virtual QPlatformSharedGraphicsCache *createPlatformSharedGraphicsCache(const char *cacheId) const; virtual QPaintEngine *createImagePaintEngine(QPaintDevice *paintDevice) const; // Event dispatcher: virtual QAbstractEventDispatcher *createEventDispatcher() const = 0; virtual void initialize(); virtual void destroy(); //Deeper window system integrations virtual QPlatformFontDatabase *fontDatabase() const; #ifndef QT_NO_CLIPBOARD virtual QPlatformClipboard *clipboard() const; #endif #if QT_CONFIG(draganddrop) virtual QPlatformDrag *drag() const; #endif virtual QPlatformInputContext *inputContext() const; #ifndef QT_NO_ACCESSIBILITY virtual QPlatformAccessibility *accessibility() const; #endif // Access native handles. The window handle is already available from Wid; virtual QPlatformNativeInterface *nativeInterface() const; virtual QPlatformServices *services() const; enum StyleHint { CursorFlashTime, KeyboardInputInterval, MouseDoubleClickInterval, StartDragDistance, StartDragTime, KeyboardAutoRepeatRate, ShowIsFullScreen, PasswordMaskDelay, FontSmoothingGamma, StartDragVelocity, UseRtlExtensions, PasswordMaskCharacter, SetFocusOnTouchRelease, ShowIsMaximized, MousePressAndHoldInterval, TabFocusBehavior, ReplayMousePressOutsidePopup, ItemViewActivateItemOnSingleClick, UiEffects, WheelScrollLines, ShowShortcutsInContextMenus, MouseQuickSelectionThreshold }; virtual QVariant styleHint(StyleHint hint) const; virtual Qt::WindowState defaultWindowState(Qt::WindowFlags) const; virtual Qt::KeyboardModifiers queryKeyboardModifiers() const; virtual QList<int> possibleKeys(const QKeyEvent *) const; virtual QStringList themeNames() const; virtual QPlatformTheme *createPlatformTheme(const QString &name) const; virtual QPlatformOffscreenSurface *createPlatformOffscreenSurface(QOffscreenSurface *surface) const; #ifndef QT_NO_SESSIONMANAGER virtual QPlatformSessionManager *createPlatformSessionManager(const QString &id, const QString &key) const; #endif virtual void sync(); #ifndef QT_NO_OPENGL virtual QOpenGLContext::OpenGLModuleType openGLModuleType(); #endif virtual void setApplicationIcon(const QIcon &icon) const; #if QT_DEPRECATED_SINCE(5, 12) QT_DEPRECATED_X("Use QWindowSystemInterface::handleScreenRemoved") void removeScreen(QScreen *screen); #endif virtual void beep() const; #if QT_CONFIG(vulkan) || defined(Q_CLANG_QDOC) virtual QPlatformVulkanInstance *createPlatformVulkanInstance(QVulkanInstance *instance) const; #endif protected: #if QT_DEPRECATED_SINCE(5, 12) QT_DEPRECATED_X("Use QWindowSystemInterface::handleScreenAdded") void screenAdded(QPlatformScreen *screen, bool isPrimary = false); QT_DEPRECATED_X("Use QWindowSystemInterface::handleScreenRemoved") void destroyScreen(QPlatformScreen *screen); QT_DEPRECATED_X("Use QWindowSystemInterface::handlePrimaryScreenChanged") void setPrimaryScreen(QPlatformScreen *newPrimary); #endif }; QT_END_NAMESPACE #endif // QPLATFORMINTEGRATION_H
[ "qq79402005@gmail.com" ]
qq79402005@gmail.com
0185c54dcf9549a9b50bef30af2aac9ac164a8c4
fc74c5c7f44fbdff161b94a9bb3e2913a350a713
/Classes/Junior Year/January 2019/Assignment 5/Additional Task 1/TUT8/2000/omega
c492cbd9bfa200d7821f62ef5d2c05c26bfc6da1
[]
no_license
cjn1012/Charlie
1158a2e1322904b28e9f523dc21048f148a14fcf
738acb4c7a8330a64619d049ae81cfefdff7b367
refs/heads/master
2021-07-17T10:53:19.810054
2020-05-03T20:40:46
2020-05-03T20:40:46
146,947,278
0
0
null
null
null
null
UTF-8
C++
false
false
36,698
/*--------------------------------*- C++ -*----------------------------------*\ | ========= | | | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | | \\ / O peration | Version: 5.x | | \\ / A nd | Web: www.OpenFOAM.org | | \\/ M anipulation | | \*---------------------------------------------------------------------------*/ /* Windows 32 and 64 bit porting by blueCAPE: http://www.bluecape.com.pt *\ | Based on Windows porting (2.0.x v4) by Symscape: http://www.symscape.com | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class volScalarField; location "2000"; object omega; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [0 0 -1 0 0 0 0]; internalField nonuniform List<scalar> 4000 ( 191.904 191.712 191.521 191.33 191.139 190.948 190.758 190.568 190.378 190.189 190 189.811 189.622 189.434 189.246 189.058 188.871 188.684 188.497 188.31 188.124 187.938 187.752 187.566 187.381 187.196 187.011 186.827 186.643 186.459 186.275 186.092 185.909 185.726 185.544 185.361 185.179 184.998 184.816 184.635 184.454 184.273 184.093 183.913 183.733 183.553 183.374 183.195 183.016 182.838 182.659 182.481 182.303 182.126 181.949 181.772 181.595 181.418 181.242 181.066 180.891 180.715 180.54 180.365 180.19 180.016 179.842 179.668 179.494 179.321 179.147 178.975 178.802 178.629 178.457 178.285 178.114 177.942 177.771 177.6 177.429 177.259 177.089 176.919 176.749 176.58 176.41 176.242 176.073 175.904 175.736 175.568 175.4 175.233 175.065 174.898 174.732 174.565 174.399 174.233 174.067 173.901 173.736 173.571 173.406 173.241 173.077 172.912 172.748 172.585 172.421 172.258 172.095 171.932 171.769 171.607 171.445 171.283 171.121 170.96 170.799 170.638 170.477 170.316 170.156 169.996 169.836 169.677 169.517 169.358 169.199 169.04 168.882 168.724 168.566 168.408 168.25 168.093 167.936 167.779 167.622 167.465 167.309 167.153 166.997 166.842 166.686 166.531 166.376 166.221 166.067 165.912 165.758 165.604 165.451 165.297 165.144 164.991 164.838 164.685 164.533 164.381 164.229 164.077 163.925 163.774 163.623 163.472 163.321 163.171 163.02 162.87 162.72 162.571 162.421 162.272 162.123 161.974 161.825 161.677 161.528 161.38 161.233 161.085 160.937 160.79 160.643 160.496 160.35 160.203 160.057 159.911 159.765 159.619 159.474 159.329 159.184 159.039 158.894 158.75 7.09424 12.8326 17.0335 20.3903 23.1972 25.6078 27.7125 29.5727 31.2298 32.7153 34.0545 35.2675 36.3702 37.3757 38.2948 39.1367 39.9094 40.62 41.2748 41.8789 42.4375 42.9546 43.4341 43.8796 44.294 44.6803 45.041 45.3784 45.6947 45.9919 46.2717 46.5358 46.7856 47.0227 47.2483 47.4636 47.6696 47.8675 48.0581 48.2422 48.4207 48.5943 48.7636 48.9294 49.0921 49.2522 49.4098 49.5655 49.7196 49.8728 50.0252 50.1774 50.3294 50.4818 50.6345 50.788 50.9423 51.0975 51.2539 51.4114 51.5702 51.7303 51.8918 52.0545 52.2185 52.3838 52.5502 52.7177 52.8862 53.0555 53.2254 53.3958 53.5665 53.7373 53.908 54.0782 54.2479 54.4169 54.585 54.7511 54.9135 55.0719 55.226 55.3752 55.5192 55.6574 55.7893 55.9145 56.0323 56.1423 56.244 56.3369 56.4205 56.4944 56.5582 56.6115 56.6539 56.6852 56.7053 56.714 56.7112 56.6971 56.6717 56.6352 56.5881 56.5307 56.4636 56.3874 56.3028 56.2106 56.1116 56.0068 55.897 55.7832 55.6664 55.5475 55.4287 55.3156 55.2096 55.1094 55.0148 54.9256 54.8417 54.763 54.6893 54.6203 54.5559 54.4956 54.4394 54.3869 54.3378 54.2918 54.2487 54.2081 54.1699 54.1337 54.0993 54.0666 54.0351 54.0049 53.9756 53.9472 53.9194 53.8922 53.8654 53.8389 53.8126 53.7865 53.7604 53.7344 53.7083 53.682 53.6557 53.6291 53.6023 53.5752 53.5478 53.5201 53.492 53.4636 53.4347 53.4054 53.3757 53.3455 53.3148 53.2836 53.2519 53.2197 53.187 53.1538 53.12 53.0856 53.0508 53.0153 52.9794 52.9429 52.9058 52.8682 52.8301 52.7914 52.7522 52.7125 52.6723 52.6316 52.5904 52.5487 52.5066 52.4641 52.4213 52.3781 52.3346 52.291 52.2473 52.2035 52.16 52.1165 52.0738 52.031 51.9906 51.9523 1.71405 2.9214 4.04599 5.07149 6.01214 6.88183 7.69088 8.44722 9.15673 9.82424 10.4538 11.0488 11.612 12.1458 12.6522 13.133 13.5898 14.0242 14.4377 14.8313 15.2064 15.5641 15.9052 16.2307 16.5416 16.8386 17.1225 17.3941 17.654 17.9029 18.1414 18.3701 18.5895 18.8001 19.0026 19.1973 19.3846 19.5651 19.7392 19.9071 20.0693 20.226 20.3777 20.5246 20.6671 20.8052 20.9395 21.0699 21.1969 21.3205 21.4411 21.5587 21.6735 21.7857 21.8955 22.0029 22.1082 22.2113 22.3124 22.4117 22.509 22.6046 22.6985 22.7907 22.8813 22.9702 23.0575 23.1432 23.2273 23.3098 23.3906 23.4697 23.547 23.6226 23.6963 23.7681 23.8379 23.9057 23.9714 24.0345 24.0944 24.1512 24.2047 24.2549 24.3016 24.3448 24.3844 24.4202 24.4522 24.4801 24.5041 24.5238 24.5393 24.5505 24.5573 24.5598 24.5579 24.5517 24.5413 24.5267 24.5081 24.4857 24.4595 24.43 24.3973 24.3618 24.3237 24.2835 24.2414 24.1979 24.1533 24.1081 24.0625 24.017 23.9719 23.9274 23.8841 23.8424 23.8029 23.7666 23.7335 23.7034 23.6764 23.6523 23.6308 23.6119 23.5955 23.5815 23.5696 23.5598 23.5518 23.5456 23.541 23.5377 23.5358 23.5351 23.5353 23.5364 23.5383 23.5409 23.544 23.5476 23.5516 23.5559 23.5604 23.565 23.5698 23.5746 23.5794 23.5842 23.5889 23.5935 23.598 23.6023 23.6063 23.6102 23.6138 23.6171 23.6202 23.6229 23.6253 23.6274 23.6292 23.6306 23.6316 23.6323 23.6326 23.6325 23.632 23.6312 23.63 23.6283 23.6263 23.6239 23.6211 23.6178 23.6141 23.6099 23.6053 23.6003 23.5949 23.589 23.5828 23.5762 23.5692 23.5618 23.5541 23.5461 23.5378 23.5292 23.5203 23.5112 23.502 23.4926 23.4832 23.4739 23.4647 23.4558 23.4472 23.4407 1.18432 1.55842 1.95886 2.35883 2.74878 3.12575 3.48915 3.83927 4.17668 4.50206 4.81604 5.11925 5.41224 5.69548 5.96939 6.23435 6.49076 6.73897 6.97929 7.21202 7.43745 7.65585 7.86745 8.07252 8.27128 8.46396 8.65077 8.83192 9.0076 9.17802 9.34336 9.5038 9.6595 9.81064 9.95738 10.0999 10.2383 10.3728 10.5034 10.6304 10.7539 10.8739 10.9906 11.1041 11.2144 11.3218 11.4262 11.5278 11.6266 11.7228 11.8164 11.9075 11.9961 12.0823 12.1661 12.2477 12.327 12.4041 12.479 12.5517 12.6224 12.6909 12.7574 12.8218 12.8841 12.9444 13.0027 13.0589 13.1131 13.1653 13.2154 13.2634 13.3094 13.3533 13.3951 13.4348 13.4724 13.5079 13.5412 13.5723 13.6013 13.628 13.6525 13.6746 13.6945 13.712 13.7272 13.7401 13.7507 13.7589 13.7647 13.7683 13.7695 13.7684 13.7652 13.7597 13.7521 13.7425 13.7309 13.7175 13.7024 13.6856 13.6674 13.6479 13.6273 13.6057 13.5833 13.5603 13.5368 13.5132 13.4894 13.4657 13.4423 13.4193 13.3969 13.3751 13.3542 13.3341 13.3152 13.2974 13.2809 13.2656 13.2518 13.2393 13.2282 13.2185 13.2101 13.203 13.197 13.1921 13.1883 13.1854 13.1834 13.1822 13.1818 13.182 13.1828 13.1842 13.1861 13.1884 13.191 13.194 13.1972 13.2007 13.2044 13.2083 13.2123 13.2164 13.2205 13.2248 13.229 13.2332 13.2375 13.2417 13.2458 13.2499 13.2539 13.2578 13.2615 13.2652 13.2687 13.2721 13.2754 13.2785 13.2814 13.2841 13.2867 13.2891 13.2914 13.2934 13.2953 13.297 13.2984 13.2997 13.3008 13.3017 13.3024 13.303 13.3033 13.3034 13.3033 13.3031 13.3026 13.302 13.3012 13.3002 13.299 13.2977 13.2962 13.2946 13.2929 13.291 13.2891 13.2872 13.2852 13.2833 13.2815 13.2797 13.2785 13.2798 1.06682 1.21676 1.39261 1.58063 1.77322 1.96636 2.15792 2.34681 2.53246 2.71463 2.89319 3.06813 3.23948 3.40728 3.57158 3.73244 3.88994 4.04414 4.19509 4.34285 4.4875 4.62907 4.76763 4.90324 5.03595 5.16582 5.29289 5.41721 5.53885 5.65785 5.77427 5.88814 5.99953 6.10847 6.21502 6.31921 6.42111 6.52075 6.61816 6.7134 6.80649 6.89746 6.98635 7.07318 7.15799 7.24079 7.32162 7.40049 7.47744 7.55247 7.6256 7.69685 7.76622 7.83373 7.89938 7.96318 8.02513 8.08524 8.1435 8.19992 8.25448 8.30719 8.35805 8.40704 8.45417 8.49942 8.54279 8.58427 8.62386 8.66155 8.69734 8.73123 8.76321 8.79328 8.82146 8.84773 8.87211 8.89462 8.91525 8.93401 8.95093 8.96603 8.97931 8.9908 9.00055 9.00856 9.01488 9.01955 9.02258 9.02404 9.02395 9.02238 9.01936 9.01496 9.00924 9.00228 8.99413 8.98489 8.97463 8.96344 8.95141 8.93865 8.92524 8.9113 8.89692 8.88221 8.86727 8.85221 8.83713 8.82211 8.80726 8.79265 8.77836 8.76446 8.75103 8.73811 8.72576 8.71402 8.70294 8.69254 8.68286 8.67389 8.66567 8.65818 8.65142 8.64538 8.64003 8.63536 8.63134 8.62793 8.62509 8.6228 8.62102 8.61971 8.61883 8.61836 8.61826 8.61849 8.61904 8.61988 8.62097 8.62229 8.62382 8.62553 8.6274 8.62941 8.63154 8.63376 8.63607 8.63844 8.64087 8.64333 8.64581 8.6483 8.65079 8.65328 8.65574 8.65818 8.66057 8.66293 8.66524 8.66749 8.66968 8.6718 8.67386 8.67584 8.67773 8.67955 8.68129 8.68293 8.68449 8.68596 8.68733 8.68862 8.68981 8.6909 8.6919 8.69281 8.69363 8.69435 8.69498 8.69552 8.69598 8.69634 8.69663 8.69683 8.69696 8.69702 8.69701 8.69694 8.69683 8.69667 8.69649 8.69631 8.69614 8.69601 8.6959 8.69603 8.69668 8.69982 1.02872 1.09731 1.18402 1.28247 1.38815 1.49805 1.61022 1.72342 1.83688 1.95008 2.06269 2.17449 2.28532 2.39507 2.50366 2.61103 2.71715 2.82197 2.92547 3.02761 3.12839 3.22779 3.32579 3.4224 3.51759 3.61138 3.70375 3.7947 3.88423 3.97234 4.05904 4.14432 4.22819 4.31065 4.39171 4.47137 4.54962 4.62649 4.70196 4.77604 4.84872 4.92001 4.98991 5.05841 5.1255 5.19118 5.25546 5.31831 5.37974 5.43973 5.49827 5.55535 5.61096 5.66509 5.71771 5.76882 5.81841 5.86644 5.91292 5.95782 6.00112 6.04282 6.0829 6.12134 6.15813 6.19326 6.22672 6.2585 6.2886 6.31701 6.34374 6.36878 6.39215 6.41384 6.43387 6.45226 6.46903 6.48419 6.49777 6.5098 6.52031 6.52933 6.53691 6.54307 6.54787 6.55136 6.55357 6.55456 6.55438 6.55308 6.55072 6.54736 6.54305 6.53786 6.53185 6.52509 6.51764 6.50957 6.50095 6.49184 6.48232 6.47246 6.46232 6.45197 6.44148 6.43092 6.42034 6.40981 6.39938 6.38911 6.37904 6.36921 6.35968 6.35046 6.34161 6.33313 6.32506 6.31741 6.31021 6.30345 6.29714 6.29129 6.2859 6.28096 6.27646 6.27239 6.26874 6.26549 6.26263 6.26014 6.25799 6.25618 6.25467 6.25346 6.25251 6.25181 6.25135 6.2511 6.25105 6.25118 6.25148 6.25193 6.25252 6.25324 6.25407 6.25499 6.25601 6.2571 6.25826 6.25947 6.26074 6.26204 6.26339 6.26475 6.26614 6.26753 6.26893 6.27033 6.27172 6.27309 6.27445 6.27578 6.27709 6.27837 6.27961 6.28083 6.282 6.28314 6.28424 6.2853 6.28631 6.28728 6.28821 6.28909 6.28992 6.29072 6.29147 6.29217 6.29283 6.29346 6.29404 6.29458 6.29508 6.29555 6.29598 6.29638 6.29675 6.29709 6.29741 6.29771 6.29799 6.29827 6.29854 6.29881 6.29911 6.29942 6.29982 6.3004 6.30152 6.3053 1.01367 1.0477 1.09348 1.14846 1.21031 1.27715 1.34759 1.42059 1.49539 1.57145 1.64838 1.72587 1.80368 1.88163 1.95957 2.03738 2.11495 2.1922 2.26906 2.34545 2.42133 2.49664 2.57133 2.64537 2.71873 2.79137 2.86327 2.9344 3.00473 3.07425 3.14293 3.21077 3.27773 3.34381 3.40899 3.47326 3.5366 3.59899 3.66043 3.72089 3.78035 3.83882 3.89625 3.95264 4.00797 4.06222 4.11537 4.1674 4.21829 4.26802 4.31656 4.36389 4.40999 4.45483 4.49839 4.54064 4.58157 4.62114 4.65934 4.69615 4.73154 4.76549 4.79799 4.82902 4.85857 4.88663 4.91319 4.93823 4.96178 4.98381 5.00434 5.02337 5.04093 5.05701 5.07165 5.08487 5.09669 5.10714 5.11626 5.12409 5.13066 5.13602 5.14021 5.14328 5.14528 5.14627 5.14629 5.14539 5.14364 5.14109 5.1378 5.13381 5.12919 5.124 5.11829 5.11211 5.10553 5.09859 5.09135 5.08387 5.07619 5.06836 5.06043 5.05246 5.04447 5.03652 5.02864 5.02087 5.01324 5.00578 4.99852 4.99148 4.98469 4.97816 4.9719 4.96594 4.96028 4.95492 4.94987 4.94514 4.94071 4.9366 4.93279 4.92928 4.92607 4.92313 4.92047 4.91808 4.91593 4.91403 4.91235 4.91089 4.90964 4.90857 4.90769 4.90697 4.90641 4.906 4.90572 4.90557 4.90553 4.90559 4.90575 4.90601 4.90634 4.90674 4.9072 4.90772 4.9083 4.90891 4.90957 4.91025 4.91097 4.9117 4.91246 4.91322 4.914 4.91478 4.91556 4.91635 4.91713 4.9179 4.91866 4.91941 4.92015 4.92087 4.92158 4.92226 4.92293 4.92358 4.9242 4.92481 4.9254 4.92597 4.92652 4.92705 4.92757 4.92807 4.92855 4.92902 4.92947 4.92991 4.93034 4.93076 4.93117 4.93157 4.93197 4.93235 4.93274 4.93312 4.9335 4.93388 4.93426 4.93465 4.93506 4.93549 4.93599 4.93665 4.93791 4.94209 1.00704 1.02516 1.05083 1.08333 1.12164 1.16478 1.21183 1.26207 1.31488 1.36976 1.4263 1.48417 1.54309 1.60283 1.6632 1.72404 1.78521 1.84659 1.90807 1.96956 2.03097 2.09225 2.15332 2.21413 2.27464 2.33478 2.39453 2.45385 2.51269 2.57104 2.62885 2.68611 2.74278 2.79884 2.85427 2.90904 2.96312 3.01651 3.06916 3.12106 3.17219 3.22252 3.27202 3.32067 3.36844 3.41532 3.46126 3.50625 3.55026 3.59326 3.63521 3.6761 3.71589 3.75455 3.79206 3.82839 3.8635 3.89739 3.93001 3.96135 3.99139 4.0201 4.04747 4.07349 4.09814 4.12141 4.1433 4.16381 4.18294 4.20069 4.21707 4.23211 4.24581 4.2582 4.2693 4.27914 4.28776 4.29519 4.30148 4.30666 4.31078 4.31388 4.31602 4.31725 4.31761 4.31717 4.31597 4.31407 4.31152 4.30838 4.3047 4.30053 4.29592 4.29093 4.28559 4.27997 4.2741 4.26804 4.26181 4.25547 4.24905 4.24259 4.23612 4.22967 4.22328 4.21698 4.21078 4.20471 4.19878 4.19303 4.18746 4.18209 4.17693 4.17198 4.16726 4.16277 4.15851 4.15448 4.15069 4.14713 4.1438 4.1407 4.13782 4.13515 4.1327 4.13045 4.12839 4.12652 4.12482 4.1233 4.12195 4.12074 4.11968 4.11876 4.11797 4.11729 4.11674 4.11628 4.11593 4.11566 4.11548 4.11538 4.11535 4.11538 4.11547 4.11562 4.11581 4.11605 4.11632 4.11663 4.11697 4.11733 4.11772 4.11812 4.11854 4.11897 4.1194 4.11985 4.1203 4.12074 4.12119 4.12164 4.12208 4.12252 4.12295 4.12338 4.1238 4.12421 4.12462 4.12502 4.12541 4.12579 4.12617 4.12654 4.12691 4.12727 4.12763 4.12798 4.12834 4.12869 4.12905 4.12941 4.12977 4.13013 4.1305 4.13087 4.13124 4.13162 4.132 4.13239 4.13278 4.13318 4.13358 4.13398 4.1344 4.13483 4.13532 4.13598 4.1373 4.14177 1.00403 1.01472 1.03056 1.05156 1.07745 1.10778 1.14203 1.17968 1.22026 1.26332 1.30848 1.35541 1.40381 1.45342 1.50403 1.55544 1.60748 1.66003 1.71294 1.76612 1.81947 1.8729 1.92634 1.97973 2.03299 2.08609 2.13897 2.19159 2.24391 2.29588 2.34749 2.39868 2.44943 2.49972 2.54951 2.59877 2.64748 2.69561 2.74312 2.79001 2.83622 2.88175 2.92656 2.97061 3.01389 3.05636 3.09799 3.13875 3.17861 3.21754 3.25551 3.29249 3.32844 3.36333 3.39714 3.42984 3.46139 3.49177 3.52096 3.54893 3.57566 3.60114 3.62534 3.64825 3.66987 3.69018 3.70918 3.72689 3.74329 3.7584 3.77224 3.78482 3.79616 3.80629 3.81524 3.82305 3.82974 3.83536 3.83996 3.84357 3.84624 3.84804 3.84899 3.84917 3.84861 3.84738 3.84553 3.8431 3.84015 3.83674 3.83291 3.82871 3.82419 3.81939 3.81436 3.80913 3.80376 3.79826 3.79269 3.78708 3.78145 3.77583 3.77025 3.76473 3.7593 3.75397 3.74876 3.74369 3.73877 3.73401 3.72942 3.72502 3.72079 3.71675 3.71291 3.70926 3.7058 3.70253 3.69946 3.69657 3.69386 3.69134 3.68899 3.68682 3.6848 3.68295 3.68125 3.67969 3.67828 3.67699 3.67584 3.6748 3.67388 3.67307 3.67235 3.67173 3.6712 3.67076 3.67039 3.67009 3.66985 3.66968 3.66957 3.6695 3.66948 3.66951 3.66957 3.66967 3.6698 3.66995 3.67013 3.67033 3.67055 3.67078 3.67102 3.67127 3.67153 3.67179 3.67206 3.67233 3.6726 3.67287 3.67314 3.67341 3.67367 3.67393 3.67419 3.67444 3.67469 3.67494 3.67519 3.67544 3.67569 3.67594 3.6762 3.67645 3.67672 3.67698 3.67726 3.67754 3.67783 3.67813 3.67844 3.67876 3.67909 3.67943 3.67977 3.68013 3.68049 3.68086 3.68124 3.68162 3.682 3.68239 3.68278 3.68318 3.68364 3.68426 3.68564 3.69034 1.00284 1.01056 1.02235 1.0385 1.05904 1.08376 1.11234 1.1444 1.17953 1.21732 1.2574 1.29944 1.34313 1.38822 1.43446 1.48166 1.52963 1.57823 1.62732 1.67678 1.72651 1.77642 1.82643 1.87647 1.92647 1.97639 2.02616 2.07574 2.1251 2.17418 2.22295 2.27138 2.31943 2.36707 2.41427 2.46101 2.50724 2.55294 2.59809 2.64265 2.6866 2.72989 2.77252 2.81443 2.85561 2.89602 2.93563 2.97441 3.01233 3.04935 3.08544 3.12057 3.1547 3.18782 3.21987 3.25084 3.2807 3.30942 3.33697 3.36333 3.38848 3.4124 3.43507 3.4565 3.47665 3.49554 3.51316 3.5295 3.54459 3.55843 3.57104 3.58243 3.59263 3.60167 3.60958 3.61639 3.62215 3.62689 3.63067 3.63352 3.6355 3.63666 3.63704 3.63671 3.63571 3.6341 3.63192 3.62924 3.6261 3.62256 3.61866 3.61445 3.60997 3.60527 3.60038 3.59536 3.59022 3.58501 3.57977 3.5745 3.56926 3.56405 3.5589 3.55384 3.54887 3.54402 3.5393 3.53472 3.53029 3.52602 3.52191 3.51798 3.51421 3.51062 3.50721 3.50398 3.50091 3.49803 3.49531 3.49276 3.49037 3.48814 3.48606 3.48414 3.48235 3.48071 3.4792 3.47781 3.47655 3.4754 3.47436 3.47343 3.47259 3.47185 3.47119 3.47062 3.47012 3.46969 3.46933 3.46904 3.46879 3.4686 3.46846 3.46837 3.46831 3.46829 3.4683 3.46834 3.46841 3.4685 3.46861 3.46874 3.46888 3.46904 3.4692 3.46937 3.46955 3.46973 3.46992 3.4701 3.47029 3.47047 3.47065 3.47083 3.47101 3.47119 3.47136 3.47153 3.4717 3.47188 3.47205 3.47223 3.47241 3.47259 3.47278 3.47297 3.47318 3.47339 3.47361 3.47385 3.47409 3.47435 3.47462 3.47491 3.4752 3.47551 3.47583 3.47615 3.47649 3.47684 3.47719 3.47754 3.47789 3.47825 3.47861 3.47898 3.47939 3.47999 3.48139 3.48629 1.00284 1.01058 1.02242 1.03866 1.05932 1.08419 1.11294 1.14517 1.18047 1.21844 1.25868 1.30088 1.34471 1.38993 1.43628 1.48358 1.53165 1.58033 1.62949 1.67901 1.72879 1.77875 1.8288 1.87888 1.92892 1.97886 2.02866 2.07826 2.12764 2.17673 2.22552 2.27396 2.32203 2.36968 2.4169 2.46365 2.50989 2.55561 2.60077 2.64534 2.6893 2.73261 2.77524 2.81717 2.85836 2.89879 2.93841 2.9772 3.01513 3.05216 3.08826 3.1234 3.15755 3.19067 3.22273 3.25371 3.28357 3.31228 3.33983 3.36619 3.39133 3.41524 3.4379 3.4593 3.47943 3.49829 3.51588 3.53219 3.54723 3.56103 3.57358 3.58492 3.59506 3.60403 3.61187 3.61862 3.6243 3.62896 3.63265 3.63542 3.63732 3.63839 3.63868 3.63826 3.63718 3.63548 3.63322 3.63046 3.62725 3.62363 3.61966 3.61539 3.61086 3.60611 3.60119 3.59613 3.59098 3.58575 3.5805 3.57524 3.57001 3.56482 3.55971 3.55468 3.54976 3.54495 3.54029 3.53577 3.5314 3.5272 3.52317 3.51931 3.51562 3.51211 3.50878 3.50562 3.50264 3.49984 3.4972 3.49472 3.49241 3.49026 3.48825 3.4864 3.48468 3.4831 3.48165 3.48032 3.47911 3.47801 3.47702 3.47613 3.47534 3.47463 3.47401 3.47347 3.473 3.47259 3.47226 3.47198 3.47176 3.47158 3.47145 3.47137 3.47132 3.47131 3.47132 3.47137 3.47143 3.47152 3.47163 3.47175 3.47189 3.47204 3.47219 3.47235 3.47251 3.47268 3.47285 3.47301 3.47318 3.47334 3.4735 3.47366 3.47381 3.47396 3.47411 3.47426 3.4744 3.47454 3.47469 3.47483 3.47498 3.47513 3.47529 3.47546 3.47563 3.47581 3.476 3.4762 3.47642 3.47664 3.47688 3.47713 3.4774 3.47767 3.47796 3.47826 3.47856 3.47887 3.47919 3.47951 3.47983 3.48015 3.48048 3.48081 3.48119 3.48176 3.48317 3.48826 1.00403 1.0148 1.03081 1.05211 1.07841 1.10922 1.144 1.18221 1.22335 1.26696 1.31264 1.36004 1.40888 1.45889 1.50986 1.56159 1.61393 1.66674 1.71988 1.77326 1.82679 1.88037 1.93395 1.98745 2.04082 2.09401 2.14698 2.19967 2.25205 2.30408 2.35574 2.40698 2.45779 2.50812 2.55795 2.60726 2.65601 2.70418 2.75174 2.79867 2.84493 2.8905 2.93535 2.97946 3.02278 3.0653 3.10698 3.14779 3.1877 3.22668 3.26469 3.30171 3.3377 3.37264 3.40648 3.43921 3.47079 3.50119 3.53039 3.55836 3.58508 3.61054 3.63471 3.65758 3.67914 3.69939 3.71832 3.73593 3.75222 3.76722 3.78092 3.79335 3.80453 3.81448 3.82324 3.83084 3.83731 3.84271 3.84706 3.85042 3.85284 3.85436 3.85504 3.85494 3.8541 3.85259 3.85047 3.84777 3.84457 3.84092 3.83686 3.83246 3.82775 3.82279 3.81762 3.81228 3.80682 3.80127 3.79566 3.79004 3.78443 3.77886 3.77335 3.76793 3.76261 3.75742 3.75238 3.74748 3.74276 3.73821 3.73384 3.72966 3.72567 3.72187 3.71828 3.71487 3.71166 3.70864 3.70581 3.70317 3.7007 3.69841 3.69628 3.69432 3.69251 3.69085 3.68934 3.68796 3.68671 3.68558 3.68457 3.68367 3.68287 3.68217 3.68156 3.68103 3.68059 3.68022 3.67991 3.67967 3.67949 3.67936 3.67927 3.67924 3.67924 3.67928 3.67935 3.67945 3.67957 3.67971 3.67988 3.68006 3.68025 3.68045 3.68065 3.68086 3.68108 3.68129 3.6815 3.68172 3.68192 3.68212 3.68232 3.68251 3.68269 3.68287 3.68304 3.68321 3.68337 3.68352 3.68368 3.68383 3.68398 3.68413 3.68429 3.68444 3.6846 3.68477 3.68494 3.68513 3.68532 3.68552 3.68572 3.68594 3.68617 3.68641 3.68666 3.68691 3.68718 3.68744 3.68772 3.68799 3.68827 3.68855 3.68883 3.68912 3.68947 3.69001 3.6914 3.69667 1.00703 1.02531 1.05138 1.08451 1.12365 1.16774 1.21584 1.26714 1.32099 1.37687 1.43436 1.4931 1.55284 1.61332 1.67437 1.73581 1.79752 1.85937 1.92127 1.98313 2.04487 2.10644 2.16776 2.22879 2.28948 2.3498 2.4097 2.46915 2.52811 2.58657 2.64449 2.70184 2.75861 2.81476 2.87028 2.92514 2.97931 3.03279 3.08553 3.13753 3.18876 3.23918 3.28879 3.33755 3.38544 3.43243 3.47849 3.5236 3.56773 3.61085 3.65292 3.69393 3.73384 3.77261 3.81023 3.84666 3.88188 3.91585 3.94855 3.97995 4.01003 4.03878 4.06616 4.09217 4.1168 4.14002 4.16184 4.18226 4.20126 4.21887 4.23509 4.24992 4.2634 4.27554 4.28636 4.2959 4.3042 4.31128 4.31719 4.32197 4.32567 4.32834 4.33004 4.33081 4.33071 4.3298 4.32814 4.32578 4.32278 4.31919 4.31508 4.3105 4.30549 4.30013 4.29447 4.28856 4.28245 4.2762 4.26984 4.26342 4.25696 4.25052 4.24411 4.23778 4.23154 4.22543 4.21947 4.21367 4.20805 4.20263 4.19742 4.19243 4.18767 4.18313 4.17883 4.17477 4.17095 4.16735 4.16399 4.16086 4.15795 4.15525 4.15277 4.15048 4.14839 4.14648 4.14475 4.14319 4.14178 4.14053 4.13942 4.13844 4.13759 4.13685 4.13623 4.13571 4.13528 4.13494 4.13468 4.1345 4.13438 4.13433 4.13433 4.13439 4.13449 4.13464 4.13482 4.13503 4.13527 4.13554 4.13583 4.13613 4.13645 4.13677 4.1371 4.13744 4.13777 4.13811 4.13844 4.13876 4.13908 4.13939 4.13969 4.13998 4.14025 4.14051 4.14077 4.141 4.14123 4.14145 4.14166 4.14186 4.14205 4.14223 4.14241 4.14258 4.14275 4.14292 4.14309 4.14325 4.14342 4.1436 4.14377 4.14395 4.14413 4.14432 4.14451 4.1447 4.1449 4.1451 4.1453 4.14551 4.14572 4.14593 4.14615 4.14638 4.14668 4.14717 4.14851 4.15394 1.01362 1.04798 1.09458 1.15082 1.21424 1.28284 1.35509 1.4299 1.50647 1.58423 1.66274 1.74169 1.82085 1.90002 1.97905 2.05784 2.13629 2.21431 2.29184 2.36883 2.44522 2.52098 2.59607 2.67046 2.74412 2.81703 2.88916 2.9605 3.03103 3.10073 3.16958 3.23758 3.30471 3.37095 3.43629 3.50073 3.56423 3.6268 3.68842 3.74907 3.80874 3.86741 3.92506 3.98168 4.03725 4.09175 4.14516 4.19746 4.24862 4.29862 4.34745 4.39507 4.44145 4.48659 4.53043 4.57297 4.61418 4.65403 4.69249 4.72954 4.76515 4.79931 4.832 4.86319 4.89287 4.92102 4.94764 4.97273 4.99626 5.01825 5.03869 5.0576 5.07499 5.09086 5.10524 5.11815 5.12962 5.13968 5.14836 5.15571 5.16176 5.16656 5.17017 5.17262 5.17398 5.1743 5.17364 5.17205 5.16961 5.16637 5.16239 5.15774 5.15248 5.14667 5.14037 5.13365 5.12656 5.11915 5.1115 5.10367 5.09573 5.08773 5.07973 5.07175 5.06385 5.05605 5.0484 5.04092 5.03364 5.02659 5.0198 5.01327 5.00702 5.00107 4.99542 4.99008 4.98505 4.98033 4.97593 4.97183 4.96804 4.96454 4.96133 4.95839 4.95572 4.9533 4.95113 4.94918 4.94746 4.94594 4.94461 4.94346 4.94248 4.94166 4.94098 4.94044 4.94003 4.93973 4.93954 4.93944 4.93944 4.93951 4.93966 4.93987 4.94014 4.94047 4.94084 4.94126 4.9417 4.94218 4.94268 4.9432 4.94374 4.94429 4.94484 4.9454 4.94595 4.9465 4.94704 4.94758 4.94809 4.9486 4.94908 4.94955 4.95 4.95042 4.95083 4.95121 4.95157 4.9519 4.95222 4.95251 4.95278 4.95303 4.95327 4.95348 4.95368 4.95386 4.95403 4.95418 4.95432 4.95445 4.95458 4.95469 4.95479 4.95489 4.95498 4.95507 4.95515 4.95523 4.9553 4.95538 4.95546 4.95554 4.95563 4.95575 4.95594 4.95633 4.95755 4.96311 1.0285 1.09781 1.18631 1.28734 1.39604 1.50914 1.62456 1.74094 1.85743 1.97347 2.08871 2.20291 2.31591 2.42762 2.53795 2.64687 2.75434 2.86035 2.96487 3.06791 3.16947 3.26954 3.36812 3.46523 3.56086 3.65503 3.74775 3.83901 3.92883 4.01722 4.10419 4.18974 4.27388 4.35663 4.43797 4.51794 4.59651 4.67372 4.74954 4.824 4.89709 4.96881 5.03916 5.10813 5.17573 5.24195 5.30678 5.37022 5.43225 5.49287 5.55206 5.6098 5.66609 5.72091 5.77424 5.82607 5.87636 5.92511 5.9723 6.0179 6.06189 6.10425 6.14496 6.18401 6.22138 6.25705 6.29101 6.32324 6.35374 6.38249 6.40951 6.43477 6.45829 6.48007 6.50012 6.51845 6.53508 6.55002 6.56331 6.57496 6.58501 6.5935 6.60046 6.60594 6.60999 6.61265 6.61398 6.61404 6.61289 6.61058 6.6072 6.60279 6.59745 6.59123 6.58421 6.57647 6.56808 6.55912 6.54966 6.53977 6.52952 6.51899 6.50826 6.49745 6.48666 6.47593 6.46532 6.45488 6.44467 6.43472 6.42508 6.41578 6.40686 6.39833 6.39021 6.38253 6.37529 6.36851 6.36217 6.35629 6.35085 6.34585 6.34128 6.33712 6.33336 6.32998 6.32697 6.3243 6.32196 6.31993 6.31818 6.3167 6.31547 6.31447 6.31368 6.31309 6.31267 6.31242 6.31232 6.31236 6.31252 6.3128 6.31317 6.31363 6.31417 6.31479 6.31546 6.31619 6.31696 6.31777 6.31861 6.31948 6.32036 6.32125 6.32215 6.32305 6.32395 6.32484 6.32571 6.32656 6.32739 6.3282 6.32898 6.32972 6.33043 6.3311 6.33174 6.33233 6.33288 6.3334 6.33386 6.33429 6.33467 6.33502 6.33531 6.33557 6.33579 6.33596 6.3361 6.3362 6.33626 6.33629 6.33628 6.33625 6.33618 6.33608 6.33596 6.33581 6.33564 6.33545 6.33525 6.33504 6.33483 6.33462 6.33443 6.33427 6.33418 6.33432 6.33527 6.34092 1.06583 1.21757 1.39781 1.59159 1.79051 1.99005 2.18781 2.38255 2.57364 2.76078 2.94384 3.12282 3.29775 3.4687 3.63576 3.79902 3.95859 4.11455 4.26701 4.41606 4.56179 4.70428 4.84363 4.9799 5.11319 5.24357 5.3711 5.49586 5.61792 5.73733 5.85417 5.96849 6.08035 6.1898 6.2969 6.4017 6.50424 6.60457 6.70274 6.79877 6.89272 6.98462 7.0745 7.1624 7.24833 7.33233 7.41443 7.49463 7.57296 7.64944 7.72408 7.79688 7.86786 7.93702 8.00436 8.06988 8.13358 8.19547 8.25551 8.31373 8.37009 8.42459 8.47722 8.52796 8.57679 8.62372 8.66871 8.71176 8.75285 8.79197 8.82911 8.86426 8.89741 8.92855 8.95766 8.98476 9.00982 9.03286 9.05387 9.07286 9.08983 9.10481 9.1178 9.12883 9.13792 9.14512 9.15045 9.15396 9.15569 9.15571 9.15406 9.15083 9.14607 9.13987 9.1323 9.12346 9.11344 9.10234 9.09025 9.07729 9.06356 9.04917 9.03422 9.01879 9.00298 8.98697 8.97098 8.95515 8.93955 8.92428 8.90939 8.89497 8.88107 8.86774 8.85503 8.84296 8.83157 8.82088 8.81089 8.80162 8.79306 8.78521 8.77804 8.77154 8.76569 8.76046 8.75583 8.75175 8.74821 8.74516 8.74258 8.74042 8.73866 8.73726 8.73619 8.73543 8.73495 8.73471 8.7347 8.73489 8.73526 8.73579 8.73647 8.73726 8.73817 8.73917 8.74026 8.74141 8.74262 8.74388 8.74517 8.74649 8.74782 8.74917 8.75051 8.75185 8.75317 8.75447 8.75574 8.75698 8.75818 8.75933 8.76043 8.76148 8.76246 8.76338 8.76423 8.76502 8.76572 8.76635 8.76691 8.76738 8.76777 8.76808 8.7683 8.76845 8.76851 8.76848 8.76837 8.76819 8.76792 8.76757 8.76714 8.76664 8.76606 8.76542 8.7647 8.76393 8.7631 8.76222 8.76131 8.76036 8.75939 8.75843 8.75748 8.75658 8.75571 8.75512 8.75533 8.76089 1.17901 1.55949 1.97315 2.38845 2.79364 3.18487 3.56126 3.92305 4.27086 4.6054 4.92738 5.2375 5.53638 5.82461 6.10271 6.37119 6.6305 6.88107 7.1233 7.35757 7.58422 7.80358 8.01597 8.22168 8.421 8.61418 8.80148 8.98313 9.15937 9.33041 9.49646 9.65772 9.81436 9.96658 10.1145 10.2584 10.3983 10.5344 10.6669 10.7959 10.9214 11.0437 11.1629 11.279 11.3922 11.5025 11.6101 11.7149 11.8172 11.917 12.0144 12.1093 12.2019 12.2922 12.3803 12.4661 12.5498 12.6314 12.7108 12.7882 12.8634 12.9366 13.0078 13.0768 13.1438 13.2087 13.2715 13.3322 13.3908 13.4472 13.5015 13.5536 13.6035 13.6512 13.6965 13.7395 13.7801 13.8182 13.8538 13.8869 13.9173 13.9452 13.9703 13.9928 14.0125 14.0295 14.0437 14.0552 14.0639 14.0699 14.0732 14.0738 14.0718 14.0673 14.0602 14.0508 14.0392 14.0253 14.0094 13.9917 13.9722 13.9511 13.9287 13.9051 13.8804 13.8549 13.8286 13.8019 13.7751 13.7489 13.7232 13.6982 13.674 13.6508 13.6286 13.6075 13.5876 13.5688 13.5513 13.535 13.5199 13.506 13.4934 13.4819 13.4716 13.4623 13.4541 13.4469 13.4406 13.4352 13.4306 13.4267 13.4235 13.4209 13.4188 13.4173 13.4162 13.4155 13.4152 13.4151 13.4154 13.4158 13.4165 13.4174 13.4183 13.4195 13.4207 13.422 13.4233 13.4247 13.4262 13.4276 13.429 13.4305 13.4319 13.4333 13.4346 13.4359 13.4371 13.4382 13.4393 13.4403 13.4411 13.4419 13.4425 13.4431 13.4435 13.4437 13.4439 13.4438 13.4437 13.4433 13.4429 13.4422 13.4414 13.4405 13.4393 13.4381 13.4366 13.435 13.4332 13.4313 13.4292 13.4269 13.4245 13.4219 13.4193 13.4164 13.4135 13.4104 13.4072 13.404 13.4007 13.3974 13.3941 13.3909 13.3878 13.3848 13.3826 13.387 1.67328 2.92087 4.10161 5.17803 6.16159 7.0667 7.90499 8.68536 9.41471 10.0985 10.7412 11.3466 11.9177 12.4574 12.9681 13.4518 13.9106 14.3462 14.76 15.1537 15.5284 15.8854 16.2259 16.5509 16.8613 17.1581 17.4421 17.714 17.9747 18.2248 18.4649 18.6957 18.9178 19.1315 19.3376 19.5364 19.7283 19.9139 20.0934 20.2673 20.436 20.5996 20.7587 20.9134 21.064 21.2108 21.354 21.4938 21.6304 21.764 21.8949 22.0231 22.1488 22.2721 22.3933 22.5123 22.6292 22.7443 22.8575 22.9689 23.0785 23.1865 23.2927 23.3973 23.5002 23.6015 23.7011 23.7989 23.895 23.9893 24.0818 24.1724 24.261 24.3473 24.4304 24.5105 24.5873 24.6608 24.731 24.7975 24.8604 24.9194 24.9744 25.0252 25.0717 25.1137 25.1512 25.184 25.2119 25.2349 25.2528 25.2657 25.2735 25.2761 25.2737 25.2662 25.2537 25.2364 25.2143 25.1878 25.1571 25.1224 25.084 25.0422 24.9975 24.9501 24.9004 24.8488 24.7954 24.7408 24.6872 24.6352 24.5849 24.5365 24.4903 24.4463 24.4046 24.3653 24.3284 24.294 24.2619 24.2323 24.205 24.18 24.1572 24.1365 24.1178 24.101 24.0859 24.0724 24.0605 24.0499 24.0405 24.0322 24.025 24.0186 24.013 24.008 24.0037 23.9998 23.9964 23.9933 23.9906 23.988 23.9857 23.9835 23.9814 23.9793 23.9774 23.9754 23.9734 23.9714 23.9693 23.9672 23.9649 23.9626 23.9601 23.9576 23.9548 23.952 23.9489 23.9456 23.942 23.9381 23.934 23.9296 23.925 23.92 23.9148 23.9092 23.9034 23.8973 23.8909 23.8841 23.8771 23.8697 23.8621 23.8541 23.8459 23.8373 23.8284 23.8192 23.8097 23.7999 23.7898 23.7794 23.7688 23.7579 23.7468 23.7355 23.724 23.7123 23.7005 23.6887 23.6769 23.6653 23.6538 23.6427 23.6321 23.6297 6.36832 12.8028 17.3519 20.9052 23.8304 26.314 28.4644 30.3514 32.0235 33.5161 34.8562 36.0651 37.1598 38.1547 39.0615 39.8903 40.6496 41.3471 41.9891 42.5815 43.1292 43.6368 44.1082 44.547 44.9563 45.3392 45.6981 46.0355 46.3535 46.6539 46.9385 47.2091 47.4669 47.7133 47.9497 48.177 48.3963 48.6086 48.8148 49.0155 49.2115 49.4036 49.5924 49.778 49.9609 50.1416 50.3206 50.4982 50.675 50.8513 51.0273 51.2034 51.3797 51.5565 51.734 51.9123 52.0915 52.2718 52.4532 52.6357 52.8194 53.0043 53.1902 53.3772 53.5651 53.7539 53.9434 54.1336 54.3241 54.5149 54.7059 54.897 55.0882 55.2786 55.4661 55.6506 55.8316 56.0087 56.1817 56.3499 56.5128 56.6701 56.821 56.9652 57.1021 57.2311 57.3518 57.4636 57.5661 57.6587 57.7411 57.8128 57.8735 57.9227 57.9602 57.9857 57.9991 58.0003 57.9892 57.9658 57.9304 57.8831 57.8244 57.7547 57.6745 57.5846 57.4856 57.3783 57.2635 57.1414 57.0119 56.878 56.7471 56.6207 56.4987 56.3813 56.2685 56.1605 56.0572 55.9586 55.8646 55.775 55.6898 55.6087 55.5317 55.4586 55.3892 55.3233 55.2606 55.201 55.1442 55.09 55.0382 54.9885 54.9407 54.8946 54.85 54.8068 54.7647 54.7236 54.6834 54.6439 54.605 54.5666 54.5286 54.491 54.4537 54.4165 54.3796 54.3427 54.306 54.2693 54.2326 54.1959 54.1592 54.1224 54.0855 54.0486 54.0115 53.9743 53.937 53.8994 53.8617 53.8238 53.7857 53.7473 53.7086 53.6697 53.6305 53.5909 53.5511 53.5109 53.4703 53.4293 53.388 53.3463 53.3042 53.2616 53.2186 53.1752 53.1314 53.0872 53.0425 52.9974 52.9519 52.906 52.8597 52.8131 52.7662 52.719 52.6716 52.6242 52.5767 52.5292 52.482 52.435 52.3888 52.3424 52.2986 52.2659 191.923 191.731 191.54 191.349 191.158 190.967 190.777 190.587 190.397 190.208 190.019 189.83 189.641 189.453 189.265 189.077 188.89 188.702 188.516 188.329 188.143 187.956 187.771 187.585 187.4 187.215 187.03 186.846 186.661 186.478 186.294 186.111 185.927 185.745 185.562 185.38 185.198 185.016 184.835 184.653 184.472 184.292 184.111 183.931 183.751 183.572 183.392 183.213 183.034 182.856 182.678 182.499 182.322 182.144 181.967 181.79 181.613 181.437 181.26 181.084 180.909 180.733 180.558 180.383 180.208 180.034 179.86 179.686 179.512 179.339 179.165 178.992 178.82 178.647 178.475 178.303 178.132 177.96 177.789 177.618 177.447 177.277 177.107 176.937 176.767 176.597 176.428 176.259 176.09 175.922 175.754 175.586 175.418 175.25 175.083 174.916 174.749 174.582 174.416 174.25 174.084 173.919 173.753 173.588 173.423 173.258 173.094 172.93 172.766 172.602 172.438 172.275 172.112 171.949 171.787 171.624 171.462 171.3 171.138 170.977 170.816 170.655 170.494 170.334 170.173 170.013 169.853 169.694 169.534 169.375 169.216 169.057 168.899 168.741 168.582 168.425 168.267 168.11 167.952 167.795 167.639 167.482 167.326 167.17 167.014 166.858 166.703 166.548 166.393 166.238 166.083 165.929 165.775 165.621 165.467 165.314 165.16 165.007 164.854 164.702 164.549 164.397 164.245 164.093 163.942 163.79 163.639 163.488 163.337 163.187 163.037 162.886 162.737 162.587 162.437 162.288 162.139 161.99 161.841 161.693 161.545 161.397 161.249 161.101 160.954 160.806 160.659 160.512 160.366 160.219 160.073 159.927 159.781 159.635 159.49 159.345 159.2 159.055 158.91 158.766 ) ; boundaryField { walls { Cmu 0.09; kappa 0.41; E 9.8; beta1 0.075; blended false; type omegaWallFunction; value nonuniform List<scalar> 400 ( 191.904 191.712 191.521 191.33 191.139 190.948 190.758 190.568 190.378 190.189 190 189.811 189.622 189.434 189.246 189.058 188.871 188.684 188.497 188.31 188.124 187.938 187.752 187.566 187.381 187.196 187.011 186.827 186.643 186.459 186.275 186.092 185.909 185.726 185.544 185.361 185.179 184.998 184.816 184.635 184.454 184.273 184.093 183.913 183.733 183.553 183.374 183.195 183.016 182.838 182.659 182.481 182.303 182.126 181.949 181.772 181.595 181.418 181.242 181.066 180.891 180.715 180.54 180.365 180.19 180.016 179.842 179.668 179.494 179.321 179.147 178.975 178.802 178.629 178.457 178.285 178.114 177.942 177.771 177.6 177.429 177.259 177.089 176.919 176.749 176.58 176.41 176.242 176.073 175.904 175.736 175.568 175.4 175.233 175.065 174.898 174.732 174.565 174.399 174.233 174.067 173.901 173.736 173.571 173.406 173.241 173.077 172.912 172.748 172.585 172.421 172.258 172.095 171.932 171.769 171.607 171.445 171.283 171.121 170.96 170.799 170.638 170.477 170.316 170.156 169.996 169.836 169.677 169.517 169.358 169.199 169.04 168.882 168.724 168.566 168.408 168.25 168.093 167.936 167.779 167.622 167.465 167.309 167.153 166.997 166.842 166.686 166.531 166.376 166.221 166.067 165.912 165.758 165.604 165.451 165.297 165.144 164.991 164.838 164.685 164.533 164.381 164.229 164.077 163.925 163.774 163.623 163.472 163.321 163.171 163.02 162.87 162.72 162.571 162.421 162.272 162.123 161.974 161.825 161.677 161.528 161.38 161.233 161.085 160.937 160.79 160.643 160.496 160.35 160.203 160.057 159.911 159.765 159.619 159.474 159.329 159.184 159.039 158.894 158.75 191.923 191.731 191.54 191.349 191.158 190.967 190.777 190.587 190.397 190.208 190.019 189.83 189.641 189.453 189.265 189.077 188.89 188.702 188.516 188.329 188.143 187.956 187.771 187.585 187.4 187.215 187.03 186.846 186.661 186.478 186.294 186.111 185.927 185.745 185.562 185.38 185.198 185.016 184.835 184.653 184.472 184.292 184.111 183.931 183.751 183.572 183.392 183.213 183.034 182.856 182.678 182.499 182.322 182.144 181.967 181.79 181.613 181.437 181.26 181.084 180.909 180.733 180.558 180.383 180.208 180.034 179.86 179.686 179.512 179.339 179.165 178.992 178.82 178.647 178.475 178.303 178.132 177.96 177.789 177.618 177.447 177.277 177.107 176.937 176.767 176.597 176.428 176.259 176.09 175.922 175.754 175.586 175.418 175.25 175.083 174.916 174.749 174.582 174.416 174.25 174.084 173.919 173.753 173.588 173.423 173.258 173.094 172.93 172.766 172.602 172.438 172.275 172.112 171.949 171.787 171.624 171.462 171.3 171.138 170.977 170.816 170.655 170.494 170.334 170.173 170.013 169.853 169.694 169.534 169.375 169.216 169.057 168.899 168.741 168.582 168.425 168.267 168.11 167.952 167.795 167.639 167.482 167.326 167.17 167.014 166.858 166.703 166.548 166.393 166.238 166.083 165.929 165.775 165.621 165.467 165.314 165.16 165.007 164.854 164.702 164.549 164.397 164.245 164.093 163.942 163.79 163.639 163.488 163.337 163.187 163.037 162.886 162.737 162.587 162.437 162.288 162.139 161.99 161.841 161.693 161.545 161.397 161.249 161.101 160.954 160.806 160.659 160.512 160.366 160.219 160.073 159.927 159.781 159.635 159.49 159.345 159.2 159.055 158.91 158.766 ) ; } inlet { type fixedValue; value uniform 1; } outlet { type freestream; freestreamValue uniform 1; value nonuniform List<scalar> 20 ( 158.75 51.9523 23.4407 13.2798 8.69982 6.3053 4.94209 4.14177 3.69034 3.48629 3.48826 3.69667 4.15394 4.96311 6.34092 8.76089 13.387 23.6297 52.2659 158.766 ) ; } frontAndBack { type empty; } } // ************************************************************************* //
[ "39833752+cjn1012@users.noreply.github.com" ]
39833752+cjn1012@users.noreply.github.com
aa1cacdd726a91136919bb28d8434483ae571509
2232c179ab4aafbac2e53475447a5494b26aa3fb
/src/common/MPI/MPISend.hpp
3d63200decd79e333c266e1b54492e4d7ac69d63
[]
no_license
martinv/pdekit
689986d252d13fb3ed0aa52a0f8f6edd8eef943c
37e127c81702f62f744c11cc2483869d8079f43e
refs/heads/master
2020-03-31T09:24:32.541648
2018-10-08T15:23:43
2018-10-08T15:23:43
152,095,058
1
0
null
null
null
null
UTF-8
C++
false
false
979
hpp
#ifndef PDEKIT_Common_MPI_MPI_SEND_HPP #define PDEKIT_Common_MPI_MPI_SEND_HPP #include <vector> #include "common/MPI/MPITypes.hpp" #include "common/PDEKit.hpp" namespace pdekit { namespace common { namespace mpi { namespace internal { template <typename T> class Send; template <typename T> class Send<std::vector<T>> { public: static int execute(const std::vector<T> &data, int destination, int tag, MPI_Comm communicator) { int size = data.size(); MPI_Send(&size, 1, MPI_INT, destination, tag, communicator); return MPI_Send(data.data(), size, MPITypes<T>::type, destination, tag, communicator); } }; } // namespace internal // Free wrapper function around MPI send - calls internal implementation template <typename T> int send(const T &data, int destination, int tag, MPI_Comm communicator) { return internal::Send<T>::execute(data, destination, tag, communicator); } } // namespace mpi } // namespace common } // namespace pdekit #endif
[ "martin.vymazal@gmail.com" ]
martin.vymazal@gmail.com
81eb246d2c50abbebcac8f644ef082b26ddfe2bd
42c9fc81ffbdb22bfde3976578337a1fe5f17c2a
/visualization/hdmap_pub/hdmap_viewer/src/view.cpp
af61de22546c657363243e6bc0336fd1ac0d9bd7
[ "MIT" ]
permissive
LiuFG/UpdatingHDmapByMonoCamera
988524461287bfa8b663cba756a787e4440268ef
dc8f06795a12669da1a8096e38851f78b2e26a62
refs/heads/master
2022-06-01T08:33:53.034821
2020-04-26T05:32:38
2020-04-26T05:32:38
258,131,871
0
0
MIT
2020-04-26T05:32:43
2020-04-23T07:49:14
Python
UTF-8
C++
false
false
3,432
cpp
// // Created by lfg on 19-8-1. // #include "view.h" View::Viewer():pcl::visualization::PCLVisualizer ("3D Viewer") { // viewer=boost::shared_ptr<pcl::visualization::PCLVisualizer>(new pcl::visualization::PCLVisualizer ("3D Viewer")); pcl::visualization::PCLVisualizer::setBackgroundColor (0, 0, 0); pcl::visualization::PCLVisualizer::initCameraParameters (); pcl::visualization::PCLVisualizer::addCoordinateSystem (0.5); } void Viewer::addCoordinateSystem(float x,float y, float z, std::string id) { pcl::visualization::PCLVisualizer::addCoordinateSystem(0.5,x,y,z,id+"CoordinateSystem",0); } void Viewer::addPointCloud(pcl::PointCloud< pcl::PointXYZRGBA >::Ptr cloud, std::string id, int r, int g, int b ) { // pcl::PointCloud< pcl::PointXYZRGBA >::Ptr out; // out = copy_pointcloud(cloud); if(r==0 and b==0 and g==0) { pcl::visualization::PointCloudColorHandlerRGBField<pcl::PointXYZRGBA> rgb(cloud); if (!pcl::visualization::PCLVisualizer::addPointCloud<pcl::PointXYZRGBA> (cloud, rgb, id)) pcl::visualization::PCLVisualizer::updatePointCloud(cloud, id); } else { pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZRGBA> rgb (cloud, r, g, b); if (!pcl::visualization::PCLVisualizer::addPointCloud<pcl::PointXYZRGBA> (cloud, rgb, id)) pcl::visualization::PCLVisualizer::updatePointCloud(cloud, id); } } // void Viewer::removePointCloud(std::string id) // { // pcl::visualization::PCLVisualizer::removePointCloud(id,0); // } // void Viewer::removeCoordinateSystem(std::string id) // { // pcl::visualization::PCLVisualizer::removeCoordinateSystem(id,0); // } void Viewer::update() { pcl::visualization::PCLVisualizer::spinOnce (10); } void Viewer::drawBoundingBox(pcl::PointCloud< pcl::PointXYZRGBA >::Ptr cloud, std::string id) { float min_x, max_x, min_y, max_y, min_z, max_z; getBoundingBox(cloud, min_x, max_x, min_y, max_y, min_z, max_z); pcl::PointXYZ pt1 (min_x, min_y, min_z); pcl::PointXYZ pt2 (min_x, min_y, max_z); pcl::PointXYZ pt3 (max_x, min_y, max_z); pcl::PointXYZ pt4 (max_x, min_y, min_z); pcl::PointXYZ pt5 (min_x, max_y, min_z); pcl::PointXYZ pt6 (min_x, max_y, max_z); pcl::PointXYZ pt7 (max_x, max_y, max_z); pcl::PointXYZ pt8 (max_x, max_y, min_z); pcl::visualization::PCLVisualizer::addLine (pt1, pt2, 1.0, 0.0, 0.0, "line_1" + id ); pcl::visualization::PCLVisualizer::addLine (pt1, pt4, 1.0, 0.0, 0.0, "line_2" + id ); pcl::visualization::PCLVisualizer::addLine (pt1, pt5, 1.0, 0.0, 0.0, "line_3" + id ); pcl::visualization::PCLVisualizer::addLine (pt5, pt6, 1.0, 0.0, 0.0, "line_4" + id ); pcl::visualization::PCLVisualizer::addLine (pt5, pt8, 1.0, 0.0, 0.0, "line_5" + id ); pcl::visualization::PCLVisualizer::addLine (pt2, pt6, 1.0, 0.0, 0.0, "line_6" + id ); pcl::visualization::PCLVisualizer::addLine (pt6, pt7, 1.0, 0.0, 0.0, "line_7" + id ); pcl::visualization::PCLVisualizer::addLine (pt7, pt8, 1.0, 0.0, 0.0, "line_8" + id ); pcl::visualization::PCLVisualizer::addLine (pt2, pt3, 1.0, 0.0, 0.0, "line_9" + id ); pcl::visualization::PCLVisualizer::addLine (pt4, pt8, 1.0, 0.0, 0.0, "line_10" + id ); pcl::visualization::PCLVisualizer::addLine (pt3, pt4, 1.0, 0.0, 0.0, "line_11" + id ); pcl::visualization::PCLVisualizer::addLine (pt3, pt7, 1.0, 0.0, 0.0, "line_12" + id ); }
[ "2022087641@qq.com" ]
2022087641@qq.com
f955f1fd3ce31b1176aa1b49e0749e6a1f070310
a3e1a101673c56e4ced1b5600612b25b145eb472
/beakjoon_algorithm/beakjoon_algorithm/CodingInterview/2-2 STL 뒤에서 k번째 원소 구하기.cpp
6eb57f9d92c568017536231515783faf3b67de5e
[]
no_license
gwanhyeon/algorithm_study
a95f3f2d559899f734b52d2d6e89d5f0125cebdf
f01af94919946e5adbdd7cb688cc2c1cf54cbbdc
refs/heads/master
2022-01-07T21:34:56.297147
2021-12-29T16:02:02
2021-12-29T16:02:02
162,471,977
0
0
null
null
null
null
UTF-8
C++
false
false
832
cpp
// // 2-2 STL 뒤에서 k번째 원소 구하기.cpp // beakjoon_algorithm // // Created by kgh on 08/07/2019. // Copyright © 2019 kgh. All rights reserved. // /* 뒤에서 k번째 원소를 구하기: 단방향 연결리스트가 주어졌을때 뒤에서 k번째 원소를 찾는 알고리즘을 구현하라. */ #include <stdio.h> #include <iostream> #include <forward_list> using namespace std; bool single_digit (const int& value) { return (value<10); } int main(void){ forward_list<int> f_list; auto iter = f_list.before_begin(); int n = 5; for(int i=0; i<n; i++){ iter = f_list.insert_after(iter,i); } int cnt = 0; int k=0; for(iter = f_list.begin(); iter != f_list.end(); iter++){ } return 0; }
[ "kgh940525@gmail.com" ]
kgh940525@gmail.com
905dd71a8dcfcbcaf6f5a72baefd7a95aafab56d
2bf4a058f72b5d81a3b575aee2d413b6cff865ae
/test/graph/graph_property.cpp
c4065f062693358b4e9ba30e9baf789fa271ebf7
[ "MIT" ]
permissive
StHamish/alglib
7be6b48017c352ef879cc0ca3e386a928d4f8f6a
464441c26ff802e0c7eb58106201c840dc37047b
refs/heads/master
2022-03-28T08:33:02.095101
2015-09-02T11:28:15
2015-09-02T11:28:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
839
cpp
#include <alglib/graph/directed_graph.h> #include <alglib/graph/graph_property.h> #include <bits/stdc++.h> using namespace std; using namespace alglib::graph; int main() { typedef directed_graph<string> GraphT; // A social network of people GraphT graph; graph.add_vertex("A"); graph.add_vertex("B"); graph.add_vertex("C"); graph.add_vertex("D"); // Property on each vertex: let us say the age of each person vertex_property<GraphT, int> P(graph); P["A"] = 10; P["B"] = 20; P["C"] = 30; P["D"] = 40; // make all property one P.bulk_update(graph.vbegin(), graph.vend(), 100); //! P["E"] = 50; // Causes exception to be thrown for(auto it = graph.vbegin(); it != graph.vend(); it++) cout << "Age of person: " << *it << " is: " << P(*it) << endl; }
[ "divkakwani@gmail.com" ]
divkakwani@gmail.com
85d940f30178a77436c77fec7ee38659a92f4d52
8d6d47d97f2889c213da13372c552ba66f4664d0
/simulation/g4simulation/g4histos/G4ScintillatorTowerTTree.cc
0b5287e83fdd44afc3ba929d8b3d979b19e301c4
[]
no_license
mccumbermike/coresoftware
bf440bd90e183bd668d9cf95f855ddf46812a0a4
cfe8912e9b362b2bee6cda6d051facde7b220828
refs/heads/master
2020-04-05T04:17:52.396368
2016-11-30T02:40:37
2016-11-30T02:40:37
41,013,413
1
0
null
2015-08-19T04:33:04
2015-08-19T04:33:04
null
UTF-8
C++
false
false
2,705
cc
#include "G4ScintillatorTowerTTree.h" #include "G4RootScintillatorTowerContainer.h" #include "G4RootScintillatorTower.h" #include <g4cemc/RawTowerContainer.h> #include <g4cemc/RawTower.h> #include <fun4all/Fun4AllHistoManager.h> #include <phool/PHCompositeNode.h> #include <phool/getClass.h> #include <TH1.h> #include <TH2.h> #include <TSystem.h> using namespace std; G4ScintillatorTowerTTree::G4ScintillatorTowerTTree(const std::string &name): SubsysReco(name), savetowers(1), evtno(0), hm(NULL) {} int G4ScintillatorTowerTTree::Init(PHCompositeNode *topNode) { if (!_detector.size()) { cout << "Detector not set via Detector(<name>) method" << endl; cout << "(it is the name appended to the G4TOWER_<name> nodename)" << endl; cout << "you do not want to run like this, exiting now" << endl; gSystem->Exit(1); } hm = new Fun4AllHistoManager("SCINTILLATORTOWERHIST"); etot_hist = new TH1F("etot", "total deposited energy", 200, 0, 20); hm->registerHisto(etot_hist); PHNodeIterator iter(topNode); PHCompositeNode *dstNode = dynamic_cast<PHCompositeNode *>(iter.findFirst("PHCompositeNode", "DST")); G4RootScintillatorTowerContainer *towers = new G4RootScintillatorTowerContainer(); PHIODataNode<PHObject> *node = new PHIODataNode<PHObject>(towers, _outnodename.c_str(), "PHObject"); dstNode->addNode(node); evtno = 0; return 0; } int G4ScintillatorTowerTTree::process_event(PHCompositeNode *topNode) { evtno++; G4RootScintillatorTowerContainer *towers = findNode::getClass<G4RootScintillatorTowerContainer>(topNode, _outnodename.c_str()); RawTowerContainer *g4towers = findNode::getClass<RawTowerContainer>(topNode, _towernodename.c_str()); if (! g4towers) { cout << "could not find " << _towernodename << endl; gSystem->Exit(1); } RawTowerContainer::ConstRange tower_range = g4towers->getTowers(); double etot = 0; for ( RawTowerContainer::ConstIterator tower_iter = tower_range.first ; tower_iter != tower_range.second; tower_iter++ ) { RawTower *intower = tower_iter->second; if (savetowers) { towers->AddTower(*intower); } etot += intower->get_energy(); } etot_hist->Fill(etot); towers->set_etotal(etot); towers->set_event(evtno); return 0; } int G4ScintillatorTowerTTree::End(PHCompositeNode *topNode) { hm->dumpHistos(_histofilename); delete hm; return 0; } void G4ScintillatorTowerTTree::Detector(const std::string &det) { _detector = det; _outnodename = "G4RootScintillatorTower_" + det; _towernodename = "TOWER_" + det; if (!_histofilename.size()) { _histofilename = "ScintillatorTowerHistos_" + det + ".root"; } }
[ "pinkenburg@bnl.gov" ]
pinkenburg@bnl.gov
85b499194037a04c07f6a4950b7b42e40b1e3c55
2e2e21c86b556242c118c6c11258d3bf2d744b13
/mastering_ros_demo_pkg/src/demo_service_server.cpp
ed2727d2b0d74c9b76ecabdbe75a02c1a23cf956
[]
no_license
lothek-ros/mastering_ros_demo_package
fbaa99247bc453f28fc635e541c182b8951d294d
9b642b13300c2e502003f94361c83b5c552a7f83
refs/heads/master
2022-12-23T20:24:32.129070
2020-09-21T06:19:11
2020-09-21T06:19:11
297,246,336
0
0
null
null
null
null
UTF-8
C++
false
false
1,331
cpp
#include "ros/ros.h" //generated header, contains our service definition and we can use this in our code #include "mastering_ros_demo_pkg/demo_srv.h" #include <iostream> #include <sstream> //for getting string streaming classes using namespace std; //this is the server callback fuction executed when a request is received on the server. //the server can receive the request from clients with a message type of req & res bool demo_service_callback( mastering_ros_demo_pkg::demo_srv::Request &req, mastering_ros_demo_pkg::demo_srv::Response &res ) { std::stringstream ss; //"Received Here" is passing to the service response instance. ss << "Received Here"; //out is the field name of the response that we have given in demo_srv.srv //this response will to to the service client node res.out = ss.str(); ROS_INFO("From Client [%s], Server says [%s]", req.in.c_str(), res.out.c_str() ); } int main (int argc, char **argv) { ros::init(argc, argv, "demo_service_server"); ros::NodeHandle n; //this creates a service called demo_servie and a callback function is executed when a req comes to this service. the callback function is demo_service_callback ros::ServiceServer service = n.advertiseService ("demo_service", demo_service_callback); ROS_INFO("Ready to receive from client."); ros::spin(); return 0; }
[ "noreply@github.com" ]
noreply@github.com
034187bbde7455854ee725dbd5fcaa8eb13fe344
91ea1cd56059b9a87a963e9097770e74c0a139a4
/mycodes/codes/duplicate.cpp
cdd5c4739d1e1b55e26714ccdf675e0466af5149
[]
no_license
farhan0581/codes
37cce0040ef27e93e0558e6d76940da6782786a7
582e3ab57d8e8b22ad2617fd6818f748d6ce481b
refs/heads/master
2016-08-11T06:32:47.887322
2015-09-03T05:43:50
2015-09-03T05:43:50
36,889,344
0
0
null
null
null
null
UTF-8
C++
false
false
664
cpp
#include<stdio.h> #include<conio.h> #include<math.h> float f(float x) { //float res; return pow((pow(x,4)+pow(x,3)-pow(x,2)+7*x),0.5); //return res; } main() { float ll,ul,ih[20],h,sum,y[20]; int n,i,j,k=0,p; // clrscr(); printf("Enter lower limit,upper limit,n: "); scanf("%f%f%d",&ll,&ul,&n); for(i=0;i<=n;i++) { p=pow(2,i); h=(ul-ll)/p; y[0]=1; y[p]=f(ul); sum=y[0]+y[p]; for(j=1;j<p;j++) sum=sum+2*f(ll+j*h); ih[i]=(sum*h)/2; } while(n>0) { k=2; p=pow(k,2); for(i=0;i<n;i++) ih[i]=(p*ih[i+1]-ih[i])/(p-1); k=k+2; n--; } printf("\n\nResult is: %f",ih[0]); // getch(); }
[ "root@farhan.com" ]
root@farhan.com
64a7d22c32a7bfb8f7190533eb95866436cb999e
2639a3aa6e7632512e35fa4555ad42e1838297fb
/Engine/Lib/include/kern/graphics/ICamera.h
7da7b99616dfafe58af3746ee5471a0166fc8bda
[]
no_license
redagito/KernEngine
682e6e4fb344ba64884ebc26c4be9283da69df37
206f5257b708775b34e29f3f95252b17ff66b36b
refs/heads/master
2023-09-01T08:52:36.837680
2023-09-01T01:27:58
2023-09-01T01:27:58
75,782,333
3
0
null
2022-01-03T07:18:26
2016-12-07T00:00:30
C++
UTF-8
C++
false
false
1,596
h
#pragma once #include <glm/glm.hpp> enum class FogType { None, Linear, Exp, Exp2 }; enum class RenderMode { Final, Color, Depth, Normals, Lights, GodRay }; struct SFeatureInfo { FogType fogType = FogType::None; bool fogActive = false; // TODO Use this flag instead FogType::NONE float fogBegin = 0.f; float fogEnd = 0.f; float fogDensity = 0.f; RenderMode renderMode = RenderMode::Final; bool shadowsActive = true; bool frustumCullingActive = true; /**< View frustum culling enabled flag. */ bool dofActive = true; float dofNearFocus = 0.5f; float dofNearBlur = 0.1f; float dofFarFocus = 10.f; float dofFarBlur = 150.f; bool fxaaActive = true; bool lenseFlareActive = false; bool godRayActive = false; bool toonActive = false; bool bloomActive = false; bool normalMappingActive = true; // Hackyyy mutable unsigned int culledObjectCount = 0; }; /** * \brief Camera interface class. */ class ICamera { public: virtual ~ICamera(); /** * \brief Returns view matrix. */ virtual const glm::mat4 &getView() const = 0; /** * \brief Returns projection matrix. */ virtual const glm::mat4 &getProjection() const = 0; virtual const glm::vec3 &getPosition() const = 0; // TODO extract functionality to a better place virtual SFeatureInfo &getFeatureInfoForWrite() { return m_info; } // TODO Rename virtual const SFeatureInfo &getFeatureInfo() const { return m_info; } private: SFeatureInfo m_info; };
[ "agitodev@gmail.com" ]
agitodev@gmail.com
70535f79374ef478918a8ca36af596c836908a77
0ab797536a86e1a535947d98ae9abdf10a2fc802
/MainMenu.cpp
d32f90ac75e77b765301800e17e84b54e41093ab
[]
no_license
mehdiRoohani/SpaceshipsBattle
899a49f3a9fb53fb24c490c823f3a802dfcba39c
7bda6922cc51d17dddba697907fdc8446642bb63
refs/heads/master
2020-03-22T17:20:45.776643
2018-07-10T06:54:36
2018-07-10T06:54:36
140,389,805
0
0
null
null
null
null
UTF-8
C++
false
false
2,675
cpp
#include "MainMenu.h" MainMenu::MainMenu() : DrawScreen() { } MainMenu::MainMenu(Texture* image,Texture* image1, Point pos):DrawScreen(image,pos) { NG = new Button(image1,pos.shift((spriteClips.w/2),(spriteClips.h/2)-50), "New Game"); LG = new Button(image1,pos.shift((spriteClips.w/2),(spriteClips.h/2)), "load Game"); Qut = new Button(image1,pos.shift((spriteClips.w/2),(spriteClips.h/2)+50), "Quit"); if(NG->returnNoOfLetter()>LG->returnNoOfLetter() && NG->returnNoOfLetter()>Qut->returnNoOfLetter()) maxNoOfL=NG->returnNoOfLetter(); else if(LG->returnNoOfLetter()>NG->returnNoOfLetter() && LG->returnNoOfLetter()>Qut->returnNoOfLetter()) maxNoOfL=LG->returnNoOfLetter(); else if(Qut->returnNoOfLetter()>LG->returnNoOfLetter() && Qut->returnNoOfLetter()>NG->returnNoOfLetter()) maxNoOfL=Qut->returnNoOfLetter(); NG->setButWidth(maxNoOfL); LG->setButWidth(maxNoOfL); Qut->setButWidth(maxNoOfL); isFile=false; } MainMenu::~MainMenu() { // delete NG; // NG = NULL; // delete LG; // LG = NULL; // delete Qut; // Qut = NULL; // delete welcome; // LG = NULL; } int MainMenu::Event(SDL_Event e,const Uint8* currentKeyStates,bool* mouseClicked,int* state,bool* quit) { if( e.type == SDL_MOUSEBUTTONDOWN && *mouseClicked == false) { Point p; int x,y; SDL_GetMouseState( &x, &y ); p.x=x; p.y=y; if (e.button.button == SDL_BUTTON_LEFT){ *mouseClicked = true; if(checkClick(NG->returnButtonRect(),p)) { *state = 2; } if (checkClick(LG->returnButtonRect(),p)) { filePointer = fopen("lastgame.txt", "r"); //Opening file as read only if (filePointer == NULL) { perror ("ERROR OPENING FILE"); } else{ isFile=1; *state=3; } fclose(filePointer); } if (checkClick(Qut->returnButtonRect(),p)) { *quit = true; } } } if( e.type == SDL_MOUSEBUTTONUP && *mouseClicked == true) { *mouseClicked=false; } return isFile; } void MainMenu::Render(SDL_Renderer* gRenderer) { image->Render( position.x, position.y, &spriteClips, 0.0, NULL, SDL_FLIP_NONE, gRenderer ); NG->Render(gRenderer,maxNoOfL); LG->Render(gRenderer,maxNoOfL); Qut->Render(gRenderer,maxNoOfL); } int MainMenu::Play( Texture* image, SDL_Renderer* gRenderer,int state) { return state; }
[ "muhammad.roohani@gmail.com" ]
muhammad.roohani@gmail.com
76501400a05f419fddc1ea22ed2d40186aba262d
7045bb4f95ada6e1669a3cd9520681b7e548c319
/Meijer/Source/SCOTAPP/SMConfirmDebitAmountBase.cpp
53f1839def1d672bd80fefc3f06de9434a9e602f
[]
no_license
co185057/MeijerTESTSVN
0ffe207db43c8e881fdbad66c1c058e25fe451f5
3a3df97b2decc1a04e6efe7c8ab74eff5409f39f
refs/heads/master
2023-05-30T00:19:36.524059
2021-06-10T08:41:31
2021-06-10T08:41:31
375,576,064
0
0
null
null
null
null
UTF-8
C++
false
false
4,983
cpp
////////////////////////////////////////////////////////////////////////////////////////////////// // // FILE: SMConfirmDebitAmountBase.cpp // // TITLE: Class implementation for Confirm Debit Amount state // // ///////////////////////////////////////////////////////////////////////////////////////////////// #include <stdafx.h> // MS MFC always needed first // // MS MFC template header #include "Common.h" // Common includes #include "SMState.h" // Base state #include "SMConfirmDebitAmount.h" #include "SMTakeCard.h" // Take Card state #include "SMSwipeCard.h" #define COMP_ID ID_SM // Base state component #define T_ID _T("ConfirmDebitAmountBase") IMPLEMENT_DYNCREATE(SMConfirmDebitAmountBase, CObject)// MFC Runtime class/object information //IMPLEMENT_STATE(ConfirmDebitAmount) DEFINE_TIMESTAMP //////////////////////////////////////// SMConfirmDebitAmountBase::SMConfirmDebitAmountBase(const TBTENDERTYPE nTyp,const long lAmt) : nTndrType(nTyp), lTenderAmt(lAmt) { IMPLEMENT_TIMESTAMP } //////////////////////////////////////// bool SMConfirmDebitAmountBase::DeliverDescriptorList(CDescriptorList &dlParameterList) { // There should be two parameters, both dwords if (dlParameterList.GetDescriptorCount() == 2) { trace(L6, _T("+SMConfirmDebitAmountBase::DeliverDescriptorList() - Parameter Count of 2")); Deliver((TBTENDERTYPE)DLParamDWORD(dlParameterList), // nTyp DLParamDWORD(dlParameterList)); // lAmt return true; } else { trace(L2, _T("+SMConfirmDebitAmountBase::DeliverDescriptorList() - ERROR - Parameter Count %d"), dlParameterList.GetDescriptorCount()); return false; } } //////////////////////////////////////// SMConfirmDebitAmountBase::SMConfirmDebitAmountBase() { IMPLEMENT_TIMESTAMP } //////////////////////////////////////// SMStateBase *SMConfirmDebitAmountBase::Deliver(const TBTENDERTYPE nTyp,const long lAmt) { nTndrType = nTyp; lTenderAmt = lAmt; return this; } ///////////////////////////////////////////// SMStateBase *SMConfirmDebitAmountBase::Initialize(void) { TellApplicationStateToSecurity(KEY_AC_SET_APP_STATE_BEGIN, _T("ConfirmDebitAmount") ); // RFC 330050 // CANNOT enter Remote Assist Mode at this state //ra.OnSetTransactionState(RA_STATE_ASSISTNOTOK); ra.RequestEnableAssistMode(false); //TAR 213249 //Update RAP window with SCOT state UpdateStateName(ps.GetPSText(LTT_CONFIRMDEBITAMT, SCOT_LANGUAGE_PRIMARY)); ps.SetCMFrame(_T("ConfirmDebitAmount")); ps.CMButtonFlash(_T("CMButton1Med"),true); ps.ShowAmountDueAmountPaid(lBalanceDue,lTotalPaid); CString csWork; CString csTenderAmt = ps.FmtDollar(lTenderAmt); if(nTndrType == TB_TENDER_DEBIT || nTndrType == TB_TENDER_PIP_DEBIT || nTndrType == TB_TENDER_PIP_DEBIT_CASHBACK) csWork.Format( ps.GetPSText(MSG_CONFIRMDEBITAMT), csTenderAmt); else csWork.Format( ps.GetPSText(MSG_CONFIRMCREDITCASHBACK), csTenderAmt); ps.Message12(csWork, true); DMSayPhrase(CONFIRMAMOUNT); DisplayAuxScreen(AUX_SCREEN_CONFIRM_DEBIT_AMT, true, 1, csTenderAmt); ps.ShowCMFrame(); return STATE_NULL; // stay here } SMStateBase *SMConfirmDebitAmountBase::PSButton1(void) { // Yes // the BALANCE/CHANGE message will change us to either // STCashPayment or STTakeChange or STTakeReceipt /* if (co.fOperationsPartialIntegratedPINPad) //PIP { if(co.fOperationsDebitMSR) { CREATE_AND_DISPENSE(SwipeCard)(TB_TENDER_DEBIT, lTenderAmt); } else return TBEnterTender(TB_TENDER_PIP_DEBIT, lTenderAmt); } */ return TBEnterTender( nTndrType, lTenderAmt); } SMStateBase *SMConfirmDebitAmountBase::PSEnterKey(void) { DMSayPhrase(KEYPADVALID); return PSButton1(); } SMStateBase *SMConfirmDebitAmountBase::PSButtonGoBack(void) { // CAN enter Remote Assist Mode after leaving this state //ra.OnSetTransactionState(RA_STATE_ASSISTOK); ra.RequestEnableAssistMode(true); //TAR213249 setAnchorState(BES_FINISH); CREATE_AND_DISPENSE(TakeCard)(false); } /////////////////////////////////////////////////////////////////////////// SMStateBase *SMConfirmDebitAmountBase::OnWtIncreaseNotAllowed() { return FinalizationWtIncrease(BES_STATERETURN); } /////////////////////////////////////////////////////////////////////////// SMStateBase *SMConfirmDebitAmountBase::OnWtDecrease() { if(!g_bIsForgiveUnexpectedDecreaseDuringTendering) return FinalizationWtDecreaseNotAllowed(BES_STATERETURN); else return STATE_NULL; } // + RFC 330050 void SMConfirmDebitAmountBase::UnInitialize(void) { TellApplicationStateToSecurity(KEY_AC_SET_APP_STATE_END, _T("ConfirmDebitAmount") ); } // - RFC 330050
[ "co185057@ncr.com" ]
co185057@ncr.com
ed9eb8ab3137eb310d0b156a03b8a6a3c47abcb3
c16cc10758f88a132ffc5ad1c95ef4e480c7473d
/2. 자료구조 기초/10799/main.cpp
98a229023eb80ec225a5ae8ee21722e0a1be1937
[ "MIT" ]
permissive
azxca1731/nogada-algorithm
2102e3da551f6c500d1e1bc91e6c4a29546d4703
4151fc09a2fb9f72875000c8dc6db0584a16cc01
refs/heads/master
2020-05-07T22:37:46.741724
2019-06-12T13:19:24
2019-06-12T13:19:24
180,952,459
2
0
MIT
2019-05-06T13:34:56
2019-04-12T07:16:48
C++
UTF-8
C++
false
false
743
cpp
#include <iostream> #include <string> #include <stack> using namespace std; int main() { stack<bool> cutter; string ironbar; bool isLazor = false; int max = 0; cin >> ironbar; for (int i = 0; i < ironbar.length(); i++) { if (ironbar[i] == '(') { cutter.push(true); isLazor = true; } if (ironbar[i] == ')') { if (isLazor) { isLazor = false; cutter.pop(); max += cutter.size(); } else { isLazor = false; max++; cutter.pop(); } } } cout << max << endl; return 0; }
[ "azxca1731@gmail.com" ]
azxca1731@gmail.com
3e1ba613cb7f645d98b93342ad7e9409c3866fb6
ec8364edc6db44b15a38b2baf34899f74c6e8d39
/include/winrt/Windows.Gaming.XboxLive.Storage.0.h
97f9174de32fe1678e3ae52cce70c1781821906c
[]
no_license
adrianstephens/win_arty
2ff906a5b0c4b080ddc366c75098d12c56967da4
3fef806596e11ab66d33cb2649aee22071daba66
refs/heads/master
2020-03-11T17:16:46.134747
2018-04-19T03:12:22
2018-04-19T03:12:22
130,142,466
0
0
null
null
null
null
UTF-8
C++
false
false
1,439
h
#pragma once // generated by isopod tools #include "pre_include.h" namespace iso_winrt { // forward types namespace Windows { namespace Gaming { namespace XboxLive { namespace Storage { enum class GameSaveErrorStatus : int { Ok = 0, Abort = -2147467260, InvalidContainerName = -2138898431, NoAccess = -2138898430, OutOfLocalStorage = -2138898429, UserCanceled = -2138898428, UpdateTooBig = -2138898427, QuotaExceeded = -2138898426, ProvidedBufferTooSmall = -2138898425, BlobNotFound = -2138898424, NoXboxLiveInfo = -2138898423, ContainerNotInSync = -2138898422, ContainerSyncFailed = -2138898421, UserHasNoXboxLiveInfo = -2138898420, ObjectExpired = -2138898419, }; struct IGameSaveProvider; struct IGameSaveContainer; struct GameSaveContainer; struct IGameSaveOperationResult; struct GameSaveOperationResult; struct IGameSaveContainerInfoQuery; struct GameSaveContainerInfoQuery; struct IGameSaveProviderStatics; struct IGameSaveProviderGetResult; struct GameSaveProviderGetResult; struct GameSaveProvider; struct IGameSaveBlobGetResult; struct GameSaveBlobGetResult; struct IGameSaveBlobInfoQuery; struct GameSaveBlobInfoQuery; struct IGameSaveContainerInfo; struct GameSaveContainerInfo; struct IGameSaveBlobInfo; struct GameSaveBlobInfo; struct IGameSaveContainerInfoGetResult; struct GameSaveContainerInfoGetResult; struct IGameSaveBlobInfoGetResult; struct GameSaveBlobInfoGetResult; }}}} } // namespace iso_winrt
[ "adrianstephens@msn.com" ]
adrianstephens@msn.com
612a7a7bd284ed3aeb7ccc8a294813b5b9c787b1
fea779942fbbe4e3c03cb9bc78b0a99e56cb17e5
/cpp/m4dm/inc/itemdfit.hpp
2557dd331b5035e64a1be1f84bae0bfdf19a2166
[]
no_license
jesuscraf/peopletech
66e372af07f9a3dd4660ef14b93daddf92a5e3c8
3ab9470cf2e7cb7a44baf4185710cb707f081ff4
refs/heads/master
2021-09-03T13:37:13.701453
2018-01-09T11:49:34
2018-01-09T11:49:34
114,750,048
0
0
null
null
null
null
UTF-8
C++
false
false
2,679
hpp
//============================================================================== // // (c) Copyright 1991-1997 Meta Software M.S., S.A // All rights reserved. // // Module: CVM - DM // File: itemdfit.hpp // Project: CVM // Author: Meta Software M.S. , S.A // Date: 29/05/98 // Language: C++ // Operating System: WINDOWS , UNIX ( HP, DEC , AIX , SUN) // Design Document: // // // Definition: // // This module defines ... // // //============================================================================== #include "m4dm_dll.hpp" #include "index.hpp" #include "handles.hpp" #include "wproxy.hpp" #ifndef __ITEMDFIT_HPP__ #define __ITEMDFIT_HPP__ class ClNodeDef; class ClColItemDef_Kernel; class _AClItemProxy; class M4_DECL_M4DM ClItemProxyIt : public _withitemproxy { public: ClItemProxyIt (); ClItemProxyIt (ClColItemDef_Kernel *ai_pClColItemDef_Kernel); ClItemProxyIt (ClColItemDef_Kernel &ai_ClColItemDef_Kernel); virtual ~ClItemProxyIt (); void Attach (ClColItemDef_Kernel *ai_pClColItemDef_Kernel); void Attach (ClColItemDef_Kernel &ai_ClColItemDef_Kernel); _AClItemProxy *operator [] (ClItemIndex ai_itemindex); _AClItemProxy *operator [] (ClHandle ai_handle); _AClItemProxy *operator [] (m4pcchar_t ai_pcId); _AClItemProxy *operator ->() const { return GetpItemProxy (); } m4return_t GetSize(ClSize &ao_size); protected: ClColItemDef_Kernel *m_pClColItemDef_Kernel; // mi papa }; class M4_DECL_M4DM ClItemProxyIt_Random : public ClItemProxyIt { public: ClItemProxyIt_Random () : ClItemProxyIt () {} ClItemProxyIt_Random (ClColItemDef_Kernel *ai_pClColItemDef_Kernel) : ClItemProxyIt (ai_pClColItemDef_Kernel) {} ClItemProxyIt_Random (ClColItemDef_Kernel &ai_ClColItemDef_Kernel) : ClItemProxyIt (ai_ClColItemDef_Kernel) {} ~ClItemProxyIt_Random (); ClItemIndex Index; // de momento m4uint16_t Count (void) const; _AClItemProxy *Begin (void); _AClItemProxy *End (void); m4bool_t Next (void); m4bool_t Prev (void); /* _AClItemProxy *operator [] (ClItemIndex ai_itemindex) { return ClItemProxyIt::operator [] (ai_itemindex); } _AClItemProxy *operator [] (ClHandle ai_handle) { return ClItemProxyIt::operator [] (ai_handle); } _AClItemProxy *operator [] (m4pcchar_t ai_pcId) { return ClItemProxyIt::operator [] (ai_pcId); } */ m4return_t GetSize(ClSize &ao_size); const _AClItemProxy *operator ->() const { return ClItemProxyIt::operator -> (); } private: }; #endif // __ITEMDFIT_HPP__
[ "jesusc@meta4.com" ]
jesusc@meta4.com
7be2a1029916ebefa31acd26e0c7c17156e9f4b5
6eeedd141c567e209374b263554774ae6bf70fd3
/240.Search a 2Dmat/source.cpp
d6410cee1c7845f212bbc7ccc79d7ac1297a4ce1
[]
no_license
uddipan/LeetCode
c275a8946de37de1a6541b45dee5df1aa45daa0c
dc8cc15725bb34716e45200730bcb0ddaa59355a
refs/heads/master
2020-12-30T12:11:07.691285
2017-05-22T00:59:48
2017-05-22T00:59:48
91,407,745
0
0
null
null
null
null
UTF-8
C++
false
false
384
cpp
class Solution { public: bool searchMatrix(vector<vector<int>>& matrix, int target) { if(matrix.empty())return false; int x = 0, y = matrix[0].size() -1; while(x < matrix.size() && y >= 0) { if(matrix[x][y] == target)return true; if(matrix[x][y] > target) y--; else x ++; } return false; } };
[ "uddipanm@gmail.com" ]
uddipanm@gmail.com
81694ec6b4c169ec71fa83d51999bbefc63a39c0
e7deb78f013cf0924446bc3e91fc81863bc350f2
/src/governance-object.h
b63da0fc2d9c5711dd4539e42179401661fad9b8
[ "MIT" ]
permissive
henryshi001/bopucoin
0684d6ca4587d7c528cad50461821f5a49a6b608
8a601affa5af1b71b5f928bf8d8f050441f5328d
refs/heads/master
2020-04-08T22:03:41.449830
2018-11-29T12:19:46
2018-11-29T12:19:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,036
h
// Copyright (c) 2014-2017 The Dash Core developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef GOVERNANCE_OBJECT_H #define GOVERNANCE_OBJECT_H //#define ENABLE_BOPUCOIN_DEBUG #include "cachemultimap.h" #include "governance-exceptions.h" #include "governance-vote.h" #include "governance-votedb.h" #include "key.h" #include "net.h" #include "sync.h" #include "util.h" #include <univalue.h> class CGovernanceManager; class CGovernanceTriggerManager; class CGovernanceObject; class CGovernanceVote; static const int MAX_GOVERNANCE_OBJECT_DATA_SIZE = 16 * 1024; static const int MIN_GOVERNANCE_PEER_PROTO_VERSION = 70206; static const int GOVERNANCE_FILTER_PROTO_VERSION = 70206; static const double GOVERNANCE_FILTER_FP_RATE = 0.001; static const int GOVERNANCE_OBJECT_UNKNOWN = 0; static const int GOVERNANCE_OBJECT_PROPOSAL = 1; static const int GOVERNANCE_OBJECT_TRIGGER = 2; static const int GOVERNANCE_OBJECT_WATCHDOG = 3; static const CAmount GOVERNANCE_PROPOSAL_FEE_TX = (5.0*COIN); static const int64_t GOVERNANCE_FEE_CONFIRMATIONS = 6; static const int64_t GOVERNANCE_MIN_RELAY_FEE_CONFIRMATIONS = 1; static const int64_t GOVERNANCE_UPDATE_MIN = 60*60; static const int64_t GOVERNANCE_DELETION_DELAY = 10*60; static const int64_t GOVERNANCE_ORPHAN_EXPIRATION_TIME = 10*60; static const int64_t GOVERNANCE_WATCHDOG_EXPIRATION_TIME = 2*60*60; static const int GOVERNANCE_TRIGGER_EXPIRATION_BLOCKS = 576; // FOR SEEN MAP ARRAYS - GOVERNANCE OBJECTS AND VOTES static const int SEEN_OBJECT_IS_VALID = 0; static const int SEEN_OBJECT_ERROR_INVALID = 1; static const int SEEN_OBJECT_ERROR_IMMATURE = 2; static const int SEEN_OBJECT_EXECUTED = 3; //used for triggers static const int SEEN_OBJECT_UNKNOWN = 4; // the default typedef std::pair<CGovernanceVote, int64_t> vote_time_pair_t; inline bool operator<(const vote_time_pair_t& p1, const vote_time_pair_t& p2) { return (p1.first < p2.first); } struct vote_instance_t { vote_outcome_enum_t eOutcome; int64_t nTime; int64_t nCreationTime; vote_instance_t(vote_outcome_enum_t eOutcomeIn = VOTE_OUTCOME_NONE, int64_t nTimeIn = 0, int64_t nCreationTimeIn = 0) : eOutcome(eOutcomeIn), nTime(nTimeIn), nCreationTime(nCreationTimeIn) {} ADD_SERIALIZE_METHODS; template <typename Stream, typename Operation> inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) { int nOutcome = int(eOutcome); READWRITE(nOutcome); READWRITE(nTime); READWRITE(nCreationTime); if(ser_action.ForRead()) { eOutcome = vote_outcome_enum_t(nOutcome); } } }; typedef std::map<int,vote_instance_t> vote_instance_m_t; typedef vote_instance_m_t::iterator vote_instance_m_it; typedef vote_instance_m_t::const_iterator vote_instance_m_cit; struct vote_rec_t { vote_instance_m_t mapInstances; ADD_SERIALIZE_METHODS; template <typename Stream, typename Operation> inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) { READWRITE(mapInstances); } }; /** * Governance Object * */ class CGovernanceObject { friend class CGovernanceManager; friend class CGovernanceTriggerManager; public: // Types typedef std::map<COutPoint, vote_rec_t> vote_m_t; typedef vote_m_t::iterator vote_m_it; typedef vote_m_t::const_iterator vote_m_cit; typedef CacheMultiMap<COutPoint, vote_time_pair_t> vote_mcache_t; private: /// critical section to protect the inner data structures mutable CCriticalSection cs; /// Object typecode int nObjectType; /// parent object, 0 is root uint256 nHashParent; /// object revision in the system int nRevision; /// time this object was created int64_t nTime; /// time this object was marked for deletion int64_t nDeletionTime; /// fee-tx uint256 nCollateralHash; /// Data field - can be used for anything std::string strData; /// Masternode info for signed objects CTxIn vinMasternode; std::vector<unsigned char> vchSig; /// is valid by blockchain bool fCachedLocalValidity; std::string strLocalValidityError; // VARIOUS FLAGS FOR OBJECT / SET VIA MASTERNODE VOTING /// true == minimum network support has been reached for this object to be funded (doesn't mean it will for sure though) bool fCachedFunding; /// true == minimum network has been reached flagging this object as a valid and understood governance object (e.g, the serialized data is correct format, etc) bool fCachedValid; /// true == minimum network support has been reached saying this object should be deleted from the system entirely bool fCachedDelete; /** true == minimum network support has been reached flagging this object as endorsed by an elected representative body * (e.g. business review board / technecial review board /etc) */ bool fCachedEndorsed; /// object was updated and cached values should be updated soon bool fDirtyCache; /// Object is no longer of interest bool fExpired; /// Failed to parse object data bool fUnparsable; vote_m_t mapCurrentMNVotes; /// Limited map of votes orphaned by MN vote_mcache_t mapOrphanVotes; CGovernanceObjectVoteFile fileVotes; public: CGovernanceObject(); CGovernanceObject(uint256 nHashParentIn, int nRevisionIn, int64_t nTime, uint256 nCollateralHashIn, std::string strDataIn); CGovernanceObject(const CGovernanceObject& other); void swap(CGovernanceObject& first, CGovernanceObject& second); // nothrow // Public Getter methods int64_t GetCreationTime() const { return nTime; } int64_t GetDeletionTime() const { return nDeletionTime; } int GetObjectType() const { return nObjectType; } const uint256& GetCollateralHash() const { return nCollateralHash; } const CTxIn& GetMasternodeVin() const { return vinMasternode; } bool IsSetCachedFunding() const { return fCachedFunding; } bool IsSetCachedValid() const { return fCachedValid; } bool IsSetCachedDelete() const { return fCachedDelete; } bool IsSetCachedEndorsed() const { return fCachedEndorsed; } bool IsSetDirtyCache() const { return fDirtyCache; } bool IsSetExpired() const { return fExpired; } void InvalidateVoteCache() { fDirtyCache = true; } CGovernanceObjectVoteFile& GetVoteFile() { return fileVotes; } // Signature related functions void SetMasternodeVin(const COutPoint& outpoint); bool Sign(CKey& keyMasternode, CPubKey& pubKeyMasternode); bool CheckSignature(CPubKey& pubKeyMasternode); std::string GetSignatureMessage() const; // CORE OBJECT FUNCTIONS bool IsValidLocally(std::string& strError, bool fCheckCollateral); bool IsValidLocally(std::string& strError, bool& fMissingMasternode, bool& fMissingConfirmations, bool fCheckCollateral); /// Check the collateral transaction for the budget proposal/finalized budget bool IsCollateralValid(std::string& strError, bool &fMissingConfirmations); void UpdateLocalValidity(); void UpdateSentinelVariables(); int GetObjectSubtype(); CAmount GetMinCollateralFee(); UniValue GetJSONObject(); void Relay(CConnman& connman); uint256 GetHash() const; // GET VOTE COUNT FOR SIGNAL int CountMatchingVotes(vote_signal_enum_t eVoteSignalIn, vote_outcome_enum_t eVoteOutcomeIn) const; int GetAbsoluteYesCount(vote_signal_enum_t eVoteSignalIn) const; int GetAbsoluteNoCount(vote_signal_enum_t eVoteSignalIn) const; int GetYesCount(vote_signal_enum_t eVoteSignalIn) const; int GetNoCount(vote_signal_enum_t eVoteSignalIn) const; int GetAbstainCount(vote_signal_enum_t eVoteSignalIn) const; bool GetCurrentMNVotes(const COutPoint& mnCollateralOutpoint, vote_rec_t& voteRecord); // FUNCTIONS FOR DEALING WITH DATA STRING std::string GetDataAsHex(); std::string GetDataAsString(); // SERIALIZER ADD_SERIALIZE_METHODS; template <typename Stream, typename Operation> inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) { // SERIALIZE DATA FOR SAVING/LOADING OR NETWORK FUNCTIONS READWRITE(nHashParent); READWRITE(nRevision); READWRITE(nTime); READWRITE(nCollateralHash); READWRITE(LIMITED_STRING(strData, MAX_GOVERNANCE_OBJECT_DATA_SIZE)); READWRITE(nObjectType); READWRITE(vinMasternode); READWRITE(vchSig); if(nType & SER_DISK) { // Only include these for the disk file format LogPrint("gobject", "CGovernanceObject::SerializationOp Reading/writing votes from/to disk\n"); READWRITE(nDeletionTime); READWRITE(fExpired); READWRITE(mapCurrentMNVotes); READWRITE(fileVotes); LogPrint("gobject", "CGovernanceObject::SerializationOp hash = %s, vote count = %d\n", GetHash().ToString(), fileVotes.GetVoteCount()); } // AFTER DESERIALIZATION OCCURS, CACHED VARIABLES MUST BE CALCULATED MANUALLY } CGovernanceObject& operator=(CGovernanceObject from) { swap(*this, from); return *this; } private: // FUNCTIONS FOR DEALING WITH DATA STRING void LoadData(); void GetData(UniValue& objResult); bool ProcessVote(CNode* pfrom, const CGovernanceVote& vote, CGovernanceException& exception, CConnman& connman); /// Called when MN's which have voted on this object have been removed void ClearMasternodeVotes(); void CheckOrphanVotes(CConnman& connman); }; #endif
[ "627400318@qq.com" ]
627400318@qq.com
1748d391fb7927e15696d85d9eb8c1c79c9ad013
cc7661edca4d5fb2fc226bd6605a533f50a2fb63
/mscorlib/Publisher.h
0bb42e9bab5c3aa3710ca47a677793aa4e6f8461
[ "MIT" ]
permissive
g91/Rust-C-SDK
698e5b573285d5793250099b59f5453c3c4599eb
d1cce1133191263cba5583c43a8d42d8d65c21b0
refs/heads/master
2020-03-27T05:49:01.747456
2017-08-23T09:07:35
2017-08-23T09:07:35
146,053,940
1
0
null
2018-08-25T01:13:44
2018-08-25T01:13:44
null
UTF-8
C++
false
false
351
h
#pragma once #include "..\System\Security\Cryptography\X509Certificates\X509Certificate.h" namespace System { namespace Security { { namespace Policy { class Publisher : public Object // 0x0 { public: System::Security::Cryptography::X509Certificates::X509Certificate* m_cert; // 0x10 (size: 0x8, flags: 0x1, type: 0x12) }; // size = 0x18 }
[ "info@cvm-solutions.co.uk" ]
info@cvm-solutions.co.uk
c2578e651088d5fe086eefb1895588203b446f21
a866673e609a83a0b8fb7dd4b9789504fde07d50
/code/pixel_test/pixel_test.ino
78baa74929de5fbeb87c0ec0d4864aca711ee1e3
[ "MIT" ]
permissive
rlankenau/thotcon0x6
555c2552b96d52ccbd7f1c24c9ffc900ef3a29b1
2cb2cd0a5341bdcd28a6571a792cf14a7b21bc43
refs/heads/master
2021-01-18T08:56:21.331551
2015-05-14T16:36:37
2015-05-14T16:36:37
27,080,940
2
0
null
null
null
null
UTF-8
C++
false
false
771
ino
#include<FastLED.h> #define LED_PIN 4 #define BRIGHTNESS 4 #define LED_TYPE WS2811 #define COLOR_ORDER GRB #define NUM_LEDS 6 CRGB leds[NUM_LEDS]; void setup(){ LEDS.addLeds<WS2812B,LED_PIN,GRB>(leds,NUM_LEDS); LEDS.setBrightness(BRIGHTNESS); for(uint8_t pixel = 0; pixel < NUM_LEDS; pixel++) { leds[pixel] = CRGB::White; FastLED.show(); // leds[pixel] = CRGB::Black; delay(500); } for (uint8_t i = BRIGHTNESS; i < (4 * BRIGHTNESS); i++) { LEDS.setBrightness(i); delay(100); FastLED.show(); } for (uint8_t i = (4 * BRIGHTNESS); i > BRIGHTNESS; i--) { LEDS.setBrightness(i); delay(100); FastLED.show(); } LEDS.setBrightness(BRIGHTNESS); FastLED.show(); } void loop() { }
[ "rudy.ristich@gmail.com" ]
rudy.ristich@gmail.com
dd4e9d141371106175dce82c03742c20418a917f
462a2b5357bfb78018258421111f91aab7ba60eb
/NetworkGame/NetworkGame/Utility/Resource/ResourceInitializer.h
67dc9bc4407e33a25d74fe638a2026b47178663a
[]
no_license
matsumoto0112/network
fbd07f7cbec00ab10341a6cda18e22a290882302
bfd9b5cdd9658d321069d13e38cf92ebc7e6f490
refs/heads/master
2020-06-22T18:04:11.901342
2019-07-24T05:10:19
2019-07-24T05:10:19
197,764,957
0
0
null
null
null
null
UTF-8
C++
false
false
180
h
#pragma once namespace Utility { class ResourceManager; class ResourceInitializeOnStart { public: ResourceInitializeOnStart(ResourceManager& resourceManager); }; } //Utility
[ "matsumoto.k017a1377@gmail.com" ]
matsumoto.k017a1377@gmail.com
28392648201242fd23f4de6d98232ab6a26dbf25
562d2183cecd232559eb89d7f733bf1fe967768c
/Source/libClang/Source/tools/clang/test/CXX/expr/expr.prim/expr.prim.lambda/p18.cpp
13008d1ffedfda1f6b3ef9303b23e08980d326c7
[ "NCSA" ]
permissive
orcun-gokbulut/ze-externals-sources
f1fd970ed6161b8f7ac19d1991f44a720c0125e9
500a237d6e0ff6308db1e2e513ad9871ac4cda65
refs/heads/master
2023-09-01T19:44:32.292637
2021-10-13T14:26:53
2021-10-13T14:26:53
416,611,297
1
1
null
null
null
null
UTF-8
C++
false
false
1,443
cpp
// RUN: %clang_cc1 -std=c++11 %s -Wunused -verify // expected-no-diagnostics template<typename T, typename U> struct is_same { static const bool value = false; }; template<typename T> struct is_same<T, T> { static const bool value = true; }; void f3() { float x, &r = x; int i; int &ir = i; const int &irc = i; [=,&irc,&ir] { static_assert(is_same<decltype(((r))), float const&>::value, "should be const float&"); static_assert(is_same<decltype(x), float>::value, "should be float"); static_assert(is_same<decltype((x)), const float&>::value, "should be const float&"); static_assert(is_same<decltype(r), float&>::value, "should be float&"); static_assert(is_same<decltype(ir), int&>::value, "should be int&"); static_assert(is_same<decltype((ir)), int&>::value, "should be int&"); static_assert(is_same<decltype(irc), const int&>::value, "should be const int&"); static_assert(is_same<decltype((irc)), const int&>::value, "should be const int&"); }(); [=] { [=] () mutable { static_assert(is_same<decltype(x), float>::value, "should be float"); static_assert(is_same<decltype((x)), float&>::value, "should be float&"); }(); }(); [&i] { static_assert(is_same<decltype((i)), int&>::value, "should be int&"); }(); }
[ "orcun.gokbulut@zinek.xyz" ]
orcun.gokbulut@zinek.xyz
79a473da90e778acd6287f251f843917e7d5c73b
daa1251d9b25abb74690377ed15717708b0f77e4
/CSCI_1300/LectureExamples/Classes/cashregister.cpp
f96aa8a5dc612e9f74e7a863715e7bf417586ce1
[]
no_license
gubatron/cu-projects
3a2193845682271afcfb31c74f2cfed42e2a009d
7214df004800c6e00a3cc8fc1e3ddef65bd211ec
refs/heads/master
2022-11-26T05:32:05.052826
2020-07-24T06:55:51
2020-07-24T06:55:51
168,641,352
1
0
null
null
null
null
UTF-8
C++
false
false
695
cpp
#include <iostream> #include <iomanip> #include "cashregister.h" // header file "cashregister.h" using namespace std; // v // v // implementation file // v // cpp file that includes the header file "cashregister.h" CashRegister::CashRegister() { clear(); } void CashRegister::clear() { item_count = 0; total_price = 0; } void CashRegister::add_item(double price) { item_count++; total_price = total_price + price; } double CashRegister::get_total() const { return total_price; } int CashRegister::get_count() const { return item_count; }
[ "nicole.leonmolina@colorado.edu" ]
nicole.leonmolina@colorado.edu
1abacae3628d2de730f32a85689ec5afde7b9707
d17a8870ff8ac77b82d0d37e20c85b23aa29ca74
/lite/backends/nnadapter/nnadapter/src/driver/amlogic_npu/converter/elementwise.cc
319121305f184624029ad915eedf9a61164e4ef6
[ "Apache-2.0" ]
permissive
PaddlePaddle/Paddle-Lite
4ab49144073451d38da6f085a8c56822caecd5b2
e241420f813bd91f5164f0d9ee0bc44166c0a172
refs/heads/develop
2023-09-02T05:28:14.017104
2023-09-01T10:32:39
2023-09-01T10:32:39
104,208,128
2,545
1,041
Apache-2.0
2023-09-12T06:46:10
2017-09-20T11:41:42
C++
UTF-8
C++
false
false
2,645
cc
// Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "operation/elementwise.h" #include "driver/amlogic_npu/converter/converter.h" #include "utility/debug.h" #include "utility/logging.h" namespace nnadapter { namespace amlogic_npu { int ConvertElementwise(Converter* converter, core::Operation* operation) { ELEMENTWISE_OPERATION_EXTRACT_INPUTS_OUTPUTS NNADAPTER_CHECK_EQ(fuse_code, NNADAPTER_FUSED_NONE) << "Unsupported fuse_code(" << fuse_code << ") is found."; // Convert to amlnpu tensors and operators auto input0_tensor = converter->GetMappedTensor(input0_operand); if (!input0_tensor) { input0_tensor = converter->ConvertOperand(input0_operand); } auto input1_tensor = converter->GetMappedTensor(input1_operand); if (!input1_tensor) { input1_tensor = converter->ConvertOperand(input1_operand); } auto output_tensor = converter->ConvertOperand(output_operand); std::vector<std::shared_ptr<aml::nn::Tensor>> input_tensors = {input0_tensor, input1_tensor}; std::vector<std::shared_ptr<aml::nn::Tensor>> output_tensors = { output_tensor}; aml::nn::OperatorType op_type; if (operation->type == NNADAPTER_ADD) { op_type = aml::nn::OperatorType::ADD; } else if (operation->type == NNADAPTER_SUB) { op_type = aml::nn::OperatorType::SUBTRACT; } else if (operation->type == NNADAPTER_MUL) { op_type = aml::nn::OperatorType::MULTIPLY; } else if (operation->type == NNADAPTER_DIV) { op_type = aml::nn::OperatorType::DIVIDE; } else { NNADAPTER_LOG(FATAL) << "Unsupported element-wise operation type " << OperationTypeToString(operation->type) << " is found."; } converter->AddOperator(op_type, input_tensors, output_tensors, nullptr); NNADAPTER_CHECK_EQ(fuse_code, NNADAPTER_FUSED_NONE) << "Missing the processing of fuse_code(" << fuse_code << ") in unpack_op_fusion.cc"; return NNADAPTER_NO_ERROR; } } // namespace amlogic_npu } // namespace nnadapter
[ "noreply@github.com" ]
noreply@github.com
906ba88d4549d9e5b4696a7f371099a5cf79d9eb
f013aa161bc57aa49a2ca64003ddc1b3a33495a8
/lcdClock/lcdClock.ino
53c827f3bfb5c39eec9b5a2eb89c2b7fa3682833
[]
no_license
fdawes1/Arduino
021aaa2267d6ad6a65adf044687c53ad085e2225
1b5291488f677efb34400dfc053fe70d62ed77ab
refs/heads/master
2021-09-03T22:48:34.377402
2018-01-12T16:26:04
2018-01-12T16:26:04
117,251,794
0
0
null
null
null
null
UTF-8
C++
false
false
1,056
ino
#include <Wire.h> #include "Sodaq_DS3231.h" #include <LiquidCrystal.h> // includes the LiquidCrystal Library LiquidCrystal lcd(12, 11, 5, 4, 3, 2);// Creates an LC object. Parameters: (rs, enable, d4, d5, d6, d7) char weekDay[][4] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }; void setup() { Wire.begin(); Serial.begin(9600); rtc.begin(); // Initialize the rtc object lcd.begin(16, 2); // Initializes the interface to the LCD screen, and specifies the dimensions (width and height) of the display } void loop() { DateTime now = rtc.now(); //get the current date-time lcd.setCursor(0, 0); lcd.print("Time: "); lcd.print(now.hour(), DEC); lcd.print(":"); lcd.print(now.minute(), DEC); lcd.print(":"); lcd.print(now.second(), DEC); lcd.setCursor(0, 1); lcd.print("Date: "); lcd.print(now.date(), DEC); lcd.print("/"); lcd.print(now.month(), DEC); lcd.print("/"); lcd.print(now.year(), DEC); lcd.print(" "); // lcd.print(weekDay[now.dayOfWeek()]); lcd.display(); delay(1000); lcd.clear(); }
[ "fdawes1@gmail.com" ]
fdawes1@gmail.com
ccbbdbec3806163df8ab25072877058e2fa4f9c5
fc0c11a5a6142a80d08c3e3ff820dadcb3a2c76c
/sbpl_perception/include/sbpl_perception/object_model.h
7c4cb41741c3cb5301956ea029812c88db3d9a1d
[]
no_license
SiChiTong/perception
7c2b82e5fbf2151f93ae231466ecd48eb5ba3bb2
b59caa820a922fd907b56ca0a11a2c9abc6fcded
refs/heads/master
2021-05-28T21:03:47.299227
2015-06-11T17:50:06
2015-06-11T17:50:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,074
h
/** * @file object_model.h * @brief Object model * @author Venkatraman Narayanan * Carnegie Mellon University, 2015 */ #ifndef _SBPL_PERCEPTION_OBJECT_MODEL_H_ #define _SBPL_PERCEPTION_OBJECT_MODEL_H_ #include <pcl/PolygonMesh.h> class ObjectModel { public: ObjectModel(const pcl::PolygonMesh mesh, const bool symmetric); double GetInscribedRadius() const; double GetCircumscribedRadius() const; // Accessors const pcl::PolygonMesh &mesh() const { return mesh_; } bool symmetric() const { return symmetric_; } double min_x() const { return min_x_; } double min_y() const { return min_y_; } double min_z() const { return min_z_; } double max_x() const { return max_x_; } double max_y() const { return max_y_; } double max_z() const { return max_z_; } private: pcl::PolygonMesh mesh_; bool symmetric_; double min_x_, min_y_, min_z_; // Bounding box in default orientation double max_x_, max_y_, max_z_; void SetObjectProperties(); }; #endif /** _SBPL_PERCEPTION_OBJECT_MODEL_H_ **/
[ "venkatrn@andrew.cmu.edu" ]
venkatrn@andrew.cmu.edu
9db1c2632fd08a3b135dd714f6fbbcb5f9dbb833
aa646aeef6ffcb0356c91dc97a1cca8b029d94ef
/src/iksdl/Spritef.cpp
030ff7a7431a181408eb5554622562db462d1361
[ "Zlib" ]
permissive
InternationalKoder/iksdl
3562ff4322c7da0c85f30a2efd4198dc50c95cde
066a60b405bab5310a500132b0bd4d82c6476f24
refs/heads/main
2023-05-13T16:27:29.203552
2021-05-29T21:20:23
2021-05-29T21:20:23
349,504,332
0
0
NOASSERTION
2021-05-29T21:20:24
2021-03-19T17:30:37
C++
UTF-8
C++
false
false
3,300
cpp
/* * IKSDL - C++ wrapper for SDL * Copyright (C) 2021 InternationalKoder * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. * */ #include "iksdl/Spritef.hpp" #include "iksdl/Texture.hpp" namespace iksdl { Spritef::Spritef(const Texture& texture, const Positionf& position) : BaseSprite(texture), m_rect({ .x = position.getX(), .y = position.getY(), .w = static_cast<float>(m_texture->m_size.getWidth()), .h = static_cast<float>(m_texture->m_size.getHeight()) }), m_centerPtr(nullptr) {} Spritef::Spritef(const Texture& texture, const Positionf& position, const Recti& textureRect) : BaseSprite(texture), m_rect({ .x = position.getX(), .y = position.getY(), .w = static_cast<float>(m_texture->m_size.getWidth()), .h = static_cast<float>(m_texture->m_size.getHeight()) }), m_centerPtr(nullptr) { Spritef::setTextureRect(textureRect); } void Spritef::scale(const Sizef& delta) { m_rect.w *= delta.getWidth(); m_rect.h *= delta.getHeight(); m_scale = m_scale * delta; } void Spritef::draw(SDL_Renderer* const renderer) const { if(m_rotation == 0.0 && m_flip == SDL_FLIP_NONE) SDL_RenderCopyF(renderer, m_texture->m_texture, m_textureRectPtr, &m_rect); else SDL_RenderCopyExF(renderer, m_texture->m_texture, m_textureRectPtr, &m_rect, m_rotation, m_centerPtr, m_flip); } void Spritef::setTextureRect(const Recti& rect) { // Update the rect to match the new texture rect's size if(rect.getWidth() != m_rect.w || rect.getHeight() != m_rect.h) { m_rect.w /= m_rect.w / rect.getWidth(); m_rect.h /= m_rect.h / rect.getHeight(); } // Apply current scale m_rect.w *= m_scale.getWidth(); m_rect.h *= m_scale.getHeight(); // Change texture rect m_textureRect = { .x = rect.getX(), .y = rect.getY(), .w = rect.getWidth(), .h = rect.getHeight() }; m_textureRectPtr = &m_textureRect; } void Spritef::resetTextureRect() { // Update the rect to match the full texture's size and apply current scale const Sizei& textureSize = m_texture->getSize(); m_rect.w = static_cast<float>(textureSize.getWidth()) * m_scale.getWidth(); m_rect.h = static_cast<float>(textureSize.getHeight()) * m_scale.getHeight(); // Ignore currently set texture rect m_textureRectPtr = nullptr; } void Spritef::setCenter(const Positionf& center) { m_center = SDL_FPoint { .x = center.getX(), .y = center.getY() }; m_centerPtr = &m_center; } }
[ "international_koder@yahoo.com" ]
international_koder@yahoo.com
e61d9fa47764bc5e330dfa908d308820bf8a9cc8
6259c0a16cb8ee1f9c047e0ca891bf32adcdf563
/NostaleReverBot/NosCrypto.cpp
a05c7621146f4cb9ce87e5d6c9e96d7a0b7af66e
[]
no_license
pusheax33/headlessNos
b3008345c3bd5c9710e36f49d150fafdcd2bf4ac
9041daf89cf2726ca5d4713f5af4df246f33004a
refs/heads/master
2022-01-19T08:00:20.232945
2019-06-04T20:10:03
2019-06-04T20:10:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,898
cpp
#include "NosCrypto.h" #include "Tools.h" DWORD prevNum = 0; DWORD generateSeed(DWORD num) { DWORD edx = (DWORD)((int)prevNum * (int)0x8088405); ++edx; prevNum = edx; edx = edx * num; return edx; } std::string generateRandomNum(DWORD* seed) { BYTE ecx = 0x0A; BYTE resto = 0x00; std::string strRandomBytes = ""; //DWORD64 randomBytes = 0x00; //BYTE counter = 0; int counter = 0; while (*seed != 0) { resto = 0x00; resto = *seed % ecx; *seed = *seed / ecx; // dec esi resto += 0x30; if (resto > 0x3A) { resto += 0x07; } counter += resto; if (strRandomBytes.length() == 7) break; strRandomBytes = (char)resto + strRandomBytes; if (strRandomBytes.length() > 7) strRandomBytes = strRandomBytes.substr(0, 8); //randomBytes += resto << (counter * 8); //++counter; } return strRandomBytes; // devuelve en hex } // ################################## LOGIN ENCRYPT/DECRYPT METHODS ############################################## std::string login_decrypt(std::string packet) { // server to client login packets decryption. for (int i = 0; i < packet.length(); ++i) { packet[i] -= 0x0F; if (packet[i] == 0x0A) { break; } if (packet[i] == 0x20) { continue; } } return packet; } std::string login_decrypt_server(std::string packet) { // method used on server side to decrypt client packets. for (int i = 0; i < packet.length(); ++i) { packet[i] = (packet[i] - 0x0F) ^ 0xC3; } return packet; } std::string login_encrypt(std::string & packet) { // client to server packet encryption for (int i = 0; i < packet.length(); ++i) { packet[i] = (packet[i] ^ 0xC3) + 0x0F; } return packet; } // ################################## INGAME ENCRYPT/DECRYPT METHODS ########################################## std::string ingame_decrypt(std::string packet) { return ""; } std::string ingame_encrypt(std::string packet) { return ""; }
[ "daniel.g7895@gmail.com" ]
daniel.g7895@gmail.com
acab1b8081c18c36000595e738492bb59d89c4e9
20ef80f5a262b7bdda1e07bc1a04d7efc9c10e15
/cpp/p3.cpp
5e775e34b10b0ba991479f9e54f1d958886aaed3
[]
no_license
cln/project-euler
cb8589467be5680dd3be527090f1747c48eb4fd5
11185b7952e90943ef39fa995ad378ac7547ac3e
refs/heads/master
2021-01-02T08:14:07.529955
2013-05-04T21:29:20
2013-05-04T21:29:20
9,860,425
0
0
null
null
null
null
UTF-8
C++
false
false
449
cpp
// Problem 3 // // The prime factors of 13195 are 5, 7, 13 and 29. // What is the largest prime factor of the number 600851475143? #include <iostream> using namespace std; int getLargestPrimeFactor(long int number) { int div = 2; while (number > 1) if ((number % div) == 0) { number = number / div; } else { div++; } return div; } int main(int argc, char** argv) { std::cout << getLargestPrimeFactor(600851475143) << std::endl; }
[ "cln.github@gmail.com" ]
cln.github@gmail.com
b99a321baccd5a9d2e559b18b5e57a83cac1fa89
8b1020b68ccf0d3dacaa40bce7d9dbb4ba915663
/tests/catch.hpp
3b759681efa0990f0b053f5c073298725257a571
[ "MIT" ]
permissive
ddemidov/ev3dev-lang-cpp
ad7df93f84b7f2069ebe28fc869fea750a0c118b
8f235a447036619f4cd12933dbd388167ab0ba35
refs/heads/master
2022-12-05T14:19:32.660769
2022-11-23T01:54:03
2022-11-23T02:17:06
48,567,832
75
53
MIT
2022-11-23T01:55:29
2015-12-25T05:31:59
C++
UTF-8
C++
false
false
368,645
hpp
/* * Catch v1.3.2 * Generated: 2015-12-28 15:07:07.166291 * ---------------------------------------------------------- * This file has been merged from multiple headers. Please don't edit it directly * Copyright (c) 2012 Two Blue Cubes Ltd. All rights reserved. * * 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) */ #ifndef TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED #define TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED #define TWOBLUECUBES_CATCH_HPP_INCLUDED #ifdef __clang__ # pragma clang system_header #elif defined __GNUC__ # pragma GCC system_header #endif // #included from: internal/catch_suppress_warnings.h #ifdef __clang__ # ifdef __ICC // icpc defines the __clang__ macro # pragma warning(push) # pragma warning(disable: 161 1682) # else // __ICC # pragma clang diagnostic ignored "-Wglobal-constructors" # pragma clang diagnostic ignored "-Wvariadic-macros" # pragma clang diagnostic ignored "-Wc99-extensions" # pragma clang diagnostic ignored "-Wunused-variable" # pragma clang diagnostic push # pragma clang diagnostic ignored "-Wpadded" # pragma clang diagnostic ignored "-Wc++98-compat" # pragma clang diagnostic ignored "-Wc++98-compat-pedantic" # pragma clang diagnostic ignored "-Wswitch-enum" # pragma clang diagnostic ignored "-Wcovered-switch-default" # endif #elif defined __GNUC__ # pragma GCC diagnostic ignored "-Wvariadic-macros" # pragma GCC diagnostic ignored "-Wunused-variable" # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wpadded" #endif #if defined(CATCH_CONFIG_MAIN) || defined(CATCH_CONFIG_RUNNER) # define CATCH_IMPL #endif #ifdef CATCH_IMPL # ifndef CLARA_CONFIG_MAIN # define CLARA_CONFIG_MAIN_NOT_DEFINED # define CLARA_CONFIG_MAIN # endif #endif // #included from: internal/catch_notimplemented_exception.h #define TWOBLUECUBES_CATCH_NOTIMPLEMENTED_EXCEPTION_H_INCLUDED // #included from: catch_common.h #define TWOBLUECUBES_CATCH_COMMON_H_INCLUDED #define INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line ) name##line #define INTERNAL_CATCH_UNIQUE_NAME_LINE( name, line ) INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line ) #define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __LINE__ ) #define INTERNAL_CATCH_STRINGIFY2( expr ) #expr #define INTERNAL_CATCH_STRINGIFY( expr ) INTERNAL_CATCH_STRINGIFY2( expr ) #include <sstream> #include <stdexcept> #include <algorithm> // #included from: catch_compiler_capabilities.h #define TWOBLUECUBES_CATCH_COMPILER_CAPABILITIES_HPP_INCLUDED // Detect a number of compiler features - mostly C++11/14 conformance - by compiler // The following features are defined: // // CATCH_CONFIG_CPP11_NULLPTR : is nullptr supported? // CATCH_CONFIG_CPP11_NOEXCEPT : is noexcept supported? // CATCH_CONFIG_CPP11_GENERATED_METHODS : The delete and default keywords for compiler generated methods // CATCH_CONFIG_CPP11_IS_ENUM : std::is_enum is supported? // CATCH_CONFIG_CPP11_TUPLE : std::tuple is supported // CATCH_CONFIG_CPP11_LONG_LONG : is long long supported? // CATCH_CONFIG_CPP11_OVERRIDE : is override supported? // CATCH_CONFIG_CPP11_UNIQUE_PTR : is unique_ptr supported (otherwise use auto_ptr) // CATCH_CONFIG_CPP11_OR_GREATER : Is C++11 supported? // CATCH_CONFIG_VARIADIC_MACROS : are variadic macros supported? // **************** // Note to maintainers: if new toggles are added please document them // in configuration.md, too // **************** // In general each macro has a _NO_<feature name> form // (e.g. CATCH_CONFIG_CPP11_NO_NULLPTR) which disables the feature. // Many features, at point of detection, define an _INTERNAL_ macro, so they // can be combined, en-mass, with the _NO_ forms later. // All the C++11 features can be disabled with CATCH_CONFIG_NO_CPP11 #ifdef __clang__ # if __has_feature(cxx_nullptr) # define CATCH_INTERNAL_CONFIG_CPP11_NULLPTR # endif # if __has_feature(cxx_noexcept) # define CATCH_INTERNAL_CONFIG_CPP11_NOEXCEPT # endif #endif // __clang__ //////////////////////////////////////////////////////////////////////////////// // Borland #ifdef __BORLANDC__ #endif // __BORLANDC__ //////////////////////////////////////////////////////////////////////////////// // EDG #ifdef __EDG_VERSION__ #endif // __EDG_VERSION__ //////////////////////////////////////////////////////////////////////////////// // Digital Mars #ifdef __DMC__ #endif // __DMC__ //////////////////////////////////////////////////////////////////////////////// // GCC #ifdef __GNUC__ #if __GNUC__ == 4 && __GNUC_MINOR__ >= 6 && defined(__GXX_EXPERIMENTAL_CXX0X__) # define CATCH_INTERNAL_CONFIG_CPP11_NULLPTR #endif // - otherwise more recent versions define __cplusplus >= 201103L // and will get picked up below #endif // __GNUC__ //////////////////////////////////////////////////////////////////////////////// // Visual C++ #ifdef _MSC_VER #if (_MSC_VER >= 1600) # define CATCH_INTERNAL_CONFIG_CPP11_NULLPTR # define CATCH_INTERNAL_CONFIG_CPP11_UNIQUE_PTR #endif #if (_MSC_VER >= 1900 ) // (VC++ 13 (VS2015)) #define CATCH_INTERNAL_CONFIG_CPP11_NOEXCEPT #define CATCH_INTERNAL_CONFIG_CPP11_GENERATED_METHODS #endif #endif // _MSC_VER //////////////////////////////////////////////////////////////////////////////// // Use variadic macros if the compiler supports them #if ( defined _MSC_VER && _MSC_VER > 1400 && !defined __EDGE__) || \ ( defined __WAVE__ && __WAVE_HAS_VARIADICS ) || \ ( defined __GNUC__ && __GNUC__ >= 3 ) || \ ( !defined __cplusplus && __STDC_VERSION__ >= 199901L || __cplusplus >= 201103L ) #define CATCH_INTERNAL_CONFIG_VARIADIC_MACROS #endif //////////////////////////////////////////////////////////////////////////////// // C++ language feature support // catch all support for C++11 #if defined(__cplusplus) && __cplusplus >= 201103L # define CATCH_CPP11_OR_GREATER # if !defined(CATCH_INTERNAL_CONFIG_CPP11_NULLPTR) # define CATCH_INTERNAL_CONFIG_CPP11_NULLPTR # endif # ifndef CATCH_INTERNAL_CONFIG_CPP11_NOEXCEPT # define CATCH_INTERNAL_CONFIG_CPP11_NOEXCEPT # endif # ifndef CATCH_INTERNAL_CONFIG_CPP11_GENERATED_METHODS # define CATCH_INTERNAL_CONFIG_CPP11_GENERATED_METHODS # endif # ifndef CATCH_INTERNAL_CONFIG_CPP11_IS_ENUM # define CATCH_INTERNAL_CONFIG_CPP11_IS_ENUM # endif # ifndef CATCH_INTERNAL_CONFIG_CPP11_TUPLE # define CATCH_INTERNAL_CONFIG_CPP11_TUPLE # endif # ifndef CATCH_INTERNAL_CONFIG_VARIADIC_MACROS # define CATCH_INTERNAL_CONFIG_VARIADIC_MACROS # endif # if !defined(CATCH_INTERNAL_CONFIG_CPP11_LONG_LONG) # define CATCH_INTERNAL_CONFIG_CPP11_LONG_LONG # endif # if !defined(CATCH_INTERNAL_CONFIG_CPP11_OVERRIDE) # define CATCH_INTERNAL_CONFIG_CPP11_OVERRIDE # endif # if !defined(CATCH_INTERNAL_CONFIG_CPP11_UNIQUE_PTR) # define CATCH_INTERNAL_CONFIG_CPP11_UNIQUE_PTR # endif #endif // __cplusplus >= 201103L // Now set the actual defines based on the above + anything the user has configured #if defined(CATCH_INTERNAL_CONFIG_CPP11_NULLPTR) && !defined(CATCH_CONFIG_CPP11_NO_NULLPTR) && !defined(CATCH_CONFIG_CPP11_NULLPTR) && !defined(CATCH_CONFIG_NO_CPP11) # define CATCH_CONFIG_CPP11_NULLPTR #endif #if defined(CATCH_INTERNAL_CONFIG_CPP11_NOEXCEPT) && !defined(CATCH_CONFIG_CPP11_NO_NOEXCEPT) && !defined(CATCH_CONFIG_CPP11_NOEXCEPT) && !defined(CATCH_CONFIG_NO_CPP11) # define CATCH_CONFIG_CPP11_NOEXCEPT #endif #if defined(CATCH_INTERNAL_CONFIG_CPP11_GENERATED_METHODS) && !defined(CATCH_CONFIG_CPP11_NO_GENERATED_METHODS) && !defined(CATCH_CONFIG_CPP11_GENERATED_METHODS) && !defined(CATCH_CONFIG_NO_CPP11) # define CATCH_CONFIG_CPP11_GENERATED_METHODS #endif #if defined(CATCH_INTERNAL_CONFIG_CPP11_IS_ENUM) && !defined(CATCH_CONFIG_CPP11_NO_IS_ENUM) && !defined(CATCH_CONFIG_CPP11_IS_ENUM) && !defined(CATCH_CONFIG_NO_CPP11) # define CATCH_CONFIG_CPP11_IS_ENUM #endif #if defined(CATCH_INTERNAL_CONFIG_CPP11_TUPLE) && !defined(CATCH_CONFIG_CPP11_NO_TUPLE) && !defined(CATCH_CONFIG_CPP11_TUPLE) && !defined(CATCH_CONFIG_NO_CPP11) # define CATCH_CONFIG_CPP11_TUPLE #endif #if defined(CATCH_INTERNAL_CONFIG_VARIADIC_MACROS) && !defined(CATCH_CONFIG_NO_VARIADIC_MACROS) && !defined(CATCH_CONFIG_VARIADIC_MACROS) # define CATCH_CONFIG_VARIADIC_MACROS #endif #if defined(CATCH_INTERNAL_CONFIG_CPP11_LONG_LONG) && !defined(CATCH_CONFIG_NO_LONG_LONG) && !defined(CATCH_CONFIG_CPP11_LONG_LONG) && !defined(CATCH_CONFIG_NO_CPP11) # define CATCH_CONFIG_CPP11_LONG_LONG #endif #if defined(CATCH_INTERNAL_CONFIG_CPP11_OVERRIDE) && !defined(CATCH_CONFIG_NO_OVERRIDE) && !defined(CATCH_CONFIG_CPP11_OVERRIDE) && !defined(CATCH_CONFIG_NO_CPP11) # define CATCH_CONFIG_CPP11_OVERRIDE #endif #if defined(CATCH_INTERNAL_CONFIG_CPP11_UNIQUE_PTR) && !defined(CATCH_CONFIG_NO_UNIQUE_PTR) && !defined(CATCH_CONFIG_CPP11_UNIQUE_PTR) && !defined(CATCH_CONFIG_NO_CPP11) # define CATCH_CONFIG_CPP11_UNIQUE_PTR #endif // noexcept support: #if defined(CATCH_CONFIG_CPP11_NOEXCEPT) && !defined(CATCH_NOEXCEPT) # define CATCH_NOEXCEPT noexcept # define CATCH_NOEXCEPT_IS(x) noexcept(x) #else # define CATCH_NOEXCEPT throw() # define CATCH_NOEXCEPT_IS(x) #endif // nullptr support #ifdef CATCH_CONFIG_CPP11_NULLPTR # define CATCH_NULL nullptr #else # define CATCH_NULL NULL #endif // override support #ifdef CATCH_CONFIG_CPP11_OVERRIDE # define CATCH_OVERRIDE override #else # define CATCH_OVERRIDE #endif // unique_ptr support #ifdef CATCH_CONFIG_CPP11_UNIQUE_PTR # define CATCH_AUTO_PTR( T ) std::unique_ptr<T> #else # define CATCH_AUTO_PTR( T ) std::auto_ptr<T> #endif namespace Catch { struct IConfig; struct CaseSensitive { enum Choice { Yes, No }; }; class NonCopyable { #ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS NonCopyable( NonCopyable const& ) = delete; NonCopyable( NonCopyable && ) = delete; NonCopyable& operator = ( NonCopyable const& ) = delete; NonCopyable& operator = ( NonCopyable && ) = delete; #else NonCopyable( NonCopyable const& info ); NonCopyable& operator = ( NonCopyable const& ); #endif protected: NonCopyable() {} virtual ~NonCopyable(); }; class SafeBool { public: typedef void (SafeBool::*type)() const; static type makeSafe( bool value ) { return value ? &SafeBool::trueValue : 0; } private: void trueValue() const {} }; template<typename ContainerT> inline void deleteAll( ContainerT& container ) { typename ContainerT::const_iterator it = container.begin(); typename ContainerT::const_iterator itEnd = container.end(); for(; it != itEnd; ++it ) delete *it; } template<typename AssociativeContainerT> inline void deleteAllValues( AssociativeContainerT& container ) { typename AssociativeContainerT::const_iterator it = container.begin(); typename AssociativeContainerT::const_iterator itEnd = container.end(); for(; it != itEnd; ++it ) delete it->second; } bool startsWith( std::string const& s, std::string const& prefix ); bool endsWith( std::string const& s, std::string const& suffix ); bool contains( std::string const& s, std::string const& infix ); void toLowerInPlace( std::string& s ); std::string toLower( std::string const& s ); std::string trim( std::string const& str ); bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis ); struct pluralise { pluralise( std::size_t count, std::string const& label ); friend std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser ); std::size_t m_count; std::string m_label; }; struct SourceLineInfo { SourceLineInfo(); SourceLineInfo( char const* _file, std::size_t _line ); SourceLineInfo( SourceLineInfo const& other ); # ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS SourceLineInfo( SourceLineInfo && ) = default; SourceLineInfo& operator = ( SourceLineInfo const& ) = default; SourceLineInfo& operator = ( SourceLineInfo && ) = default; # endif bool empty() const; bool operator == ( SourceLineInfo const& other ) const; bool operator < ( SourceLineInfo const& other ) const; std::string file; std::size_t line; }; std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info ); // This is just here to avoid compiler warnings with macro constants and boolean literals inline bool isTrue( bool value ){ return value; } inline bool alwaysTrue() { return true; } inline bool alwaysFalse() { return false; } void throwLogicError( std::string const& message, SourceLineInfo const& locationInfo ); void seedRng( IConfig const& config ); unsigned int rngSeed(); // Use this in variadic streaming macros to allow // >> +StreamEndStop // as well as // >> stuff +StreamEndStop struct StreamEndStop { std::string operator+() { return std::string(); } }; template<typename T> T const& operator + ( T const& value, StreamEndStop ) { return value; } } #define CATCH_INTERNAL_LINEINFO ::Catch::SourceLineInfo( __FILE__, static_cast<std::size_t>( __LINE__ ) ) #define CATCH_INTERNAL_ERROR( msg ) ::Catch::throwLogicError( msg, CATCH_INTERNAL_LINEINFO ); #include <ostream> namespace Catch { class NotImplementedException : public std::exception { public: NotImplementedException( SourceLineInfo const& lineInfo ); NotImplementedException( NotImplementedException const& ) {} virtual ~NotImplementedException() CATCH_NOEXCEPT {} virtual const char* what() const CATCH_NOEXCEPT; private: std::string m_what; SourceLineInfo m_lineInfo; }; } // end namespace Catch /////////////////////////////////////////////////////////////////////////////// #define CATCH_NOT_IMPLEMENTED throw Catch::NotImplementedException( CATCH_INTERNAL_LINEINFO ) // #included from: internal/catch_context.h #define TWOBLUECUBES_CATCH_CONTEXT_H_INCLUDED // #included from: catch_interfaces_generators.h #define TWOBLUECUBES_CATCH_INTERFACES_GENERATORS_H_INCLUDED #include <string> namespace Catch { struct IGeneratorInfo { virtual ~IGeneratorInfo(); virtual bool moveNext() = 0; virtual std::size_t getCurrentIndex() const = 0; }; struct IGeneratorsForTest { virtual ~IGeneratorsForTest(); virtual IGeneratorInfo& getGeneratorInfo( std::string const& fileInfo, std::size_t size ) = 0; virtual bool moveNext() = 0; }; IGeneratorsForTest* createGeneratorsForTest(); } // end namespace Catch // #included from: catch_ptr.hpp #define TWOBLUECUBES_CATCH_PTR_HPP_INCLUDED #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wpadded" #endif namespace Catch { // An intrusive reference counting smart pointer. // T must implement addRef() and release() methods // typically implementing the IShared interface template<typename T> class Ptr { public: Ptr() : m_p( CATCH_NULL ){} Ptr( T* p ) : m_p( p ){ if( m_p ) m_p->addRef(); } Ptr( Ptr const& other ) : m_p( other.m_p ){ if( m_p ) m_p->addRef(); } ~Ptr(){ if( m_p ) m_p->release(); } void reset() { if( m_p ) m_p->release(); m_p = CATCH_NULL; } Ptr& operator = ( T* p ){ Ptr temp( p ); swap( temp ); return *this; } Ptr& operator = ( Ptr const& other ){ Ptr temp( other ); swap( temp ); return *this; } void swap( Ptr& other ) { std::swap( m_p, other.m_p ); } T* get() const{ return m_p; } T& operator*() const { return *m_p; } T* operator->() const { return m_p; } bool operator !() const { return m_p == CATCH_NULL; } operator SafeBool::type() const { return SafeBool::makeSafe( m_p != CATCH_NULL ); } private: T* m_p; }; struct IShared : NonCopyable { virtual ~IShared(); virtual void addRef() const = 0; virtual void release() const = 0; }; template<typename T = IShared> struct SharedImpl : T { SharedImpl() : m_rc( 0 ){} virtual void addRef() const { ++m_rc; } virtual void release() const { if( --m_rc == 0 ) delete this; } mutable unsigned int m_rc; }; } // end namespace Catch #ifdef __clang__ #pragma clang diagnostic pop #endif #include <memory> #include <vector> #include <stdlib.h> namespace Catch { class TestCase; class Stream; struct IResultCapture; struct IRunner; struct IGeneratorsForTest; struct IConfig; struct IContext { virtual ~IContext(); virtual IResultCapture* getResultCapture() = 0; virtual IRunner* getRunner() = 0; virtual size_t getGeneratorIndex( std::string const& fileInfo, size_t totalSize ) = 0; virtual bool advanceGeneratorsForCurrentTest() = 0; virtual Ptr<IConfig const> getConfig() const = 0; }; struct IMutableContext : IContext { virtual ~IMutableContext(); virtual void setResultCapture( IResultCapture* resultCapture ) = 0; virtual void setRunner( IRunner* runner ) = 0; virtual void setConfig( Ptr<IConfig const> const& config ) = 0; }; IContext& getCurrentContext(); IMutableContext& getCurrentMutableContext(); void cleanUpContext(); Stream createStream( std::string const& streamName ); } // #included from: internal/catch_test_registry.hpp #define TWOBLUECUBES_CATCH_TEST_REGISTRY_HPP_INCLUDED // #included from: catch_interfaces_testcase.h #define TWOBLUECUBES_CATCH_INTERFACES_TESTCASE_H_INCLUDED #include <vector> namespace Catch { class TestSpec; struct ITestCase : IShared { virtual void invoke () const = 0; protected: virtual ~ITestCase(); }; class TestCase; struct IConfig; struct ITestCaseRegistry { virtual ~ITestCaseRegistry(); virtual std::vector<TestCase> const& getAllTests() const = 0; virtual std::vector<TestCase> const& getAllTestsSorted( IConfig const& config ) const = 0; }; bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config ); std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config ); std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config ); } namespace Catch { template<typename C> class MethodTestCase : public SharedImpl<ITestCase> { public: MethodTestCase( void (C::*method)() ) : m_method( method ) {} virtual void invoke() const { C obj; (obj.*m_method)(); } private: virtual ~MethodTestCase() {} void (C::*m_method)(); }; typedef void(*TestFunction)(); struct NameAndDesc { NameAndDesc( const char* _name = "", const char* _description= "" ) : name( _name ), description( _description ) {} const char* name; const char* description; }; void registerTestCase ( ITestCase* testCase, char const* className, NameAndDesc const& nameAndDesc, SourceLineInfo const& lineInfo ); struct AutoReg { AutoReg ( TestFunction function, SourceLineInfo const& lineInfo, NameAndDesc const& nameAndDesc ); template<typename C> AutoReg ( void (C::*method)(), char const* className, NameAndDesc const& nameAndDesc, SourceLineInfo const& lineInfo ) { registerTestCase ( new MethodTestCase<C>( method ), className, nameAndDesc, lineInfo ); } ~AutoReg(); private: AutoReg( AutoReg const& ); void operator= ( AutoReg const& ); }; void registerTestCaseFunction ( TestFunction function, SourceLineInfo const& lineInfo, NameAndDesc const& nameAndDesc ); } // end namespace Catch #ifdef CATCH_CONFIG_VARIADIC_MACROS /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_TESTCASE( ... ) \ static void INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )(); \ namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( &INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), CATCH_INTERNAL_LINEINFO, Catch::NameAndDesc( __VA_ARGS__ ) ); }\ static void INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )() /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_METHOD_AS_TEST_CASE( QualifiedMethod, ... ) \ namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( &QualifiedMethod, "&" #QualifiedMethod, Catch::NameAndDesc( __VA_ARGS__ ), CATCH_INTERNAL_LINEINFO ); } /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_TEST_CASE_METHOD( ClassName, ... )\ namespace{ \ struct INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ) : ClassName{ \ void test(); \ }; \ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar ) ( &INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )::test, #ClassName, Catch::NameAndDesc( __VA_ARGS__ ), CATCH_INTERNAL_LINEINFO ); \ } \ void INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )::test() /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_REGISTER_TESTCASE( Function, ... ) \ Catch::AutoReg( Function, CATCH_INTERNAL_LINEINFO, Catch::NameAndDesc( __VA_ARGS__ ) ); #else /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_TESTCASE( Name, Desc ) \ static void INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )(); \ namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( &INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), CATCH_INTERNAL_LINEINFO, Catch::NameAndDesc( Name, Desc ) ); }\ static void INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )() /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_METHOD_AS_TEST_CASE( QualifiedMethod, Name, Desc ) \ namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( &QualifiedMethod, "&" #QualifiedMethod, Catch::NameAndDesc( Name, Desc ), CATCH_INTERNAL_LINEINFO ); } /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_TEST_CASE_METHOD( ClassName, TestName, Desc )\ namespace{ \ struct INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ) : ClassName{ \ void test(); \ }; \ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar ) ( &INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )::test, #ClassName, Catch::NameAndDesc( TestName, Desc ), CATCH_INTERNAL_LINEINFO ); \ } \ void INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )::test() /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_REGISTER_TESTCASE( Function, Name, Desc ) \ Catch::AutoReg( Function, CATCH_INTERNAL_LINEINFO, Catch::NameAndDesc( Name, Desc ) ); #endif // #included from: internal/catch_capture.hpp #define TWOBLUECUBES_CATCH_CAPTURE_HPP_INCLUDED // #included from: catch_result_builder.h #define TWOBLUECUBES_CATCH_RESULT_BUILDER_H_INCLUDED // #included from: catch_result_type.h #define TWOBLUECUBES_CATCH_RESULT_TYPE_H_INCLUDED namespace Catch { // ResultWas::OfType enum struct ResultWas { enum OfType { Unknown = -1, Ok = 0, Info = 1, Warning = 2, FailureBit = 0x10, ExpressionFailed = FailureBit | 1, ExplicitFailure = FailureBit | 2, Exception = 0x100 | FailureBit, ThrewException = Exception | 1, DidntThrowException = Exception | 2, FatalErrorCondition = 0x200 | FailureBit }; }; inline bool isOk( ResultWas::OfType resultType ) { return ( resultType & ResultWas::FailureBit ) == 0; } inline bool isJustInfo( int flags ) { return flags == ResultWas::Info; } // ResultDisposition::Flags enum struct ResultDisposition { enum Flags { Normal = 0x01, ContinueOnFailure = 0x02, // Failures fail test, but execution continues FalseTest = 0x04, // Prefix expression with ! SuppressFail = 0x08 // Failures are reported but do not fail the test }; }; inline ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs ) { return static_cast<ResultDisposition::Flags>( static_cast<int>( lhs ) | static_cast<int>( rhs ) ); } inline bool shouldContinueOnFailure( int flags ) { return ( flags & ResultDisposition::ContinueOnFailure ) != 0; } inline bool isFalseTest( int flags ) { return ( flags & ResultDisposition::FalseTest ) != 0; } inline bool shouldSuppressFailure( int flags ) { return ( flags & ResultDisposition::SuppressFail ) != 0; } } // end namespace Catch // #included from: catch_assertionresult.h #define TWOBLUECUBES_CATCH_ASSERTIONRESULT_H_INCLUDED #include <string> namespace Catch { struct AssertionInfo { AssertionInfo() {} AssertionInfo( std::string const& _macroName, SourceLineInfo const& _lineInfo, std::string const& _capturedExpression, ResultDisposition::Flags _resultDisposition ); std::string macroName; SourceLineInfo lineInfo; std::string capturedExpression; ResultDisposition::Flags resultDisposition; }; struct AssertionResultData { AssertionResultData() : resultType( ResultWas::Unknown ) {} std::string reconstructedExpression; std::string message; ResultWas::OfType resultType; }; class AssertionResult { public: AssertionResult(); AssertionResult( AssertionInfo const& info, AssertionResultData const& data ); ~AssertionResult(); # ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS AssertionResult( AssertionResult const& ) = default; AssertionResult( AssertionResult && ) = default; AssertionResult& operator = ( AssertionResult const& ) = default; AssertionResult& operator = ( AssertionResult && ) = default; # endif bool isOk() const; bool succeeded() const; ResultWas::OfType getResultType() const; bool hasExpression() const; bool hasMessage() const; std::string getExpression() const; std::string getExpressionInMacro() const; bool hasExpandedExpression() const; std::string getExpandedExpression() const; std::string getMessage() const; SourceLineInfo getSourceInfo() const; std::string getTestMacroName() const; protected: AssertionInfo m_info; AssertionResultData m_resultData; }; } // end namespace Catch // #included from: catch_matchers.hpp #define TWOBLUECUBES_CATCH_MATCHERS_HPP_INCLUDED namespace Catch { namespace Matchers { namespace Impl { namespace Generic { template<typename ExpressionT> class AllOf; template<typename ExpressionT> class AnyOf; template<typename ExpressionT> class Not; } template<typename ExpressionT> struct Matcher : SharedImpl<IShared> { typedef ExpressionT ExpressionType; virtual ~Matcher() {} virtual Ptr<Matcher> clone() const = 0; virtual bool match( ExpressionT const& expr ) const = 0; virtual std::string toString() const = 0; Generic::AllOf<ExpressionT> operator && ( Matcher<ExpressionT> const& other ) const; Generic::AnyOf<ExpressionT> operator || ( Matcher<ExpressionT> const& other ) const; Generic::Not<ExpressionT> operator ! () const; }; template<typename DerivedT, typename ExpressionT> struct MatcherImpl : Matcher<ExpressionT> { virtual Ptr<Matcher<ExpressionT> > clone() const { return Ptr<Matcher<ExpressionT> >( new DerivedT( static_cast<DerivedT const&>( *this ) ) ); } }; namespace Generic { template<typename ExpressionT> class Not : public MatcherImpl<Not<ExpressionT>, ExpressionT> { public: explicit Not( Matcher<ExpressionT> const& matcher ) : m_matcher(matcher.clone()) {} Not( Not const& other ) : m_matcher( other.m_matcher ) {} virtual bool match( ExpressionT const& expr ) const CATCH_OVERRIDE { return !m_matcher->match( expr ); } virtual std::string toString() const CATCH_OVERRIDE { return "not " + m_matcher->toString(); } private: Ptr< Matcher<ExpressionT> > m_matcher; }; template<typename ExpressionT> class AllOf : public MatcherImpl<AllOf<ExpressionT>, ExpressionT> { public: AllOf() {} AllOf( AllOf const& other ) : m_matchers( other.m_matchers ) {} AllOf& add( Matcher<ExpressionT> const& matcher ) { m_matchers.push_back( matcher.clone() ); return *this; } virtual bool match( ExpressionT const& expr ) const { for( std::size_t i = 0; i < m_matchers.size(); ++i ) if( !m_matchers[i]->match( expr ) ) return false; return true; } virtual std::string toString() const { std::ostringstream oss; oss << "( "; for( std::size_t i = 0; i < m_matchers.size(); ++i ) { if( i != 0 ) oss << " and "; oss << m_matchers[i]->toString(); } oss << " )"; return oss.str(); } AllOf operator && ( Matcher<ExpressionT> const& other ) const { AllOf allOfExpr( *this ); allOfExpr.add( other ); return allOfExpr; } private: std::vector<Ptr<Matcher<ExpressionT> > > m_matchers; }; template<typename ExpressionT> class AnyOf : public MatcherImpl<AnyOf<ExpressionT>, ExpressionT> { public: AnyOf() {} AnyOf( AnyOf const& other ) : m_matchers( other.m_matchers ) {} AnyOf& add( Matcher<ExpressionT> const& matcher ) { m_matchers.push_back( matcher.clone() ); return *this; } virtual bool match( ExpressionT const& expr ) const { for( std::size_t i = 0; i < m_matchers.size(); ++i ) if( m_matchers[i]->match( expr ) ) return true; return false; } virtual std::string toString() const { std::ostringstream oss; oss << "( "; for( std::size_t i = 0; i < m_matchers.size(); ++i ) { if( i != 0 ) oss << " or "; oss << m_matchers[i]->toString(); } oss << " )"; return oss.str(); } AnyOf operator || ( Matcher<ExpressionT> const& other ) const { AnyOf anyOfExpr( *this ); anyOfExpr.add( other ); return anyOfExpr; } private: std::vector<Ptr<Matcher<ExpressionT> > > m_matchers; }; } // namespace Generic template<typename ExpressionT> Generic::AllOf<ExpressionT> Matcher<ExpressionT>::operator && ( Matcher<ExpressionT> const& other ) const { Generic::AllOf<ExpressionT> allOfExpr; allOfExpr.add( *this ); allOfExpr.add( other ); return allOfExpr; } template<typename ExpressionT> Generic::AnyOf<ExpressionT> Matcher<ExpressionT>::operator || ( Matcher<ExpressionT> const& other ) const { Generic::AnyOf<ExpressionT> anyOfExpr; anyOfExpr.add( *this ); anyOfExpr.add( other ); return anyOfExpr; } template<typename ExpressionT> Generic::Not<ExpressionT> Matcher<ExpressionT>::operator ! () const { return Generic::Not<ExpressionT>( *this ); } namespace StdString { inline std::string makeString( std::string const& str ) { return str; } inline std::string makeString( const char* str ) { return str ? std::string( str ) : std::string(); } struct CasedString { CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity ) : m_caseSensitivity( caseSensitivity ), m_str( adjustString( str ) ) {} std::string adjustString( std::string const& str ) const { return m_caseSensitivity == CaseSensitive::No ? toLower( str ) : str; } std::string toStringSuffix() const { return m_caseSensitivity == CaseSensitive::No ? " (case insensitive)" : ""; } CaseSensitive::Choice m_caseSensitivity; std::string m_str; }; struct Equals : MatcherImpl<Equals, std::string> { Equals( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes ) : m_data( str, caseSensitivity ) {} Equals( Equals const& other ) : m_data( other.m_data ){} virtual ~Equals(); virtual bool match( std::string const& expr ) const { return m_data.m_str == m_data.adjustString( expr );; } virtual std::string toString() const { return "equals: \"" + m_data.m_str + "\"" + m_data.toStringSuffix(); } CasedString m_data; }; struct Contains : MatcherImpl<Contains, std::string> { Contains( std::string const& substr, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes ) : m_data( substr, caseSensitivity ){} Contains( Contains const& other ) : m_data( other.m_data ){} virtual ~Contains(); virtual bool match( std::string const& expr ) const { return m_data.adjustString( expr ).find( m_data.m_str ) != std::string::npos; } virtual std::string toString() const { return "contains: \"" + m_data.m_str + "\"" + m_data.toStringSuffix(); } CasedString m_data; }; struct StartsWith : MatcherImpl<StartsWith, std::string> { StartsWith( std::string const& substr, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes ) : m_data( substr, caseSensitivity ){} StartsWith( StartsWith const& other ) : m_data( other.m_data ){} virtual ~StartsWith(); virtual bool match( std::string const& expr ) const { return m_data.adjustString( expr ).find( m_data.m_str ) == 0; } virtual std::string toString() const { return "starts with: \"" + m_data.m_str + "\"" + m_data.toStringSuffix(); } CasedString m_data; }; struct EndsWith : MatcherImpl<EndsWith, std::string> { EndsWith( std::string const& substr, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes ) : m_data( substr, caseSensitivity ){} EndsWith( EndsWith const& other ) : m_data( other.m_data ){} virtual ~EndsWith(); virtual bool match( std::string const& expr ) const { return m_data.adjustString( expr ).find( m_data.m_str ) == expr.size() - m_data.m_str.size(); } virtual std::string toString() const { return "ends with: \"" + m_data.m_str + "\"" + m_data.toStringSuffix(); } CasedString m_data; }; } // namespace StdString } // namespace Impl // The following functions create the actual matcher objects. // This allows the types to be inferred template<typename ExpressionT> inline Impl::Generic::Not<ExpressionT> Not( Impl::Matcher<ExpressionT> const& m ) { return Impl::Generic::Not<ExpressionT>( m ); } template<typename ExpressionT> inline Impl::Generic::AllOf<ExpressionT> AllOf( Impl::Matcher<ExpressionT> const& m1, Impl::Matcher<ExpressionT> const& m2 ) { return Impl::Generic::AllOf<ExpressionT>().add( m1 ).add( m2 ); } template<typename ExpressionT> inline Impl::Generic::AllOf<ExpressionT> AllOf( Impl::Matcher<ExpressionT> const& m1, Impl::Matcher<ExpressionT> const& m2, Impl::Matcher<ExpressionT> const& m3 ) { return Impl::Generic::AllOf<ExpressionT>().add( m1 ).add( m2 ).add( m3 ); } template<typename ExpressionT> inline Impl::Generic::AnyOf<ExpressionT> AnyOf( Impl::Matcher<ExpressionT> const& m1, Impl::Matcher<ExpressionT> const& m2 ) { return Impl::Generic::AnyOf<ExpressionT>().add( m1 ).add( m2 ); } template<typename ExpressionT> inline Impl::Generic::AnyOf<ExpressionT> AnyOf( Impl::Matcher<ExpressionT> const& m1, Impl::Matcher<ExpressionT> const& m2, Impl::Matcher<ExpressionT> const& m3 ) { return Impl::Generic::AnyOf<ExpressionT>().add( m1 ).add( m2 ).add( m3 ); } inline Impl::StdString::Equals Equals( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes ) { return Impl::StdString::Equals( str, caseSensitivity ); } inline Impl::StdString::Equals Equals( const char* str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes ) { return Impl::StdString::Equals( Impl::StdString::makeString( str ), caseSensitivity ); } inline Impl::StdString::Contains Contains( std::string const& substr, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes ) { return Impl::StdString::Contains( substr, caseSensitivity ); } inline Impl::StdString::Contains Contains( const char* substr, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes ) { return Impl::StdString::Contains( Impl::StdString::makeString( substr ), caseSensitivity ); } inline Impl::StdString::StartsWith StartsWith( std::string const& substr ) { return Impl::StdString::StartsWith( substr ); } inline Impl::StdString::StartsWith StartsWith( const char* substr ) { return Impl::StdString::StartsWith( Impl::StdString::makeString( substr ) ); } inline Impl::StdString::EndsWith EndsWith( std::string const& substr ) { return Impl::StdString::EndsWith( substr ); } inline Impl::StdString::EndsWith EndsWith( const char* substr ) { return Impl::StdString::EndsWith( Impl::StdString::makeString( substr ) ); } } // namespace Matchers using namespace Matchers; } // namespace Catch namespace Catch { struct TestFailureException{}; template<typename T> class ExpressionLhs; struct STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison; struct CopyableStream { CopyableStream() {} CopyableStream( CopyableStream const& other ) { oss << other.oss.str(); } CopyableStream& operator=( CopyableStream const& other ) { oss.str(""); oss << other.oss.str(); return *this; } std::ostringstream oss; }; class ResultBuilder { public: ResultBuilder( char const* macroName, SourceLineInfo const& lineInfo, char const* capturedExpression, ResultDisposition::Flags resultDisposition, char const* secondArg = "" ); template<typename T> ExpressionLhs<T const&> operator <= ( T const& operand ); ExpressionLhs<bool> operator <= ( bool value ); template<typename T> ResultBuilder& operator << ( T const& value ) { m_stream.oss << value; return *this; } template<typename RhsT> STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator && ( RhsT const& ); template<typename RhsT> STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator || ( RhsT const& ); ResultBuilder& setResultType( ResultWas::OfType result ); ResultBuilder& setResultType( bool result ); ResultBuilder& setLhs( std::string const& lhs ); ResultBuilder& setRhs( std::string const& rhs ); ResultBuilder& setOp( std::string const& op ); void endExpression(); std::string reconstructExpression() const; AssertionResult build() const; void useActiveException( ResultDisposition::Flags resultDisposition = ResultDisposition::Normal ); void captureResult( ResultWas::OfType resultType ); void captureExpression(); void captureExpectedException( std::string const& expectedMessage ); void captureExpectedException( Matchers::Impl::Matcher<std::string> const& matcher ); void handleResult( AssertionResult const& result ); void react(); bool shouldDebugBreak() const; bool allowThrows() const; private: AssertionInfo m_assertionInfo; AssertionResultData m_data; struct ExprComponents { ExprComponents() : testFalse( false ) {} bool testFalse; std::string lhs, rhs, op; } m_exprComponents; CopyableStream m_stream; bool m_shouldDebugBreak; bool m_shouldThrow; }; } // namespace Catch // Include after due to circular dependency: // #included from: catch_expression_lhs.hpp #define TWOBLUECUBES_CATCH_EXPRESSION_LHS_HPP_INCLUDED // #included from: catch_evaluate.hpp #define TWOBLUECUBES_CATCH_EVALUATE_HPP_INCLUDED #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable:4389) // '==' : signed/unsigned mismatch #endif #include <cstddef> namespace Catch { namespace Internal { enum Operator { IsEqualTo, IsNotEqualTo, IsLessThan, IsGreaterThan, IsLessThanOrEqualTo, IsGreaterThanOrEqualTo }; template<Operator Op> struct OperatorTraits { static const char* getName(){ return "*error*"; } }; template<> struct OperatorTraits<IsEqualTo> { static const char* getName(){ return "=="; } }; template<> struct OperatorTraits<IsNotEqualTo> { static const char* getName(){ return "!="; } }; template<> struct OperatorTraits<IsLessThan> { static const char* getName(){ return "<"; } }; template<> struct OperatorTraits<IsGreaterThan> { static const char* getName(){ return ">"; } }; template<> struct OperatorTraits<IsLessThanOrEqualTo> { static const char* getName(){ return "<="; } }; template<> struct OperatorTraits<IsGreaterThanOrEqualTo>{ static const char* getName(){ return ">="; } }; template<typename T> inline T& opCast(T const& t) { return const_cast<T&>(t); } // nullptr_t support based on pull request #154 from Konstantin Baumann #ifdef CATCH_CONFIG_CPP11_NULLPTR inline std::nullptr_t opCast(std::nullptr_t) { return nullptr; } #endif // CATCH_CONFIG_CPP11_NULLPTR // So the compare overloads can be operator agnostic we convey the operator as a template // enum, which is used to specialise an Evaluator for doing the comparison. template<typename T1, typename T2, Operator Op> class Evaluator{}; template<typename T1, typename T2> struct Evaluator<T1, T2, IsEqualTo> { static bool evaluate( T1 const& lhs, T2 const& rhs) { return opCast( lhs ) == opCast( rhs ); } }; template<typename T1, typename T2> struct Evaluator<T1, T2, IsNotEqualTo> { static bool evaluate( T1 const& lhs, T2 const& rhs ) { return opCast( lhs ) != opCast( rhs ); } }; template<typename T1, typename T2> struct Evaluator<T1, T2, IsLessThan> { static bool evaluate( T1 const& lhs, T2 const& rhs ) { return opCast( lhs ) < opCast( rhs ); } }; template<typename T1, typename T2> struct Evaluator<T1, T2, IsGreaterThan> { static bool evaluate( T1 const& lhs, T2 const& rhs ) { return opCast( lhs ) > opCast( rhs ); } }; template<typename T1, typename T2> struct Evaluator<T1, T2, IsGreaterThanOrEqualTo> { static bool evaluate( T1 const& lhs, T2 const& rhs ) { return opCast( lhs ) >= opCast( rhs ); } }; template<typename T1, typename T2> struct Evaluator<T1, T2, IsLessThanOrEqualTo> { static bool evaluate( T1 const& lhs, T2 const& rhs ) { return opCast( lhs ) <= opCast( rhs ); } }; template<Operator Op, typename T1, typename T2> bool applyEvaluator( T1 const& lhs, T2 const& rhs ) { return Evaluator<T1, T2, Op>::evaluate( lhs, rhs ); } // This level of indirection allows us to specialise for integer types // to avoid signed/ unsigned warnings // "base" overload template<Operator Op, typename T1, typename T2> bool compare( T1 const& lhs, T2 const& rhs ) { return Evaluator<T1, T2, Op>::evaluate( lhs, rhs ); } // unsigned X to int template<Operator Op> bool compare( unsigned int lhs, int rhs ) { return applyEvaluator<Op>( lhs, static_cast<unsigned int>( rhs ) ); } template<Operator Op> bool compare( unsigned long lhs, int rhs ) { return applyEvaluator<Op>( lhs, static_cast<unsigned int>( rhs ) ); } template<Operator Op> bool compare( unsigned char lhs, int rhs ) { return applyEvaluator<Op>( lhs, static_cast<unsigned int>( rhs ) ); } // unsigned X to long template<Operator Op> bool compare( unsigned int lhs, long rhs ) { return applyEvaluator<Op>( lhs, static_cast<unsigned long>( rhs ) ); } template<Operator Op> bool compare( unsigned long lhs, long rhs ) { return applyEvaluator<Op>( lhs, static_cast<unsigned long>( rhs ) ); } template<Operator Op> bool compare( unsigned char lhs, long rhs ) { return applyEvaluator<Op>( lhs, static_cast<unsigned long>( rhs ) ); } // int to unsigned X template<Operator Op> bool compare( int lhs, unsigned int rhs ) { return applyEvaluator<Op>( static_cast<unsigned int>( lhs ), rhs ); } template<Operator Op> bool compare( int lhs, unsigned long rhs ) { return applyEvaluator<Op>( static_cast<unsigned int>( lhs ), rhs ); } template<Operator Op> bool compare( int lhs, unsigned char rhs ) { return applyEvaluator<Op>( static_cast<unsigned int>( lhs ), rhs ); } // long to unsigned X template<Operator Op> bool compare( long lhs, unsigned int rhs ) { return applyEvaluator<Op>( static_cast<unsigned long>( lhs ), rhs ); } template<Operator Op> bool compare( long lhs, unsigned long rhs ) { return applyEvaluator<Op>( static_cast<unsigned long>( lhs ), rhs ); } template<Operator Op> bool compare( long lhs, unsigned char rhs ) { return applyEvaluator<Op>( static_cast<unsigned long>( lhs ), rhs ); } // pointer to long (when comparing against NULL) template<Operator Op, typename T> bool compare( long lhs, T* rhs ) { return Evaluator<T*, T*, Op>::evaluate( reinterpret_cast<T*>( lhs ), rhs ); } template<Operator Op, typename T> bool compare( T* lhs, long rhs ) { return Evaluator<T*, T*, Op>::evaluate( lhs, reinterpret_cast<T*>( rhs ) ); } // pointer to int (when comparing against NULL) template<Operator Op, typename T> bool compare( int lhs, T* rhs ) { return Evaluator<T*, T*, Op>::evaluate( reinterpret_cast<T*>( lhs ), rhs ); } template<Operator Op, typename T> bool compare( T* lhs, int rhs ) { return Evaluator<T*, T*, Op>::evaluate( lhs, reinterpret_cast<T*>( rhs ) ); } #ifdef CATCH_CONFIG_CPP11_LONG_LONG // long long to unsigned X template<Operator Op> bool compare( long long lhs, unsigned int rhs ) { return applyEvaluator<Op>( static_cast<unsigned long>( lhs ), rhs ); } template<Operator Op> bool compare( long long lhs, unsigned long rhs ) { return applyEvaluator<Op>( static_cast<unsigned long>( lhs ), rhs ); } template<Operator Op> bool compare( long long lhs, unsigned long long rhs ) { return applyEvaluator<Op>( static_cast<unsigned long>( lhs ), rhs ); } template<Operator Op> bool compare( long long lhs, unsigned char rhs ) { return applyEvaluator<Op>( static_cast<unsigned long>( lhs ), rhs ); } // unsigned long long to X template<Operator Op> bool compare( unsigned long long lhs, int rhs ) { return applyEvaluator<Op>( static_cast<long>( lhs ), rhs ); } template<Operator Op> bool compare( unsigned long long lhs, long rhs ) { return applyEvaluator<Op>( static_cast<long>( lhs ), rhs ); } template<Operator Op> bool compare( unsigned long long lhs, long long rhs ) { return applyEvaluator<Op>( static_cast<long>( lhs ), rhs ); } template<Operator Op> bool compare( unsigned long long lhs, char rhs ) { return applyEvaluator<Op>( static_cast<long>( lhs ), rhs ); } // pointer to long long (when comparing against NULL) template<Operator Op, typename T> bool compare( long long lhs, T* rhs ) { return Evaluator<T*, T*, Op>::evaluate( reinterpret_cast<T*>( lhs ), rhs ); } template<Operator Op, typename T> bool compare( T* lhs, long long rhs ) { return Evaluator<T*, T*, Op>::evaluate( lhs, reinterpret_cast<T*>( rhs ) ); } #endif // CATCH_CONFIG_CPP11_LONG_LONG #ifdef CATCH_CONFIG_CPP11_NULLPTR // pointer to nullptr_t (when comparing against nullptr) template<Operator Op, typename T> bool compare( std::nullptr_t, T* rhs ) { return Evaluator<T*, T*, Op>::evaluate( nullptr, rhs ); } template<Operator Op, typename T> bool compare( T* lhs, std::nullptr_t ) { return Evaluator<T*, T*, Op>::evaluate( lhs, nullptr ); } #endif // CATCH_CONFIG_CPP11_NULLPTR } // end of namespace Internal } // end of namespace Catch #ifdef _MSC_VER #pragma warning(pop) #endif // #included from: catch_tostring.h #define TWOBLUECUBES_CATCH_TOSTRING_H_INCLUDED #include <sstream> #include <iomanip> #include <limits> #include <vector> #include <cstddef> #ifdef __OBJC__ // #included from: catch_objc_arc.hpp #define TWOBLUECUBES_CATCH_OBJC_ARC_HPP_INCLUDED #import <Foundation/Foundation.h> #ifdef __has_feature #define CATCH_ARC_ENABLED __has_feature(objc_arc) #else #define CATCH_ARC_ENABLED 0 #endif void arcSafeRelease( NSObject* obj ); id performOptionalSelector( id obj, SEL sel ); #if !CATCH_ARC_ENABLED inline void arcSafeRelease( NSObject* obj ) { [obj release]; } inline id performOptionalSelector( id obj, SEL sel ) { if( [obj respondsToSelector: sel] ) return [obj performSelector: sel]; return nil; } #define CATCH_UNSAFE_UNRETAINED #define CATCH_ARC_STRONG #else inline void arcSafeRelease( NSObject* ){} inline id performOptionalSelector( id obj, SEL sel ) { #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Warc-performSelector-leaks" #endif if( [obj respondsToSelector: sel] ) return [obj performSelector: sel]; #ifdef __clang__ #pragma clang diagnostic pop #endif return nil; } #define CATCH_UNSAFE_UNRETAINED __unsafe_unretained #define CATCH_ARC_STRONG __strong #endif #endif #ifdef CATCH_CONFIG_CPP11_TUPLE #include <tuple> #endif #ifdef CATCH_CONFIG_CPP11_IS_ENUM #include <type_traits> #endif namespace Catch { // Why we're here. template<typename T> std::string toString( T const& value ); // Built in overloads std::string toString( std::string const& value ); std::string toString( std::wstring const& value ); std::string toString( const char* const value ); std::string toString( char* const value ); std::string toString( const wchar_t* const value ); std::string toString( wchar_t* const value ); std::string toString( int value ); std::string toString( unsigned long value ); std::string toString( unsigned int value ); std::string toString( const double value ); std::string toString( const float value ); std::string toString( bool value ); std::string toString( char value ); std::string toString( signed char value ); std::string toString( unsigned char value ); #ifdef CATCH_CONFIG_CPP11_LONG_LONG std::string toString( long long value ); std::string toString( unsigned long long value ); #endif #ifdef CATCH_CONFIG_CPP11_NULLPTR std::string toString( std::nullptr_t ); #endif #ifdef __OBJC__ std::string toString( NSString const * const& nsstring ); std::string toString( NSString * CATCH_ARC_STRONG const& nsstring ); std::string toString( NSObject* const& nsObject ); #endif namespace Detail { extern const std::string unprintableString; struct BorgType { template<typename T> BorgType( T const& ); }; struct TrueType { char sizer[1]; }; struct FalseType { char sizer[2]; }; TrueType& testStreamable( std::ostream& ); FalseType testStreamable( FalseType ); FalseType operator<<( std::ostream const&, BorgType const& ); template<typename T> struct IsStreamInsertable { static std::ostream &s; static T const&t; enum { value = sizeof( testStreamable(s << t) ) == sizeof( TrueType ) }; }; #if defined(CATCH_CONFIG_CPP11_IS_ENUM) template<typename T, bool IsEnum = std::is_enum<T>::value > struct EnumStringMaker { static std::string convert( T const& ) { return unprintableString; } }; template<typename T> struct EnumStringMaker<T,true> { static std::string convert( T const& v ) { return ::Catch::toString( static_cast<typename std::underlying_type<T>::type>(v) ); } }; #endif template<bool C> struct StringMakerBase { #if defined(CATCH_CONFIG_CPP11_IS_ENUM) template<typename T> static std::string convert( T const& v ) { return EnumStringMaker<T>::convert( v ); } #else template<typename T> static std::string convert( T const& ) { return unprintableString; } #endif }; template<> struct StringMakerBase<true> { template<typename T> static std::string convert( T const& _value ) { std::ostringstream oss; oss << _value; return oss.str(); } }; std::string rawMemoryToString( const void *object, std::size_t size ); template<typename T> inline std::string rawMemoryToString( const T& object ) { return rawMemoryToString( &object, sizeof(object) ); } } // end namespace Detail template<typename T> struct StringMaker : Detail::StringMakerBase<Detail::IsStreamInsertable<T>::value> {}; template<typename T> struct StringMaker<T*> { template<typename U> static std::string convert( U* p ) { if( !p ) return "NULL"; else return Detail::rawMemoryToString( p ); } }; template<typename R, typename C> struct StringMaker<R C::*> { static std::string convert( R C::* p ) { if( !p ) return "NULL"; else return Detail::rawMemoryToString( p ); } }; namespace Detail { template<typename InputIterator> std::string rangeToString( InputIterator first, InputIterator last ); } //template<typename T, typename Allocator> //struct StringMaker<std::vector<T, Allocator> > { // static std::string convert( std::vector<T,Allocator> const& v ) { // return Detail::rangeToString( v.begin(), v.end() ); // } //}; template<typename T, typename Allocator> std::string toString( std::vector<T,Allocator> const& v ) { return Detail::rangeToString( v.begin(), v.end() ); } #ifdef CATCH_CONFIG_CPP11_TUPLE // toString for tuples namespace TupleDetail { template< typename Tuple, std::size_t N = 0, bool = (N < std::tuple_size<Tuple>::value) > struct ElementPrinter { static void print( const Tuple& tuple, std::ostream& os ) { os << ( N ? ", " : " " ) << Catch::toString(std::get<N>(tuple)); ElementPrinter<Tuple,N+1>::print(tuple,os); } }; template< typename Tuple, std::size_t N > struct ElementPrinter<Tuple,N,false> { static void print( const Tuple&, std::ostream& ) {} }; } template<typename ...Types> struct StringMaker<std::tuple<Types...>> { static std::string convert( const std::tuple<Types...>& tuple ) { std::ostringstream os; os << '{'; TupleDetail::ElementPrinter<std::tuple<Types...>>::print( tuple, os ); os << " }"; return os.str(); } }; #endif // CATCH_CONFIG_CPP11_TUPLE namespace Detail { template<typename T> std::string makeString( T const& value ) { return StringMaker<T>::convert( value ); } } // end namespace Detail /// \brief converts any type to a string /// /// The default template forwards on to ostringstream - except when an /// ostringstream overload does not exist - in which case it attempts to detect /// that and writes {?}. /// Overload (not specialise) this template for custom typs that you don't want /// to provide an ostream overload for. template<typename T> std::string toString( T const& value ) { return StringMaker<T>::convert( value ); } namespace Detail { template<typename InputIterator> std::string rangeToString( InputIterator first, InputIterator last ) { std::ostringstream oss; oss << "{ "; if( first != last ) { oss << Catch::toString( *first ); for( ++first ; first != last ; ++first ) oss << ", " << Catch::toString( *first ); } oss << " }"; return oss.str(); } } } // end namespace Catch namespace Catch { // Wraps the LHS of an expression and captures the operator and RHS (if any) - // wrapping them all in a ResultBuilder object template<typename T> class ExpressionLhs { ExpressionLhs& operator = ( ExpressionLhs const& ); # ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS ExpressionLhs& operator = ( ExpressionLhs && ) = delete; # endif public: ExpressionLhs( ResultBuilder& rb, T lhs ) : m_rb( rb ), m_lhs( lhs ) {} # ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS ExpressionLhs( ExpressionLhs const& ) = default; ExpressionLhs( ExpressionLhs && ) = default; # endif template<typename RhsT> ResultBuilder& operator == ( RhsT const& rhs ) { return captureExpression<Internal::IsEqualTo>( rhs ); } template<typename RhsT> ResultBuilder& operator != ( RhsT const& rhs ) { return captureExpression<Internal::IsNotEqualTo>( rhs ); } template<typename RhsT> ResultBuilder& operator < ( RhsT const& rhs ) { return captureExpression<Internal::IsLessThan>( rhs ); } template<typename RhsT> ResultBuilder& operator > ( RhsT const& rhs ) { return captureExpression<Internal::IsGreaterThan>( rhs ); } template<typename RhsT> ResultBuilder& operator <= ( RhsT const& rhs ) { return captureExpression<Internal::IsLessThanOrEqualTo>( rhs ); } template<typename RhsT> ResultBuilder& operator >= ( RhsT const& rhs ) { return captureExpression<Internal::IsGreaterThanOrEqualTo>( rhs ); } ResultBuilder& operator == ( bool rhs ) { return captureExpression<Internal::IsEqualTo>( rhs ); } ResultBuilder& operator != ( bool rhs ) { return captureExpression<Internal::IsNotEqualTo>( rhs ); } void endExpression() { bool value = m_lhs ? true : false; m_rb .setLhs( Catch::toString( value ) ) .setResultType( value ) .endExpression(); } // Only simple binary expressions are allowed on the LHS. // If more complex compositions are required then place the sub expression in parentheses template<typename RhsT> STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator + ( RhsT const& ); template<typename RhsT> STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator - ( RhsT const& ); template<typename RhsT> STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator / ( RhsT const& ); template<typename RhsT> STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator * ( RhsT const& ); template<typename RhsT> STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator && ( RhsT const& ); template<typename RhsT> STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator || ( RhsT const& ); private: template<Internal::Operator Op, typename RhsT> ResultBuilder& captureExpression( RhsT const& rhs ) { return m_rb .setResultType( Internal::compare<Op>( m_lhs, rhs ) ) .setLhs( Catch::toString( m_lhs ) ) .setRhs( Catch::toString( rhs ) ) .setOp( Internal::OperatorTraits<Op>::getName() ); } private: ResultBuilder& m_rb; T m_lhs; }; } // end namespace Catch namespace Catch { template<typename T> inline ExpressionLhs<T const&> ResultBuilder::operator <= ( T const& operand ) { return ExpressionLhs<T const&>( *this, operand ); } inline ExpressionLhs<bool> ResultBuilder::operator <= ( bool value ) { return ExpressionLhs<bool>( *this, value ); } } // namespace Catch // #included from: catch_message.h #define TWOBLUECUBES_CATCH_MESSAGE_H_INCLUDED #include <string> namespace Catch { struct MessageInfo { MessageInfo( std::string const& _macroName, SourceLineInfo const& _lineInfo, ResultWas::OfType _type ); std::string macroName; SourceLineInfo lineInfo; ResultWas::OfType type; std::string message; unsigned int sequence; bool operator == ( MessageInfo const& other ) const { return sequence == other.sequence; } bool operator < ( MessageInfo const& other ) const { return sequence < other.sequence; } private: static unsigned int globalCount; }; struct MessageBuilder { MessageBuilder( std::string const& macroName, SourceLineInfo const& lineInfo, ResultWas::OfType type ) : m_info( macroName, lineInfo, type ) {} template<typename T> MessageBuilder& operator << ( T const& value ) { m_stream << value; return *this; } MessageInfo m_info; std::ostringstream m_stream; }; class ScopedMessage { public: ScopedMessage( MessageBuilder const& builder ); ScopedMessage( ScopedMessage const& other ); ~ScopedMessage(); MessageInfo m_info; }; } // end namespace Catch // #included from: catch_interfaces_capture.h #define TWOBLUECUBES_CATCH_INTERFACES_CAPTURE_H_INCLUDED #include <string> namespace Catch { class TestCase; class AssertionResult; struct AssertionInfo; struct SectionInfo; struct SectionEndInfo; struct MessageInfo; class ScopedMessageBuilder; struct Counts; struct IResultCapture { virtual ~IResultCapture(); virtual void assertionEnded( AssertionResult const& result ) = 0; virtual bool sectionStarted( SectionInfo const& sectionInfo, Counts& assertions ) = 0; virtual void sectionEnded( SectionEndInfo const& endInfo ) = 0; virtual void sectionEndedEarly( SectionEndInfo const& endInfo ) = 0; virtual void pushScopedMessage( MessageInfo const& message ) = 0; virtual void popScopedMessage( MessageInfo const& message ) = 0; virtual std::string getCurrentTestName() const = 0; virtual const AssertionResult* getLastResult() const = 0; virtual void handleFatalErrorCondition( std::string const& message ) = 0; }; IResultCapture& getResultCapture(); } // #included from: catch_debugger.h #define TWOBLUECUBES_CATCH_DEBUGGER_H_INCLUDED // #included from: catch_platform.h #define TWOBLUECUBES_CATCH_PLATFORM_H_INCLUDED #if defined(__MAC_OS_X_VERSION_MIN_REQUIRED) #define CATCH_PLATFORM_MAC #elif defined(__IPHONE_OS_VERSION_MIN_REQUIRED) #define CATCH_PLATFORM_IPHONE #elif defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) #define CATCH_PLATFORM_WINDOWS #endif #include <string> namespace Catch{ bool isDebuggerActive(); void writeToDebugConsole( std::string const& text ); } #ifdef CATCH_PLATFORM_MAC // The following code snippet based on: // http://cocoawithlove.com/2008/03/break-into-debugger.html #ifdef DEBUG #if defined(__ppc64__) || defined(__ppc__) #define CATCH_BREAK_INTO_DEBUGGER() \ if( Catch::isDebuggerActive() ) { \ __asm__("li r0, 20\nsc\nnop\nli r0, 37\nli r4, 2\nsc\nnop\n" \ : : : "memory","r0","r3","r4" ); \ } #else #define CATCH_BREAK_INTO_DEBUGGER() if( Catch::isDebuggerActive() ) {__asm__("int $3\n" : : );} #endif #endif #elif defined(_MSC_VER) #define CATCH_BREAK_INTO_DEBUGGER() if( Catch::isDebuggerActive() ) { __debugbreak(); } #elif defined(__MINGW32__) extern "C" __declspec(dllimport) void __stdcall DebugBreak(); #define CATCH_BREAK_INTO_DEBUGGER() if( Catch::isDebuggerActive() ) { DebugBreak(); } #endif #ifndef CATCH_BREAK_INTO_DEBUGGER #define CATCH_BREAK_INTO_DEBUGGER() Catch::alwaysTrue(); #endif // #included from: catch_interfaces_runner.h #define TWOBLUECUBES_CATCH_INTERFACES_RUNNER_H_INCLUDED namespace Catch { class TestCase; struct IRunner { virtual ~IRunner(); virtual bool aborting() const = 0; }; } /////////////////////////////////////////////////////////////////////////////// // In the event of a failure works out if the debugger needs to be invoked // and/or an exception thrown and takes appropriate action. // This needs to be done as a macro so the debugger will stop in the user // source code rather than in Catch library code #define INTERNAL_CATCH_REACT( resultBuilder ) \ if( resultBuilder.shouldDebugBreak() ) CATCH_BREAK_INTO_DEBUGGER(); \ resultBuilder.react(); /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_TEST( expr, resultDisposition, macroName ) \ do { \ Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, #expr, resultDisposition ); \ try { \ ( __catchResult <= expr ).endExpression(); \ } \ catch( ... ) { \ __catchResult.useActiveException( Catch::ResultDisposition::Normal ); \ } \ INTERNAL_CATCH_REACT( __catchResult ) \ } while( Catch::isTrue( false && (expr) ) ) // expr here is never evaluated at runtime but it forces the compiler to give it a look /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_IF( expr, resultDisposition, macroName ) \ INTERNAL_CATCH_TEST( expr, resultDisposition, macroName ); \ if( Catch::getResultCapture().getLastResult()->succeeded() ) /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_ELSE( expr, resultDisposition, macroName ) \ INTERNAL_CATCH_TEST( expr, resultDisposition, macroName ); \ if( !Catch::getResultCapture().getLastResult()->succeeded() ) /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_NO_THROW( expr, resultDisposition, macroName ) \ do { \ Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, #expr, resultDisposition ); \ try { \ expr; \ __catchResult.captureResult( Catch::ResultWas::Ok ); \ } \ catch( ... ) { \ __catchResult.useActiveException( resultDisposition ); \ } \ INTERNAL_CATCH_REACT( __catchResult ) \ } while( Catch::alwaysFalse() ) /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_THROWS( expr, resultDisposition, matcher, macroName ) \ do { \ Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, #expr, resultDisposition, #matcher ); \ if( __catchResult.allowThrows() ) \ try { \ expr; \ __catchResult.captureResult( Catch::ResultWas::DidntThrowException ); \ } \ catch( ... ) { \ __catchResult.captureExpectedException( matcher ); \ } \ else \ __catchResult.captureResult( Catch::ResultWas::Ok ); \ INTERNAL_CATCH_REACT( __catchResult ) \ } while( Catch::alwaysFalse() ) /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_THROWS_AS( expr, exceptionType, resultDisposition, macroName ) \ do { \ Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, #expr, resultDisposition ); \ if( __catchResult.allowThrows() ) \ try { \ expr; \ __catchResult.captureResult( Catch::ResultWas::DidntThrowException ); \ } \ catch( exceptionType ) { \ __catchResult.captureResult( Catch::ResultWas::Ok ); \ } \ catch( ... ) { \ __catchResult.useActiveException( resultDisposition ); \ } \ else \ __catchResult.captureResult( Catch::ResultWas::Ok ); \ INTERNAL_CATCH_REACT( __catchResult ) \ } while( Catch::alwaysFalse() ) /////////////////////////////////////////////////////////////////////////////// #ifdef CATCH_CONFIG_VARIADIC_MACROS #define INTERNAL_CATCH_MSG( messageType, resultDisposition, macroName, ... ) \ do { \ Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, "", resultDisposition ); \ __catchResult << __VA_ARGS__ + ::Catch::StreamEndStop(); \ __catchResult.captureResult( messageType ); \ INTERNAL_CATCH_REACT( __catchResult ) \ } while( Catch::alwaysFalse() ) #else #define INTERNAL_CATCH_MSG( messageType, resultDisposition, macroName, log ) \ do { \ Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, "", resultDisposition ); \ __catchResult << log + ::Catch::StreamEndStop(); \ __catchResult.captureResult( messageType ); \ INTERNAL_CATCH_REACT( __catchResult ) \ } while( Catch::alwaysFalse() ) #endif /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_INFO( log, macroName ) \ Catch::ScopedMessage INTERNAL_CATCH_UNIQUE_NAME( scopedMessage ) = Catch::MessageBuilder( macroName, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log; /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CHECK_THAT( arg, matcher, resultDisposition, macroName ) \ do { \ Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, #arg ", " #matcher, resultDisposition ); \ try { \ std::string matcherAsString = (matcher).toString(); \ __catchResult \ .setLhs( Catch::toString( arg ) ) \ .setRhs( matcherAsString == Catch::Detail::unprintableString ? #matcher : matcherAsString ) \ .setOp( "matches" ) \ .setResultType( (matcher).match( arg ) ); \ __catchResult.captureExpression(); \ } catch( ... ) { \ __catchResult.useActiveException( resultDisposition | Catch::ResultDisposition::ContinueOnFailure ); \ } \ INTERNAL_CATCH_REACT( __catchResult ) \ } while( Catch::alwaysFalse() ) // #included from: internal/catch_section.h #define TWOBLUECUBES_CATCH_SECTION_H_INCLUDED // #included from: catch_section_info.h #define TWOBLUECUBES_CATCH_SECTION_INFO_H_INCLUDED // #included from: catch_totals.hpp #define TWOBLUECUBES_CATCH_TOTALS_HPP_INCLUDED #include <cstddef> namespace Catch { struct Counts { Counts() : passed( 0 ), failed( 0 ), failedButOk( 0 ) {} Counts operator - ( Counts const& other ) const { Counts diff; diff.passed = passed - other.passed; diff.failed = failed - other.failed; diff.failedButOk = failedButOk - other.failedButOk; return diff; } Counts& operator += ( Counts const& other ) { passed += other.passed; failed += other.failed; failedButOk += other.failedButOk; return *this; } std::size_t total() const { return passed + failed + failedButOk; } bool allPassed() const { return failed == 0 && failedButOk == 0; } bool allOk() const { return failed == 0; } std::size_t passed; std::size_t failed; std::size_t failedButOk; }; struct Totals { Totals operator - ( Totals const& other ) const { Totals diff; diff.assertions = assertions - other.assertions; diff.testCases = testCases - other.testCases; return diff; } Totals delta( Totals const& prevTotals ) const { Totals diff = *this - prevTotals; if( diff.assertions.failed > 0 ) ++diff.testCases.failed; else if( diff.assertions.failedButOk > 0 ) ++diff.testCases.failedButOk; else ++diff.testCases.passed; return diff; } Totals& operator += ( Totals const& other ) { assertions += other.assertions; testCases += other.testCases; return *this; } Counts assertions; Counts testCases; }; } namespace Catch { struct SectionInfo { SectionInfo ( SourceLineInfo const& _lineInfo, std::string const& _name, std::string const& _description = std::string() ); std::string name; std::string description; SourceLineInfo lineInfo; }; struct SectionEndInfo { SectionEndInfo( SectionInfo const& _sectionInfo, Counts const& _prevAssertions, double _durationInSeconds ) : sectionInfo( _sectionInfo ), prevAssertions( _prevAssertions ), durationInSeconds( _durationInSeconds ) {} SectionInfo sectionInfo; Counts prevAssertions; double durationInSeconds; }; } // end namespace Catch // #included from: catch_timer.h #define TWOBLUECUBES_CATCH_TIMER_H_INCLUDED #ifdef CATCH_PLATFORM_WINDOWS typedef unsigned long long uint64_t; #else #include <stdint.h> #endif namespace Catch { class Timer { public: Timer() : m_ticks( 0 ) {} void start(); unsigned int getElapsedMicroseconds() const; unsigned int getElapsedMilliseconds() const; double getElapsedSeconds() const; private: uint64_t m_ticks; }; } // namespace Catch #include <string> namespace Catch { class Section : NonCopyable { public: Section( SectionInfo const& info ); ~Section(); // This indicates whether the section should be executed or not operator bool() const; private: SectionInfo m_info; std::string m_name; Counts m_assertions; bool m_sectionIncluded; Timer m_timer; }; } // end namespace Catch #ifdef CATCH_CONFIG_VARIADIC_MACROS #define INTERNAL_CATCH_SECTION( ... ) \ if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, __VA_ARGS__ ) ) #else #define INTERNAL_CATCH_SECTION( name, desc ) \ if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, name, desc ) ) #endif // #included from: internal/catch_generators.hpp #define TWOBLUECUBES_CATCH_GENERATORS_HPP_INCLUDED #include <iterator> #include <vector> #include <string> #include <stdlib.h> namespace Catch { template<typename T> struct IGenerator { virtual ~IGenerator() {} virtual T getValue( std::size_t index ) const = 0; virtual std::size_t size () const = 0; }; template<typename T> class BetweenGenerator : public IGenerator<T> { public: BetweenGenerator( T from, T to ) : m_from( from ), m_to( to ){} virtual T getValue( std::size_t index ) const { return m_from+static_cast<int>( index ); } virtual std::size_t size() const { return static_cast<std::size_t>( 1+m_to-m_from ); } private: T m_from; T m_to; }; template<typename T> class ValuesGenerator : public IGenerator<T> { public: ValuesGenerator(){} void add( T value ) { m_values.push_back( value ); } virtual T getValue( std::size_t index ) const { return m_values[index]; } virtual std::size_t size() const { return m_values.size(); } private: std::vector<T> m_values; }; template<typename T> class CompositeGenerator { public: CompositeGenerator() : m_totalSize( 0 ) {} // *** Move semantics, similar to auto_ptr *** CompositeGenerator( CompositeGenerator& other ) : m_fileInfo( other.m_fileInfo ), m_totalSize( 0 ) { move( other ); } CompositeGenerator& setFileInfo( const char* fileInfo ) { m_fileInfo = fileInfo; return *this; } ~CompositeGenerator() { deleteAll( m_composed ); } operator T () const { size_t overallIndex = getCurrentContext().getGeneratorIndex( m_fileInfo, m_totalSize ); typename std::vector<const IGenerator<T>*>::const_iterator it = m_composed.begin(); typename std::vector<const IGenerator<T>*>::const_iterator itEnd = m_composed.end(); for( size_t index = 0; it != itEnd; ++it ) { const IGenerator<T>* generator = *it; if( overallIndex >= index && overallIndex < index + generator->size() ) { return generator->getValue( overallIndex-index ); } index += generator->size(); } CATCH_INTERNAL_ERROR( "Indexed past end of generated range" ); return T(); // Suppress spurious "not all control paths return a value" warning in Visual Studio - if you know how to fix this please do so } void add( const IGenerator<T>* generator ) { m_totalSize += generator->size(); m_composed.push_back( generator ); } CompositeGenerator& then( CompositeGenerator& other ) { move( other ); return *this; } CompositeGenerator& then( T value ) { ValuesGenerator<T>* valuesGen = new ValuesGenerator<T>(); valuesGen->add( value ); add( valuesGen ); return *this; } private: void move( CompositeGenerator& other ) { std::copy( other.m_composed.begin(), other.m_composed.end(), std::back_inserter( m_composed ) ); m_totalSize += other.m_totalSize; other.m_composed.clear(); } std::vector<const IGenerator<T>*> m_composed; std::string m_fileInfo; size_t m_totalSize; }; namespace Generators { template<typename T> CompositeGenerator<T> between( T from, T to ) { CompositeGenerator<T> generators; generators.add( new BetweenGenerator<T>( from, to ) ); return generators; } template<typename T> CompositeGenerator<T> values( T val1, T val2 ) { CompositeGenerator<T> generators; ValuesGenerator<T>* valuesGen = new ValuesGenerator<T>(); valuesGen->add( val1 ); valuesGen->add( val2 ); generators.add( valuesGen ); return generators; } template<typename T> CompositeGenerator<T> values( T val1, T val2, T val3 ){ CompositeGenerator<T> generators; ValuesGenerator<T>* valuesGen = new ValuesGenerator<T>(); valuesGen->add( val1 ); valuesGen->add( val2 ); valuesGen->add( val3 ); generators.add( valuesGen ); return generators; } template<typename T> CompositeGenerator<T> values( T val1, T val2, T val3, T val4 ) { CompositeGenerator<T> generators; ValuesGenerator<T>* valuesGen = new ValuesGenerator<T>(); valuesGen->add( val1 ); valuesGen->add( val2 ); valuesGen->add( val3 ); valuesGen->add( val4 ); generators.add( valuesGen ); return generators; } } // end namespace Generators using namespace Generators; } // end namespace Catch #define INTERNAL_CATCH_LINESTR2( line ) #line #define INTERNAL_CATCH_LINESTR( line ) INTERNAL_CATCH_LINESTR2( line ) #define INTERNAL_CATCH_GENERATE( expr ) expr.setFileInfo( __FILE__ "(" INTERNAL_CATCH_LINESTR( __LINE__ ) ")" ) // #included from: internal/catch_interfaces_exception.h #define TWOBLUECUBES_CATCH_INTERFACES_EXCEPTION_H_INCLUDED #include <string> #include <vector> // #included from: catch_interfaces_registry_hub.h #define TWOBLUECUBES_CATCH_INTERFACES_REGISTRY_HUB_H_INCLUDED #include <string> namespace Catch { class TestCase; struct ITestCaseRegistry; struct IExceptionTranslatorRegistry; struct IExceptionTranslator; struct IReporterRegistry; struct IReporterFactory; struct IRegistryHub { virtual ~IRegistryHub(); virtual IReporterRegistry const& getReporterRegistry() const = 0; virtual ITestCaseRegistry const& getTestCaseRegistry() const = 0; virtual IExceptionTranslatorRegistry& getExceptionTranslatorRegistry() = 0; }; struct IMutableRegistryHub { virtual ~IMutableRegistryHub(); virtual void registerReporter( std::string const& name, Ptr<IReporterFactory> const& factory ) = 0; virtual void registerListener( Ptr<IReporterFactory> const& factory ) = 0; virtual void registerTest( TestCase const& testInfo ) = 0; virtual void registerTranslator( const IExceptionTranslator* translator ) = 0; }; IRegistryHub& getRegistryHub(); IMutableRegistryHub& getMutableRegistryHub(); void cleanUp(); std::string translateActiveException(); } namespace Catch { typedef std::string(*exceptionTranslateFunction)(); struct IExceptionTranslator; typedef std::vector<const IExceptionTranslator*> ExceptionTranslators; struct IExceptionTranslator { virtual ~IExceptionTranslator(); virtual std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const = 0; }; struct IExceptionTranslatorRegistry { virtual ~IExceptionTranslatorRegistry(); virtual std::string translateActiveException() const = 0; }; class ExceptionTranslatorRegistrar { template<typename T> class ExceptionTranslator : public IExceptionTranslator { public: ExceptionTranslator( std::string(*translateFunction)( T& ) ) : m_translateFunction( translateFunction ) {} virtual std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const CATCH_OVERRIDE { try { if( it == itEnd ) throw; else return (*it)->translate( it+1, itEnd ); } catch( T& ex ) { return m_translateFunction( ex ); } } protected: std::string(*m_translateFunction)( T& ); }; public: template<typename T> ExceptionTranslatorRegistrar( std::string(*translateFunction)( T& ) ) { getMutableRegistryHub().registerTranslator ( new ExceptionTranslator<T>( translateFunction ) ); } }; } /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature ) \ static std::string INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator )( signature ); \ namespace{ Catch::ExceptionTranslatorRegistrar INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionRegistrar )( &INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ) ); }\ static std::string INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator )( signature ) // #included from: internal/catch_approx.hpp #define TWOBLUECUBES_CATCH_APPROX_HPP_INCLUDED #include <cmath> #include <limits> namespace Catch { namespace Detail { class Approx { public: explicit Approx ( double value ) : m_epsilon( std::numeric_limits<float>::epsilon()*100 ), m_scale( 1.0 ), m_value( value ) {} Approx( Approx const& other ) : m_epsilon( other.m_epsilon ), m_scale( other.m_scale ), m_value( other.m_value ) {} static Approx custom() { return Approx( 0 ); } Approx operator()( double value ) { Approx approx( value ); approx.epsilon( m_epsilon ); approx.scale( m_scale ); return approx; } friend bool operator == ( double lhs, Approx const& rhs ) { // Thanks to Richard Harris for his help refining this formula return fabs( lhs - rhs.m_value ) < rhs.m_epsilon * (rhs.m_scale + (std::max)( fabs(lhs), fabs(rhs.m_value) ) ); } friend bool operator == ( Approx const& lhs, double rhs ) { return operator==( rhs, lhs ); } friend bool operator != ( double lhs, Approx const& rhs ) { return !operator==( lhs, rhs ); } friend bool operator != ( Approx const& lhs, double rhs ) { return !operator==( rhs, lhs ); } Approx& epsilon( double newEpsilon ) { m_epsilon = newEpsilon; return *this; } Approx& scale( double newScale ) { m_scale = newScale; return *this; } std::string toString() const { std::ostringstream oss; oss << "Approx( " << Catch::toString( m_value ) << " )"; return oss.str(); } private: double m_epsilon; double m_scale; double m_value; }; } template<> inline std::string toString<Detail::Approx>( Detail::Approx const& value ) { return value.toString(); } } // end namespace Catch // #included from: internal/catch_interfaces_tag_alias_registry.h #define TWOBLUECUBES_CATCH_INTERFACES_TAG_ALIAS_REGISTRY_H_INCLUDED // #included from: catch_tag_alias.h #define TWOBLUECUBES_CATCH_TAG_ALIAS_H_INCLUDED #include <string> namespace Catch { struct TagAlias { TagAlias( std::string _tag, SourceLineInfo _lineInfo ) : tag( _tag ), lineInfo( _lineInfo ) {} std::string tag; SourceLineInfo lineInfo; }; struct RegistrarForTagAliases { RegistrarForTagAliases( char const* alias, char const* tag, SourceLineInfo const& lineInfo ); }; } // end namespace Catch #define CATCH_REGISTER_TAG_ALIAS( alias, spec ) namespace{ Catch::RegistrarForTagAliases INTERNAL_CATCH_UNIQUE_NAME( AutoRegisterTagAlias )( alias, spec, CATCH_INTERNAL_LINEINFO ); } // #included from: catch_option.hpp #define TWOBLUECUBES_CATCH_OPTION_HPP_INCLUDED namespace Catch { // An optional type template<typename T> class Option { public: Option() : nullableValue( CATCH_NULL ) {} Option( T const& _value ) : nullableValue( new( storage ) T( _value ) ) {} Option( Option const& _other ) : nullableValue( _other ? new( storage ) T( *_other ) : CATCH_NULL ) {} ~Option() { reset(); } Option& operator= ( Option const& _other ) { if( &_other != this ) { reset(); if( _other ) nullableValue = new( storage ) T( *_other ); } return *this; } Option& operator = ( T const& _value ) { reset(); nullableValue = new( storage ) T( _value ); return *this; } void reset() { if( nullableValue ) nullableValue->~T(); nullableValue = CATCH_NULL; } T& operator*() { return *nullableValue; } T const& operator*() const { return *nullableValue; } T* operator->() { return nullableValue; } const T* operator->() const { return nullableValue; } T valueOr( T const& defaultValue ) const { return nullableValue ? *nullableValue : defaultValue; } bool some() const { return nullableValue != CATCH_NULL; } bool none() const { return nullableValue == CATCH_NULL; } bool operator !() const { return nullableValue == CATCH_NULL; } operator SafeBool::type() const { return SafeBool::makeSafe( some() ); } private: T* nullableValue; char storage[sizeof(T)]; }; } // end namespace Catch namespace Catch { struct ITagAliasRegistry { virtual ~ITagAliasRegistry(); virtual Option<TagAlias> find( std::string const& alias ) const = 0; virtual std::string expandAliases( std::string const& unexpandedTestSpec ) const = 0; static ITagAliasRegistry const& get(); }; } // end namespace Catch // These files are included here so the single_include script doesn't put them // in the conditionally compiled sections // #included from: internal/catch_test_case_info.h #define TWOBLUECUBES_CATCH_TEST_CASE_INFO_H_INCLUDED #include <string> #include <set> #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wpadded" #endif namespace Catch { struct ITestCase; struct TestCaseInfo { enum SpecialProperties{ None = 0, IsHidden = 1 << 1, ShouldFail = 1 << 2, MayFail = 1 << 3, Throws = 1 << 4 }; TestCaseInfo( std::string const& _name, std::string const& _className, std::string const& _description, std::set<std::string> const& _tags, SourceLineInfo const& _lineInfo ); TestCaseInfo( TestCaseInfo const& other ); friend void setTags( TestCaseInfo& testCaseInfo, std::set<std::string> const& tags ); bool isHidden() const; bool throws() const; bool okToFail() const; bool expectedToFail() const; std::string name; std::string className; std::string description; std::set<std::string> tags; std::set<std::string> lcaseTags; std::string tagsAsString; SourceLineInfo lineInfo; SpecialProperties properties; }; class TestCase : public TestCaseInfo { public: TestCase( ITestCase* testCase, TestCaseInfo const& info ); TestCase( TestCase const& other ); TestCase withName( std::string const& _newName ) const; void invoke() const; TestCaseInfo const& getTestCaseInfo() const; void swap( TestCase& other ); bool operator == ( TestCase const& other ) const; bool operator < ( TestCase const& other ) const; TestCase& operator = ( TestCase const& other ); private: Ptr<ITestCase> test; }; TestCase makeTestCase( ITestCase* testCase, std::string const& className, std::string const& name, std::string const& description, SourceLineInfo const& lineInfo ); } #ifdef __clang__ #pragma clang diagnostic pop #endif #ifdef __OBJC__ // #included from: internal/catch_objc.hpp #define TWOBLUECUBES_CATCH_OBJC_HPP_INCLUDED #import <objc/runtime.h> #include <string> // NB. Any general catch headers included here must be included // in catch.hpp first to make sure they are included by the single // header for non obj-usage /////////////////////////////////////////////////////////////////////////////// // This protocol is really only here for (self) documenting purposes, since // all its methods are optional. @protocol OcFixture @optional -(void) setUp; -(void) tearDown; @end namespace Catch { class OcMethod : public SharedImpl<ITestCase> { public: OcMethod( Class cls, SEL sel ) : m_cls( cls ), m_sel( sel ) {} virtual void invoke() const { id obj = [[m_cls alloc] init]; performOptionalSelector( obj, @selector(setUp) ); performOptionalSelector( obj, m_sel ); performOptionalSelector( obj, @selector(tearDown) ); arcSafeRelease( obj ); } private: virtual ~OcMethod() {} Class m_cls; SEL m_sel; }; namespace Detail{ inline std::string getAnnotation( Class cls, std::string const& annotationName, std::string const& testCaseName ) { NSString* selStr = [[NSString alloc] initWithFormat:@"Catch_%s_%s", annotationName.c_str(), testCaseName.c_str()]; SEL sel = NSSelectorFromString( selStr ); arcSafeRelease( selStr ); id value = performOptionalSelector( cls, sel ); if( value ) return [(NSString*)value UTF8String]; return ""; } } inline size_t registerTestMethods() { size_t noTestMethods = 0; int noClasses = objc_getClassList( CATCH_NULL, 0 ); Class* classes = (CATCH_UNSAFE_UNRETAINED Class *)malloc( sizeof(Class) * noClasses); objc_getClassList( classes, noClasses ); for( int c = 0; c < noClasses; c++ ) { Class cls = classes[c]; { u_int count; Method* methods = class_copyMethodList( cls, &count ); for( u_int m = 0; m < count ; m++ ) { SEL selector = method_getName(methods[m]); std::string methodName = sel_getName(selector); if( startsWith( methodName, "Catch_TestCase_" ) ) { std::string testCaseName = methodName.substr( 15 ); std::string name = Detail::getAnnotation( cls, "Name", testCaseName ); std::string desc = Detail::getAnnotation( cls, "Description", testCaseName ); const char* className = class_getName( cls ); getMutableRegistryHub().registerTest( makeTestCase( new OcMethod( cls, selector ), className, name.c_str(), desc.c_str(), SourceLineInfo() ) ); noTestMethods++; } } free(methods); } } return noTestMethods; } namespace Matchers { namespace Impl { namespace NSStringMatchers { template<typename MatcherT> struct StringHolder : MatcherImpl<MatcherT, NSString*>{ StringHolder( NSString* substr ) : m_substr( [substr copy] ){} StringHolder( StringHolder const& other ) : m_substr( [other.m_substr copy] ){} StringHolder() { arcSafeRelease( m_substr ); } NSString* m_substr; }; struct Equals : StringHolder<Equals> { Equals( NSString* substr ) : StringHolder( substr ){} virtual bool match( ExpressionType const& str ) const { return (str != nil || m_substr == nil ) && [str isEqualToString:m_substr]; } virtual std::string toString() const { return "equals string: " + Catch::toString( m_substr ); } }; struct Contains : StringHolder<Contains> { Contains( NSString* substr ) : StringHolder( substr ){} virtual bool match( ExpressionType const& str ) const { return (str != nil || m_substr == nil ) && [str rangeOfString:m_substr].location != NSNotFound; } virtual std::string toString() const { return "contains string: " + Catch::toString( m_substr ); } }; struct StartsWith : StringHolder<StartsWith> { StartsWith( NSString* substr ) : StringHolder( substr ){} virtual bool match( ExpressionType const& str ) const { return (str != nil || m_substr == nil ) && [str rangeOfString:m_substr].location == 0; } virtual std::string toString() const { return "starts with: " + Catch::toString( m_substr ); } }; struct EndsWith : StringHolder<EndsWith> { EndsWith( NSString* substr ) : StringHolder( substr ){} virtual bool match( ExpressionType const& str ) const { return (str != nil || m_substr == nil ) && [str rangeOfString:m_substr].location == [str length] - [m_substr length]; } virtual std::string toString() const { return "ends with: " + Catch::toString( m_substr ); } }; } // namespace NSStringMatchers } // namespace Impl inline Impl::NSStringMatchers::Equals Equals( NSString* substr ){ return Impl::NSStringMatchers::Equals( substr ); } inline Impl::NSStringMatchers::Contains Contains( NSString* substr ){ return Impl::NSStringMatchers::Contains( substr ); } inline Impl::NSStringMatchers::StartsWith StartsWith( NSString* substr ){ return Impl::NSStringMatchers::StartsWith( substr ); } inline Impl::NSStringMatchers::EndsWith EndsWith( NSString* substr ){ return Impl::NSStringMatchers::EndsWith( substr ); } } // namespace Matchers using namespace Matchers; } // namespace Catch /////////////////////////////////////////////////////////////////////////////// #define OC_TEST_CASE( name, desc )\ +(NSString*) INTERNAL_CATCH_UNIQUE_NAME( Catch_Name_test ) \ {\ return @ name; \ }\ +(NSString*) INTERNAL_CATCH_UNIQUE_NAME( Catch_Description_test ) \ { \ return @ desc; \ } \ -(void) INTERNAL_CATCH_UNIQUE_NAME( Catch_TestCase_test ) #endif #ifdef CATCH_IMPL // #included from: internal/catch_impl.hpp #define TWOBLUECUBES_CATCH_IMPL_HPP_INCLUDED // Collect all the implementation files together here // These are the equivalent of what would usually be cpp files #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wweak-vtables" #endif // #included from: ../catch_session.hpp #define TWOBLUECUBES_CATCH_RUNNER_HPP_INCLUDED // #included from: internal/catch_commandline.hpp #define TWOBLUECUBES_CATCH_COMMANDLINE_HPP_INCLUDED // #included from: catch_config.hpp #define TWOBLUECUBES_CATCH_CONFIG_HPP_INCLUDED // #included from: catch_test_spec_parser.hpp #define TWOBLUECUBES_CATCH_TEST_SPEC_PARSER_HPP_INCLUDED #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wpadded" #endif // #included from: catch_test_spec.hpp #define TWOBLUECUBES_CATCH_TEST_SPEC_HPP_INCLUDED #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wpadded" #endif // #included from: catch_wildcard_pattern.hpp #define TWOBLUECUBES_CATCH_WILDCARD_PATTERN_HPP_INCLUDED namespace Catch { class WildcardPattern { enum WildcardPosition { NoWildcard = 0, WildcardAtStart = 1, WildcardAtEnd = 2, WildcardAtBothEnds = WildcardAtStart | WildcardAtEnd }; public: WildcardPattern( std::string const& pattern, CaseSensitive::Choice caseSensitivity ) : m_caseSensitivity( caseSensitivity ), m_wildcard( NoWildcard ), m_pattern( adjustCase( pattern ) ) { if( startsWith( m_pattern, "*" ) ) { m_pattern = m_pattern.substr( 1 ); m_wildcard = WildcardAtStart; } if( endsWith( m_pattern, "*" ) ) { m_pattern = m_pattern.substr( 0, m_pattern.size()-1 ); m_wildcard = static_cast<WildcardPosition>( m_wildcard | WildcardAtEnd ); } } virtual ~WildcardPattern(); virtual bool matches( std::string const& str ) const { switch( m_wildcard ) { case NoWildcard: return m_pattern == adjustCase( str ); case WildcardAtStart: return endsWith( adjustCase( str ), m_pattern ); case WildcardAtEnd: return startsWith( adjustCase( str ), m_pattern ); case WildcardAtBothEnds: return contains( adjustCase( str ), m_pattern ); } #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunreachable-code" #endif throw std::logic_error( "Unknown enum" ); #ifdef __clang__ #pragma clang diagnostic pop #endif } private: std::string adjustCase( std::string const& str ) const { return m_caseSensitivity == CaseSensitive::No ? toLower( str ) : str; } CaseSensitive::Choice m_caseSensitivity; WildcardPosition m_wildcard; std::string m_pattern; }; } #include <string> #include <vector> namespace Catch { class TestSpec { struct Pattern : SharedImpl<> { virtual ~Pattern(); virtual bool matches( TestCaseInfo const& testCase ) const = 0; }; class NamePattern : public Pattern { public: NamePattern( std::string const& name ) : m_wildcardPattern( toLower( name ), CaseSensitive::No ) {} virtual ~NamePattern(); virtual bool matches( TestCaseInfo const& testCase ) const { return m_wildcardPattern.matches( toLower( testCase.name ) ); } private: WildcardPattern m_wildcardPattern; }; class TagPattern : public Pattern { public: TagPattern( std::string const& tag ) : m_tag( toLower( tag ) ) {} virtual ~TagPattern(); virtual bool matches( TestCaseInfo const& testCase ) const { return testCase.lcaseTags.find( m_tag ) != testCase.lcaseTags.end(); } private: std::string m_tag; }; class ExcludedPattern : public Pattern { public: ExcludedPattern( Ptr<Pattern> const& underlyingPattern ) : m_underlyingPattern( underlyingPattern ) {} virtual ~ExcludedPattern(); virtual bool matches( TestCaseInfo const& testCase ) const { return !m_underlyingPattern->matches( testCase ); } private: Ptr<Pattern> m_underlyingPattern; }; struct Filter { std::vector<Ptr<Pattern> > m_patterns; bool matches( TestCaseInfo const& testCase ) const { // All patterns in a filter must match for the filter to be a match for( std::vector<Ptr<Pattern> >::const_iterator it = m_patterns.begin(), itEnd = m_patterns.end(); it != itEnd; ++it ) if( !(*it)->matches( testCase ) ) return false; return true; } }; public: bool hasFilters() const { return !m_filters.empty(); } bool matches( TestCaseInfo const& testCase ) const { // A TestSpec matches if any filter matches for( std::vector<Filter>::const_iterator it = m_filters.begin(), itEnd = m_filters.end(); it != itEnd; ++it ) if( it->matches( testCase ) ) return true; return false; } private: std::vector<Filter> m_filters; friend class TestSpecParser; }; } #ifdef __clang__ #pragma clang diagnostic pop #endif namespace Catch { class TestSpecParser { enum Mode{ None, Name, QuotedName, Tag }; Mode m_mode; bool m_exclusion; std::size_t m_start, m_pos; std::string m_arg; TestSpec::Filter m_currentFilter; TestSpec m_testSpec; ITagAliasRegistry const* m_tagAliases; public: TestSpecParser( ITagAliasRegistry const& tagAliases ) : m_tagAliases( &tagAliases ) {} TestSpecParser& parse( std::string const& arg ) { m_mode = None; m_exclusion = false; m_start = std::string::npos; m_arg = m_tagAliases->expandAliases( arg ); for( m_pos = 0; m_pos < m_arg.size(); ++m_pos ) visitChar( m_arg[m_pos] ); if( m_mode == Name ) addPattern<TestSpec::NamePattern>(); return *this; } TestSpec testSpec() { addFilter(); return m_testSpec; } private: void visitChar( char c ) { if( m_mode == None ) { switch( c ) { case ' ': return; case '~': m_exclusion = true; return; case '[': return startNewMode( Tag, ++m_pos ); case '"': return startNewMode( QuotedName, ++m_pos ); default: startNewMode( Name, m_pos ); break; } } if( m_mode == Name ) { if( c == ',' ) { addPattern<TestSpec::NamePattern>(); addFilter(); } else if( c == '[' ) { if( subString() == "exclude:" ) m_exclusion = true; else addPattern<TestSpec::NamePattern>(); startNewMode( Tag, ++m_pos ); } } else if( m_mode == QuotedName && c == '"' ) addPattern<TestSpec::NamePattern>(); else if( m_mode == Tag && c == ']' ) addPattern<TestSpec::TagPattern>(); } void startNewMode( Mode mode, std::size_t start ) { m_mode = mode; m_start = start; } std::string subString() const { return m_arg.substr( m_start, m_pos - m_start ); } template<typename T> void addPattern() { std::string token = subString(); if( startsWith( token, "exclude:" ) ) { m_exclusion = true; token = token.substr( 8 ); } if( !token.empty() ) { Ptr<TestSpec::Pattern> pattern = new T( token ); if( m_exclusion ) pattern = new TestSpec::ExcludedPattern( pattern ); m_currentFilter.m_patterns.push_back( pattern ); } m_exclusion = false; m_mode = None; } void addFilter() { if( !m_currentFilter.m_patterns.empty() ) { m_testSpec.m_filters.push_back( m_currentFilter ); m_currentFilter = TestSpec::Filter(); } } }; inline TestSpec parseTestSpec( std::string const& arg ) { return TestSpecParser( ITagAliasRegistry::get() ).parse( arg ).testSpec(); } } // namespace Catch #ifdef __clang__ #pragma clang diagnostic pop #endif // #included from: catch_interfaces_config.h #define TWOBLUECUBES_CATCH_INTERFACES_CONFIG_H_INCLUDED #include <iostream> #include <string> #include <vector> namespace Catch { struct Verbosity { enum Level { NoOutput = 0, Quiet, Normal }; }; struct WarnAbout { enum What { Nothing = 0x00, NoAssertions = 0x01 }; }; struct ShowDurations { enum OrNot { DefaultForReporter, Always, Never }; }; struct RunTests { enum InWhatOrder { InDeclarationOrder, InLexicographicalOrder, InRandomOrder }; }; class TestSpec; struct IConfig : IShared { virtual ~IConfig(); virtual bool allowThrows() const = 0; virtual std::ostream& stream() const = 0; virtual std::string name() const = 0; virtual bool includeSuccessfulResults() const = 0; virtual bool shouldDebugBreak() const = 0; virtual bool warnAboutMissingAssertions() const = 0; virtual int abortAfter() const = 0; virtual bool showInvisibles() const = 0; virtual ShowDurations::OrNot showDurations() const = 0; virtual TestSpec const& testSpec() const = 0; virtual RunTests::InWhatOrder runOrder() const = 0; virtual unsigned int rngSeed() const = 0; virtual bool forceColour() const = 0; }; } // #included from: catch_stream.h #define TWOBLUECUBES_CATCH_STREAM_H_INCLUDED // #included from: catch_streambuf.h #define TWOBLUECUBES_CATCH_STREAMBUF_H_INCLUDED #include <streambuf> namespace Catch { class StreamBufBase : public std::streambuf { public: virtual ~StreamBufBase() CATCH_NOEXCEPT; }; } #include <streambuf> #include <ostream> #include <fstream> namespace Catch { std::ostream& cout(); std::ostream& cerr(); struct IStream { virtual ~IStream() CATCH_NOEXCEPT; virtual std::ostream& stream() const = 0; }; class FileStream : public IStream { mutable std::ofstream m_ofs; public: FileStream( std::string const& filename ); virtual ~FileStream() CATCH_NOEXCEPT; public: // IStream virtual std::ostream& stream() const CATCH_OVERRIDE; }; class CoutStream : public IStream { mutable std::ostream m_os; public: CoutStream(); virtual ~CoutStream() CATCH_NOEXCEPT; public: // IStream virtual std::ostream& stream() const CATCH_OVERRIDE; }; class DebugOutStream : public IStream { std::auto_ptr<StreamBufBase> m_streamBuf; mutable std::ostream m_os; public: DebugOutStream(); virtual ~DebugOutStream() CATCH_NOEXCEPT; public: // IStream virtual std::ostream& stream() const CATCH_OVERRIDE; }; } #include <memory> #include <vector> #include <string> #include <iostream> #include <ctime> #ifndef CATCH_CONFIG_CONSOLE_WIDTH #define CATCH_CONFIG_CONSOLE_WIDTH 80 #endif namespace Catch { struct ConfigData { ConfigData() : listTests( false ), listTags( false ), listReporters( false ), listTestNamesOnly( false ), showSuccessfulTests( false ), shouldDebugBreak( false ), noThrow( false ), showHelp( false ), showInvisibles( false ), forceColour( false ), filenamesAsTags( false ), abortAfter( -1 ), rngSeed( 0 ), verbosity( Verbosity::Normal ), warnings( WarnAbout::Nothing ), showDurations( ShowDurations::DefaultForReporter ), runOrder( RunTests::InDeclarationOrder ) {} bool listTests; bool listTags; bool listReporters; bool listTestNamesOnly; bool showSuccessfulTests; bool shouldDebugBreak; bool noThrow; bool showHelp; bool showInvisibles; bool forceColour; bool filenamesAsTags; int abortAfter; unsigned int rngSeed; Verbosity::Level verbosity; WarnAbout::What warnings; ShowDurations::OrNot showDurations; RunTests::InWhatOrder runOrder; std::string outputFilename; std::string name; std::string processName; std::vector<std::string> reporterNames; std::vector<std::string> testsOrTags; }; class Config : public SharedImpl<IConfig> { private: Config( Config const& other ); Config& operator = ( Config const& other ); virtual void dummy(); public: Config() {} Config( ConfigData const& data ) : m_data( data ), m_stream( openStream() ) { if( !data.testsOrTags.empty() ) { TestSpecParser parser( ITagAliasRegistry::get() ); for( std::size_t i = 0; i < data.testsOrTags.size(); ++i ) parser.parse( data.testsOrTags[i] ); m_testSpec = parser.testSpec(); } } virtual ~Config() { } std::string const& getFilename() const { return m_data.outputFilename ; } bool listTests() const { return m_data.listTests; } bool listTestNamesOnly() const { return m_data.listTestNamesOnly; } bool listTags() const { return m_data.listTags; } bool listReporters() const { return m_data.listReporters; } std::string getProcessName() const { return m_data.processName; } bool shouldDebugBreak() const { return m_data.shouldDebugBreak; } std::vector<std::string> getReporterNames() const { return m_data.reporterNames; } int abortAfter() const { return m_data.abortAfter; } TestSpec const& testSpec() const { return m_testSpec; } bool showHelp() const { return m_data.showHelp; } bool showInvisibles() const { return m_data.showInvisibles; } // IConfig interface virtual bool allowThrows() const { return !m_data.noThrow; } virtual std::ostream& stream() const { return m_stream->stream(); } virtual std::string name() const { return m_data.name.empty() ? m_data.processName : m_data.name; } virtual bool includeSuccessfulResults() const { return m_data.showSuccessfulTests; } virtual bool warnAboutMissingAssertions() const { return m_data.warnings & WarnAbout::NoAssertions; } virtual ShowDurations::OrNot showDurations() const { return m_data.showDurations; } virtual RunTests::InWhatOrder runOrder() const { return m_data.runOrder; } virtual unsigned int rngSeed() const { return m_data.rngSeed; } virtual bool forceColour() const { return m_data.forceColour; } private: IStream const* openStream() { if( m_data.outputFilename.empty() ) return new CoutStream(); else if( m_data.outputFilename[0] == '%' ) { if( m_data.outputFilename == "%debug" ) return new DebugOutStream(); else throw std::domain_error( "Unrecognised stream: " + m_data.outputFilename ); } else return new FileStream( m_data.outputFilename ); } ConfigData m_data; std::auto_ptr<IStream const> m_stream; TestSpec m_testSpec; }; } // end namespace Catch // #included from: catch_clara.h #define TWOBLUECUBES_CATCH_CLARA_H_INCLUDED // Use Catch's value for console width (store Clara's off to the side, if present) #ifdef CLARA_CONFIG_CONSOLE_WIDTH #define CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH CLARA_CONFIG_CONSOLE_WIDTH #undef CLARA_CONFIG_CONSOLE_WIDTH #endif #define CLARA_CONFIG_CONSOLE_WIDTH CATCH_CONFIG_CONSOLE_WIDTH // Declare Clara inside the Catch namespace #define STITCH_CLARA_OPEN_NAMESPACE namespace Catch { // #included from: ../external/clara.h // Only use header guard if we are not using an outer namespace #if !defined(TWOBLUECUBES_CLARA_H_INCLUDED) || defined(STITCH_CLARA_OPEN_NAMESPACE) #ifndef STITCH_CLARA_OPEN_NAMESPACE #define TWOBLUECUBES_CLARA_H_INCLUDED #define STITCH_CLARA_OPEN_NAMESPACE #define STITCH_CLARA_CLOSE_NAMESPACE #else #define STITCH_CLARA_CLOSE_NAMESPACE } #endif #define STITCH_TBC_TEXT_FORMAT_OPEN_NAMESPACE STITCH_CLARA_OPEN_NAMESPACE // ----------- #included from tbc_text_format.h ----------- // Only use header guard if we are not using an outer namespace #if !defined(TBC_TEXT_FORMAT_H_INCLUDED) || defined(STITCH_TBC_TEXT_FORMAT_OUTER_NAMESPACE) #ifndef STITCH_TBC_TEXT_FORMAT_OUTER_NAMESPACE #define TBC_TEXT_FORMAT_H_INCLUDED #endif #include <string> #include <vector> #include <sstream> // Use optional outer namespace #ifdef STITCH_TBC_TEXT_FORMAT_OUTER_NAMESPACE namespace STITCH_TBC_TEXT_FORMAT_OUTER_NAMESPACE { #endif namespace Tbc { #ifdef TBC_TEXT_FORMAT_CONSOLE_WIDTH const unsigned int consoleWidth = TBC_TEXT_FORMAT_CONSOLE_WIDTH; #else const unsigned int consoleWidth = 80; #endif struct TextAttributes { TextAttributes() : initialIndent( std::string::npos ), indent( 0 ), width( consoleWidth-1 ), tabChar( '\t' ) {} TextAttributes& setInitialIndent( std::size_t _value ) { initialIndent = _value; return *this; } TextAttributes& setIndent( std::size_t _value ) { indent = _value; return *this; } TextAttributes& setWidth( std::size_t _value ) { width = _value; return *this; } TextAttributes& setTabChar( char _value ) { tabChar = _value; return *this; } std::size_t initialIndent; // indent of first line, or npos std::size_t indent; // indent of subsequent lines, or all if initialIndent is npos std::size_t width; // maximum width of text, including indent. Longer text will wrap char tabChar; // If this char is seen the indent is changed to current pos }; class Text { public: Text( std::string const& _str, TextAttributes const& _attr = TextAttributes() ) : attr( _attr ) { std::string wrappableChars = " [({.,/|\\-"; std::size_t indent = _attr.initialIndent != std::string::npos ? _attr.initialIndent : _attr.indent; std::string remainder = _str; while( !remainder.empty() ) { if( lines.size() >= 1000 ) { lines.push_back( "... message truncated due to excessive size" ); return; } std::size_t tabPos = std::string::npos; std::size_t width = (std::min)( remainder.size(), _attr.width - indent ); std::size_t pos = remainder.find_first_of( '\n' ); if( pos <= width ) { width = pos; } pos = remainder.find_last_of( _attr.tabChar, width ); if( pos != std::string::npos ) { tabPos = pos; if( remainder[width] == '\n' ) width--; remainder = remainder.substr( 0, tabPos ) + remainder.substr( tabPos+1 ); } if( width == remainder.size() ) { spliceLine( indent, remainder, width ); } else if( remainder[width] == '\n' ) { spliceLine( indent, remainder, width ); if( width <= 1 || remainder.size() != 1 ) remainder = remainder.substr( 1 ); indent = _attr.indent; } else { pos = remainder.find_last_of( wrappableChars, width ); if( pos != std::string::npos && pos > 0 ) { spliceLine( indent, remainder, pos ); if( remainder[0] == ' ' ) remainder = remainder.substr( 1 ); } else { spliceLine( indent, remainder, width-1 ); lines.back() += "-"; } if( lines.size() == 1 ) indent = _attr.indent; if( tabPos != std::string::npos ) indent += tabPos; } } } void spliceLine( std::size_t _indent, std::string& _remainder, std::size_t _pos ) { lines.push_back( std::string( _indent, ' ' ) + _remainder.substr( 0, _pos ) ); _remainder = _remainder.substr( _pos ); } typedef std::vector<std::string>::const_iterator const_iterator; const_iterator begin() const { return lines.begin(); } const_iterator end() const { return lines.end(); } std::string const& last() const { return lines.back(); } std::size_t size() const { return lines.size(); } std::string const& operator[]( std::size_t _index ) const { return lines[_index]; } std::string toString() const { std::ostringstream oss; oss << *this; return oss.str(); } inline friend std::ostream& operator << ( std::ostream& _stream, Text const& _text ) { for( Text::const_iterator it = _text.begin(), itEnd = _text.end(); it != itEnd; ++it ) { if( it != _text.begin() ) _stream << "\n"; _stream << *it; } return _stream; } private: std::string str; TextAttributes attr; std::vector<std::string> lines; }; } // end namespace Tbc #ifdef STITCH_TBC_TEXT_FORMAT_OUTER_NAMESPACE } // end outer namespace #endif #endif // TBC_TEXT_FORMAT_H_INCLUDED // ----------- end of #include from tbc_text_format.h ----------- // ........... back in /Users/philnash/Dev/OSS/Clara/srcs/clara.h #undef STITCH_TBC_TEXT_FORMAT_OPEN_NAMESPACE #include <map> #include <algorithm> #include <stdexcept> #include <memory> // Use optional outer namespace #ifdef STITCH_CLARA_OPEN_NAMESPACE STITCH_CLARA_OPEN_NAMESPACE #endif namespace Clara { struct UnpositionalTag {}; extern UnpositionalTag _; #ifdef CLARA_CONFIG_MAIN UnpositionalTag _; #endif namespace Detail { #ifdef CLARA_CONSOLE_WIDTH const unsigned int consoleWidth = CLARA_CONFIG_CONSOLE_WIDTH; #else const unsigned int consoleWidth = 80; #endif using namespace Tbc; inline bool startsWith( std::string const& str, std::string const& prefix ) { return str.size() >= prefix.size() && str.substr( 0, prefix.size() ) == prefix; } template<typename T> struct RemoveConstRef{ typedef T type; }; template<typename T> struct RemoveConstRef<T&>{ typedef T type; }; template<typename T> struct RemoveConstRef<T const&>{ typedef T type; }; template<typename T> struct RemoveConstRef<T const>{ typedef T type; }; template<typename T> struct IsBool { static const bool value = false; }; template<> struct IsBool<bool> { static const bool value = true; }; template<typename T> void convertInto( std::string const& _source, T& _dest ) { std::stringstream ss; ss << _source; ss >> _dest; if( ss.fail() ) throw std::runtime_error( "Unable to convert " + _source + " to destination type" ); } inline void convertInto( std::string const& _source, std::string& _dest ) { _dest = _source; } inline void convertInto( std::string const& _source, bool& _dest ) { std::string sourceLC = _source; std::transform( sourceLC.begin(), sourceLC.end(), sourceLC.begin(), ::tolower ); if( sourceLC == "y" || sourceLC == "1" || sourceLC == "true" || sourceLC == "yes" || sourceLC == "on" ) _dest = true; else if( sourceLC == "n" || sourceLC == "0" || sourceLC == "false" || sourceLC == "no" || sourceLC == "off" ) _dest = false; else throw std::runtime_error( "Expected a boolean value but did not recognise:\n '" + _source + "'" ); } inline void convertInto( bool _source, bool& _dest ) { _dest = _source; } template<typename T> inline void convertInto( bool, T& ) { throw std::runtime_error( "Invalid conversion" ); } template<typename ConfigT> struct IArgFunction { virtual ~IArgFunction() {} # ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS IArgFunction() = default; IArgFunction( IArgFunction const& ) = default; # endif virtual void set( ConfigT& config, std::string const& value ) const = 0; virtual void setFlag( ConfigT& config ) const = 0; virtual bool takesArg() const = 0; virtual IArgFunction* clone() const = 0; }; template<typename ConfigT> class BoundArgFunction { public: BoundArgFunction() : functionObj( CATCH_NULL ) {} BoundArgFunction( IArgFunction<ConfigT>* _functionObj ) : functionObj( _functionObj ) {} BoundArgFunction( BoundArgFunction const& other ) : functionObj( other.functionObj ? other.functionObj->clone() : CATCH_NULL ) {} BoundArgFunction& operator = ( BoundArgFunction const& other ) { IArgFunction<ConfigT>* newFunctionObj = other.functionObj ? other.functionObj->clone() : CATCH_NULL; delete functionObj; functionObj = newFunctionObj; return *this; } ~BoundArgFunction() { delete functionObj; } void set( ConfigT& config, std::string const& value ) const { functionObj->set( config, value ); } void setFlag( ConfigT& config ) const { functionObj->setFlag( config ); } bool takesArg() const { return functionObj->takesArg(); } bool isSet() const { return functionObj != CATCH_NULL; } private: IArgFunction<ConfigT>* functionObj; }; template<typename C> struct NullBinder : IArgFunction<C>{ virtual void set( C&, std::string const& ) const {} virtual void setFlag( C& ) const {} virtual bool takesArg() const { return true; } virtual IArgFunction<C>* clone() const { return new NullBinder( *this ); } }; template<typename C, typename M> struct BoundDataMember : IArgFunction<C>{ BoundDataMember( M C::* _member ) : member( _member ) {} virtual void set( C& p, std::string const& stringValue ) const { convertInto( stringValue, p.*member ); } virtual void setFlag( C& p ) const { convertInto( true, p.*member ); } virtual bool takesArg() const { return !IsBool<M>::value; } virtual IArgFunction<C>* clone() const { return new BoundDataMember( *this ); } M C::* member; }; template<typename C, typename M> struct BoundUnaryMethod : IArgFunction<C>{ BoundUnaryMethod( void (C::*_member)( M ) ) : member( _member ) {} virtual void set( C& p, std::string const& stringValue ) const { typename RemoveConstRef<M>::type value; convertInto( stringValue, value ); (p.*member)( value ); } virtual void setFlag( C& p ) const { typename RemoveConstRef<M>::type value; convertInto( true, value ); (p.*member)( value ); } virtual bool takesArg() const { return !IsBool<M>::value; } virtual IArgFunction<C>* clone() const { return new BoundUnaryMethod( *this ); } void (C::*member)( M ); }; template<typename C> struct BoundNullaryMethod : IArgFunction<C>{ BoundNullaryMethod( void (C::*_member)() ) : member( _member ) {} virtual void set( C& p, std::string const& stringValue ) const { bool value; convertInto( stringValue, value ); if( value ) (p.*member)(); } virtual void setFlag( C& p ) const { (p.*member)(); } virtual bool takesArg() const { return false; } virtual IArgFunction<C>* clone() const { return new BoundNullaryMethod( *this ); } void (C::*member)(); }; template<typename C> struct BoundUnaryFunction : IArgFunction<C>{ BoundUnaryFunction( void (*_function)( C& ) ) : function( _function ) {} virtual void set( C& obj, std::string const& stringValue ) const { bool value; convertInto( stringValue, value ); if( value ) function( obj ); } virtual void setFlag( C& p ) const { function( p ); } virtual bool takesArg() const { return false; } virtual IArgFunction<C>* clone() const { return new BoundUnaryFunction( *this ); } void (*function)( C& ); }; template<typename C, typename T> struct BoundBinaryFunction : IArgFunction<C>{ BoundBinaryFunction( void (*_function)( C&, T ) ) : function( _function ) {} virtual void set( C& obj, std::string const& stringValue ) const { typename RemoveConstRef<T>::type value; convertInto( stringValue, value ); function( obj, value ); } virtual void setFlag( C& obj ) const { typename RemoveConstRef<T>::type value; convertInto( true, value ); function( obj, value ); } virtual bool takesArg() const { return !IsBool<T>::value; } virtual IArgFunction<C>* clone() const { return new BoundBinaryFunction( *this ); } void (*function)( C&, T ); }; } // namespace Detail struct Parser { Parser() : separators( " \t=:" ) {} struct Token { enum Type { Positional, ShortOpt, LongOpt }; Token( Type _type, std::string const& _data ) : type( _type ), data( _data ) {} Type type; std::string data; }; void parseIntoTokens( int argc, char const * const * argv, std::vector<Parser::Token>& tokens ) const { const std::string doubleDash = "--"; for( int i = 1; i < argc && argv[i] != doubleDash; ++i ) parseIntoTokens( argv[i] , tokens); } void parseIntoTokens( std::string arg, std::vector<Parser::Token>& tokens ) const { while( !arg.empty() ) { Parser::Token token( Parser::Token::Positional, arg ); arg = ""; if( token.data[0] == '-' ) { if( token.data.size() > 1 && token.data[1] == '-' ) { token = Parser::Token( Parser::Token::LongOpt, token.data.substr( 2 ) ); } else { token = Parser::Token( Parser::Token::ShortOpt, token.data.substr( 1 ) ); if( token.data.size() > 1 && separators.find( token.data[1] ) == std::string::npos ) { arg = "-" + token.data.substr( 1 ); token.data = token.data.substr( 0, 1 ); } } } if( token.type != Parser::Token::Positional ) { std::size_t pos = token.data.find_first_of( separators ); if( pos != std::string::npos ) { arg = token.data.substr( pos+1 ); token.data = token.data.substr( 0, pos ); } } tokens.push_back( token ); } } std::string separators; }; template<typename ConfigT> struct CommonArgProperties { CommonArgProperties() {} CommonArgProperties( Detail::BoundArgFunction<ConfigT> const& _boundField ) : boundField( _boundField ) {} Detail::BoundArgFunction<ConfigT> boundField; std::string description; std::string detail; std::string placeholder; // Only value if boundField takes an arg bool takesArg() const { return !placeholder.empty(); } void validate() const { if( !boundField.isSet() ) throw std::logic_error( "option not bound" ); } }; struct OptionArgProperties { std::vector<std::string> shortNames; std::string longName; bool hasShortName( std::string const& shortName ) const { return std::find( shortNames.begin(), shortNames.end(), shortName ) != shortNames.end(); } bool hasLongName( std::string const& _longName ) const { return _longName == longName; } }; struct PositionalArgProperties { PositionalArgProperties() : position( -1 ) {} int position; // -1 means non-positional (floating) bool isFixedPositional() const { return position != -1; } }; template<typename ConfigT> class CommandLine { struct Arg : CommonArgProperties<ConfigT>, OptionArgProperties, PositionalArgProperties { Arg() {} Arg( Detail::BoundArgFunction<ConfigT> const& _boundField ) : CommonArgProperties<ConfigT>( _boundField ) {} using CommonArgProperties<ConfigT>::placeholder; // !TBD std::string dbgName() const { if( !longName.empty() ) return "--" + longName; if( !shortNames.empty() ) return "-" + shortNames[0]; return "positional args"; } std::string commands() const { std::ostringstream oss; bool first = true; std::vector<std::string>::const_iterator it = shortNames.begin(), itEnd = shortNames.end(); for(; it != itEnd; ++it ) { if( first ) first = false; else oss << ", "; oss << "-" << *it; } if( !longName.empty() ) { if( !first ) oss << ", "; oss << "--" << longName; } if( !placeholder.empty() ) oss << " <" << placeholder << ">"; return oss.str(); } }; typedef CATCH_AUTO_PTR( Arg ) ArgAutoPtr; friend void addOptName( Arg& arg, std::string const& optName ) { if( optName.empty() ) return; if( Detail::startsWith( optName, "--" ) ) { if( !arg.longName.empty() ) throw std::logic_error( "Only one long opt may be specified. '" + arg.longName + "' already specified, now attempting to add '" + optName + "'" ); arg.longName = optName.substr( 2 ); } else if( Detail::startsWith( optName, "-" ) ) arg.shortNames.push_back( optName.substr( 1 ) ); else throw std::logic_error( "option must begin with - or --. Option was: '" + optName + "'" ); } friend void setPositionalArg( Arg& arg, int position ) { arg.position = position; } class ArgBuilder { public: ArgBuilder( Arg* arg ) : m_arg( arg ) {} // Bind a non-boolean data member (requires placeholder string) template<typename C, typename M> void bind( M C::* field, std::string const& placeholder ) { m_arg->boundField = new Detail::BoundDataMember<C,M>( field ); m_arg->placeholder = placeholder; } // Bind a boolean data member (no placeholder required) template<typename C> void bind( bool C::* field ) { m_arg->boundField = new Detail::BoundDataMember<C,bool>( field ); } // Bind a method taking a single, non-boolean argument (requires a placeholder string) template<typename C, typename M> void bind( void (C::* unaryMethod)( M ), std::string const& placeholder ) { m_arg->boundField = new Detail::BoundUnaryMethod<C,M>( unaryMethod ); m_arg->placeholder = placeholder; } // Bind a method taking a single, boolean argument (no placeholder string required) template<typename C> void bind( void (C::* unaryMethod)( bool ) ) { m_arg->boundField = new Detail::BoundUnaryMethod<C,bool>( unaryMethod ); } // Bind a method that takes no arguments (will be called if opt is present) template<typename C> void bind( void (C::* nullaryMethod)() ) { m_arg->boundField = new Detail::BoundNullaryMethod<C>( nullaryMethod ); } // Bind a free function taking a single argument - the object to operate on (no placeholder string required) template<typename C> void bind( void (* unaryFunction)( C& ) ) { m_arg->boundField = new Detail::BoundUnaryFunction<C>( unaryFunction ); } // Bind a free function taking a single argument - the object to operate on (requires a placeholder string) template<typename C, typename T> void bind( void (* binaryFunction)( C&, T ), std::string const& placeholder ) { m_arg->boundField = new Detail::BoundBinaryFunction<C, T>( binaryFunction ); m_arg->placeholder = placeholder; } ArgBuilder& describe( std::string const& description ) { m_arg->description = description; return *this; } ArgBuilder& detail( std::string const& _detail ) { m_arg->detail = _detail; return *this; } protected: Arg* m_arg; }; class OptBuilder : public ArgBuilder { public: OptBuilder( Arg* arg ) : ArgBuilder( arg ) {} OptBuilder( OptBuilder& other ) : ArgBuilder( other ) {} OptBuilder& operator[]( std::string const& optName ) { addOptName( *ArgBuilder::m_arg, optName ); return *this; } }; public: CommandLine() : m_boundProcessName( new Detail::NullBinder<ConfigT>() ), m_highestSpecifiedArgPosition( 0 ), m_throwOnUnrecognisedTokens( false ) {} CommandLine( CommandLine const& other ) : m_boundProcessName( other.m_boundProcessName ), m_options ( other.m_options ), m_positionalArgs( other.m_positionalArgs ), m_highestSpecifiedArgPosition( other.m_highestSpecifiedArgPosition ), m_throwOnUnrecognisedTokens( other.m_throwOnUnrecognisedTokens ) { if( other.m_floatingArg.get() ) m_floatingArg.reset( new Arg( *other.m_floatingArg ) ); } CommandLine& setThrowOnUnrecognisedTokens( bool shouldThrow = true ) { m_throwOnUnrecognisedTokens = shouldThrow; return *this; } OptBuilder operator[]( std::string const& optName ) { m_options.push_back( Arg() ); addOptName( m_options.back(), optName ); OptBuilder builder( &m_options.back() ); return builder; } ArgBuilder operator[]( int position ) { m_positionalArgs.insert( std::make_pair( position, Arg() ) ); if( position > m_highestSpecifiedArgPosition ) m_highestSpecifiedArgPosition = position; setPositionalArg( m_positionalArgs[position], position ); ArgBuilder builder( &m_positionalArgs[position] ); return builder; } // Invoke this with the _ instance ArgBuilder operator[]( UnpositionalTag ) { if( m_floatingArg.get() ) throw std::logic_error( "Only one unpositional argument can be added" ); m_floatingArg.reset( new Arg() ); ArgBuilder builder( m_floatingArg.get() ); return builder; } template<typename C, typename M> void bindProcessName( M C::* field ) { m_boundProcessName = new Detail::BoundDataMember<C,M>( field ); } template<typename C, typename M> void bindProcessName( void (C::*_unaryMethod)( M ) ) { m_boundProcessName = new Detail::BoundUnaryMethod<C,M>( _unaryMethod ); } void optUsage( std::ostream& os, std::size_t indent = 0, std::size_t width = Detail::consoleWidth ) const { typename std::vector<Arg>::const_iterator itBegin = m_options.begin(), itEnd = m_options.end(), it; std::size_t maxWidth = 0; for( it = itBegin; it != itEnd; ++it ) maxWidth = (std::max)( maxWidth, it->commands().size() ); for( it = itBegin; it != itEnd; ++it ) { Detail::Text usageText( it->commands(), Detail::TextAttributes() .setWidth( maxWidth+indent ) .setIndent( indent ) ); Detail::Text desc( it->description, Detail::TextAttributes() .setWidth( width - maxWidth - 3 ) ); for( std::size_t i = 0; i < (std::max)( usageText.size(), desc.size() ); ++i ) { std::string usageCol = i < usageText.size() ? usageText[i] : ""; os << usageCol; if( i < desc.size() && !desc[i].empty() ) os << std::string( indent + 2 + maxWidth - usageCol.size(), ' ' ) << desc[i]; os << "\n"; } } } std::string optUsage() const { std::ostringstream oss; optUsage( oss ); return oss.str(); } void argSynopsis( std::ostream& os ) const { for( int i = 1; i <= m_highestSpecifiedArgPosition; ++i ) { if( i > 1 ) os << " "; typename std::map<int, Arg>::const_iterator it = m_positionalArgs.find( i ); if( it != m_positionalArgs.end() ) os << "<" << it->second.placeholder << ">"; else if( m_floatingArg.get() ) os << "<" << m_floatingArg->placeholder << ">"; else throw std::logic_error( "non consecutive positional arguments with no floating args" ); } // !TBD No indication of mandatory args if( m_floatingArg.get() ) { if( m_highestSpecifiedArgPosition > 1 ) os << " "; os << "[<" << m_floatingArg->placeholder << "> ...]"; } } std::string argSynopsis() const { std::ostringstream oss; argSynopsis( oss ); return oss.str(); } void usage( std::ostream& os, std::string const& procName ) const { validate(); os << "usage:\n " << procName << " "; argSynopsis( os ); if( !m_options.empty() ) { os << " [options]\n\nwhere options are: \n"; optUsage( os, 2 ); } os << "\n"; } std::string usage( std::string const& procName ) const { std::ostringstream oss; usage( oss, procName ); return oss.str(); } ConfigT parse( int argc, char const * const * argv ) const { ConfigT config; parseInto( argc, argv, config ); return config; } std::vector<Parser::Token> parseInto( int argc, char const * const * argv, ConfigT& config ) const { std::string processName = argv[0]; std::size_t lastSlash = processName.find_last_of( "/\\" ); if( lastSlash != std::string::npos ) processName = processName.substr( lastSlash+1 ); m_boundProcessName.set( config, processName ); std::vector<Parser::Token> tokens; Parser parser; parser.parseIntoTokens( argc, argv, tokens ); return populate( tokens, config ); } std::vector<Parser::Token> populate( std::vector<Parser::Token> const& tokens, ConfigT& config ) const { validate(); std::vector<Parser::Token> unusedTokens = populateOptions( tokens, config ); unusedTokens = populateFixedArgs( unusedTokens, config ); unusedTokens = populateFloatingArgs( unusedTokens, config ); return unusedTokens; } std::vector<Parser::Token> populateOptions( std::vector<Parser::Token> const& tokens, ConfigT& config ) const { std::vector<Parser::Token> unusedTokens; std::vector<std::string> errors; for( std::size_t i = 0; i < tokens.size(); ++i ) { Parser::Token const& token = tokens[i]; typename std::vector<Arg>::const_iterator it = m_options.begin(), itEnd = m_options.end(); for(; it != itEnd; ++it ) { Arg const& arg = *it; try { if( ( token.type == Parser::Token::ShortOpt && arg.hasShortName( token.data ) ) || ( token.type == Parser::Token::LongOpt && arg.hasLongName( token.data ) ) ) { if( arg.takesArg() ) { if( i == tokens.size()-1 || tokens[i+1].type != Parser::Token::Positional ) errors.push_back( "Expected argument to option: " + token.data ); else arg.boundField.set( config, tokens[++i].data ); } else { arg.boundField.setFlag( config ); } break; } } catch( std::exception& ex ) { errors.push_back( std::string( ex.what() ) + "\n- while parsing: (" + arg.commands() + ")" ); } } if( it == itEnd ) { if( token.type == Parser::Token::Positional || !m_throwOnUnrecognisedTokens ) unusedTokens.push_back( token ); else if( errors.empty() && m_throwOnUnrecognisedTokens ) errors.push_back( "unrecognised option: " + token.data ); } } if( !errors.empty() ) { std::ostringstream oss; for( std::vector<std::string>::const_iterator it = errors.begin(), itEnd = errors.end(); it != itEnd; ++it ) { if( it != errors.begin() ) oss << "\n"; oss << *it; } throw std::runtime_error( oss.str() ); } return unusedTokens; } std::vector<Parser::Token> populateFixedArgs( std::vector<Parser::Token> const& tokens, ConfigT& config ) const { std::vector<Parser::Token> unusedTokens; int position = 1; for( std::size_t i = 0; i < tokens.size(); ++i ) { Parser::Token const& token = tokens[i]; typename std::map<int, Arg>::const_iterator it = m_positionalArgs.find( position ); if( it != m_positionalArgs.end() ) it->second.boundField.set( config, token.data ); else unusedTokens.push_back( token ); if( token.type == Parser::Token::Positional ) position++; } return unusedTokens; } std::vector<Parser::Token> populateFloatingArgs( std::vector<Parser::Token> const& tokens, ConfigT& config ) const { if( !m_floatingArg.get() ) return tokens; std::vector<Parser::Token> unusedTokens; for( std::size_t i = 0; i < tokens.size(); ++i ) { Parser::Token const& token = tokens[i]; if( token.type == Parser::Token::Positional ) m_floatingArg->boundField.set( config, token.data ); else unusedTokens.push_back( token ); } return unusedTokens; } void validate() const { if( m_options.empty() && m_positionalArgs.empty() && !m_floatingArg.get() ) throw std::logic_error( "No options or arguments specified" ); for( typename std::vector<Arg>::const_iterator it = m_options.begin(), itEnd = m_options.end(); it != itEnd; ++it ) it->validate(); } private: Detail::BoundArgFunction<ConfigT> m_boundProcessName; std::vector<Arg> m_options; std::map<int, Arg> m_positionalArgs; ArgAutoPtr m_floatingArg; int m_highestSpecifiedArgPosition; bool m_throwOnUnrecognisedTokens; }; } // end namespace Clara STITCH_CLARA_CLOSE_NAMESPACE #undef STITCH_CLARA_OPEN_NAMESPACE #undef STITCH_CLARA_CLOSE_NAMESPACE #endif // TWOBLUECUBES_CLARA_H_INCLUDED #undef STITCH_CLARA_OPEN_NAMESPACE // Restore Clara's value for console width, if present #ifdef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH #define CLARA_CONFIG_CONSOLE_WIDTH CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH #undef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH #endif #include <fstream> namespace Catch { inline void abortAfterFirst( ConfigData& config ) { config.abortAfter = 1; } inline void abortAfterX( ConfigData& config, int x ) { if( x < 1 ) throw std::runtime_error( "Value after -x or --abortAfter must be greater than zero" ); config.abortAfter = x; } inline void addTestOrTags( ConfigData& config, std::string const& _testSpec ) { config.testsOrTags.push_back( _testSpec ); } inline void addReporterName( ConfigData& config, std::string const& _reporterName ) { config.reporterNames.push_back( _reporterName ); } inline void addWarning( ConfigData& config, std::string const& _warning ) { if( _warning == "NoAssertions" ) config.warnings = static_cast<WarnAbout::What>( config.warnings | WarnAbout::NoAssertions ); else throw std::runtime_error( "Unrecognised warning: '" + _warning + "'" ); } inline void setOrder( ConfigData& config, std::string const& order ) { if( startsWith( "declared", order ) ) config.runOrder = RunTests::InDeclarationOrder; else if( startsWith( "lexical", order ) ) config.runOrder = RunTests::InLexicographicalOrder; else if( startsWith( "random", order ) ) config.runOrder = RunTests::InRandomOrder; else throw std::runtime_error( "Unrecognised ordering: '" + order + "'" ); } inline void setRngSeed( ConfigData& config, std::string const& seed ) { if( seed == "time" ) { config.rngSeed = static_cast<unsigned int>( std::time(0) ); } else { std::stringstream ss; ss << seed; ss >> config.rngSeed; if( ss.fail() ) throw std::runtime_error( "Argment to --rng-seed should be the word 'time' or a number" ); } } inline void setVerbosity( ConfigData& config, int level ) { // !TBD: accept strings? config.verbosity = static_cast<Verbosity::Level>( level ); } inline void setShowDurations( ConfigData& config, bool _showDurations ) { config.showDurations = _showDurations ? ShowDurations::Always : ShowDurations::Never; } inline void loadTestNamesFromFile( ConfigData& config, std::string const& _filename ) { std::ifstream f( _filename.c_str() ); if( !f.is_open() ) throw std::domain_error( "Unable to load input file: " + _filename ); std::string line; while( std::getline( f, line ) ) { line = trim(line); if( !line.empty() && !startsWith( line, "#" ) ) addTestOrTags( config, "\"" + line + "\"," ); } } inline Clara::CommandLine<ConfigData> makeCommandLineParser() { using namespace Clara; CommandLine<ConfigData> cli; cli.bindProcessName( &ConfigData::processName ); cli["-?"]["-h"]["--help"] .describe( "display usage information" ) .bind( &ConfigData::showHelp ); cli["-l"]["--list-tests"] .describe( "list all/matching test cases" ) .bind( &ConfigData::listTests ); cli["-t"]["--list-tags"] .describe( "list all/matching tags" ) .bind( &ConfigData::listTags ); cli["-s"]["--success"] .describe( "include successful tests in output" ) .bind( &ConfigData::showSuccessfulTests ); cli["-b"]["--break"] .describe( "break into debugger on failure" ) .bind( &ConfigData::shouldDebugBreak ); cli["-e"]["--nothrow"] .describe( "skip exception tests" ) .bind( &ConfigData::noThrow ); cli["-i"]["--invisibles"] .describe( "show invisibles (tabs, newlines)" ) .bind( &ConfigData::showInvisibles ); cli["-o"]["--out"] .describe( "output filename" ) .bind( &ConfigData::outputFilename, "filename" ); cli["-r"]["--reporter"] // .placeholder( "name[:filename]" ) .describe( "reporter to use (defaults to console)" ) .bind( &addReporterName, "name" ); cli["-n"]["--name"] .describe( "suite name" ) .bind( &ConfigData::name, "name" ); cli["-a"]["--abort"] .describe( "abort at first failure" ) .bind( &abortAfterFirst ); cli["-x"]["--abortx"] .describe( "abort after x failures" ) .bind( &abortAfterX, "no. failures" ); cli["-w"]["--warn"] .describe( "enable warnings" ) .bind( &addWarning, "warning name" ); // - needs updating if reinstated // cli.into( &setVerbosity ) // .describe( "level of verbosity (0=no output)" ) // .shortOpt( "v") // .longOpt( "verbosity" ) // .placeholder( "level" ); cli[_] .describe( "which test or tests to use" ) .bind( &addTestOrTags, "test name, pattern or tags" ); cli["-d"]["--durations"] .describe( "show test durations" ) .bind( &setShowDurations, "yes/no" ); cli["-f"]["--input-file"] .describe( "load test names to run from a file" ) .bind( &loadTestNamesFromFile, "filename" ); cli["-#"]["--filenames-as-tags"] .describe( "adds a tag for the filename" ) .bind( &ConfigData::filenamesAsTags ); // Less common commands which don't have a short form cli["--list-test-names-only"] .describe( "list all/matching test cases names only" ) .bind( &ConfigData::listTestNamesOnly ); cli["--list-reporters"] .describe( "list all reporters" ) .bind( &ConfigData::listReporters ); cli["--order"] .describe( "test case order (defaults to decl)" ) .bind( &setOrder, "decl|lex|rand" ); cli["--rng-seed"] .describe( "set a specific seed for random numbers" ) .bind( &setRngSeed, "'time'|number" ); cli["--force-colour"] .describe( "force colourised output" ) .bind( &ConfigData::forceColour ); return cli; } } // end namespace Catch // #included from: internal/catch_list.hpp #define TWOBLUECUBES_CATCH_LIST_HPP_INCLUDED // #included from: catch_text.h #define TWOBLUECUBES_CATCH_TEXT_H_INCLUDED #define TBC_TEXT_FORMAT_CONSOLE_WIDTH CATCH_CONFIG_CONSOLE_WIDTH #define CLICHE_TBC_TEXT_FORMAT_OUTER_NAMESPACE Catch // #included from: ../external/tbc_text_format.h // Only use header guard if we are not using an outer namespace #ifndef CLICHE_TBC_TEXT_FORMAT_OUTER_NAMESPACE # ifdef TWOBLUECUBES_TEXT_FORMAT_H_INCLUDED # ifndef TWOBLUECUBES_TEXT_FORMAT_H_ALREADY_INCLUDED # define TWOBLUECUBES_TEXT_FORMAT_H_ALREADY_INCLUDED # endif # else # define TWOBLUECUBES_TEXT_FORMAT_H_INCLUDED # endif #endif #ifndef TWOBLUECUBES_TEXT_FORMAT_H_ALREADY_INCLUDED #include <string> #include <vector> #include <sstream> // Use optional outer namespace #ifdef CLICHE_TBC_TEXT_FORMAT_OUTER_NAMESPACE namespace CLICHE_TBC_TEXT_FORMAT_OUTER_NAMESPACE { #endif namespace Tbc { #ifdef TBC_TEXT_FORMAT_CONSOLE_WIDTH const unsigned int consoleWidth = TBC_TEXT_FORMAT_CONSOLE_WIDTH; #else const unsigned int consoleWidth = 80; #endif struct TextAttributes { TextAttributes() : initialIndent( std::string::npos ), indent( 0 ), width( consoleWidth-1 ), tabChar( '\t' ) {} TextAttributes& setInitialIndent( std::size_t _value ) { initialIndent = _value; return *this; } TextAttributes& setIndent( std::size_t _value ) { indent = _value; return *this; } TextAttributes& setWidth( std::size_t _value ) { width = _value; return *this; } TextAttributes& setTabChar( char _value ) { tabChar = _value; return *this; } std::size_t initialIndent; // indent of first line, or npos std::size_t indent; // indent of subsequent lines, or all if initialIndent is npos std::size_t width; // maximum width of text, including indent. Longer text will wrap char tabChar; // If this char is seen the indent is changed to current pos }; class Text { public: Text( std::string const& _str, TextAttributes const& _attr = TextAttributes() ) : attr( _attr ) { std::string wrappableChars = " [({.,/|\\-"; std::size_t indent = _attr.initialIndent != std::string::npos ? _attr.initialIndent : _attr.indent; std::string remainder = _str; while( !remainder.empty() ) { if( lines.size() >= 1000 ) { lines.push_back( "... message truncated due to excessive size" ); return; } std::size_t tabPos = std::string::npos; std::size_t width = (std::min)( remainder.size(), _attr.width - indent ); std::size_t pos = remainder.find_first_of( '\n' ); if( pos <= width ) { width = pos; } pos = remainder.find_last_of( _attr.tabChar, width ); if( pos != std::string::npos ) { tabPos = pos; if( remainder[width] == '\n' ) width--; remainder = remainder.substr( 0, tabPos ) + remainder.substr( tabPos+1 ); } if( width == remainder.size() ) { spliceLine( indent, remainder, width ); } else if( remainder[width] == '\n' ) { spliceLine( indent, remainder, width ); if( width <= 1 || remainder.size() != 1 ) remainder = remainder.substr( 1 ); indent = _attr.indent; } else { pos = remainder.find_last_of( wrappableChars, width ); if( pos != std::string::npos && pos > 0 ) { spliceLine( indent, remainder, pos ); if( remainder[0] == ' ' ) remainder = remainder.substr( 1 ); } else { spliceLine( indent, remainder, width-1 ); lines.back() += "-"; } if( lines.size() == 1 ) indent = _attr.indent; if( tabPos != std::string::npos ) indent += tabPos; } } } void spliceLine( std::size_t _indent, std::string& _remainder, std::size_t _pos ) { lines.push_back( std::string( _indent, ' ' ) + _remainder.substr( 0, _pos ) ); _remainder = _remainder.substr( _pos ); } typedef std::vector<std::string>::const_iterator const_iterator; const_iterator begin() const { return lines.begin(); } const_iterator end() const { return lines.end(); } std::string const& last() const { return lines.back(); } std::size_t size() const { return lines.size(); } std::string const& operator[]( std::size_t _index ) const { return lines[_index]; } std::string toString() const { std::ostringstream oss; oss << *this; return oss.str(); } inline friend std::ostream& operator << ( std::ostream& _stream, Text const& _text ) { for( Text::const_iterator it = _text.begin(), itEnd = _text.end(); it != itEnd; ++it ) { if( it != _text.begin() ) _stream << "\n"; _stream << *it; } return _stream; } private: std::string str; TextAttributes attr; std::vector<std::string> lines; }; } // end namespace Tbc #ifdef CLICHE_TBC_TEXT_FORMAT_OUTER_NAMESPACE } // end outer namespace #endif #endif // TWOBLUECUBES_TEXT_FORMAT_H_ALREADY_INCLUDED #undef CLICHE_TBC_TEXT_FORMAT_OUTER_NAMESPACE namespace Catch { using Tbc::Text; using Tbc::TextAttributes; } // #included from: catch_console_colour.hpp #define TWOBLUECUBES_CATCH_CONSOLE_COLOUR_HPP_INCLUDED namespace Catch { struct Colour { enum Code { None = 0, White, Red, Green, Blue, Cyan, Yellow, Grey, Bright = 0x10, BrightRed = Bright | Red, BrightGreen = Bright | Green, LightGrey = Bright | Grey, BrightWhite = Bright | White, // By intention FileName = LightGrey, Warning = Yellow, ResultError = BrightRed, ResultSuccess = BrightGreen, ResultExpectedFailure = Warning, Error = BrightRed, Success = Green, OriginalExpression = Cyan, ReconstructedExpression = Yellow, SecondaryText = LightGrey, Headers = White }; // Use constructed object for RAII guard Colour( Code _colourCode ); Colour( Colour const& other ); ~Colour(); // Use static method for one-shot changes static void use( Code _colourCode ); private: bool m_moved; }; inline std::ostream& operator << ( std::ostream& os, Colour const& ) { return os; } } // end namespace Catch // #included from: catch_interfaces_reporter.h #define TWOBLUECUBES_CATCH_INTERFACES_REPORTER_H_INCLUDED #include <string> #include <ostream> #include <map> #include <assert.h> namespace Catch { struct ReporterConfig { explicit ReporterConfig( Ptr<IConfig const> const& _fullConfig ) : m_stream( &_fullConfig->stream() ), m_fullConfig( _fullConfig ) {} ReporterConfig( Ptr<IConfig const> const& _fullConfig, std::ostream& _stream ) : m_stream( &_stream ), m_fullConfig( _fullConfig ) {} std::ostream& stream() const { return *m_stream; } Ptr<IConfig const> fullConfig() const { return m_fullConfig; } private: std::ostream* m_stream; Ptr<IConfig const> m_fullConfig; }; struct ReporterPreferences { ReporterPreferences() : shouldRedirectStdOut( false ) {} bool shouldRedirectStdOut; }; template<typename T> struct LazyStat : Option<T> { LazyStat() : used( false ) {} LazyStat& operator=( T const& _value ) { Option<T>::operator=( _value ); used = false; return *this; } void reset() { Option<T>::reset(); used = false; } bool used; }; struct TestRunInfo { TestRunInfo( std::string const& _name ) : name( _name ) {} std::string name; }; struct GroupInfo { GroupInfo( std::string const& _name, std::size_t _groupIndex, std::size_t _groupsCount ) : name( _name ), groupIndex( _groupIndex ), groupsCounts( _groupsCount ) {} std::string name; std::size_t groupIndex; std::size_t groupsCounts; }; struct AssertionStats { AssertionStats( AssertionResult const& _assertionResult, std::vector<MessageInfo> const& _infoMessages, Totals const& _totals ) : assertionResult( _assertionResult ), infoMessages( _infoMessages ), totals( _totals ) { if( assertionResult.hasMessage() ) { // Copy message into messages list. // !TBD This should have been done earlier, somewhere MessageBuilder builder( assertionResult.getTestMacroName(), assertionResult.getSourceInfo(), assertionResult.getResultType() ); builder << assertionResult.getMessage(); builder.m_info.message = builder.m_stream.str(); infoMessages.push_back( builder.m_info ); } } virtual ~AssertionStats(); # ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS AssertionStats( AssertionStats const& ) = default; AssertionStats( AssertionStats && ) = default; AssertionStats& operator = ( AssertionStats const& ) = default; AssertionStats& operator = ( AssertionStats && ) = default; # endif AssertionResult assertionResult; std::vector<MessageInfo> infoMessages; Totals totals; }; struct SectionStats { SectionStats( SectionInfo const& _sectionInfo, Counts const& _assertions, double _durationInSeconds, bool _missingAssertions ) : sectionInfo( _sectionInfo ), assertions( _assertions ), durationInSeconds( _durationInSeconds ), missingAssertions( _missingAssertions ) {} virtual ~SectionStats(); # ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS SectionStats( SectionStats const& ) = default; SectionStats( SectionStats && ) = default; SectionStats& operator = ( SectionStats const& ) = default; SectionStats& operator = ( SectionStats && ) = default; # endif SectionInfo sectionInfo; Counts assertions; double durationInSeconds; bool missingAssertions; }; struct TestCaseStats { TestCaseStats( TestCaseInfo const& _testInfo, Totals const& _totals, std::string const& _stdOut, std::string const& _stdErr, bool _aborting ) : testInfo( _testInfo ), totals( _totals ), stdOut( _stdOut ), stdErr( _stdErr ), aborting( _aborting ) {} virtual ~TestCaseStats(); # ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS TestCaseStats( TestCaseStats const& ) = default; TestCaseStats( TestCaseStats && ) = default; TestCaseStats& operator = ( TestCaseStats const& ) = default; TestCaseStats& operator = ( TestCaseStats && ) = default; # endif TestCaseInfo testInfo; Totals totals; std::string stdOut; std::string stdErr; bool aborting; }; struct TestGroupStats { TestGroupStats( GroupInfo const& _groupInfo, Totals const& _totals, bool _aborting ) : groupInfo( _groupInfo ), totals( _totals ), aborting( _aborting ) {} TestGroupStats( GroupInfo const& _groupInfo ) : groupInfo( _groupInfo ), aborting( false ) {} virtual ~TestGroupStats(); # ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS TestGroupStats( TestGroupStats const& ) = default; TestGroupStats( TestGroupStats && ) = default; TestGroupStats& operator = ( TestGroupStats const& ) = default; TestGroupStats& operator = ( TestGroupStats && ) = default; # endif GroupInfo groupInfo; Totals totals; bool aborting; }; struct TestRunStats { TestRunStats( TestRunInfo const& _runInfo, Totals const& _totals, bool _aborting ) : runInfo( _runInfo ), totals( _totals ), aborting( _aborting ) {} virtual ~TestRunStats(); # ifndef CATCH_CONFIG_CPP11_GENERATED_METHODS TestRunStats( TestRunStats const& _other ) : runInfo( _other.runInfo ), totals( _other.totals ), aborting( _other.aborting ) {} # else TestRunStats( TestRunStats const& ) = default; TestRunStats( TestRunStats && ) = default; TestRunStats& operator = ( TestRunStats const& ) = default; TestRunStats& operator = ( TestRunStats && ) = default; # endif TestRunInfo runInfo; Totals totals; bool aborting; }; struct IStreamingReporter : IShared { virtual ~IStreamingReporter(); // Implementing class must also provide the following static method: // static std::string getDescription(); virtual ReporterPreferences getPreferences() const = 0; virtual void noMatchingTestCases( std::string const& spec ) = 0; virtual void testRunStarting( TestRunInfo const& testRunInfo ) = 0; virtual void testGroupStarting( GroupInfo const& groupInfo ) = 0; virtual void testCaseStarting( TestCaseInfo const& testInfo ) = 0; virtual void sectionStarting( SectionInfo const& sectionInfo ) = 0; virtual void assertionStarting( AssertionInfo const& assertionInfo ) = 0; // The return value indicates if the messages buffer should be cleared: virtual bool assertionEnded( AssertionStats const& assertionStats ) = 0; virtual void sectionEnded( SectionStats const& sectionStats ) = 0; virtual void testCaseEnded( TestCaseStats const& testCaseStats ) = 0; virtual void testGroupEnded( TestGroupStats const& testGroupStats ) = 0; virtual void testRunEnded( TestRunStats const& testRunStats ) = 0; virtual void skipTest( TestCaseInfo const& testInfo ) = 0; }; struct IReporterFactory : IShared { virtual ~IReporterFactory(); virtual IStreamingReporter* create( ReporterConfig const& config ) const = 0; virtual std::string getDescription() const = 0; }; struct IReporterRegistry { typedef std::map<std::string, Ptr<IReporterFactory> > FactoryMap; typedef std::vector<Ptr<IReporterFactory> > Listeners; virtual ~IReporterRegistry(); virtual IStreamingReporter* create( std::string const& name, Ptr<IConfig const> const& config ) const = 0; virtual FactoryMap const& getFactories() const = 0; virtual Listeners const& getListeners() const = 0; }; Ptr<IStreamingReporter> addReporter( Ptr<IStreamingReporter> const& existingReporter, Ptr<IStreamingReporter> const& additionalReporter ); } #include <limits> #include <algorithm> namespace Catch { inline std::size_t listTests( Config const& config ) { TestSpec testSpec = config.testSpec(); if( config.testSpec().hasFilters() ) Catch::cout() << "Matching test cases:\n"; else { Catch::cout() << "All available test cases:\n"; testSpec = TestSpecParser( ITagAliasRegistry::get() ).parse( "*" ).testSpec(); } std::size_t matchedTests = 0; TextAttributes nameAttr, tagsAttr; nameAttr.setInitialIndent( 2 ).setIndent( 4 ); tagsAttr.setIndent( 6 ); std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config ); for( std::vector<TestCase>::const_iterator it = matchedTestCases.begin(), itEnd = matchedTestCases.end(); it != itEnd; ++it ) { matchedTests++; TestCaseInfo const& testCaseInfo = it->getTestCaseInfo(); Colour::Code colour = testCaseInfo.isHidden() ? Colour::SecondaryText : Colour::None; Colour colourGuard( colour ); Catch::cout() << Text( testCaseInfo.name, nameAttr ) << std::endl; if( !testCaseInfo.tags.empty() ) Catch::cout() << Text( testCaseInfo.tagsAsString, tagsAttr ) << std::endl; } if( !config.testSpec().hasFilters() ) Catch::cout() << pluralise( matchedTests, "test case" ) << "\n" << std::endl; else Catch::cout() << pluralise( matchedTests, "matching test case" ) << "\n" << std::endl; return matchedTests; } inline std::size_t listTestsNamesOnly( Config const& config ) { TestSpec testSpec = config.testSpec(); if( !config.testSpec().hasFilters() ) testSpec = TestSpecParser( ITagAliasRegistry::get() ).parse( "*" ).testSpec(); std::size_t matchedTests = 0; std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config ); for( std::vector<TestCase>::const_iterator it = matchedTestCases.begin(), itEnd = matchedTestCases.end(); it != itEnd; ++it ) { matchedTests++; TestCaseInfo const& testCaseInfo = it->getTestCaseInfo(); Catch::cout() << testCaseInfo.name << std::endl; } return matchedTests; } struct TagInfo { TagInfo() : count ( 0 ) {} void add( std::string const& spelling ) { ++count; spellings.insert( spelling ); } std::string all() const { std::string out; for( std::set<std::string>::const_iterator it = spellings.begin(), itEnd = spellings.end(); it != itEnd; ++it ) out += "[" + *it + "]"; return out; } std::set<std::string> spellings; std::size_t count; }; inline std::size_t listTags( Config const& config ) { TestSpec testSpec = config.testSpec(); if( config.testSpec().hasFilters() ) Catch::cout() << "Tags for matching test cases:\n"; else { Catch::cout() << "All available tags:\n"; testSpec = TestSpecParser( ITagAliasRegistry::get() ).parse( "*" ).testSpec(); } std::map<std::string, TagInfo> tagCounts; std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config ); for( std::vector<TestCase>::const_iterator it = matchedTestCases.begin(), itEnd = matchedTestCases.end(); it != itEnd; ++it ) { for( std::set<std::string>::const_iterator tagIt = it->getTestCaseInfo().tags.begin(), tagItEnd = it->getTestCaseInfo().tags.end(); tagIt != tagItEnd; ++tagIt ) { std::string tagName = *tagIt; std::string lcaseTagName = toLower( tagName ); std::map<std::string, TagInfo>::iterator countIt = tagCounts.find( lcaseTagName ); if( countIt == tagCounts.end() ) countIt = tagCounts.insert( std::make_pair( lcaseTagName, TagInfo() ) ).first; countIt->second.add( tagName ); } } for( std::map<std::string, TagInfo>::const_iterator countIt = tagCounts.begin(), countItEnd = tagCounts.end(); countIt != countItEnd; ++countIt ) { std::ostringstream oss; oss << " " << std::setw(2) << countIt->second.count << " "; Text wrapper( countIt->second.all(), TextAttributes() .setInitialIndent( 0 ) .setIndent( oss.str().size() ) .setWidth( CATCH_CONFIG_CONSOLE_WIDTH-10 ) ); Catch::cout() << oss.str() << wrapper << "\n"; } Catch::cout() << pluralise( tagCounts.size(), "tag" ) << "\n" << std::endl; return tagCounts.size(); } inline std::size_t listReporters( Config const& /*config*/ ) { Catch::cout() << "Available reporters:\n"; IReporterRegistry::FactoryMap const& factories = getRegistryHub().getReporterRegistry().getFactories(); IReporterRegistry::FactoryMap::const_iterator itBegin = factories.begin(), itEnd = factories.end(), it; std::size_t maxNameLen = 0; for(it = itBegin; it != itEnd; ++it ) maxNameLen = (std::max)( maxNameLen, it->first.size() ); for(it = itBegin; it != itEnd; ++it ) { Text wrapper( it->second->getDescription(), TextAttributes() .setInitialIndent( 0 ) .setIndent( 7+maxNameLen ) .setWidth( CATCH_CONFIG_CONSOLE_WIDTH - maxNameLen-8 ) ); Catch::cout() << " " << it->first << ":" << std::string( maxNameLen - it->first.size() + 2, ' ' ) << wrapper << "\n"; } Catch::cout() << std::endl; return factories.size(); } inline Option<std::size_t> list( Config const& config ) { Option<std::size_t> listedCount; if( config.listTests() ) listedCount = listedCount.valueOr(0) + listTests( config ); if( config.listTestNamesOnly() ) listedCount = listedCount.valueOr(0) + listTestsNamesOnly( config ); if( config.listTags() ) listedCount = listedCount.valueOr(0) + listTags( config ); if( config.listReporters() ) listedCount = listedCount.valueOr(0) + listReporters( config ); return listedCount; } } // end namespace Catch // #included from: internal/catch_run_context.hpp #define TWOBLUECUBES_CATCH_RUNNER_IMPL_HPP_INCLUDED // #included from: catch_test_case_tracker.hpp #define TWOBLUECUBES_CATCH_TEST_CASE_TRACKER_HPP_INCLUDED #include <map> #include <string> #include <assert.h> #include <vector> namespace Catch { namespace TestCaseTracking { struct ITracker : SharedImpl<> { virtual ~ITracker(); // static queries virtual std::string name() const = 0; // dynamic queries virtual bool isComplete() const = 0; // Successfully completed or failed virtual bool isSuccessfullyCompleted() const = 0; virtual bool isOpen() const = 0; // Started but not complete virtual bool hasChildren() const = 0; virtual ITracker& parent() = 0; // actions virtual void close() = 0; // Successfully complete virtual void fail() = 0; virtual void markAsNeedingAnotherRun() = 0; virtual void addChild( Ptr<ITracker> const& child ) = 0; virtual ITracker* findChild( std::string const& name ) = 0; virtual void openChild() = 0; }; class TrackerContext { enum RunState { NotStarted, Executing, CompletedCycle }; Ptr<ITracker> m_rootTracker; ITracker* m_currentTracker; RunState m_runState; public: static TrackerContext& instance() { static TrackerContext s_instance; return s_instance; } TrackerContext() : m_currentTracker( CATCH_NULL ), m_runState( NotStarted ) {} ITracker& startRun(); void endRun() { m_rootTracker.reset(); m_currentTracker = CATCH_NULL; m_runState = NotStarted; } void startCycle() { m_currentTracker = m_rootTracker.get(); m_runState = Executing; } void completeCycle() { m_runState = CompletedCycle; } bool completedCycle() const { return m_runState == CompletedCycle; } ITracker& currentTracker() { return *m_currentTracker; } void setCurrentTracker( ITracker* tracker ) { m_currentTracker = tracker; } }; class TrackerBase : public ITracker { protected: enum CycleState { NotStarted, Executing, ExecutingChildren, NeedsAnotherRun, CompletedSuccessfully, Failed }; class TrackerHasName { std::string m_name; public: TrackerHasName( std::string const& name ) : m_name( name ) {} bool operator ()( Ptr<ITracker> const& tracker ) { return tracker->name() == m_name; } }; typedef std::vector<Ptr<ITracker> > Children; std::string m_name; TrackerContext& m_ctx; ITracker* m_parent; Children m_children; CycleState m_runState; public: TrackerBase( std::string const& name, TrackerContext& ctx, ITracker* parent ) : m_name( name ), m_ctx( ctx ), m_parent( parent ), m_runState( NotStarted ) {} virtual ~TrackerBase(); virtual std::string name() const CATCH_OVERRIDE { return m_name; } virtual bool isComplete() const CATCH_OVERRIDE { return m_runState == CompletedSuccessfully || m_runState == Failed; } virtual bool isSuccessfullyCompleted() const CATCH_OVERRIDE { return m_runState == CompletedSuccessfully; } virtual bool isOpen() const CATCH_OVERRIDE { return m_runState != NotStarted && !isComplete(); } virtual bool hasChildren() const CATCH_OVERRIDE { return !m_children.empty(); } virtual void addChild( Ptr<ITracker> const& child ) CATCH_OVERRIDE { m_children.push_back( child ); } virtual ITracker* findChild( std::string const& name ) CATCH_OVERRIDE { Children::const_iterator it = std::find_if( m_children.begin(), m_children.end(), TrackerHasName( name ) ); return( it != m_children.end() ) ? it->get() : CATCH_NULL; } virtual ITracker& parent() CATCH_OVERRIDE { assert( m_parent ); // Should always be non-null except for root return *m_parent; } virtual void openChild() CATCH_OVERRIDE { if( m_runState != ExecutingChildren ) { m_runState = ExecutingChildren; if( m_parent ) m_parent->openChild(); } } void open() { m_runState = Executing; moveToThis(); if( m_parent ) m_parent->openChild(); } virtual void close() CATCH_OVERRIDE { // Close any still open children (e.g. generators) while( &m_ctx.currentTracker() != this ) m_ctx.currentTracker().close(); switch( m_runState ) { case NotStarted: case CompletedSuccessfully: case Failed: throw std::logic_error( "Illogical state" ); case NeedsAnotherRun: break;; case Executing: m_runState = CompletedSuccessfully; break; case ExecutingChildren: if( m_children.empty() || m_children.back()->isComplete() ) m_runState = CompletedSuccessfully; break; default: throw std::logic_error( "Unexpected state" ); } moveToParent(); m_ctx.completeCycle(); } virtual void fail() CATCH_OVERRIDE { m_runState = Failed; if( m_parent ) m_parent->markAsNeedingAnotherRun(); moveToParent(); m_ctx.completeCycle(); } virtual void markAsNeedingAnotherRun() CATCH_OVERRIDE { m_runState = NeedsAnotherRun; } private: void moveToParent() { assert( m_parent ); m_ctx.setCurrentTracker( m_parent ); } void moveToThis() { m_ctx.setCurrentTracker( this ); } }; class SectionTracker : public TrackerBase { public: SectionTracker( std::string const& name, TrackerContext& ctx, ITracker* parent ) : TrackerBase( name, ctx, parent ) {} virtual ~SectionTracker(); static SectionTracker& acquire( TrackerContext& ctx, std::string const& name ) { SectionTracker* section = CATCH_NULL; ITracker& currentTracker = ctx.currentTracker(); if( ITracker* childTracker = currentTracker.findChild( name ) ) { section = dynamic_cast<SectionTracker*>( childTracker ); assert( section ); } else { section = new SectionTracker( name, ctx, &currentTracker ); currentTracker.addChild( section ); } if( !ctx.completedCycle() && !section->isComplete() ) { section->open(); } return *section; } }; class IndexTracker : public TrackerBase { int m_size; int m_index; public: IndexTracker( std::string const& name, TrackerContext& ctx, ITracker* parent, int size ) : TrackerBase( name, ctx, parent ), m_size( size ), m_index( -1 ) {} virtual ~IndexTracker(); static IndexTracker& acquire( TrackerContext& ctx, std::string const& name, int size ) { IndexTracker* tracker = CATCH_NULL; ITracker& currentTracker = ctx.currentTracker(); if( ITracker* childTracker = currentTracker.findChild( name ) ) { tracker = dynamic_cast<IndexTracker*>( childTracker ); assert( tracker ); } else { tracker = new IndexTracker( name, ctx, &currentTracker, size ); currentTracker.addChild( tracker ); } if( !ctx.completedCycle() && !tracker->isComplete() ) { if( tracker->m_runState != ExecutingChildren && tracker->m_runState != NeedsAnotherRun ) tracker->moveNext(); tracker->open(); } return *tracker; } int index() const { return m_index; } void moveNext() { m_index++; m_children.clear(); } virtual void close() CATCH_OVERRIDE { TrackerBase::close(); if( m_runState == CompletedSuccessfully && m_index < m_size-1 ) m_runState = Executing; } }; inline ITracker& TrackerContext::startRun() { m_rootTracker = new SectionTracker( "{root}", *this, CATCH_NULL ); m_currentTracker = CATCH_NULL; m_runState = Executing; return *m_rootTracker; } } // namespace TestCaseTracking using TestCaseTracking::ITracker; using TestCaseTracking::TrackerContext; using TestCaseTracking::SectionTracker; using TestCaseTracking::IndexTracker; } // namespace Catch // #included from: catch_fatal_condition.hpp #define TWOBLUECUBES_CATCH_FATAL_CONDITION_H_INCLUDED namespace Catch { // Report the error condition then exit the process inline void fatal( std::string const& message, int exitCode ) { IContext& context = Catch::getCurrentContext(); IResultCapture* resultCapture = context.getResultCapture(); resultCapture->handleFatalErrorCondition( message ); if( Catch::alwaysTrue() ) // avoids "no return" warnings exit( exitCode ); } } // namespace Catch #if defined ( CATCH_PLATFORM_WINDOWS ) ///////////////////////////////////////// namespace Catch { struct FatalConditionHandler { void reset() {} }; } // namespace Catch #else // Not Windows - assumed to be POSIX compatible ////////////////////////// #include <signal.h> namespace Catch { struct SignalDefs { int id; const char* name; }; extern SignalDefs signalDefs[]; SignalDefs signalDefs[] = { { SIGINT, "SIGINT - Terminal interrupt signal" }, { SIGILL, "SIGILL - Illegal instruction signal" }, { SIGFPE, "SIGFPE - Floating point error signal" }, { SIGSEGV, "SIGSEGV - Segmentation violation signal" }, { SIGTERM, "SIGTERM - Termination request signal" }, { SIGABRT, "SIGABRT - Abort (abnormal termination) signal" } }; struct FatalConditionHandler { static void handleSignal( int sig ) { for( std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i ) if( sig == signalDefs[i].id ) fatal( signalDefs[i].name, -sig ); fatal( "<unknown signal>", -sig ); } FatalConditionHandler() : m_isSet( true ) { for( std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i ) signal( signalDefs[i].id, handleSignal ); } ~FatalConditionHandler() { reset(); } void reset() { if( m_isSet ) { for( std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i ) signal( signalDefs[i].id, SIG_DFL ); m_isSet = false; } } bool m_isSet; }; } // namespace Catch #endif // not Windows #include <set> #include <string> namespace Catch { class StreamRedirect { public: StreamRedirect( std::ostream& stream, std::string& targetString ) : m_stream( stream ), m_prevBuf( stream.rdbuf() ), m_targetString( targetString ) { stream.rdbuf( m_oss.rdbuf() ); } ~StreamRedirect() { m_targetString += m_oss.str(); m_stream.rdbuf( m_prevBuf ); } private: std::ostream& m_stream; std::streambuf* m_prevBuf; std::ostringstream m_oss; std::string& m_targetString; }; /////////////////////////////////////////////////////////////////////////// class RunContext : public IResultCapture, public IRunner { RunContext( RunContext const& ); void operator =( RunContext const& ); public: explicit RunContext( Ptr<IConfig const> const& _config, Ptr<IStreamingReporter> const& reporter ) : m_runInfo( _config->name() ), m_context( getCurrentMutableContext() ), m_activeTestCase( CATCH_NULL ), m_config( _config ), m_reporter( reporter ) { m_context.setRunner( this ); m_context.setConfig( m_config ); m_context.setResultCapture( this ); m_reporter->testRunStarting( m_runInfo ); } virtual ~RunContext() { m_reporter->testRunEnded( TestRunStats( m_runInfo, m_totals, aborting() ) ); } void testGroupStarting( std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount ) { m_reporter->testGroupStarting( GroupInfo( testSpec, groupIndex, groupsCount ) ); } void testGroupEnded( std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount ) { m_reporter->testGroupEnded( TestGroupStats( GroupInfo( testSpec, groupIndex, groupsCount ), totals, aborting() ) ); } Totals runTest( TestCase const& testCase ) { Totals prevTotals = m_totals; std::string redirectedCout; std::string redirectedCerr; TestCaseInfo testInfo = testCase.getTestCaseInfo(); m_reporter->testCaseStarting( testInfo ); m_activeTestCase = &testCase; do { m_trackerContext.startRun(); do { m_trackerContext.startCycle(); m_testCaseTracker = &SectionTracker::acquire( m_trackerContext, testInfo.name ); runCurrentTest( redirectedCout, redirectedCerr ); } while( !m_testCaseTracker->isSuccessfullyCompleted() && !aborting() ); } // !TBD: deprecated - this will be replaced by indexed trackers while( getCurrentContext().advanceGeneratorsForCurrentTest() && !aborting() ); Totals deltaTotals = m_totals.delta( prevTotals ); m_totals.testCases += deltaTotals.testCases; m_reporter->testCaseEnded( TestCaseStats( testInfo, deltaTotals, redirectedCout, redirectedCerr, aborting() ) ); m_activeTestCase = CATCH_NULL; m_testCaseTracker = CATCH_NULL; return deltaTotals; } Ptr<IConfig const> config() const { return m_config; } private: // IResultCapture virtual void assertionEnded( AssertionResult const& result ) { if( result.getResultType() == ResultWas::Ok ) { m_totals.assertions.passed++; } else if( !result.isOk() ) { m_totals.assertions.failed++; } if( m_reporter->assertionEnded( AssertionStats( result, m_messages, m_totals ) ) ) m_messages.clear(); // Reset working state m_lastAssertionInfo = AssertionInfo( "", m_lastAssertionInfo.lineInfo, "{Unknown expression after the reported line}" , m_lastAssertionInfo.resultDisposition ); m_lastResult = result; } virtual bool sectionStarted ( SectionInfo const& sectionInfo, Counts& assertions ) { std::ostringstream oss; oss << sectionInfo.name << "@" << sectionInfo.lineInfo; ITracker& sectionTracker = SectionTracker::acquire( m_trackerContext, oss.str() ); if( !sectionTracker.isOpen() ) return false; m_activeSections.push_back( &sectionTracker ); m_lastAssertionInfo.lineInfo = sectionInfo.lineInfo; m_reporter->sectionStarting( sectionInfo ); assertions = m_totals.assertions; return true; } bool testForMissingAssertions( Counts& assertions ) { if( assertions.total() != 0 ) return false; if( !m_config->warnAboutMissingAssertions() ) return false; if( m_trackerContext.currentTracker().hasChildren() ) return false; m_totals.assertions.failed++; assertions.failed++; return true; } virtual void sectionEnded( SectionEndInfo const& endInfo ) { Counts assertions = m_totals.assertions - endInfo.prevAssertions; bool missingAssertions = testForMissingAssertions( assertions ); if( !m_activeSections.empty() ) { m_activeSections.back()->close(); m_activeSections.pop_back(); } m_reporter->sectionEnded( SectionStats( endInfo.sectionInfo, assertions, endInfo.durationInSeconds, missingAssertions ) ); m_messages.clear(); } virtual void sectionEndedEarly( SectionEndInfo const& endInfo ) { if( m_unfinishedSections.empty() ) m_activeSections.back()->fail(); else m_activeSections.back()->close(); m_activeSections.pop_back(); m_unfinishedSections.push_back( endInfo ); } virtual void pushScopedMessage( MessageInfo const& message ) { m_messages.push_back( message ); } virtual void popScopedMessage( MessageInfo const& message ) { m_messages.erase( std::remove( m_messages.begin(), m_messages.end(), message ), m_messages.end() ); } virtual std::string getCurrentTestName() const { return m_activeTestCase ? m_activeTestCase->getTestCaseInfo().name : ""; } virtual const AssertionResult* getLastResult() const { return &m_lastResult; } virtual void handleFatalErrorCondition( std::string const& message ) { ResultBuilder resultBuilder = makeUnexpectedResultBuilder(); resultBuilder.setResultType( ResultWas::FatalErrorCondition ); resultBuilder << message; resultBuilder.captureExpression(); handleUnfinishedSections(); // Recreate section for test case (as we will lose the one that was in scope) TestCaseInfo const& testCaseInfo = m_activeTestCase->getTestCaseInfo(); SectionInfo testCaseSection( testCaseInfo.lineInfo, testCaseInfo.name, testCaseInfo.description ); Counts assertions; assertions.failed = 1; SectionStats testCaseSectionStats( testCaseSection, assertions, 0, false ); m_reporter->sectionEnded( testCaseSectionStats ); TestCaseInfo testInfo = m_activeTestCase->getTestCaseInfo(); Totals deltaTotals; deltaTotals.testCases.failed = 1; m_reporter->testCaseEnded( TestCaseStats( testInfo, deltaTotals, "", "", false ) ); m_totals.testCases.failed++; testGroupEnded( "", m_totals, 1, 1 ); m_reporter->testRunEnded( TestRunStats( m_runInfo, m_totals, false ) ); } public: // !TBD We need to do this another way! bool aborting() const { return m_totals.assertions.failed == static_cast<std::size_t>( m_config->abortAfter() ); } private: void runCurrentTest( std::string& redirectedCout, std::string& redirectedCerr ) { TestCaseInfo const& testCaseInfo = m_activeTestCase->getTestCaseInfo(); SectionInfo testCaseSection( testCaseInfo.lineInfo, testCaseInfo.name, testCaseInfo.description ); m_reporter->sectionStarting( testCaseSection ); Counts prevAssertions = m_totals.assertions; double duration = 0; try { m_lastAssertionInfo = AssertionInfo( "TEST_CASE", testCaseInfo.lineInfo, "", ResultDisposition::Normal ); seedRng( *m_config ); Timer timer; timer.start(); if( m_reporter->getPreferences().shouldRedirectStdOut ) { StreamRedirect coutRedir( Catch::cout(), redirectedCout ); StreamRedirect cerrRedir( Catch::cerr(), redirectedCerr ); invokeActiveTestCase(); } else { invokeActiveTestCase(); } duration = timer.getElapsedSeconds(); } catch( TestFailureException& ) { // This just means the test was aborted due to failure } catch(...) { makeUnexpectedResultBuilder().useActiveException(); } m_testCaseTracker->close(); handleUnfinishedSections(); m_messages.clear(); Counts assertions = m_totals.assertions - prevAssertions; bool missingAssertions = testForMissingAssertions( assertions ); if( testCaseInfo.okToFail() ) { std::swap( assertions.failedButOk, assertions.failed ); m_totals.assertions.failed -= assertions.failedButOk; m_totals.assertions.failedButOk += assertions.failedButOk; } SectionStats testCaseSectionStats( testCaseSection, assertions, duration, missingAssertions ); m_reporter->sectionEnded( testCaseSectionStats ); } void invokeActiveTestCase() { FatalConditionHandler fatalConditionHandler; // Handle signals m_activeTestCase->invoke(); fatalConditionHandler.reset(); } private: ResultBuilder makeUnexpectedResultBuilder() const { return ResultBuilder( m_lastAssertionInfo.macroName.c_str(), m_lastAssertionInfo.lineInfo, m_lastAssertionInfo.capturedExpression.c_str(), m_lastAssertionInfo.resultDisposition ); } void handleUnfinishedSections() { // If sections ended prematurely due to an exception we stored their // infos here so we can tear them down outside the unwind process. for( std::vector<SectionEndInfo>::const_reverse_iterator it = m_unfinishedSections.rbegin(), itEnd = m_unfinishedSections.rend(); it != itEnd; ++it ) sectionEnded( *it ); m_unfinishedSections.clear(); } TestRunInfo m_runInfo; IMutableContext& m_context; TestCase const* m_activeTestCase; ITracker* m_testCaseTracker; ITracker* m_currentSectionTracker; AssertionResult m_lastResult; Ptr<IConfig const> m_config; Totals m_totals; Ptr<IStreamingReporter> m_reporter; std::vector<MessageInfo> m_messages; AssertionInfo m_lastAssertionInfo; std::vector<SectionEndInfo> m_unfinishedSections; std::vector<ITracker*> m_activeSections; TrackerContext m_trackerContext; }; IResultCapture& getResultCapture() { if( IResultCapture* capture = getCurrentContext().getResultCapture() ) return *capture; else throw std::logic_error( "No result capture instance" ); } } // end namespace Catch // #included from: internal/catch_version.h #define TWOBLUECUBES_CATCH_VERSION_H_INCLUDED namespace Catch { // Versioning information struct Version { Version( unsigned int _majorVersion, unsigned int _minorVersion, unsigned int _patchNumber, std::string const& _branchName, unsigned int _buildNumber ); unsigned int const majorVersion; unsigned int const minorVersion; unsigned int const patchNumber; // buildNumber is only used if branchName is not null std::string const branchName; unsigned int const buildNumber; friend std::ostream& operator << ( std::ostream& os, Version const& version ); private: void operator=( Version const& ); }; extern Version libraryVersion; } #include <fstream> #include <stdlib.h> #include <limits> namespace Catch { Ptr<IStreamingReporter> createReporter( std::string const& reporterName, Ptr<Config> const& config ) { Ptr<IStreamingReporter> reporter = getRegistryHub().getReporterRegistry().create( reporterName, config.get() ); if( !reporter ) { std::ostringstream oss; oss << "No reporter registered with name: '" << reporterName << "'"; throw std::domain_error( oss.str() ); } return reporter; } Ptr<IStreamingReporter> makeReporter( Ptr<Config> const& config ) { std::vector<std::string> reporters = config->getReporterNames(); if( reporters.empty() ) reporters.push_back( "console" ); Ptr<IStreamingReporter> reporter; for( std::vector<std::string>::const_iterator it = reporters.begin(), itEnd = reporters.end(); it != itEnd; ++it ) reporter = addReporter( reporter, createReporter( *it, config ) ); return reporter; } Ptr<IStreamingReporter> addListeners( Ptr<IConfig const> const& config, Ptr<IStreamingReporter> reporters ) { IReporterRegistry::Listeners listeners = getRegistryHub().getReporterRegistry().getListeners(); for( IReporterRegistry::Listeners::const_iterator it = listeners.begin(), itEnd = listeners.end(); it != itEnd; ++it ) reporters = addReporter(reporters, (*it)->create( ReporterConfig( config ) ) ); return reporters; } Totals runTests( Ptr<Config> const& config ) { Ptr<IConfig const> iconfig = config.get(); Ptr<IStreamingReporter> reporter = makeReporter( config ); reporter = addListeners( iconfig, reporter ); RunContext context( iconfig, reporter ); Totals totals; context.testGroupStarting( config->name(), 1, 1 ); TestSpec testSpec = config->testSpec(); if( !testSpec.hasFilters() ) testSpec = TestSpecParser( ITagAliasRegistry::get() ).parse( "~[.]" ).testSpec(); // All not hidden tests std::vector<TestCase> const& allTestCases = getAllTestCasesSorted( *iconfig ); for( std::vector<TestCase>::const_iterator it = allTestCases.begin(), itEnd = allTestCases.end(); it != itEnd; ++it ) { if( !context.aborting() && matchTest( *it, testSpec, *iconfig ) ) totals += context.runTest( *it ); else reporter->skipTest( *it ); } context.testGroupEnded( iconfig->name(), totals, 1, 1 ); return totals; } void applyFilenamesAsTags( IConfig const& config ) { std::vector<TestCase> const& tests = getAllTestCasesSorted( config ); for(std::size_t i = 0; i < tests.size(); ++i ) { TestCase& test = const_cast<TestCase&>( tests[i] ); std::set<std::string> tags = test.tags; std::string filename = test.lineInfo.file; std::string::size_type lastSlash = filename.find_last_of( "\\/" ); if( lastSlash != std::string::npos ) filename = filename.substr( lastSlash+1 ); std::string::size_type lastDot = filename.find_last_of( "." ); if( lastDot != std::string::npos ) filename = filename.substr( 0, lastDot ); tags.insert( "#" + filename ); setTags( test, tags ); } } class Session : NonCopyable { static bool alreadyInstantiated; public: struct OnUnusedOptions { enum DoWhat { Ignore, Fail }; }; Session() : m_cli( makeCommandLineParser() ) { if( alreadyInstantiated ) { std::string msg = "Only one instance of Catch::Session can ever be used"; Catch::cerr() << msg << std::endl; throw std::logic_error( msg ); } alreadyInstantiated = true; } ~Session() { Catch::cleanUp(); } void showHelp( std::string const& processName ) { Catch::cout() << "\nCatch v" << libraryVersion << "\n"; m_cli.usage( Catch::cout(), processName ); Catch::cout() << "For more detail usage please see the project docs\n" << std::endl; } int applyCommandLine( int argc, char const* const argv[], OnUnusedOptions::DoWhat unusedOptionBehaviour = OnUnusedOptions::Fail ) { try { m_cli.setThrowOnUnrecognisedTokens( unusedOptionBehaviour == OnUnusedOptions::Fail ); m_unusedTokens = m_cli.parseInto( argc, argv, m_configData ); if( m_configData.showHelp ) showHelp( m_configData.processName ); m_config.reset(); } catch( std::exception& ex ) { { Colour colourGuard( Colour::Red ); Catch::cerr() << "\nError(s) in input:\n" << Text( ex.what(), TextAttributes().setIndent(2) ) << "\n\n"; } m_cli.usage( Catch::cout(), m_configData.processName ); return (std::numeric_limits<int>::max)(); } return 0; } void useConfigData( ConfigData const& _configData ) { m_configData = _configData; m_config.reset(); } int run( int argc, char const* const argv[] ) { int returnCode = applyCommandLine( argc, argv ); if( returnCode == 0 ) returnCode = run(); return returnCode; } int run() { if( m_configData.showHelp ) return 0; try { config(); // Force config to be constructed seedRng( *m_config ); if( m_configData.filenamesAsTags ) applyFilenamesAsTags( *m_config ); // Handle list request if( Option<std::size_t> listed = list( config() ) ) return static_cast<int>( *listed ); return static_cast<int>( runTests( m_config ).assertions.failed ); } catch( std::exception& ex ) { Catch::cerr() << ex.what() << std::endl; return (std::numeric_limits<int>::max)(); } } Clara::CommandLine<ConfigData> const& cli() const { return m_cli; } std::vector<Clara::Parser::Token> const& unusedTokens() const { return m_unusedTokens; } ConfigData& configData() { return m_configData; } Config& config() { if( !m_config ) m_config = new Config( m_configData ); return *m_config; } private: Clara::CommandLine<ConfigData> m_cli; std::vector<Clara::Parser::Token> m_unusedTokens; ConfigData m_configData; Ptr<Config> m_config; }; bool Session::alreadyInstantiated = false; } // end namespace Catch // #included from: catch_registry_hub.hpp #define TWOBLUECUBES_CATCH_REGISTRY_HUB_HPP_INCLUDED // #included from: catch_test_case_registry_impl.hpp #define TWOBLUECUBES_CATCH_TEST_CASE_REGISTRY_IMPL_HPP_INCLUDED #include <vector> #include <set> #include <sstream> #include <iostream> #include <algorithm> namespace Catch { struct LexSort { bool operator() (TestCase i,TestCase j) const { return (i<j);} }; struct RandomNumberGenerator { int operator()( int n ) const { return std::rand() % n; } }; inline std::vector<TestCase> sortTests( IConfig const& config, std::vector<TestCase> const& unsortedTestCases ) { std::vector<TestCase> sorted = unsortedTestCases; switch( config.runOrder() ) { case RunTests::InLexicographicalOrder: std::sort( sorted.begin(), sorted.end(), LexSort() ); break; case RunTests::InRandomOrder: { seedRng( config ); RandomNumberGenerator rng; std::random_shuffle( sorted.begin(), sorted.end(), rng ); } break; case RunTests::InDeclarationOrder: // already in declaration order break; } return sorted; } bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config ) { return testSpec.matches( testCase ) && ( config.allowThrows() || !testCase.throws() ); } void enforceNoDuplicateTestCases( std::vector<TestCase> const& functions ) { std::set<TestCase> seenFunctions; for( std::vector<TestCase>::const_iterator it = functions.begin(), itEnd = functions.end(); it != itEnd; ++it ) { std::pair<std::set<TestCase>::const_iterator, bool> prev = seenFunctions.insert( *it ); if( !prev.second ){ Catch::cerr() << Colour( Colour::Red ) << "error: TEST_CASE( \"" << it->name << "\" ) already defined.\n" << "\tFirst seen at " << prev.first->getTestCaseInfo().lineInfo << "\n" << "\tRedefined at " << it->getTestCaseInfo().lineInfo << std::endl; exit(1); } } } std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config ) { std::vector<TestCase> filtered; filtered.reserve( testCases.size() ); for( std::vector<TestCase>::const_iterator it = testCases.begin(), itEnd = testCases.end(); it != itEnd; ++it ) if( matchTest( *it, testSpec, config ) ) filtered.push_back( *it ); return filtered; } std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config ) { return getRegistryHub().getTestCaseRegistry().getAllTestsSorted( config ); } class TestRegistry : public ITestCaseRegistry { public: TestRegistry() : m_currentSortOrder( RunTests::InDeclarationOrder ), m_unnamedCount( 0 ) {} virtual ~TestRegistry(); virtual void registerTest( TestCase const& testCase ) { std::string name = testCase.getTestCaseInfo().name; if( name == "" ) { std::ostringstream oss; oss << "Anonymous test case " << ++m_unnamedCount; return registerTest( testCase.withName( oss.str() ) ); } m_functions.push_back( testCase ); } virtual std::vector<TestCase> const& getAllTests() const { return m_functions; } virtual std::vector<TestCase> const& getAllTestsSorted( IConfig const& config ) const { if( m_sortedFunctions.empty() ) enforceNoDuplicateTestCases( m_functions ); if( m_currentSortOrder != config.runOrder() || m_sortedFunctions.empty() ) { m_sortedFunctions = sortTests( config, m_functions ); m_currentSortOrder = config.runOrder(); } return m_sortedFunctions; } private: std::vector<TestCase> m_functions; mutable RunTests::InWhatOrder m_currentSortOrder; mutable std::vector<TestCase> m_sortedFunctions; size_t m_unnamedCount; std::ios_base::Init m_ostreamInit; // Forces cout/ cerr to be initialised }; /////////////////////////////////////////////////////////////////////////// class FreeFunctionTestCase : public SharedImpl<ITestCase> { public: FreeFunctionTestCase( TestFunction fun ) : m_fun( fun ) {} virtual void invoke() const { m_fun(); } private: virtual ~FreeFunctionTestCase(); TestFunction m_fun; }; inline std::string extractClassName( std::string const& classOrQualifiedMethodName ) { std::string className = classOrQualifiedMethodName; if( startsWith( className, "&" ) ) { std::size_t lastColons = className.rfind( "::" ); std::size_t penultimateColons = className.rfind( "::", lastColons-1 ); if( penultimateColons == std::string::npos ) penultimateColons = 1; className = className.substr( penultimateColons, lastColons-penultimateColons ); } return className; } void registerTestCase ( ITestCase* testCase, char const* classOrQualifiedMethodName, NameAndDesc const& nameAndDesc, SourceLineInfo const& lineInfo ) { getMutableRegistryHub().registerTest ( makeTestCase ( testCase, extractClassName( classOrQualifiedMethodName ), nameAndDesc.name, nameAndDesc.description, lineInfo ) ); } void registerTestCaseFunction ( TestFunction function, SourceLineInfo const& lineInfo, NameAndDesc const& nameAndDesc ) { registerTestCase( new FreeFunctionTestCase( function ), "", nameAndDesc, lineInfo ); } /////////////////////////////////////////////////////////////////////////// AutoReg::AutoReg ( TestFunction function, SourceLineInfo const& lineInfo, NameAndDesc const& nameAndDesc ) { registerTestCaseFunction( function, lineInfo, nameAndDesc ); } AutoReg::~AutoReg() {} } // end namespace Catch // #included from: catch_reporter_registry.hpp #define TWOBLUECUBES_CATCH_REPORTER_REGISTRY_HPP_INCLUDED #include <map> namespace Catch { class ReporterRegistry : public IReporterRegistry { public: virtual ~ReporterRegistry() CATCH_OVERRIDE {} virtual IStreamingReporter* create( std::string const& name, Ptr<IConfig const> const& config ) const CATCH_OVERRIDE { FactoryMap::const_iterator it = m_factories.find( name ); if( it == m_factories.end() ) return CATCH_NULL; return it->second->create( ReporterConfig( config ) ); } void registerReporter( std::string const& name, Ptr<IReporterFactory> const& factory ) { m_factories.insert( std::make_pair( name, factory ) ); } void registerListener( Ptr<IReporterFactory> const& factory ) { m_listeners.push_back( factory ); } virtual FactoryMap const& getFactories() const CATCH_OVERRIDE { return m_factories; } virtual Listeners const& getListeners() const CATCH_OVERRIDE { return m_listeners; } private: FactoryMap m_factories; Listeners m_listeners; }; } // #included from: catch_exception_translator_registry.hpp #define TWOBLUECUBES_CATCH_EXCEPTION_TRANSLATOR_REGISTRY_HPP_INCLUDED #ifdef __OBJC__ #import "Foundation/Foundation.h" #endif namespace Catch { class ExceptionTranslatorRegistry : public IExceptionTranslatorRegistry { public: ~ExceptionTranslatorRegistry() { deleteAll( m_translators ); } virtual void registerTranslator( const IExceptionTranslator* translator ) { m_translators.push_back( translator ); } virtual std::string translateActiveException() const { try { #ifdef __OBJC__ // In Objective-C try objective-c exceptions first @try { return tryTranslators(); } @catch (NSException *exception) { return Catch::toString( [exception description] ); } #else return tryTranslators(); #endif } catch( TestFailureException& ) { throw; } catch( std::exception& ex ) { return ex.what(); } catch( std::string& msg ) { return msg; } catch( const char* msg ) { return msg; } catch(...) { return "Unknown exception"; } } std::string tryTranslators() const { if( m_translators.empty() ) throw; else return m_translators[0]->translate( m_translators.begin()+1, m_translators.end() ); } private: std::vector<const IExceptionTranslator*> m_translators; }; } namespace Catch { namespace { class RegistryHub : public IRegistryHub, public IMutableRegistryHub { RegistryHub( RegistryHub const& ); void operator=( RegistryHub const& ); public: // IRegistryHub RegistryHub() { } virtual IReporterRegistry const& getReporterRegistry() const CATCH_OVERRIDE { return m_reporterRegistry; } virtual ITestCaseRegistry const& getTestCaseRegistry() const CATCH_OVERRIDE { return m_testCaseRegistry; } virtual IExceptionTranslatorRegistry& getExceptionTranslatorRegistry() CATCH_OVERRIDE { return m_exceptionTranslatorRegistry; } public: // IMutableRegistryHub virtual void registerReporter( std::string const& name, Ptr<IReporterFactory> const& factory ) CATCH_OVERRIDE { m_reporterRegistry.registerReporter( name, factory ); } virtual void registerListener( Ptr<IReporterFactory> const& factory ) CATCH_OVERRIDE { m_reporterRegistry.registerListener( factory ); } virtual void registerTest( TestCase const& testInfo ) CATCH_OVERRIDE { m_testCaseRegistry.registerTest( testInfo ); } virtual void registerTranslator( const IExceptionTranslator* translator ) CATCH_OVERRIDE { m_exceptionTranslatorRegistry.registerTranslator( translator ); } private: TestRegistry m_testCaseRegistry; ReporterRegistry m_reporterRegistry; ExceptionTranslatorRegistry m_exceptionTranslatorRegistry; }; // Single, global, instance inline RegistryHub*& getTheRegistryHub() { static RegistryHub* theRegistryHub = CATCH_NULL; if( !theRegistryHub ) theRegistryHub = new RegistryHub(); return theRegistryHub; } } IRegistryHub& getRegistryHub() { return *getTheRegistryHub(); } IMutableRegistryHub& getMutableRegistryHub() { return *getTheRegistryHub(); } void cleanUp() { delete getTheRegistryHub(); getTheRegistryHub() = CATCH_NULL; cleanUpContext(); } std::string translateActiveException() { return getRegistryHub().getExceptionTranslatorRegistry().translateActiveException(); } } // end namespace Catch // #included from: catch_notimplemented_exception.hpp #define TWOBLUECUBES_CATCH_NOTIMPLEMENTED_EXCEPTION_HPP_INCLUDED #include <ostream> namespace Catch { NotImplementedException::NotImplementedException( SourceLineInfo const& lineInfo ) : m_lineInfo( lineInfo ) { std::ostringstream oss; oss << lineInfo << ": function "; oss << "not implemented"; m_what = oss.str(); } const char* NotImplementedException::what() const CATCH_NOEXCEPT { return m_what.c_str(); } } // end namespace Catch // #included from: catch_context_impl.hpp #define TWOBLUECUBES_CATCH_CONTEXT_IMPL_HPP_INCLUDED // #included from: catch_stream.hpp #define TWOBLUECUBES_CATCH_STREAM_HPP_INCLUDED #include <stdexcept> #include <cstdio> #include <iostream> namespace Catch { template<typename WriterF, size_t bufferSize=256> class StreamBufImpl : public StreamBufBase { char data[bufferSize]; WriterF m_writer; public: StreamBufImpl() { setp( data, data + sizeof(data) ); } ~StreamBufImpl() CATCH_NOEXCEPT { sync(); } private: int overflow( int c ) { sync(); if( c != EOF ) { if( pbase() == epptr() ) m_writer( std::string( 1, static_cast<char>( c ) ) ); else sputc( static_cast<char>( c ) ); } return 0; } int sync() { if( pbase() != pptr() ) { m_writer( std::string( pbase(), static_cast<std::string::size_type>( pptr() - pbase() ) ) ); setp( pbase(), epptr() ); } return 0; } }; /////////////////////////////////////////////////////////////////////////// FileStream::FileStream( std::string const& filename ) { m_ofs.open( filename.c_str() ); if( m_ofs.fail() ) { std::ostringstream oss; oss << "Unable to open file: '" << filename << "'"; throw std::domain_error( oss.str() ); } } std::ostream& FileStream::stream() const { return m_ofs; } struct OutputDebugWriter { void operator()( std::string const&str ) { writeToDebugConsole( str ); } }; DebugOutStream::DebugOutStream() : m_streamBuf( new StreamBufImpl<OutputDebugWriter>() ), m_os( m_streamBuf.get() ) {} std::ostream& DebugOutStream::stream() const { return m_os; } // Store the streambuf from cout up-front because // cout may get redirected when running tests CoutStream::CoutStream() : m_os( Catch::cout().rdbuf() ) {} std::ostream& CoutStream::stream() const { return m_os; } #ifndef CATCH_CONFIG_NOSTDOUT // If you #define this you must implement these functions std::ostream& cout() { return std::cout; } std::ostream& cerr() { return std::cerr; } #endif } namespace Catch { class Context : public IMutableContext { Context() : m_config( CATCH_NULL ), m_runner( CATCH_NULL ), m_resultCapture( CATCH_NULL ) {} Context( Context const& ); void operator=( Context const& ); public: // IContext virtual IResultCapture* getResultCapture() { return m_resultCapture; } virtual IRunner* getRunner() { return m_runner; } virtual size_t getGeneratorIndex( std::string const& fileInfo, size_t totalSize ) { return getGeneratorsForCurrentTest() .getGeneratorInfo( fileInfo, totalSize ) .getCurrentIndex(); } virtual bool advanceGeneratorsForCurrentTest() { IGeneratorsForTest* generators = findGeneratorsForCurrentTest(); return generators && generators->moveNext(); } virtual Ptr<IConfig const> getConfig() const { return m_config; } public: // IMutableContext virtual void setResultCapture( IResultCapture* resultCapture ) { m_resultCapture = resultCapture; } virtual void setRunner( IRunner* runner ) { m_runner = runner; } virtual void setConfig( Ptr<IConfig const> const& config ) { m_config = config; } friend IMutableContext& getCurrentMutableContext(); private: IGeneratorsForTest* findGeneratorsForCurrentTest() { std::string testName = getResultCapture()->getCurrentTestName(); std::map<std::string, IGeneratorsForTest*>::const_iterator it = m_generatorsByTestName.find( testName ); return it != m_generatorsByTestName.end() ? it->second : CATCH_NULL; } IGeneratorsForTest& getGeneratorsForCurrentTest() { IGeneratorsForTest* generators = findGeneratorsForCurrentTest(); if( !generators ) { std::string testName = getResultCapture()->getCurrentTestName(); generators = createGeneratorsForTest(); m_generatorsByTestName.insert( std::make_pair( testName, generators ) ); } return *generators; } private: Ptr<IConfig const> m_config; IRunner* m_runner; IResultCapture* m_resultCapture; std::map<std::string, IGeneratorsForTest*> m_generatorsByTestName; }; namespace { Context* currentContext = CATCH_NULL; } IMutableContext& getCurrentMutableContext() { if( !currentContext ) currentContext = new Context(); return *currentContext; } IContext& getCurrentContext() { return getCurrentMutableContext(); } void cleanUpContext() { delete currentContext; currentContext = CATCH_NULL; } } // #included from: catch_console_colour_impl.hpp #define TWOBLUECUBES_CATCH_CONSOLE_COLOUR_IMPL_HPP_INCLUDED namespace Catch { namespace { struct IColourImpl { virtual ~IColourImpl() {} virtual void use( Colour::Code _colourCode ) = 0; }; struct NoColourImpl : IColourImpl { void use( Colour::Code ) {} static IColourImpl* instance() { static NoColourImpl s_instance; return &s_instance; } }; } // anon namespace } // namespace Catch #if !defined( CATCH_CONFIG_COLOUR_NONE ) && !defined( CATCH_CONFIG_COLOUR_WINDOWS ) && !defined( CATCH_CONFIG_COLOUR_ANSI ) # ifdef CATCH_PLATFORM_WINDOWS # define CATCH_CONFIG_COLOUR_WINDOWS # else # define CATCH_CONFIG_COLOUR_ANSI # endif #endif #if defined ( CATCH_CONFIG_COLOUR_WINDOWS ) ///////////////////////////////////////// #ifndef NOMINMAX #define NOMINMAX #endif #ifdef __AFXDLL #include <AfxWin.h> #else #include <windows.h> #endif namespace Catch { namespace { class Win32ColourImpl : public IColourImpl { public: Win32ColourImpl() : stdoutHandle( GetStdHandle(STD_OUTPUT_HANDLE) ) { CONSOLE_SCREEN_BUFFER_INFO csbiInfo; GetConsoleScreenBufferInfo( stdoutHandle, &csbiInfo ); originalForegroundAttributes = csbiInfo.wAttributes & ~( BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_BLUE | BACKGROUND_INTENSITY ); originalBackgroundAttributes = csbiInfo.wAttributes & ~( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY ); } virtual void use( Colour::Code _colourCode ) { switch( _colourCode ) { case Colour::None: return setTextAttribute( originalForegroundAttributes ); case Colour::White: return setTextAttribute( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE ); case Colour::Red: return setTextAttribute( FOREGROUND_RED ); case Colour::Green: return setTextAttribute( FOREGROUND_GREEN ); case Colour::Blue: return setTextAttribute( FOREGROUND_BLUE ); case Colour::Cyan: return setTextAttribute( FOREGROUND_BLUE | FOREGROUND_GREEN ); case Colour::Yellow: return setTextAttribute( FOREGROUND_RED | FOREGROUND_GREEN ); case Colour::Grey: return setTextAttribute( 0 ); case Colour::LightGrey: return setTextAttribute( FOREGROUND_INTENSITY ); case Colour::BrightRed: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED ); case Colour::BrightGreen: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN ); case Colour::BrightWhite: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE ); case Colour::Bright: throw std::logic_error( "not a colour" ); } } private: void setTextAttribute( WORD _textAttribute ) { SetConsoleTextAttribute( stdoutHandle, _textAttribute | originalBackgroundAttributes ); } HANDLE stdoutHandle; WORD originalForegroundAttributes; WORD originalBackgroundAttributes; }; IColourImpl* platformColourInstance() { static Win32ColourImpl s_instance; return &s_instance; } } // end anon namespace } // end namespace Catch #elif defined( CATCH_CONFIG_COLOUR_ANSI ) ////////////////////////////////////// #include <unistd.h> namespace Catch { namespace { // use POSIX/ ANSI console terminal codes // Thanks to Adam Strzelecki for original contribution // (http://github.com/nanoant) // https://github.com/philsquared/Catch/pull/131 class PosixColourImpl : public IColourImpl { public: virtual void use( Colour::Code _colourCode ) { switch( _colourCode ) { case Colour::None: case Colour::White: return setColour( "[0m" ); case Colour::Red: return setColour( "[0;31m" ); case Colour::Green: return setColour( "[0;32m" ); case Colour::Blue: return setColour( "[0:34m" ); case Colour::Cyan: return setColour( "[0;36m" ); case Colour::Yellow: return setColour( "[0;33m" ); case Colour::Grey: return setColour( "[1;30m" ); case Colour::LightGrey: return setColour( "[0;37m" ); case Colour::BrightRed: return setColour( "[1;31m" ); case Colour::BrightGreen: return setColour( "[1;32m" ); case Colour::BrightWhite: return setColour( "[1;37m" ); case Colour::Bright: throw std::logic_error( "not a colour" ); } } static IColourImpl* instance() { static PosixColourImpl s_instance; return &s_instance; } private: void setColour( const char* _escapeCode ) { Catch::cout() << '\033' << _escapeCode; } }; IColourImpl* platformColourInstance() { Ptr<IConfig const> config = getCurrentContext().getConfig(); return (config && config->forceColour()) || isatty(STDOUT_FILENO) ? PosixColourImpl::instance() : NoColourImpl::instance(); } } // end anon namespace } // end namespace Catch #else // not Windows or ANSI /////////////////////////////////////////////// namespace Catch { static IColourImpl* platformColourInstance() { return NoColourImpl::instance(); } } // end namespace Catch #endif // Windows/ ANSI/ None namespace Catch { Colour::Colour( Code _colourCode ) : m_moved( false ) { use( _colourCode ); } Colour::Colour( Colour const& _other ) : m_moved( false ) { const_cast<Colour&>( _other ).m_moved = true; } Colour::~Colour(){ if( !m_moved ) use( None ); } void Colour::use( Code _colourCode ) { static IColourImpl* impl = isDebuggerActive() ? NoColourImpl::instance() : platformColourInstance(); impl->use( _colourCode ); } } // end namespace Catch // #included from: catch_generators_impl.hpp #define TWOBLUECUBES_CATCH_GENERATORS_IMPL_HPP_INCLUDED #include <vector> #include <string> #include <map> namespace Catch { struct GeneratorInfo : IGeneratorInfo { GeneratorInfo( std::size_t size ) : m_size( size ), m_currentIndex( 0 ) {} bool moveNext() { if( ++m_currentIndex == m_size ) { m_currentIndex = 0; return false; } return true; } std::size_t getCurrentIndex() const { return m_currentIndex; } std::size_t m_size; std::size_t m_currentIndex; }; /////////////////////////////////////////////////////////////////////////// class GeneratorsForTest : public IGeneratorsForTest { public: ~GeneratorsForTest() { deleteAll( m_generatorsInOrder ); } IGeneratorInfo& getGeneratorInfo( std::string const& fileInfo, std::size_t size ) { std::map<std::string, IGeneratorInfo*>::const_iterator it = m_generatorsByName.find( fileInfo ); if( it == m_generatorsByName.end() ) { IGeneratorInfo* info = new GeneratorInfo( size ); m_generatorsByName.insert( std::make_pair( fileInfo, info ) ); m_generatorsInOrder.push_back( info ); return *info; } return *it->second; } bool moveNext() { std::vector<IGeneratorInfo*>::const_iterator it = m_generatorsInOrder.begin(); std::vector<IGeneratorInfo*>::const_iterator itEnd = m_generatorsInOrder.end(); for(; it != itEnd; ++it ) { if( (*it)->moveNext() ) return true; } return false; } private: std::map<std::string, IGeneratorInfo*> m_generatorsByName; std::vector<IGeneratorInfo*> m_generatorsInOrder; }; IGeneratorsForTest* createGeneratorsForTest() { return new GeneratorsForTest(); } } // end namespace Catch // #included from: catch_assertionresult.hpp #define TWOBLUECUBES_CATCH_ASSERTIONRESULT_HPP_INCLUDED namespace Catch { AssertionInfo::AssertionInfo( std::string const& _macroName, SourceLineInfo const& _lineInfo, std::string const& _capturedExpression, ResultDisposition::Flags _resultDisposition ) : macroName( _macroName ), lineInfo( _lineInfo ), capturedExpression( _capturedExpression ), resultDisposition( _resultDisposition ) {} AssertionResult::AssertionResult() {} AssertionResult::AssertionResult( AssertionInfo const& info, AssertionResultData const& data ) : m_info( info ), m_resultData( data ) {} AssertionResult::~AssertionResult() {} // Result was a success bool AssertionResult::succeeded() const { return Catch::isOk( m_resultData.resultType ); } // Result was a success, or failure is suppressed bool AssertionResult::isOk() const { return Catch::isOk( m_resultData.resultType ) || shouldSuppressFailure( m_info.resultDisposition ); } ResultWas::OfType AssertionResult::getResultType() const { return m_resultData.resultType; } bool AssertionResult::hasExpression() const { return !m_info.capturedExpression.empty(); } bool AssertionResult::hasMessage() const { return !m_resultData.message.empty(); } std::string AssertionResult::getExpression() const { if( isFalseTest( m_info.resultDisposition ) ) return "!" + m_info.capturedExpression; else return m_info.capturedExpression; } std::string AssertionResult::getExpressionInMacro() const { if( m_info.macroName.empty() ) return m_info.capturedExpression; else return m_info.macroName + "( " + m_info.capturedExpression + " )"; } bool AssertionResult::hasExpandedExpression() const { return hasExpression() && getExpandedExpression() != getExpression(); } std::string AssertionResult::getExpandedExpression() const { return m_resultData.reconstructedExpression; } std::string AssertionResult::getMessage() const { return m_resultData.message; } SourceLineInfo AssertionResult::getSourceInfo() const { return m_info.lineInfo; } std::string AssertionResult::getTestMacroName() const { return m_info.macroName; } } // end namespace Catch // #included from: catch_test_case_info.hpp #define TWOBLUECUBES_CATCH_TEST_CASE_INFO_HPP_INCLUDED namespace Catch { inline TestCaseInfo::SpecialProperties parseSpecialTag( std::string const& tag ) { if( startsWith( tag, "." ) || tag == "hide" || tag == "!hide" ) return TestCaseInfo::IsHidden; else if( tag == "!throws" ) return TestCaseInfo::Throws; else if( tag == "!shouldfail" ) return TestCaseInfo::ShouldFail; else if( tag == "!mayfail" ) return TestCaseInfo::MayFail; else return TestCaseInfo::None; } inline bool isReservedTag( std::string const& tag ) { return parseSpecialTag( tag ) == TestCaseInfo::None && tag.size() > 0 && !isalnum( tag[0] ); } inline void enforceNotReservedTag( std::string const& tag, SourceLineInfo const& _lineInfo ) { if( isReservedTag( tag ) ) { { Colour colourGuard( Colour::Red ); Catch::cerr() << "Tag name [" << tag << "] not allowed.\n" << "Tag names starting with non alpha-numeric characters are reserved\n"; } { Colour colourGuard( Colour::FileName ); Catch::cerr() << _lineInfo << std::endl; } exit(1); } } TestCase makeTestCase( ITestCase* _testCase, std::string const& _className, std::string const& _name, std::string const& _descOrTags, SourceLineInfo const& _lineInfo ) { bool isHidden( startsWith( _name, "./" ) ); // Legacy support // Parse out tags std::set<std::string> tags; std::string desc, tag; bool inTag = false; for( std::size_t i = 0; i < _descOrTags.size(); ++i ) { char c = _descOrTags[i]; if( !inTag ) { if( c == '[' ) inTag = true; else desc += c; } else { if( c == ']' ) { TestCaseInfo::SpecialProperties prop = parseSpecialTag( tag ); if( prop == TestCaseInfo::IsHidden ) isHidden = true; else if( prop == TestCaseInfo::None ) enforceNotReservedTag( tag, _lineInfo ); tags.insert( tag ); tag.clear(); inTag = false; } else tag += c; } } if( isHidden ) { tags.insert( "hide" ); tags.insert( "." ); } TestCaseInfo info( _name, _className, desc, tags, _lineInfo ); return TestCase( _testCase, info ); } void setTags( TestCaseInfo& testCaseInfo, std::set<std::string> const& tags ) { testCaseInfo.tags = tags; testCaseInfo.lcaseTags.clear(); std::ostringstream oss; for( std::set<std::string>::const_iterator it = tags.begin(), itEnd = tags.end(); it != itEnd; ++it ) { oss << "[" << *it << "]"; std::string lcaseTag = toLower( *it ); testCaseInfo.properties = static_cast<TestCaseInfo::SpecialProperties>( testCaseInfo.properties | parseSpecialTag( lcaseTag ) ); testCaseInfo.lcaseTags.insert( lcaseTag ); } testCaseInfo.tagsAsString = oss.str(); } TestCaseInfo::TestCaseInfo( std::string const& _name, std::string const& _className, std::string const& _description, std::set<std::string> const& _tags, SourceLineInfo const& _lineInfo ) : name( _name ), className( _className ), description( _description ), lineInfo( _lineInfo ), properties( None ) { setTags( *this, _tags ); } TestCaseInfo::TestCaseInfo( TestCaseInfo const& other ) : name( other.name ), className( other.className ), description( other.description ), tags( other.tags ), lcaseTags( other.lcaseTags ), tagsAsString( other.tagsAsString ), lineInfo( other.lineInfo ), properties( other.properties ) {} bool TestCaseInfo::isHidden() const { return ( properties & IsHidden ) != 0; } bool TestCaseInfo::throws() const { return ( properties & Throws ) != 0; } bool TestCaseInfo::okToFail() const { return ( properties & (ShouldFail | MayFail ) ) != 0; } bool TestCaseInfo::expectedToFail() const { return ( properties & (ShouldFail ) ) != 0; } TestCase::TestCase( ITestCase* testCase, TestCaseInfo const& info ) : TestCaseInfo( info ), test( testCase ) {} TestCase::TestCase( TestCase const& other ) : TestCaseInfo( other ), test( other.test ) {} TestCase TestCase::withName( std::string const& _newName ) const { TestCase other( *this ); other.name = _newName; return other; } void TestCase::swap( TestCase& other ) { test.swap( other.test ); name.swap( other.name ); className.swap( other.className ); description.swap( other.description ); tags.swap( other.tags ); lcaseTags.swap( other.lcaseTags ); tagsAsString.swap( other.tagsAsString ); std::swap( TestCaseInfo::properties, static_cast<TestCaseInfo&>( other ).properties ); std::swap( lineInfo, other.lineInfo ); } void TestCase::invoke() const { test->invoke(); } bool TestCase::operator == ( TestCase const& other ) const { return test.get() == other.test.get() && name == other.name && className == other.className; } bool TestCase::operator < ( TestCase const& other ) const { return name < other.name; } TestCase& TestCase::operator = ( TestCase const& other ) { TestCase temp( other ); swap( temp ); return *this; } TestCaseInfo const& TestCase::getTestCaseInfo() const { return *this; } } // end namespace Catch // #included from: catch_version.hpp #define TWOBLUECUBES_CATCH_VERSION_HPP_INCLUDED namespace Catch { Version::Version ( unsigned int _majorVersion, unsigned int _minorVersion, unsigned int _patchNumber, std::string const& _branchName, unsigned int _buildNumber ) : majorVersion( _majorVersion ), minorVersion( _minorVersion ), patchNumber( _patchNumber ), branchName( _branchName ), buildNumber( _buildNumber ) {} std::ostream& operator << ( std::ostream& os, Version const& version ) { os << version.majorVersion << "." << version.minorVersion << "." << version.patchNumber; if( !version.branchName.empty() ) { os << "-" << version.branchName << "." << version.buildNumber; } return os; } Version libraryVersion( 1, 3, 2, "", 0 ); } // #included from: catch_message.hpp #define TWOBLUECUBES_CATCH_MESSAGE_HPP_INCLUDED namespace Catch { MessageInfo::MessageInfo( std::string const& _macroName, SourceLineInfo const& _lineInfo, ResultWas::OfType _type ) : macroName( _macroName ), lineInfo( _lineInfo ), type( _type ), sequence( ++globalCount ) {} // This may need protecting if threading support is added unsigned int MessageInfo::globalCount = 0; //////////////////////////////////////////////////////////////////////////// ScopedMessage::ScopedMessage( MessageBuilder const& builder ) : m_info( builder.m_info ) { m_info.message = builder.m_stream.str(); getResultCapture().pushScopedMessage( m_info ); } ScopedMessage::ScopedMessage( ScopedMessage const& other ) : m_info( other.m_info ) {} ScopedMessage::~ScopedMessage() { getResultCapture().popScopedMessage( m_info ); } } // end namespace Catch // #included from: catch_legacy_reporter_adapter.hpp #define TWOBLUECUBES_CATCH_LEGACY_REPORTER_ADAPTER_HPP_INCLUDED // #included from: catch_legacy_reporter_adapter.h #define TWOBLUECUBES_CATCH_LEGACY_REPORTER_ADAPTER_H_INCLUDED namespace Catch { // Deprecated struct IReporter : IShared { virtual ~IReporter(); virtual bool shouldRedirectStdout() const = 0; virtual void StartTesting() = 0; virtual void EndTesting( Totals const& totals ) = 0; virtual void StartGroup( std::string const& groupName ) = 0; virtual void EndGroup( std::string const& groupName, Totals const& totals ) = 0; virtual void StartTestCase( TestCaseInfo const& testInfo ) = 0; virtual void EndTestCase( TestCaseInfo const& testInfo, Totals const& totals, std::string const& stdOut, std::string const& stdErr ) = 0; virtual void StartSection( std::string const& sectionName, std::string const& description ) = 0; virtual void EndSection( std::string const& sectionName, Counts const& assertions ) = 0; virtual void NoAssertionsInSection( std::string const& sectionName ) = 0; virtual void NoAssertionsInTestCase( std::string const& testName ) = 0; virtual void Aborted() = 0; virtual void Result( AssertionResult const& result ) = 0; }; class LegacyReporterAdapter : public SharedImpl<IStreamingReporter> { public: LegacyReporterAdapter( Ptr<IReporter> const& legacyReporter ); virtual ~LegacyReporterAdapter(); virtual ReporterPreferences getPreferences() const; virtual void noMatchingTestCases( std::string const& ); virtual void testRunStarting( TestRunInfo const& ); virtual void testGroupStarting( GroupInfo const& groupInfo ); virtual void testCaseStarting( TestCaseInfo const& testInfo ); virtual void sectionStarting( SectionInfo const& sectionInfo ); virtual void assertionStarting( AssertionInfo const& ); virtual bool assertionEnded( AssertionStats const& assertionStats ); virtual void sectionEnded( SectionStats const& sectionStats ); virtual void testCaseEnded( TestCaseStats const& testCaseStats ); virtual void testGroupEnded( TestGroupStats const& testGroupStats ); virtual void testRunEnded( TestRunStats const& testRunStats ); virtual void skipTest( TestCaseInfo const& ); private: Ptr<IReporter> m_legacyReporter; }; } namespace Catch { LegacyReporterAdapter::LegacyReporterAdapter( Ptr<IReporter> const& legacyReporter ) : m_legacyReporter( legacyReporter ) {} LegacyReporterAdapter::~LegacyReporterAdapter() {} ReporterPreferences LegacyReporterAdapter::getPreferences() const { ReporterPreferences prefs; prefs.shouldRedirectStdOut = m_legacyReporter->shouldRedirectStdout(); return prefs; } void LegacyReporterAdapter::noMatchingTestCases( std::string const& ) {} void LegacyReporterAdapter::testRunStarting( TestRunInfo const& ) { m_legacyReporter->StartTesting(); } void LegacyReporterAdapter::testGroupStarting( GroupInfo const& groupInfo ) { m_legacyReporter->StartGroup( groupInfo.name ); } void LegacyReporterAdapter::testCaseStarting( TestCaseInfo const& testInfo ) { m_legacyReporter->StartTestCase( testInfo ); } void LegacyReporterAdapter::sectionStarting( SectionInfo const& sectionInfo ) { m_legacyReporter->StartSection( sectionInfo.name, sectionInfo.description ); } void LegacyReporterAdapter::assertionStarting( AssertionInfo const& ) { // Not on legacy interface } bool LegacyReporterAdapter::assertionEnded( AssertionStats const& assertionStats ) { if( assertionStats.assertionResult.getResultType() != ResultWas::Ok ) { for( std::vector<MessageInfo>::const_iterator it = assertionStats.infoMessages.begin(), itEnd = assertionStats.infoMessages.end(); it != itEnd; ++it ) { if( it->type == ResultWas::Info ) { ResultBuilder rb( it->macroName.c_str(), it->lineInfo, "", ResultDisposition::Normal ); rb << it->message; rb.setResultType( ResultWas::Info ); AssertionResult result = rb.build(); m_legacyReporter->Result( result ); } } } m_legacyReporter->Result( assertionStats.assertionResult ); return true; } void LegacyReporterAdapter::sectionEnded( SectionStats const& sectionStats ) { if( sectionStats.missingAssertions ) m_legacyReporter->NoAssertionsInSection( sectionStats.sectionInfo.name ); m_legacyReporter->EndSection( sectionStats.sectionInfo.name, sectionStats.assertions ); } void LegacyReporterAdapter::testCaseEnded( TestCaseStats const& testCaseStats ) { m_legacyReporter->EndTestCase ( testCaseStats.testInfo, testCaseStats.totals, testCaseStats.stdOut, testCaseStats.stdErr ); } void LegacyReporterAdapter::testGroupEnded( TestGroupStats const& testGroupStats ) { if( testGroupStats.aborting ) m_legacyReporter->Aborted(); m_legacyReporter->EndGroup( testGroupStats.groupInfo.name, testGroupStats.totals ); } void LegacyReporterAdapter::testRunEnded( TestRunStats const& testRunStats ) { m_legacyReporter->EndTesting( testRunStats.totals ); } void LegacyReporterAdapter::skipTest( TestCaseInfo const& ) { } } // #included from: catch_timer.hpp #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wc++11-long-long" #endif #ifdef CATCH_PLATFORM_WINDOWS #include <windows.h> #else #include <sys/time.h> #endif namespace Catch { namespace { #ifdef CATCH_PLATFORM_WINDOWS uint64_t getCurrentTicks() { static uint64_t hz=0, hzo=0; if (!hz) { QueryPerformanceFrequency( reinterpret_cast<LARGE_INTEGER*>( &hz ) ); QueryPerformanceCounter( reinterpret_cast<LARGE_INTEGER*>( &hzo ) ); } uint64_t t; QueryPerformanceCounter( reinterpret_cast<LARGE_INTEGER*>( &t ) ); return ((t-hzo)*1000000)/hz; } #else uint64_t getCurrentTicks() { timeval t; gettimeofday(&t,CATCH_NULL); return static_cast<uint64_t>( t.tv_sec ) * 1000000ull + static_cast<uint64_t>( t.tv_usec ); } #endif } void Timer::start() { m_ticks = getCurrentTicks(); } unsigned int Timer::getElapsedMicroseconds() const { return static_cast<unsigned int>(getCurrentTicks() - m_ticks); } unsigned int Timer::getElapsedMilliseconds() const { return static_cast<unsigned int>(getElapsedMicroseconds()/1000); } double Timer::getElapsedSeconds() const { return getElapsedMicroseconds()/1000000.0; } } // namespace Catch #ifdef __clang__ #pragma clang diagnostic pop #endif // #included from: catch_common.hpp #define TWOBLUECUBES_CATCH_COMMON_HPP_INCLUDED namespace Catch { bool startsWith( std::string const& s, std::string const& prefix ) { return s.size() >= prefix.size() && s.substr( 0, prefix.size() ) == prefix; } bool endsWith( std::string const& s, std::string const& suffix ) { return s.size() >= suffix.size() && s.substr( s.size()-suffix.size(), suffix.size() ) == suffix; } bool contains( std::string const& s, std::string const& infix ) { return s.find( infix ) != std::string::npos; } void toLowerInPlace( std::string& s ) { std::transform( s.begin(), s.end(), s.begin(), ::tolower ); } std::string toLower( std::string const& s ) { std::string lc = s; toLowerInPlace( lc ); return lc; } std::string trim( std::string const& str ) { static char const* whitespaceChars = "\n\r\t "; std::string::size_type start = str.find_first_not_of( whitespaceChars ); std::string::size_type end = str.find_last_not_of( whitespaceChars ); return start != std::string::npos ? str.substr( start, 1+end-start ) : ""; } bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis ) { bool replaced = false; std::size_t i = str.find( replaceThis ); while( i != std::string::npos ) { replaced = true; str = str.substr( 0, i ) + withThis + str.substr( i+replaceThis.size() ); if( i < str.size()-withThis.size() ) i = str.find( replaceThis, i+withThis.size() ); else i = std::string::npos; } return replaced; } pluralise::pluralise( std::size_t count, std::string const& label ) : m_count( count ), m_label( label ) {} std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser ) { os << pluraliser.m_count << " " << pluraliser.m_label; if( pluraliser.m_count != 1 ) os << "s"; return os; } SourceLineInfo::SourceLineInfo() : line( 0 ){} SourceLineInfo::SourceLineInfo( char const* _file, std::size_t _line ) : file( _file ), line( _line ) {} SourceLineInfo::SourceLineInfo( SourceLineInfo const& other ) : file( other.file ), line( other.line ) {} bool SourceLineInfo::empty() const { return file.empty(); } bool SourceLineInfo::operator == ( SourceLineInfo const& other ) const { return line == other.line && file == other.file; } bool SourceLineInfo::operator < ( SourceLineInfo const& other ) const { return line < other.line || ( line == other.line && file < other.file ); } void seedRng( IConfig const& config ) { if( config.rngSeed() != 0 ) std::srand( config.rngSeed() ); } unsigned int rngSeed() { return getCurrentContext().getConfig()->rngSeed(); } std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info ) { #ifndef __GNUG__ os << info.file << "(" << info.line << ")"; #else os << info.file << ":" << info.line; #endif return os; } void throwLogicError( std::string const& message, SourceLineInfo const& locationInfo ) { std::ostringstream oss; oss << locationInfo << ": Internal Catch error: '" << message << "'"; if( alwaysTrue() ) throw std::logic_error( oss.str() ); } } // #included from: catch_section.hpp #define TWOBLUECUBES_CATCH_SECTION_HPP_INCLUDED namespace Catch { SectionInfo::SectionInfo ( SourceLineInfo const& _lineInfo, std::string const& _name, std::string const& _description ) : name( _name ), description( _description ), lineInfo( _lineInfo ) {} Section::Section( SectionInfo const& info ) : m_info( info ), m_sectionIncluded( getResultCapture().sectionStarted( m_info, m_assertions ) ) { m_timer.start(); } Section::~Section() { if( m_sectionIncluded ) { SectionEndInfo endInfo( m_info, m_assertions, m_timer.getElapsedSeconds() ); if( std::uncaught_exception() ) getResultCapture().sectionEndedEarly( endInfo ); else getResultCapture().sectionEnded( endInfo ); } } // This indicates whether the section should be executed or not Section::operator bool() const { return m_sectionIncluded; } } // end namespace Catch // #included from: catch_debugger.hpp #define TWOBLUECUBES_CATCH_DEBUGGER_HPP_INCLUDED #include <iostream> #ifdef CATCH_PLATFORM_MAC #include <assert.h> #include <stdbool.h> #include <sys/types.h> #include <unistd.h> #include <sys/sysctl.h> namespace Catch{ // The following function is taken directly from the following technical note: // http://developer.apple.com/library/mac/#qa/qa2004/qa1361.html // Returns true if the current process is being debugged (either // running under the debugger or has a debugger attached post facto). bool isDebuggerActive(){ int mib[4]; struct kinfo_proc info; size_t size; // Initialize the flags so that, if sysctl fails for some bizarre // reason, we get a predictable result. info.kp_proc.p_flag = 0; // Initialize mib, which tells sysctl the info we want, in this case // we're looking for information about a specific process ID. mib[0] = CTL_KERN; mib[1] = KERN_PROC; mib[2] = KERN_PROC_PID; mib[3] = getpid(); // Call sysctl. size = sizeof(info); if( sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, CATCH_NULL, 0) != 0 ) { Catch::cerr() << "\n** Call to sysctl failed - unable to determine if debugger is active **\n" << std::endl; return false; } // We're being debugged if the P_TRACED flag is set. return ( (info.kp_proc.p_flag & P_TRACED) != 0 ); } } // namespace Catch #elif defined(_MSC_VER) extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent(); namespace Catch { bool isDebuggerActive() { return IsDebuggerPresent() != 0; } } #elif defined(__MINGW32__) extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent(); namespace Catch { bool isDebuggerActive() { return IsDebuggerPresent() != 0; } } #else namespace Catch { inline bool isDebuggerActive() { return false; } } #endif // Platform #ifdef CATCH_PLATFORM_WINDOWS extern "C" __declspec(dllimport) void __stdcall OutputDebugStringA( const char* ); namespace Catch { void writeToDebugConsole( std::string const& text ) { ::OutputDebugStringA( text.c_str() ); } } #else namespace Catch { void writeToDebugConsole( std::string const& text ) { // !TBD: Need a version for Mac/ XCode and other IDEs Catch::cout() << text; } } #endif // Platform // #included from: catch_tostring.hpp #define TWOBLUECUBES_CATCH_TOSTRING_HPP_INCLUDED namespace Catch { namespace Detail { const std::string unprintableString = "{?}"; namespace { const int hexThreshold = 255; struct Endianness { enum Arch { Big, Little }; static Arch which() { union _{ int asInt; char asChar[sizeof (int)]; } u; u.asInt = 1; return ( u.asChar[sizeof(int)-1] == 1 ) ? Big : Little; } }; } std::string rawMemoryToString( const void *object, std::size_t size ) { // Reverse order for little endian architectures int i = 0, end = static_cast<int>( size ), inc = 1; if( Endianness::which() == Endianness::Little ) { i = end-1; end = inc = -1; } unsigned char const *bytes = static_cast<unsigned char const *>(object); std::ostringstream os; os << "0x" << std::setfill('0') << std::hex; for( ; i != end; i += inc ) os << std::setw(2) << static_cast<unsigned>(bytes[i]); return os.str(); } } std::string toString( std::string const& value ) { std::string s = value; if( getCurrentContext().getConfig()->showInvisibles() ) { for(size_t i = 0; i < s.size(); ++i ) { std::string subs; switch( s[i] ) { case '\n': subs = "\\n"; break; case '\t': subs = "\\t"; break; default: break; } if( !subs.empty() ) { s = s.substr( 0, i ) + subs + s.substr( i+1 ); ++i; } } } return "\"" + s + "\""; } std::string toString( std::wstring const& value ) { std::string s; s.reserve( value.size() ); for(size_t i = 0; i < value.size(); ++i ) s += value[i] <= 0xff ? static_cast<char>( value[i] ) : '?'; return Catch::toString( s ); } std::string toString( const char* const value ) { return value ? Catch::toString( std::string( value ) ) : std::string( "{null string}" ); } std::string toString( char* const value ) { return Catch::toString( static_cast<const char*>( value ) ); } std::string toString( const wchar_t* const value ) { return value ? Catch::toString( std::wstring(value) ) : std::string( "{null string}" ); } std::string toString( wchar_t* const value ) { return Catch::toString( static_cast<const wchar_t*>( value ) ); } std::string toString( int value ) { std::ostringstream oss; oss << value; if( value > Detail::hexThreshold ) oss << " (0x" << std::hex << value << ")"; return oss.str(); } std::string toString( unsigned long value ) { std::ostringstream oss; oss << value; if( value > Detail::hexThreshold ) oss << " (0x" << std::hex << value << ")"; return oss.str(); } std::string toString( unsigned int value ) { return Catch::toString( static_cast<unsigned long>( value ) ); } template<typename T> std::string fpToString( T value, int precision ) { std::ostringstream oss; oss << std::setprecision( precision ) << std::fixed << value; std::string d = oss.str(); std::size_t i = d.find_last_not_of( '0' ); if( i != std::string::npos && i != d.size()-1 ) { if( d[i] == '.' ) i++; d = d.substr( 0, i+1 ); } return d; } std::string toString( const double value ) { return fpToString( value, 10 ); } std::string toString( const float value ) { return fpToString( value, 5 ) + "f"; } std::string toString( bool value ) { return value ? "true" : "false"; } std::string toString( char value ) { return value < ' ' ? toString( static_cast<unsigned int>( value ) ) : Detail::makeString( value ); } std::string toString( signed char value ) { return toString( static_cast<char>( value ) ); } std::string toString( unsigned char value ) { return toString( static_cast<char>( value ) ); } #ifdef CATCH_CONFIG_CPP11_LONG_LONG std::string toString( long long value ) { std::ostringstream oss; oss << value; if( value > Detail::hexThreshold ) oss << " (0x" << std::hex << value << ")"; return oss.str(); } std::string toString( unsigned long long value ) { std::ostringstream oss; oss << value; if( value > Detail::hexThreshold ) oss << " (0x" << std::hex << value << ")"; return oss.str(); } #endif #ifdef CATCH_CONFIG_CPP11_NULLPTR std::string toString( std::nullptr_t ) { return "nullptr"; } #endif #ifdef __OBJC__ std::string toString( NSString const * const& nsstring ) { if( !nsstring ) return "nil"; return "@" + toString([nsstring UTF8String]); } std::string toString( NSString * CATCH_ARC_STRONG const& nsstring ) { if( !nsstring ) return "nil"; return "@" + toString([nsstring UTF8String]); } std::string toString( NSObject* const& nsObject ) { return toString( [nsObject description] ); } #endif } // end namespace Catch // #included from: catch_result_builder.hpp #define TWOBLUECUBES_CATCH_RESULT_BUILDER_HPP_INCLUDED namespace Catch { std::string capturedExpressionWithSecondArgument( std::string const& capturedExpression, std::string const& secondArg ) { return secondArg.empty() || secondArg == "\"\"" ? capturedExpression : capturedExpression + ", " + secondArg; } ResultBuilder::ResultBuilder( char const* macroName, SourceLineInfo const& lineInfo, char const* capturedExpression, ResultDisposition::Flags resultDisposition, char const* secondArg ) : m_assertionInfo( macroName, lineInfo, capturedExpressionWithSecondArgument( capturedExpression, secondArg ), resultDisposition ), m_shouldDebugBreak( false ), m_shouldThrow( false ) {} ResultBuilder& ResultBuilder::setResultType( ResultWas::OfType result ) { m_data.resultType = result; return *this; } ResultBuilder& ResultBuilder::setResultType( bool result ) { m_data.resultType = result ? ResultWas::Ok : ResultWas::ExpressionFailed; return *this; } ResultBuilder& ResultBuilder::setLhs( std::string const& lhs ) { m_exprComponents.lhs = lhs; return *this; } ResultBuilder& ResultBuilder::setRhs( std::string const& rhs ) { m_exprComponents.rhs = rhs; return *this; } ResultBuilder& ResultBuilder::setOp( std::string const& op ) { m_exprComponents.op = op; return *this; } void ResultBuilder::endExpression() { m_exprComponents.testFalse = isFalseTest( m_assertionInfo.resultDisposition ); captureExpression(); } void ResultBuilder::useActiveException( ResultDisposition::Flags resultDisposition ) { m_assertionInfo.resultDisposition = resultDisposition; m_stream.oss << Catch::translateActiveException(); captureResult( ResultWas::ThrewException ); } void ResultBuilder::captureResult( ResultWas::OfType resultType ) { setResultType( resultType ); captureExpression(); } void ResultBuilder::captureExpectedException( std::string const& expectedMessage ) { if( expectedMessage.empty() ) captureExpectedException( Matchers::Impl::Generic::AllOf<std::string>() ); else captureExpectedException( Matchers::Equals( expectedMessage ) ); } void ResultBuilder::captureExpectedException( Matchers::Impl::Matcher<std::string> const& matcher ) { assert( m_exprComponents.testFalse == false ); AssertionResultData data = m_data; data.resultType = ResultWas::Ok; data.reconstructedExpression = m_assertionInfo.capturedExpression; std::string actualMessage = Catch::translateActiveException(); if( !matcher.match( actualMessage ) ) { data.resultType = ResultWas::ExpressionFailed; data.reconstructedExpression = actualMessage; } AssertionResult result( m_assertionInfo, data ); handleResult( result ); } void ResultBuilder::captureExpression() { AssertionResult result = build(); handleResult( result ); } void ResultBuilder::handleResult( AssertionResult const& result ) { getResultCapture().assertionEnded( result ); if( !result.isOk() ) { if( getCurrentContext().getConfig()->shouldDebugBreak() ) m_shouldDebugBreak = true; if( getCurrentContext().getRunner()->aborting() || (m_assertionInfo.resultDisposition & ResultDisposition::Normal) ) m_shouldThrow = true; } } void ResultBuilder::react() { if( m_shouldThrow ) throw Catch::TestFailureException(); } bool ResultBuilder::shouldDebugBreak() const { return m_shouldDebugBreak; } bool ResultBuilder::allowThrows() const { return getCurrentContext().getConfig()->allowThrows(); } AssertionResult ResultBuilder::build() const { assert( m_data.resultType != ResultWas::Unknown ); AssertionResultData data = m_data; // Flip bool results if testFalse is set if( m_exprComponents.testFalse ) { if( data.resultType == ResultWas::Ok ) data.resultType = ResultWas::ExpressionFailed; else if( data.resultType == ResultWas::ExpressionFailed ) data.resultType = ResultWas::Ok; } data.message = m_stream.oss.str(); data.reconstructedExpression = reconstructExpression(); if( m_exprComponents.testFalse ) { if( m_exprComponents.op == "" ) data.reconstructedExpression = "!" + data.reconstructedExpression; else data.reconstructedExpression = "!(" + data.reconstructedExpression + ")"; } return AssertionResult( m_assertionInfo, data ); } std::string ResultBuilder::reconstructExpression() const { if( m_exprComponents.op == "" ) return m_exprComponents.lhs.empty() ? m_assertionInfo.capturedExpression : m_exprComponents.op + m_exprComponents.lhs; else if( m_exprComponents.op == "matches" ) return m_exprComponents.lhs + " " + m_exprComponents.rhs; else if( m_exprComponents.op != "!" ) { if( m_exprComponents.lhs.size() + m_exprComponents.rhs.size() < 40 && m_exprComponents.lhs.find("\n") == std::string::npos && m_exprComponents.rhs.find("\n") == std::string::npos ) return m_exprComponents.lhs + " " + m_exprComponents.op + " " + m_exprComponents.rhs; else return m_exprComponents.lhs + "\n" + m_exprComponents.op + "\n" + m_exprComponents.rhs; } else return "{can't expand - use " + m_assertionInfo.macroName + "_FALSE( " + m_assertionInfo.capturedExpression.substr(1) + " ) instead of " + m_assertionInfo.macroName + "( " + m_assertionInfo.capturedExpression + " ) for better diagnostics}"; } } // end namespace Catch // #included from: catch_tag_alias_registry.hpp #define TWOBLUECUBES_CATCH_TAG_ALIAS_REGISTRY_HPP_INCLUDED // #included from: catch_tag_alias_registry.h #define TWOBLUECUBES_CATCH_TAG_ALIAS_REGISTRY_H_INCLUDED #include <map> namespace Catch { class TagAliasRegistry : public ITagAliasRegistry { public: virtual ~TagAliasRegistry(); virtual Option<TagAlias> find( std::string const& alias ) const; virtual std::string expandAliases( std::string const& unexpandedTestSpec ) const; void add( char const* alias, char const* tag, SourceLineInfo const& lineInfo ); static TagAliasRegistry& get(); private: std::map<std::string, TagAlias> m_registry; }; } // end namespace Catch #include <map> #include <iostream> namespace Catch { TagAliasRegistry::~TagAliasRegistry() {} Option<TagAlias> TagAliasRegistry::find( std::string const& alias ) const { std::map<std::string, TagAlias>::const_iterator it = m_registry.find( alias ); if( it != m_registry.end() ) return it->second; else return Option<TagAlias>(); } std::string TagAliasRegistry::expandAliases( std::string const& unexpandedTestSpec ) const { std::string expandedTestSpec = unexpandedTestSpec; for( std::map<std::string, TagAlias>::const_iterator it = m_registry.begin(), itEnd = m_registry.end(); it != itEnd; ++it ) { std::size_t pos = expandedTestSpec.find( it->first ); if( pos != std::string::npos ) { expandedTestSpec = expandedTestSpec.substr( 0, pos ) + it->second.tag + expandedTestSpec.substr( pos + it->first.size() ); } } return expandedTestSpec; } void TagAliasRegistry::add( char const* alias, char const* tag, SourceLineInfo const& lineInfo ) { if( !startsWith( alias, "[@" ) || !endsWith( alias, "]" ) ) { std::ostringstream oss; oss << "error: tag alias, \"" << alias << "\" is not of the form [@alias name].\n" << lineInfo; throw std::domain_error( oss.str().c_str() ); } if( !m_registry.insert( std::make_pair( alias, TagAlias( tag, lineInfo ) ) ).second ) { std::ostringstream oss; oss << "error: tag alias, \"" << alias << "\" already registered.\n" << "\tFirst seen at " << find(alias)->lineInfo << "\n" << "\tRedefined at " << lineInfo; throw std::domain_error( oss.str().c_str() ); } } TagAliasRegistry& TagAliasRegistry::get() { static TagAliasRegistry instance; return instance; } ITagAliasRegistry::~ITagAliasRegistry() {} ITagAliasRegistry const& ITagAliasRegistry::get() { return TagAliasRegistry::get(); } RegistrarForTagAliases::RegistrarForTagAliases( char const* alias, char const* tag, SourceLineInfo const& lineInfo ) { try { TagAliasRegistry::get().add( alias, tag, lineInfo ); } catch( std::exception& ex ) { Colour colourGuard( Colour::Red ); Catch::cerr() << ex.what() << std::endl; exit(1); } } } // end namespace Catch // #included from: ../reporters/catch_reporter_multi.hpp #define TWOBLUECUBES_CATCH_REPORTER_MULTI_HPP_INCLUDED namespace Catch { class MultipleReporters : public SharedImpl<IStreamingReporter> { typedef std::vector<Ptr<IStreamingReporter> > Reporters; Reporters m_reporters; public: void add( Ptr<IStreamingReporter> const& reporter ) { m_reporters.push_back( reporter ); } public: // IStreamingReporter virtual ReporterPreferences getPreferences() const CATCH_OVERRIDE { return m_reporters[0]->getPreferences(); } virtual void noMatchingTestCases( std::string const& spec ) CATCH_OVERRIDE { for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end(); it != itEnd; ++it ) (*it)->noMatchingTestCases( spec ); } virtual void testRunStarting( TestRunInfo const& testRunInfo ) CATCH_OVERRIDE { for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end(); it != itEnd; ++it ) (*it)->testRunStarting( testRunInfo ); } virtual void testGroupStarting( GroupInfo const& groupInfo ) CATCH_OVERRIDE { for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end(); it != itEnd; ++it ) (*it)->testGroupStarting( groupInfo ); } virtual void testCaseStarting( TestCaseInfo const& testInfo ) CATCH_OVERRIDE { for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end(); it != itEnd; ++it ) (*it)->testCaseStarting( testInfo ); } virtual void sectionStarting( SectionInfo const& sectionInfo ) CATCH_OVERRIDE { for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end(); it != itEnd; ++it ) (*it)->sectionStarting( sectionInfo ); } virtual void assertionStarting( AssertionInfo const& assertionInfo ) CATCH_OVERRIDE { for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end(); it != itEnd; ++it ) (*it)->assertionStarting( assertionInfo ); } // The return value indicates if the messages buffer should be cleared: virtual bool assertionEnded( AssertionStats const& assertionStats ) CATCH_OVERRIDE { bool clearBuffer = false; for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end(); it != itEnd; ++it ) clearBuffer |= (*it)->assertionEnded( assertionStats ); return clearBuffer; } virtual void sectionEnded( SectionStats const& sectionStats ) CATCH_OVERRIDE { for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end(); it != itEnd; ++it ) (*it)->sectionEnded( sectionStats ); } virtual void testCaseEnded( TestCaseStats const& testCaseStats ) CATCH_OVERRIDE { for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end(); it != itEnd; ++it ) (*it)->testCaseEnded( testCaseStats ); } virtual void testGroupEnded( TestGroupStats const& testGroupStats ) CATCH_OVERRIDE { for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end(); it != itEnd; ++it ) (*it)->testGroupEnded( testGroupStats ); } virtual void testRunEnded( TestRunStats const& testRunStats ) CATCH_OVERRIDE { for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end(); it != itEnd; ++it ) (*it)->testRunEnded( testRunStats ); } virtual void skipTest( TestCaseInfo const& testInfo ) CATCH_OVERRIDE { for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end(); it != itEnd; ++it ) (*it)->skipTest( testInfo ); } }; Ptr<IStreamingReporter> addReporter( Ptr<IStreamingReporter> const& existingReporter, Ptr<IStreamingReporter> const& additionalReporter ) { Ptr<IStreamingReporter> resultingReporter; if( existingReporter ) { MultipleReporters* multi = dynamic_cast<MultipleReporters*>( existingReporter.get() ); if( !multi ) { multi = new MultipleReporters; resultingReporter = Ptr<IStreamingReporter>( multi ); if( existingReporter ) multi->add( existingReporter ); } else resultingReporter = existingReporter; multi->add( additionalReporter ); } else resultingReporter = additionalReporter; return resultingReporter; } } // end namespace Catch // #included from: ../reporters/catch_reporter_xml.hpp #define TWOBLUECUBES_CATCH_REPORTER_XML_HPP_INCLUDED // #included from: catch_reporter_bases.hpp #define TWOBLUECUBES_CATCH_REPORTER_BASES_HPP_INCLUDED #include <cstring> namespace Catch { struct StreamingReporterBase : SharedImpl<IStreamingReporter> { StreamingReporterBase( ReporterConfig const& _config ) : m_config( _config.fullConfig() ), stream( _config.stream() ) { m_reporterPrefs.shouldRedirectStdOut = false; } virtual ReporterPreferences getPreferences() const CATCH_OVERRIDE { return m_reporterPrefs; } virtual ~StreamingReporterBase() CATCH_OVERRIDE; virtual void noMatchingTestCases( std::string const& ) CATCH_OVERRIDE {} virtual void testRunStarting( TestRunInfo const& _testRunInfo ) CATCH_OVERRIDE { currentTestRunInfo = _testRunInfo; } virtual void testGroupStarting( GroupInfo const& _groupInfo ) CATCH_OVERRIDE { currentGroupInfo = _groupInfo; } virtual void testCaseStarting( TestCaseInfo const& _testInfo ) CATCH_OVERRIDE { currentTestCaseInfo = _testInfo; } virtual void sectionStarting( SectionInfo const& _sectionInfo ) CATCH_OVERRIDE { m_sectionStack.push_back( _sectionInfo ); } virtual void sectionEnded( SectionStats const& /* _sectionStats */ ) CATCH_OVERRIDE { m_sectionStack.pop_back(); } virtual void testCaseEnded( TestCaseStats const& /* _testCaseStats */ ) CATCH_OVERRIDE { currentTestCaseInfo.reset(); } virtual void testGroupEnded( TestGroupStats const& /* _testGroupStats */ ) CATCH_OVERRIDE { currentGroupInfo.reset(); } virtual void testRunEnded( TestRunStats const& /* _testRunStats */ ) CATCH_OVERRIDE { currentTestCaseInfo.reset(); currentGroupInfo.reset(); currentTestRunInfo.reset(); } virtual void skipTest( TestCaseInfo const& ) CATCH_OVERRIDE { // Don't do anything with this by default. // It can optionally be overridden in the derived class. } Ptr<IConfig const> m_config; std::ostream& stream; LazyStat<TestRunInfo> currentTestRunInfo; LazyStat<GroupInfo> currentGroupInfo; LazyStat<TestCaseInfo> currentTestCaseInfo; std::vector<SectionInfo> m_sectionStack; ReporterPreferences m_reporterPrefs; }; struct CumulativeReporterBase : SharedImpl<IStreamingReporter> { template<typename T, typename ChildNodeT> struct Node : SharedImpl<> { explicit Node( T const& _value ) : value( _value ) {} virtual ~Node() {} typedef std::vector<Ptr<ChildNodeT> > ChildNodes; T value; ChildNodes children; }; struct SectionNode : SharedImpl<> { explicit SectionNode( SectionStats const& _stats ) : stats( _stats ) {} virtual ~SectionNode(); bool operator == ( SectionNode const& other ) const { return stats.sectionInfo.lineInfo == other.stats.sectionInfo.lineInfo; } bool operator == ( Ptr<SectionNode> const& other ) const { return operator==( *other ); } SectionStats stats; typedef std::vector<Ptr<SectionNode> > ChildSections; typedef std::vector<AssertionStats> Assertions; ChildSections childSections; Assertions assertions; std::string stdOut; std::string stdErr; }; struct BySectionInfo { BySectionInfo( SectionInfo const& other ) : m_other( other ) {} BySectionInfo( BySectionInfo const& other ) : m_other( other.m_other ) {} bool operator() ( Ptr<SectionNode> const& node ) const { return node->stats.sectionInfo.lineInfo == m_other.lineInfo; } private: void operator=( BySectionInfo const& ); SectionInfo const& m_other; }; typedef Node<TestCaseStats, SectionNode> TestCaseNode; typedef Node<TestGroupStats, TestCaseNode> TestGroupNode; typedef Node<TestRunStats, TestGroupNode> TestRunNode; CumulativeReporterBase( ReporterConfig const& _config ) : m_config( _config.fullConfig() ), stream( _config.stream() ) { m_reporterPrefs.shouldRedirectStdOut = false; } ~CumulativeReporterBase(); virtual ReporterPreferences getPreferences() const CATCH_OVERRIDE { return m_reporterPrefs; } virtual void testRunStarting( TestRunInfo const& ) CATCH_OVERRIDE {} virtual void testGroupStarting( GroupInfo const& ) CATCH_OVERRIDE {} virtual void testCaseStarting( TestCaseInfo const& ) CATCH_OVERRIDE {} virtual void sectionStarting( SectionInfo const& sectionInfo ) CATCH_OVERRIDE { SectionStats incompleteStats( sectionInfo, Counts(), 0, false ); Ptr<SectionNode> node; if( m_sectionStack.empty() ) { if( !m_rootSection ) m_rootSection = new SectionNode( incompleteStats ); node = m_rootSection; } else { SectionNode& parentNode = *m_sectionStack.back(); SectionNode::ChildSections::const_iterator it = std::find_if( parentNode.childSections.begin(), parentNode.childSections.end(), BySectionInfo( sectionInfo ) ); if( it == parentNode.childSections.end() ) { node = new SectionNode( incompleteStats ); parentNode.childSections.push_back( node ); } else node = *it; } m_sectionStack.push_back( node ); m_deepestSection = node; } virtual void assertionStarting( AssertionInfo const& ) CATCH_OVERRIDE {} virtual bool assertionEnded( AssertionStats const& assertionStats ) { assert( !m_sectionStack.empty() ); SectionNode& sectionNode = *m_sectionStack.back(); sectionNode.assertions.push_back( assertionStats ); return true; } virtual void sectionEnded( SectionStats const& sectionStats ) CATCH_OVERRIDE { assert( !m_sectionStack.empty() ); SectionNode& node = *m_sectionStack.back(); node.stats = sectionStats; m_sectionStack.pop_back(); } virtual void testCaseEnded( TestCaseStats const& testCaseStats ) CATCH_OVERRIDE { Ptr<TestCaseNode> node = new TestCaseNode( testCaseStats ); assert( m_sectionStack.size() == 0 ); node->children.push_back( m_rootSection ); m_testCases.push_back( node ); m_rootSection.reset(); assert( m_deepestSection ); m_deepestSection->stdOut = testCaseStats.stdOut; m_deepestSection->stdErr = testCaseStats.stdErr; } virtual void testGroupEnded( TestGroupStats const& testGroupStats ) CATCH_OVERRIDE { Ptr<TestGroupNode> node = new TestGroupNode( testGroupStats ); node->children.swap( m_testCases ); m_testGroups.push_back( node ); } virtual void testRunEnded( TestRunStats const& testRunStats ) CATCH_OVERRIDE { Ptr<TestRunNode> node = new TestRunNode( testRunStats ); node->children.swap( m_testGroups ); m_testRuns.push_back( node ); testRunEndedCumulative(); } virtual void testRunEndedCumulative() = 0; virtual void skipTest( TestCaseInfo const& ) CATCH_OVERRIDE {} Ptr<IConfig const> m_config; std::ostream& stream; std::vector<AssertionStats> m_assertions; std::vector<std::vector<Ptr<SectionNode> > > m_sections; std::vector<Ptr<TestCaseNode> > m_testCases; std::vector<Ptr<TestGroupNode> > m_testGroups; std::vector<Ptr<TestRunNode> > m_testRuns; Ptr<SectionNode> m_rootSection; Ptr<SectionNode> m_deepestSection; std::vector<Ptr<SectionNode> > m_sectionStack; ReporterPreferences m_reporterPrefs; }; template<char C> char const* getLineOfChars() { static char line[CATCH_CONFIG_CONSOLE_WIDTH] = {0}; if( !*line ) { memset( line, C, CATCH_CONFIG_CONSOLE_WIDTH-1 ); line[CATCH_CONFIG_CONSOLE_WIDTH-1] = 0; } return line; } struct TestEventListenerBase : StreamingReporterBase { TestEventListenerBase( ReporterConfig const& _config ) : StreamingReporterBase( _config ) {} virtual void assertionStarting( AssertionInfo const& ) CATCH_OVERRIDE {} virtual bool assertionEnded( AssertionStats const& ) CATCH_OVERRIDE { return false; } }; } // end namespace Catch // #included from: ../internal/catch_reporter_registrars.hpp #define TWOBLUECUBES_CATCH_REPORTER_REGISTRARS_HPP_INCLUDED namespace Catch { template<typename T> class LegacyReporterRegistrar { class ReporterFactory : public IReporterFactory { virtual IStreamingReporter* create( ReporterConfig const& config ) const { return new LegacyReporterAdapter( new T( config ) ); } virtual std::string getDescription() const { return T::getDescription(); } }; public: LegacyReporterRegistrar( std::string const& name ) { getMutableRegistryHub().registerReporter( name, new ReporterFactory() ); } }; template<typename T> class ReporterRegistrar { class ReporterFactory : public SharedImpl<IReporterFactory> { // *** Please Note ***: // - If you end up here looking at a compiler error because it's trying to register // your custom reporter class be aware that the native reporter interface has changed // to IStreamingReporter. The "legacy" interface, IReporter, is still supported via // an adapter. Just use REGISTER_LEGACY_REPORTER to take advantage of the adapter. // However please consider updating to the new interface as the old one is now // deprecated and will probably be removed quite soon! // Please contact me via github if you have any questions at all about this. // In fact, ideally, please contact me anyway to let me know you've hit this - as I have // no idea who is actually using custom reporters at all (possibly no-one!). // The new interface is designed to minimise exposure to interface changes in the future. virtual IStreamingReporter* create( ReporterConfig const& config ) const { return new T( config ); } virtual std::string getDescription() const { return T::getDescription(); } }; public: ReporterRegistrar( std::string const& name ) { getMutableRegistryHub().registerReporter( name, new ReporterFactory() ); } }; template<typename T> class ListenerRegistrar { class ListenerFactory : public SharedImpl<IReporterFactory> { virtual IStreamingReporter* create( ReporterConfig const& config ) const { return new T( config ); } virtual std::string getDescription() const { return ""; } }; public: ListenerRegistrar() { getMutableRegistryHub().registerListener( new ListenerFactory() ); } }; } #define INTERNAL_CATCH_REGISTER_LEGACY_REPORTER( name, reporterType ) \ namespace{ Catch::LegacyReporterRegistrar<reporterType> catch_internal_RegistrarFor##reporterType( name ); } #define INTERNAL_CATCH_REGISTER_REPORTER( name, reporterType ) \ namespace{ Catch::ReporterRegistrar<reporterType> catch_internal_RegistrarFor##reporterType( name ); } #define INTERNAL_CATCH_REGISTER_LISTENER( listenerType ) \ namespace{ Catch::ListenerRegistrar<listenerType> catch_internal_RegistrarFor##listenerType; } // #included from: ../internal/catch_xmlwriter.hpp #define TWOBLUECUBES_CATCH_XMLWRITER_HPP_INCLUDED #include <sstream> #include <string> #include <vector> #include <iomanip> namespace Catch { class XmlEncode { public: enum ForWhat { ForTextNodes, ForAttributes }; XmlEncode( std::string const& str, ForWhat forWhat = ForTextNodes ) : m_str( str ), m_forWhat( forWhat ) {} void encodeTo( std::ostream& os ) const { // Apostrophe escaping not necessary if we always use " to write attributes // (see: http://www.w3.org/TR/xml/#syntax) for( std::size_t i = 0; i < m_str.size(); ++ i ) { char c = m_str[i]; switch( c ) { case '<': os << "&lt;"; break; case '&': os << "&amp;"; break; case '>': // See: http://www.w3.org/TR/xml/#syntax if( i > 2 && m_str[i-1] == ']' && m_str[i-2] == ']' ) os << "&gt;"; else os << c; break; case '\"': if( m_forWhat == ForAttributes ) os << "&quot;"; else os << c; break; default: // Escape control chars - based on contribution by @espenalb in PR #465 if ( ( c < '\x09' ) || ( c > '\x0D' && c < '\x20') || c=='\x7F' ) os << "&#x" << std::uppercase << std::hex << static_cast<int>( c ); else os << c; } } } friend std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode ) { xmlEncode.encodeTo( os ); return os; } private: std::string m_str; ForWhat m_forWhat; }; class XmlWriter { public: class ScopedElement { public: ScopedElement( XmlWriter* writer ) : m_writer( writer ) {} ScopedElement( ScopedElement const& other ) : m_writer( other.m_writer ){ other.m_writer = CATCH_NULL; } ~ScopedElement() { if( m_writer ) m_writer->endElement(); } ScopedElement& writeText( std::string const& text, bool indent = true ) { m_writer->writeText( text, indent ); return *this; } template<typename T> ScopedElement& writeAttribute( std::string const& name, T const& attribute ) { m_writer->writeAttribute( name, attribute ); return *this; } private: mutable XmlWriter* m_writer; }; XmlWriter() : m_tagIsOpen( false ), m_needsNewline( false ), m_os( &Catch::cout() ) {} XmlWriter( std::ostream& os ) : m_tagIsOpen( false ), m_needsNewline( false ), m_os( &os ) {} ~XmlWriter() { while( !m_tags.empty() ) endElement(); } XmlWriter& startElement( std::string const& name ) { ensureTagClosed(); newlineIfNecessary(); stream() << m_indent << "<" << name; m_tags.push_back( name ); m_indent += " "; m_tagIsOpen = true; return *this; } ScopedElement scopedElement( std::string const& name ) { ScopedElement scoped( this ); startElement( name ); return scoped; } XmlWriter& endElement() { newlineIfNecessary(); m_indent = m_indent.substr( 0, m_indent.size()-2 ); if( m_tagIsOpen ) { stream() << "/>\n"; m_tagIsOpen = false; } else { stream() << m_indent << "</" << m_tags.back() << ">\n"; } m_tags.pop_back(); return *this; } XmlWriter& writeAttribute( std::string const& name, std::string const& attribute ) { if( !name.empty() && !attribute.empty() ) stream() << " " << name << "=\"" << XmlEncode( attribute, XmlEncode::ForAttributes ) << "\""; return *this; } XmlWriter& writeAttribute( std::string const& name, bool attribute ) { stream() << " " << name << "=\"" << ( attribute ? "true" : "false" ) << "\""; return *this; } template<typename T> XmlWriter& writeAttribute( std::string const& name, T const& attribute ) { std::ostringstream oss; oss << attribute; return writeAttribute( name, oss.str() ); } XmlWriter& writeText( std::string const& text, bool indent = true ) { if( !text.empty() ){ bool tagWasOpen = m_tagIsOpen; ensureTagClosed(); if( tagWasOpen && indent ) stream() << m_indent; stream() << XmlEncode( text ); m_needsNewline = true; } return *this; } XmlWriter& writeComment( std::string const& text ) { ensureTagClosed(); stream() << m_indent << "<!--" << text << "-->"; m_needsNewline = true; return *this; } XmlWriter& writeBlankLine() { ensureTagClosed(); stream() << "\n"; return *this; } void setStream( std::ostream& os ) { m_os = &os; } private: XmlWriter( XmlWriter const& ); void operator=( XmlWriter const& ); std::ostream& stream() { return *m_os; } void ensureTagClosed() { if( m_tagIsOpen ) { stream() << ">\n"; m_tagIsOpen = false; } } void newlineIfNecessary() { if( m_needsNewline ) { stream() << "\n"; m_needsNewline = false; } } bool m_tagIsOpen; bool m_needsNewline; std::vector<std::string> m_tags; std::string m_indent; std::ostream* m_os; }; } // #included from: catch_reenable_warnings.h #define TWOBLUECUBES_CATCH_REENABLE_WARNINGS_H_INCLUDED #ifdef __clang__ # ifdef __ICC // icpc defines the __clang__ macro # pragma warning(pop) # else # pragma clang diagnostic pop # endif #elif defined __GNUC__ # pragma GCC diagnostic pop #endif namespace Catch { class XmlReporter : public StreamingReporterBase { public: XmlReporter( ReporterConfig const& _config ) : StreamingReporterBase( _config ), m_sectionDepth( 0 ) { m_reporterPrefs.shouldRedirectStdOut = true; } virtual ~XmlReporter() CATCH_OVERRIDE; static std::string getDescription() { return "Reports test results as an XML document"; } public: // StreamingReporterBase virtual void noMatchingTestCases( std::string const& s ) CATCH_OVERRIDE { StreamingReporterBase::noMatchingTestCases( s ); } virtual void testRunStarting( TestRunInfo const& testInfo ) CATCH_OVERRIDE { StreamingReporterBase::testRunStarting( testInfo ); m_xml.setStream( stream ); m_xml.startElement( "Catch" ); if( !m_config->name().empty() ) m_xml.writeAttribute( "name", m_config->name() ); } virtual void testGroupStarting( GroupInfo const& groupInfo ) CATCH_OVERRIDE { StreamingReporterBase::testGroupStarting( groupInfo ); m_xml.startElement( "Group" ) .writeAttribute( "name", groupInfo.name ); } virtual void testCaseStarting( TestCaseInfo const& testInfo ) CATCH_OVERRIDE { StreamingReporterBase::testCaseStarting(testInfo); m_xml.startElement( "TestCase" ).writeAttribute( "name", trim( testInfo.name ) ); if ( m_config->showDurations() == ShowDurations::Always ) m_testCaseTimer.start(); } virtual void sectionStarting( SectionInfo const& sectionInfo ) CATCH_OVERRIDE { StreamingReporterBase::sectionStarting( sectionInfo ); if( m_sectionDepth++ > 0 ) { m_xml.startElement( "Section" ) .writeAttribute( "name", trim( sectionInfo.name ) ) .writeAttribute( "description", sectionInfo.description ); } } virtual void assertionStarting( AssertionInfo const& ) CATCH_OVERRIDE { } virtual bool assertionEnded( AssertionStats const& assertionStats ) CATCH_OVERRIDE { const AssertionResult& assertionResult = assertionStats.assertionResult; // Print any info messages in <Info> tags. if( assertionStats.assertionResult.getResultType() != ResultWas::Ok ) { for( std::vector<MessageInfo>::const_iterator it = assertionStats.infoMessages.begin(), itEnd = assertionStats.infoMessages.end(); it != itEnd; ++it ) { if( it->type == ResultWas::Info ) { m_xml.scopedElement( "Info" ) .writeText( it->message ); } else if ( it->type == ResultWas::Warning ) { m_xml.scopedElement( "Warning" ) .writeText( it->message ); } } } // Drop out if result was successful but we're not printing them. if( !m_config->includeSuccessfulResults() && isOk(assertionResult.getResultType()) ) return true; // Print the expression if there is one. if( assertionResult.hasExpression() ) { m_xml.startElement( "Expression" ) .writeAttribute( "success", assertionResult.succeeded() ) .writeAttribute( "type", assertionResult.getTestMacroName() ) .writeAttribute( "filename", assertionResult.getSourceInfo().file ) .writeAttribute( "line", assertionResult.getSourceInfo().line ); m_xml.scopedElement( "Original" ) .writeText( assertionResult.getExpression() ); m_xml.scopedElement( "Expanded" ) .writeText( assertionResult.getExpandedExpression() ); } // And... Print a result applicable to each result type. switch( assertionResult.getResultType() ) { case ResultWas::ThrewException: m_xml.scopedElement( "Exception" ) .writeAttribute( "filename", assertionResult.getSourceInfo().file ) .writeAttribute( "line", assertionResult.getSourceInfo().line ) .writeText( assertionResult.getMessage() ); break; case ResultWas::FatalErrorCondition: m_xml.scopedElement( "Fatal Error Condition" ) .writeAttribute( "filename", assertionResult.getSourceInfo().file ) .writeAttribute( "line", assertionResult.getSourceInfo().line ) .writeText( assertionResult.getMessage() ); break; case ResultWas::Info: m_xml.scopedElement( "Info" ) .writeText( assertionResult.getMessage() ); break; case ResultWas::Warning: // Warning will already have been written break; case ResultWas::ExplicitFailure: m_xml.scopedElement( "Failure" ) .writeText( assertionResult.getMessage() ); break; default: break; } if( assertionResult.hasExpression() ) m_xml.endElement(); return true; } virtual void sectionEnded( SectionStats const& sectionStats ) CATCH_OVERRIDE { StreamingReporterBase::sectionEnded( sectionStats ); if( --m_sectionDepth > 0 ) { XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResults" ); e.writeAttribute( "successes", sectionStats.assertions.passed ); e.writeAttribute( "failures", sectionStats.assertions.failed ); e.writeAttribute( "expectedFailures", sectionStats.assertions.failedButOk ); if ( m_config->showDurations() == ShowDurations::Always ) e.writeAttribute( "durationInSeconds", sectionStats.durationInSeconds ); m_xml.endElement(); } } virtual void testCaseEnded( TestCaseStats const& testCaseStats ) CATCH_OVERRIDE { StreamingReporterBase::testCaseEnded( testCaseStats ); XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResult" ); e.writeAttribute( "success", testCaseStats.totals.assertions.allOk() ); if ( m_config->showDurations() == ShowDurations::Always ) e.writeAttribute( "durationInSeconds", m_testCaseTimer.getElapsedSeconds() ); m_xml.endElement(); } virtual void testGroupEnded( TestGroupStats const& testGroupStats ) CATCH_OVERRIDE { StreamingReporterBase::testGroupEnded( testGroupStats ); // TODO: Check testGroupStats.aborting and act accordingly. m_xml.scopedElement( "OverallResults" ) .writeAttribute( "successes", testGroupStats.totals.assertions.passed ) .writeAttribute( "failures", testGroupStats.totals.assertions.failed ) .writeAttribute( "expectedFailures", testGroupStats.totals.assertions.failedButOk ); m_xml.endElement(); } virtual void testRunEnded( TestRunStats const& testRunStats ) CATCH_OVERRIDE { StreamingReporterBase::testRunEnded( testRunStats ); m_xml.scopedElement( "OverallResults" ) .writeAttribute( "successes", testRunStats.totals.assertions.passed ) .writeAttribute( "failures", testRunStats.totals.assertions.failed ) .writeAttribute( "expectedFailures", testRunStats.totals.assertions.failedButOk ); m_xml.endElement(); } private: Timer m_testCaseTimer; XmlWriter m_xml; int m_sectionDepth; }; INTERNAL_CATCH_REGISTER_REPORTER( "xml", XmlReporter ) } // end namespace Catch // #included from: ../reporters/catch_reporter_junit.hpp #define TWOBLUECUBES_CATCH_REPORTER_JUNIT_HPP_INCLUDED #include <assert.h> namespace Catch { class JunitReporter : public CumulativeReporterBase { public: JunitReporter( ReporterConfig const& _config ) : CumulativeReporterBase( _config ), xml( _config.stream() ) { m_reporterPrefs.shouldRedirectStdOut = true; } virtual ~JunitReporter() CATCH_OVERRIDE; static std::string getDescription() { return "Reports test results in an XML format that looks like Ant's junitreport target"; } virtual void noMatchingTestCases( std::string const& /*spec*/ ) CATCH_OVERRIDE {} virtual void testRunStarting( TestRunInfo const& runInfo ) CATCH_OVERRIDE { CumulativeReporterBase::testRunStarting( runInfo ); xml.startElement( "testsuites" ); } virtual void testGroupStarting( GroupInfo const& groupInfo ) CATCH_OVERRIDE { suiteTimer.start(); stdOutForSuite.str(""); stdErrForSuite.str(""); unexpectedExceptions = 0; CumulativeReporterBase::testGroupStarting( groupInfo ); } virtual bool assertionEnded( AssertionStats const& assertionStats ) CATCH_OVERRIDE { if( assertionStats.assertionResult.getResultType() == ResultWas::ThrewException ) unexpectedExceptions++; return CumulativeReporterBase::assertionEnded( assertionStats ); } virtual void testCaseEnded( TestCaseStats const& testCaseStats ) CATCH_OVERRIDE { stdOutForSuite << testCaseStats.stdOut; stdErrForSuite << testCaseStats.stdErr; CumulativeReporterBase::testCaseEnded( testCaseStats ); } virtual void testGroupEnded( TestGroupStats const& testGroupStats ) CATCH_OVERRIDE { double suiteTime = suiteTimer.getElapsedSeconds(); CumulativeReporterBase::testGroupEnded( testGroupStats ); writeGroup( *m_testGroups.back(), suiteTime ); } virtual void testRunEndedCumulative() CATCH_OVERRIDE { xml.endElement(); } void writeGroup( TestGroupNode const& groupNode, double suiteTime ) { XmlWriter::ScopedElement e = xml.scopedElement( "testsuite" ); TestGroupStats const& stats = groupNode.value; xml.writeAttribute( "name", stats.groupInfo.name ); xml.writeAttribute( "errors", unexpectedExceptions ); xml.writeAttribute( "failures", stats.totals.assertions.failed-unexpectedExceptions ); xml.writeAttribute( "tests", stats.totals.assertions.total() ); xml.writeAttribute( "hostname", "tbd" ); // !TBD if( m_config->showDurations() == ShowDurations::Never ) xml.writeAttribute( "time", "" ); else xml.writeAttribute( "time", suiteTime ); xml.writeAttribute( "timestamp", "tbd" ); // !TBD // Write test cases for( TestGroupNode::ChildNodes::const_iterator it = groupNode.children.begin(), itEnd = groupNode.children.end(); it != itEnd; ++it ) writeTestCase( **it ); xml.scopedElement( "system-out" ).writeText( trim( stdOutForSuite.str() ), false ); xml.scopedElement( "system-err" ).writeText( trim( stdErrForSuite.str() ), false ); } void writeTestCase( TestCaseNode const& testCaseNode ) { TestCaseStats const& stats = testCaseNode.value; // All test cases have exactly one section - which represents the // test case itself. That section may have 0-n nested sections assert( testCaseNode.children.size() == 1 ); SectionNode const& rootSection = *testCaseNode.children.front(); std::string className = stats.testInfo.className; if( className.empty() ) { if( rootSection.childSections.empty() ) className = "global"; } writeSection( className, "", rootSection ); } void writeSection( std::string const& className, std::string const& rootName, SectionNode const& sectionNode ) { std::string name = trim( sectionNode.stats.sectionInfo.name ); if( !rootName.empty() ) name = rootName + "/" + name; if( !sectionNode.assertions.empty() || !sectionNode.stdOut.empty() || !sectionNode.stdErr.empty() ) { XmlWriter::ScopedElement e = xml.scopedElement( "testcase" ); if( className.empty() ) { xml.writeAttribute( "classname", name ); xml.writeAttribute( "name", "root" ); } else { xml.writeAttribute( "classname", className ); xml.writeAttribute( "name", name ); } xml.writeAttribute( "time", Catch::toString( sectionNode.stats.durationInSeconds ) ); writeAssertions( sectionNode ); if( !sectionNode.stdOut.empty() ) xml.scopedElement( "system-out" ).writeText( trim( sectionNode.stdOut ), false ); if( !sectionNode.stdErr.empty() ) xml.scopedElement( "system-err" ).writeText( trim( sectionNode.stdErr ), false ); } for( SectionNode::ChildSections::const_iterator it = sectionNode.childSections.begin(), itEnd = sectionNode.childSections.end(); it != itEnd; ++it ) if( className.empty() ) writeSection( name, "", **it ); else writeSection( className, name, **it ); } void writeAssertions( SectionNode const& sectionNode ) { for( SectionNode::Assertions::const_iterator it = sectionNode.assertions.begin(), itEnd = sectionNode.assertions.end(); it != itEnd; ++it ) writeAssertion( *it ); } void writeAssertion( AssertionStats const& stats ) { AssertionResult const& result = stats.assertionResult; if( !result.isOk() ) { std::string elementName; switch( result.getResultType() ) { case ResultWas::ThrewException: case ResultWas::FatalErrorCondition: elementName = "error"; break; case ResultWas::ExplicitFailure: elementName = "failure"; break; case ResultWas::ExpressionFailed: elementName = "failure"; break; case ResultWas::DidntThrowException: elementName = "failure"; break; // We should never see these here: case ResultWas::Info: case ResultWas::Warning: case ResultWas::Ok: case ResultWas::Unknown: case ResultWas::FailureBit: case ResultWas::Exception: elementName = "internalError"; break; } XmlWriter::ScopedElement e = xml.scopedElement( elementName ); xml.writeAttribute( "message", result.getExpandedExpression() ); xml.writeAttribute( "type", result.getTestMacroName() ); std::ostringstream oss; if( !result.getMessage().empty() ) oss << result.getMessage() << "\n"; for( std::vector<MessageInfo>::const_iterator it = stats.infoMessages.begin(), itEnd = stats.infoMessages.end(); it != itEnd; ++it ) if( it->type == ResultWas::Info ) oss << it->message << "\n"; oss << "at " << result.getSourceInfo(); xml.writeText( oss.str(), false ); } } XmlWriter xml; Timer suiteTimer; std::ostringstream stdOutForSuite; std::ostringstream stdErrForSuite; unsigned int unexpectedExceptions; }; INTERNAL_CATCH_REGISTER_REPORTER( "junit", JunitReporter ) } // end namespace Catch // #included from: ../reporters/catch_reporter_console.hpp #define TWOBLUECUBES_CATCH_REPORTER_CONSOLE_HPP_INCLUDED namespace Catch { struct ConsoleReporter : StreamingReporterBase { ConsoleReporter( ReporterConfig const& _config ) : StreamingReporterBase( _config ), m_headerPrinted( false ) {} virtual ~ConsoleReporter() CATCH_OVERRIDE; static std::string getDescription() { return "Reports test results as plain lines of text"; } virtual void noMatchingTestCases( std::string const& spec ) CATCH_OVERRIDE { stream << "No test cases matched '" << spec << "'" << std::endl; } virtual void assertionStarting( AssertionInfo const& ) CATCH_OVERRIDE { } virtual bool assertionEnded( AssertionStats const& _assertionStats ) CATCH_OVERRIDE { AssertionResult const& result = _assertionStats.assertionResult; bool printInfoMessages = true; // Drop out if result was successful and we're not printing those if( !m_config->includeSuccessfulResults() && result.isOk() ) { if( result.getResultType() != ResultWas::Warning ) return false; printInfoMessages = false; } lazyPrint(); AssertionPrinter printer( stream, _assertionStats, printInfoMessages ); printer.print(); stream << std::endl; return true; } virtual void sectionStarting( SectionInfo const& _sectionInfo ) CATCH_OVERRIDE { m_headerPrinted = false; StreamingReporterBase::sectionStarting( _sectionInfo ); } virtual void sectionEnded( SectionStats const& _sectionStats ) CATCH_OVERRIDE { if( _sectionStats.missingAssertions ) { lazyPrint(); Colour colour( Colour::ResultError ); if( m_sectionStack.size() > 1 ) stream << "\nNo assertions in section"; else stream << "\nNo assertions in test case"; stream << " '" << _sectionStats.sectionInfo.name << "'\n" << std::endl; } if( m_headerPrinted ) { if( m_config->showDurations() == ShowDurations::Always ) stream << "Completed in " << _sectionStats.durationInSeconds << "s" << std::endl; m_headerPrinted = false; } else { if( m_config->showDurations() == ShowDurations::Always ) stream << _sectionStats.sectionInfo.name << " completed in " << _sectionStats.durationInSeconds << "s" << std::endl; } StreamingReporterBase::sectionEnded( _sectionStats ); } virtual void testCaseEnded( TestCaseStats const& _testCaseStats ) CATCH_OVERRIDE { StreamingReporterBase::testCaseEnded( _testCaseStats ); m_headerPrinted = false; } virtual void testGroupEnded( TestGroupStats const& _testGroupStats ) CATCH_OVERRIDE { if( currentGroupInfo.used ) { printSummaryDivider(); stream << "Summary for group '" << _testGroupStats.groupInfo.name << "':\n"; printTotals( _testGroupStats.totals ); stream << "\n" << std::endl; } StreamingReporterBase::testGroupEnded( _testGroupStats ); } virtual void testRunEnded( TestRunStats const& _testRunStats ) CATCH_OVERRIDE { printTotalsDivider( _testRunStats.totals ); printTotals( _testRunStats.totals ); stream << std::endl; StreamingReporterBase::testRunEnded( _testRunStats ); } private: class AssertionPrinter { void operator= ( AssertionPrinter const& ); public: AssertionPrinter( std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages ) : stream( _stream ), stats( _stats ), result( _stats.assertionResult ), colour( Colour::None ), message( result.getMessage() ), messages( _stats.infoMessages ), printInfoMessages( _printInfoMessages ) { switch( result.getResultType() ) { case ResultWas::Ok: colour = Colour::Success; passOrFail = "PASSED"; //if( result.hasMessage() ) if( _stats.infoMessages.size() == 1 ) messageLabel = "with message"; if( _stats.infoMessages.size() > 1 ) messageLabel = "with messages"; break; case ResultWas::ExpressionFailed: if( result.isOk() ) { colour = Colour::Success; passOrFail = "FAILED - but was ok"; } else { colour = Colour::Error; passOrFail = "FAILED"; } if( _stats.infoMessages.size() == 1 ) messageLabel = "with message"; if( _stats.infoMessages.size() > 1 ) messageLabel = "with messages"; break; case ResultWas::ThrewException: colour = Colour::Error; passOrFail = "FAILED"; messageLabel = "due to unexpected exception with message"; break; case ResultWas::FatalErrorCondition: colour = Colour::Error; passOrFail = "FAILED"; messageLabel = "due to a fatal error condition"; break; case ResultWas::DidntThrowException: colour = Colour::Error; passOrFail = "FAILED"; messageLabel = "because no exception was thrown where one was expected"; break; case ResultWas::Info: messageLabel = "info"; break; case ResultWas::Warning: messageLabel = "warning"; break; case ResultWas::ExplicitFailure: passOrFail = "FAILED"; colour = Colour::Error; if( _stats.infoMessages.size() == 1 ) messageLabel = "explicitly with message"; if( _stats.infoMessages.size() > 1 ) messageLabel = "explicitly with messages"; break; // These cases are here to prevent compiler warnings case ResultWas::Unknown: case ResultWas::FailureBit: case ResultWas::Exception: passOrFail = "** internal error **"; colour = Colour::Error; break; } } void print() const { printSourceInfo(); if( stats.totals.assertions.total() > 0 ) { if( result.isOk() ) stream << "\n"; printResultType(); printOriginalExpression(); printReconstructedExpression(); } else { stream << "\n"; } printMessage(); } private: void printResultType() const { if( !passOrFail.empty() ) { Colour colourGuard( colour ); stream << passOrFail << ":\n"; } } void printOriginalExpression() const { if( result.hasExpression() ) { Colour colourGuard( Colour::OriginalExpression ); stream << " "; stream << result.getExpressionInMacro(); stream << "\n"; } } void printReconstructedExpression() const { if( result.hasExpandedExpression() ) { stream << "with expansion:\n"; Colour colourGuard( Colour::ReconstructedExpression ); stream << Text( result.getExpandedExpression(), TextAttributes().setIndent(2) ) << "\n"; } } void printMessage() const { if( !messageLabel.empty() ) stream << messageLabel << ":" << "\n"; for( std::vector<MessageInfo>::const_iterator it = messages.begin(), itEnd = messages.end(); it != itEnd; ++it ) { // If this assertion is a warning ignore any INFO messages if( printInfoMessages || it->type != ResultWas::Info ) stream << Text( it->message, TextAttributes().setIndent(2) ) << "\n"; } } void printSourceInfo() const { Colour colourGuard( Colour::FileName ); stream << result.getSourceInfo() << ": "; } std::ostream& stream; AssertionStats const& stats; AssertionResult const& result; Colour::Code colour; std::string passOrFail; std::string messageLabel; std::string message; std::vector<MessageInfo> messages; bool printInfoMessages; }; void lazyPrint() { if( !currentTestRunInfo.used ) lazyPrintRunInfo(); if( !currentGroupInfo.used ) lazyPrintGroupInfo(); if( !m_headerPrinted ) { printTestCaseAndSectionHeader(); m_headerPrinted = true; } } void lazyPrintRunInfo() { stream << "\n" << getLineOfChars<'~'>() << "\n"; Colour colour( Colour::SecondaryText ); stream << currentTestRunInfo->name << " is a Catch v" << libraryVersion << " host application.\n" << "Run with -? for options\n\n"; if( m_config->rngSeed() != 0 ) stream << "Randomness seeded to: " << m_config->rngSeed() << "\n\n"; currentTestRunInfo.used = true; } void lazyPrintGroupInfo() { if( !currentGroupInfo->name.empty() && currentGroupInfo->groupsCounts > 1 ) { printClosedHeader( "Group: " + currentGroupInfo->name ); currentGroupInfo.used = true; } } void printTestCaseAndSectionHeader() { assert( !m_sectionStack.empty() ); printOpenHeader( currentTestCaseInfo->name ); if( m_sectionStack.size() > 1 ) { Colour colourGuard( Colour::Headers ); std::vector<SectionInfo>::const_iterator it = m_sectionStack.begin()+1, // Skip first section (test case) itEnd = m_sectionStack.end(); for( ; it != itEnd; ++it ) printHeaderString( it->name, 2 ); } SourceLineInfo lineInfo = m_sectionStack.front().lineInfo; if( !lineInfo.empty() ){ stream << getLineOfChars<'-'>() << "\n"; Colour colourGuard( Colour::FileName ); stream << lineInfo << "\n"; } stream << getLineOfChars<'.'>() << "\n" << std::endl; } void printClosedHeader( std::string const& _name ) { printOpenHeader( _name ); stream << getLineOfChars<'.'>() << "\n"; } void printOpenHeader( std::string const& _name ) { stream << getLineOfChars<'-'>() << "\n"; { Colour colourGuard( Colour::Headers ); printHeaderString( _name ); } } // if string has a : in first line will set indent to follow it on // subsequent lines void printHeaderString( std::string const& _string, std::size_t indent = 0 ) { std::size_t i = _string.find( ": " ); if( i != std::string::npos ) i+=2; else i = 0; stream << Text( _string, TextAttributes() .setIndent( indent+i) .setInitialIndent( indent ) ) << "\n"; } struct SummaryColumn { SummaryColumn( std::string const& _label, Colour::Code _colour ) : label( _label ), colour( _colour ) {} SummaryColumn addRow( std::size_t count ) { std::ostringstream oss; oss << count; std::string row = oss.str(); for( std::vector<std::string>::iterator it = rows.begin(); it != rows.end(); ++it ) { while( it->size() < row.size() ) *it = " " + *it; while( it->size() > row.size() ) row = " " + row; } rows.push_back( row ); return *this; } std::string label; Colour::Code colour; std::vector<std::string> rows; }; void printTotals( Totals const& totals ) { if( totals.testCases.total() == 0 ) { stream << Colour( Colour::Warning ) << "No tests ran\n"; } else if( totals.assertions.total() > 0 && totals.assertions.allPassed() ) { stream << Colour( Colour::ResultSuccess ) << "All tests passed"; stream << " (" << pluralise( totals.assertions.passed, "assertion" ) << " in " << pluralise( totals.testCases.passed, "test case" ) << ")" << "\n"; } else { std::vector<SummaryColumn> columns; columns.push_back( SummaryColumn( "", Colour::None ) .addRow( totals.testCases.total() ) .addRow( totals.assertions.total() ) ); columns.push_back( SummaryColumn( "passed", Colour::Success ) .addRow( totals.testCases.passed ) .addRow( totals.assertions.passed ) ); columns.push_back( SummaryColumn( "failed", Colour::ResultError ) .addRow( totals.testCases.failed ) .addRow( totals.assertions.failed ) ); columns.push_back( SummaryColumn( "failed as expected", Colour::ResultExpectedFailure ) .addRow( totals.testCases.failedButOk ) .addRow( totals.assertions.failedButOk ) ); printSummaryRow( "test cases", columns, 0 ); printSummaryRow( "assertions", columns, 1 ); } } void printSummaryRow( std::string const& label, std::vector<SummaryColumn> const& cols, std::size_t row ) { for( std::vector<SummaryColumn>::const_iterator it = cols.begin(); it != cols.end(); ++it ) { std::string value = it->rows[row]; if( it->label.empty() ) { stream << label << ": "; if( value != "0" ) stream << value; else stream << Colour( Colour::Warning ) << "- none -"; } else if( value != "0" ) { stream << Colour( Colour::LightGrey ) << " | "; stream << Colour( it->colour ) << value << " " << it->label; } } stream << "\n"; } static std::size_t makeRatio( std::size_t number, std::size_t total ) { std::size_t ratio = total > 0 ? CATCH_CONFIG_CONSOLE_WIDTH * number/ total : 0; return ( ratio == 0 && number > 0 ) ? 1 : ratio; } static std::size_t& findMax( std::size_t& i, std::size_t& j, std::size_t& k ) { if( i > j && i > k ) return i; else if( j > k ) return j; else return k; } void printTotalsDivider( Totals const& totals ) { if( totals.testCases.total() > 0 ) { std::size_t failedRatio = makeRatio( totals.testCases.failed, totals.testCases.total() ); std::size_t failedButOkRatio = makeRatio( totals.testCases.failedButOk, totals.testCases.total() ); std::size_t passedRatio = makeRatio( totals.testCases.passed, totals.testCases.total() ); while( failedRatio + failedButOkRatio + passedRatio < CATCH_CONFIG_CONSOLE_WIDTH-1 ) findMax( failedRatio, failedButOkRatio, passedRatio )++; while( failedRatio + failedButOkRatio + passedRatio > CATCH_CONFIG_CONSOLE_WIDTH-1 ) findMax( failedRatio, failedButOkRatio, passedRatio )--; stream << Colour( Colour::Error ) << std::string( failedRatio, '=' ); stream << Colour( Colour::ResultExpectedFailure ) << std::string( failedButOkRatio, '=' ); if( totals.testCases.allPassed() ) stream << Colour( Colour::ResultSuccess ) << std::string( passedRatio, '=' ); else stream << Colour( Colour::Success ) << std::string( passedRatio, '=' ); } else { stream << Colour( Colour::Warning ) << std::string( CATCH_CONFIG_CONSOLE_WIDTH-1, '=' ); } stream << "\n"; } void printSummaryDivider() { stream << getLineOfChars<'-'>() << "\n"; } private: bool m_headerPrinted; }; INTERNAL_CATCH_REGISTER_REPORTER( "console", ConsoleReporter ) } // end namespace Catch // #included from: ../reporters/catch_reporter_compact.hpp #define TWOBLUECUBES_CATCH_REPORTER_COMPACT_HPP_INCLUDED namespace Catch { struct CompactReporter : StreamingReporterBase { CompactReporter( ReporterConfig const& _config ) : StreamingReporterBase( _config ) {} virtual ~CompactReporter(); static std::string getDescription() { return "Reports test results on a single line, suitable for IDEs"; } virtual ReporterPreferences getPreferences() const { ReporterPreferences prefs; prefs.shouldRedirectStdOut = false; return prefs; } virtual void noMatchingTestCases( std::string const& spec ) { stream << "No test cases matched '" << spec << "'" << std::endl; } virtual void assertionStarting( AssertionInfo const& ) { } virtual bool assertionEnded( AssertionStats const& _assertionStats ) { AssertionResult const& result = _assertionStats.assertionResult; bool printInfoMessages = true; // Drop out if result was successful and we're not printing those if( !m_config->includeSuccessfulResults() && result.isOk() ) { if( result.getResultType() != ResultWas::Warning ) return false; printInfoMessages = false; } AssertionPrinter printer( stream, _assertionStats, printInfoMessages ); printer.print(); stream << std::endl; return true; } virtual void testRunEnded( TestRunStats const& _testRunStats ) { printTotals( _testRunStats.totals ); stream << "\n" << std::endl; StreamingReporterBase::testRunEnded( _testRunStats ); } private: class AssertionPrinter { void operator= ( AssertionPrinter const& ); public: AssertionPrinter( std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages ) : stream( _stream ) , stats( _stats ) , result( _stats.assertionResult ) , messages( _stats.infoMessages ) , itMessage( _stats.infoMessages.begin() ) , printInfoMessages( _printInfoMessages ) {} void print() { printSourceInfo(); itMessage = messages.begin(); switch( result.getResultType() ) { case ResultWas::Ok: printResultType( Colour::ResultSuccess, passedString() ); printOriginalExpression(); printReconstructedExpression(); if ( ! result.hasExpression() ) printRemainingMessages( Colour::None ); else printRemainingMessages(); break; case ResultWas::ExpressionFailed: if( result.isOk() ) printResultType( Colour::ResultSuccess, failedString() + std::string( " - but was ok" ) ); else printResultType( Colour::Error, failedString() ); printOriginalExpression(); printReconstructedExpression(); printRemainingMessages(); break; case ResultWas::ThrewException: printResultType( Colour::Error, failedString() ); printIssue( "unexpected exception with message:" ); printMessage(); printExpressionWas(); printRemainingMessages(); break; case ResultWas::FatalErrorCondition: printResultType( Colour::Error, failedString() ); printIssue( "fatal error condition with message:" ); printMessage(); printExpressionWas(); printRemainingMessages(); break; case ResultWas::DidntThrowException: printResultType( Colour::Error, failedString() ); printIssue( "expected exception, got none" ); printExpressionWas(); printRemainingMessages(); break; case ResultWas::Info: printResultType( Colour::None, "info" ); printMessage(); printRemainingMessages(); break; case ResultWas::Warning: printResultType( Colour::None, "warning" ); printMessage(); printRemainingMessages(); break; case ResultWas::ExplicitFailure: printResultType( Colour::Error, failedString() ); printIssue( "explicitly" ); printRemainingMessages( Colour::None ); break; // These cases are here to prevent compiler warnings case ResultWas::Unknown: case ResultWas::FailureBit: case ResultWas::Exception: printResultType( Colour::Error, "** internal error **" ); break; } } private: // Colour::LightGrey static Colour::Code dimColour() { return Colour::FileName; } #ifdef CATCH_PLATFORM_MAC static const char* failedString() { return "FAILED"; } static const char* passedString() { return "PASSED"; } #else static const char* failedString() { return "failed"; } static const char* passedString() { return "passed"; } #endif void printSourceInfo() const { Colour colourGuard( Colour::FileName ); stream << result.getSourceInfo() << ":"; } void printResultType( Colour::Code colour, std::string passOrFail ) const { if( !passOrFail.empty() ) { { Colour colourGuard( colour ); stream << " " << passOrFail; } stream << ":"; } } void printIssue( std::string issue ) const { stream << " " << issue; } void printExpressionWas() { if( result.hasExpression() ) { stream << ";"; { Colour colour( dimColour() ); stream << " expression was:"; } printOriginalExpression(); } } void printOriginalExpression() const { if( result.hasExpression() ) { stream << " " << result.getExpression(); } } void printReconstructedExpression() const { if( result.hasExpandedExpression() ) { { Colour colour( dimColour() ); stream << " for: "; } stream << result.getExpandedExpression(); } } void printMessage() { if ( itMessage != messages.end() ) { stream << " '" << itMessage->message << "'"; ++itMessage; } } void printRemainingMessages( Colour::Code colour = dimColour() ) { if ( itMessage == messages.end() ) return; // using messages.end() directly yields compilation error: std::vector<MessageInfo>::const_iterator itEnd = messages.end(); const std::size_t N = static_cast<std::size_t>( std::distance( itMessage, itEnd ) ); { Colour colourGuard( colour ); stream << " with " << pluralise( N, "message" ) << ":"; } for(; itMessage != itEnd; ) { // If this assertion is a warning ignore any INFO messages if( printInfoMessages || itMessage->type != ResultWas::Info ) { stream << " '" << itMessage->message << "'"; if ( ++itMessage != itEnd ) { Colour colourGuard( dimColour() ); stream << " and"; } } } } private: std::ostream& stream; AssertionStats const& stats; AssertionResult const& result; std::vector<MessageInfo> messages; std::vector<MessageInfo>::const_iterator itMessage; bool printInfoMessages; }; // Colour, message variants: // - white: No tests ran. // - red: Failed [both/all] N test cases, failed [both/all] M assertions. // - white: Passed [both/all] N test cases (no assertions). // - red: Failed N tests cases, failed M assertions. // - green: Passed [both/all] N tests cases with M assertions. std::string bothOrAll( std::size_t count ) const { return count == 1 ? "" : count == 2 ? "both " : "all " ; } void printTotals( const Totals& totals ) const { if( totals.testCases.total() == 0 ) { stream << "No tests ran."; } else if( totals.testCases.failed == totals.testCases.total() ) { Colour colour( Colour::ResultError ); const std::string qualify_assertions_failed = totals.assertions.failed == totals.assertions.total() ? bothOrAll( totals.assertions.failed ) : ""; stream << "Failed " << bothOrAll( totals.testCases.failed ) << pluralise( totals.testCases.failed, "test case" ) << ", " "failed " << qualify_assertions_failed << pluralise( totals.assertions.failed, "assertion" ) << "."; } else if( totals.assertions.total() == 0 ) { stream << "Passed " << bothOrAll( totals.testCases.total() ) << pluralise( totals.testCases.total(), "test case" ) << " (no assertions)."; } else if( totals.assertions.failed ) { Colour colour( Colour::ResultError ); stream << "Failed " << pluralise( totals.testCases.failed, "test case" ) << ", " "failed " << pluralise( totals.assertions.failed, "assertion" ) << "."; } else { Colour colour( Colour::ResultSuccess ); stream << "Passed " << bothOrAll( totals.testCases.passed ) << pluralise( totals.testCases.passed, "test case" ) << " with " << pluralise( totals.assertions.passed, "assertion" ) << "."; } } }; INTERNAL_CATCH_REGISTER_REPORTER( "compact", CompactReporter ) } // end namespace Catch namespace Catch { // These are all here to avoid warnings about not having any out of line // virtual methods NonCopyable::~NonCopyable() {} IShared::~IShared() {} IStream::~IStream() CATCH_NOEXCEPT {} FileStream::~FileStream() CATCH_NOEXCEPT {} CoutStream::~CoutStream() CATCH_NOEXCEPT {} DebugOutStream::~DebugOutStream() CATCH_NOEXCEPT {} StreamBufBase::~StreamBufBase() CATCH_NOEXCEPT {} IContext::~IContext() {} IResultCapture::~IResultCapture() {} ITestCase::~ITestCase() {} ITestCaseRegistry::~ITestCaseRegistry() {} IRegistryHub::~IRegistryHub() {} IMutableRegistryHub::~IMutableRegistryHub() {} IExceptionTranslator::~IExceptionTranslator() {} IExceptionTranslatorRegistry::~IExceptionTranslatorRegistry() {} IReporter::~IReporter() {} IReporterFactory::~IReporterFactory() {} IReporterRegistry::~IReporterRegistry() {} IStreamingReporter::~IStreamingReporter() {} AssertionStats::~AssertionStats() {} SectionStats::~SectionStats() {} TestCaseStats::~TestCaseStats() {} TestGroupStats::~TestGroupStats() {} TestRunStats::~TestRunStats() {} CumulativeReporterBase::SectionNode::~SectionNode() {} CumulativeReporterBase::~CumulativeReporterBase() {} StreamingReporterBase::~StreamingReporterBase() {} ConsoleReporter::~ConsoleReporter() {} CompactReporter::~CompactReporter() {} IRunner::~IRunner() {} IMutableContext::~IMutableContext() {} IConfig::~IConfig() {} XmlReporter::~XmlReporter() {} JunitReporter::~JunitReporter() {} TestRegistry::~TestRegistry() {} FreeFunctionTestCase::~FreeFunctionTestCase() {} IGeneratorInfo::~IGeneratorInfo() {} IGeneratorsForTest::~IGeneratorsForTest() {} WildcardPattern::~WildcardPattern() {} TestSpec::Pattern::~Pattern() {} TestSpec::NamePattern::~NamePattern() {} TestSpec::TagPattern::~TagPattern() {} TestSpec::ExcludedPattern::~ExcludedPattern() {} Matchers::Impl::StdString::Equals::~Equals() {} Matchers::Impl::StdString::Contains::~Contains() {} Matchers::Impl::StdString::StartsWith::~StartsWith() {} Matchers::Impl::StdString::EndsWith::~EndsWith() {} void Config::dummy() {} namespace TestCaseTracking { ITracker::~ITracker() {} TrackerBase::~TrackerBase() {} SectionTracker::~SectionTracker() {} IndexTracker::~IndexTracker() {} } } #ifdef __clang__ #pragma clang diagnostic pop #endif #endif #ifdef CATCH_CONFIG_MAIN // #included from: internal/catch_default_main.hpp #define TWOBLUECUBES_CATCH_DEFAULT_MAIN_HPP_INCLUDED #ifndef __OBJC__ // Standard C/C++ main entry point int main (int argc, char * argv[]) { return Catch::Session().run( argc, argv ); } #else // __OBJC__ // Objective-C entry point int main (int argc, char * const argv[]) { #if !CATCH_ARC_ENABLED NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; #endif Catch::registerTestMethods(); int result = Catch::Session().run( argc, (char* const*)argv ); #if !CATCH_ARC_ENABLED [pool drain]; #endif return result; } #endif // __OBJC__ #endif #ifdef CLARA_CONFIG_MAIN_NOT_DEFINED # undef CLARA_CONFIG_MAIN #endif ////// // If this config identifier is defined then all CATCH macros are prefixed with CATCH_ #ifdef CATCH_CONFIG_PREFIX_ALL #define CATCH_REQUIRE( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::Normal, "CATCH_REQUIRE" ) #define CATCH_REQUIRE_FALSE( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, "CATCH_REQUIRE_FALSE" ) #define CATCH_REQUIRE_THROWS( expr ) INTERNAL_CATCH_THROWS( expr, Catch::ResultDisposition::Normal, "", "CATCH_REQUIRE_THROWS" ) #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( expr, exceptionType, Catch::ResultDisposition::Normal, "CATCH_REQUIRE_THROWS_AS" ) #define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS( expr, Catch::ResultDisposition::Normal, matcher, "CATCH_REQUIRE_THROWS_WITH" ) #define CATCH_REQUIRE_NOTHROW( expr ) INTERNAL_CATCH_NO_THROW( expr, Catch::ResultDisposition::Normal, "CATCH_REQUIRE_NOTHROW" ) #define CATCH_CHECK( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::ContinueOnFailure, "CATCH_CHECK" ) #define CATCH_CHECK_FALSE( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, "CATCH_CHECK_FALSE" ) #define CATCH_CHECKED_IF( expr ) INTERNAL_CATCH_IF( expr, Catch::ResultDisposition::ContinueOnFailure, "CATCH_CHECKED_IF" ) #define CATCH_CHECKED_ELSE( expr ) INTERNAL_CATCH_ELSE( expr, Catch::ResultDisposition::ContinueOnFailure, "CATCH_CHECKED_ELSE" ) #define CATCH_CHECK_NOFAIL( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, "CATCH_CHECK_NOFAIL" ) #define CATCH_CHECK_THROWS( expr ) INTERNAL_CATCH_THROWS( expr, Catch::ResultDisposition::ContinueOnFailure, "CATCH_CHECK_THROWS" ) #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( expr, exceptionType, Catch::ResultDisposition::ContinueOnFailure, "CATCH_CHECK_THROWS_AS" ) #define CATCH_CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS( expr, Catch::ResultDisposition::ContinueOnFailure, matcher, "CATCH_CHECK_THROWS_WITH" ) #define CATCH_CHECK_NOTHROW( expr ) INTERNAL_CATCH_NO_THROW( expr, Catch::ResultDisposition::ContinueOnFailure, "CATCH_CHECK_NOTHROW" ) #define CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( arg, matcher, Catch::ResultDisposition::ContinueOnFailure, "CATCH_CHECK_THAT" ) #define CATCH_REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( arg, matcher, Catch::ResultDisposition::Normal, "CATCH_REQUIRE_THAT" ) #define CATCH_INFO( msg ) INTERNAL_CATCH_INFO( msg, "CATCH_INFO" ) #define CATCH_WARN( msg ) INTERNAL_CATCH_MSG( Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, "CATCH_WARN", msg ) #define CATCH_SCOPED_INFO( msg ) INTERNAL_CATCH_INFO( msg, "CATCH_INFO" ) #define CATCH_CAPTURE( msg ) INTERNAL_CATCH_INFO( #msg " := " << msg, "CATCH_CAPTURE" ) #define CATCH_SCOPED_CAPTURE( msg ) INTERNAL_CATCH_INFO( #msg " := " << msg, "CATCH_CAPTURE" ) #ifdef CATCH_CONFIG_VARIADIC_MACROS #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ ) #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ ) #define CATCH_METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ ) #define CATCH_REGISTER_TEST_CASE( ... ) INTERNAL_CATCH_REGISTER_TESTCASE( __VA_ARGS__ ) #define CATCH_SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ ) #define CATCH_FAIL( ... ) INTERNAL_CATCH_MSG( Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, "CATCH_FAIL", __VA_ARGS__ ) #define CATCH_SUCCEED( ... ) INTERNAL_CATCH_MSG( Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, "CATCH_SUCCEED", __VA_ARGS__ ) #else #define CATCH_TEST_CASE( name, description ) INTERNAL_CATCH_TESTCASE( name, description ) #define CATCH_TEST_CASE_METHOD( className, name, description ) INTERNAL_CATCH_TEST_CASE_METHOD( className, name, description ) #define CATCH_METHOD_AS_TEST_CASE( method, name, description ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, name, description ) #define CATCH_REGISTER_TEST_CASE( function, name, description ) INTERNAL_CATCH_REGISTER_TESTCASE( function, name, description ) #define CATCH_SECTION( name, description ) INTERNAL_CATCH_SECTION( name, description ) #define CATCH_FAIL( msg ) INTERNAL_CATCH_MSG( Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, "CATCH_FAIL", msg ) #define CATCH_SUCCEED( msg ) INTERNAL_CATCH_MSG( Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, "CATCH_SUCCEED", msg ) #endif #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE( "", "" ) #define CATCH_REGISTER_REPORTER( name, reporterType ) INTERNAL_CATCH_REGISTER_REPORTER( name, reporterType ) #define CATCH_REGISTER_LEGACY_REPORTER( name, reporterType ) INTERNAL_CATCH_REGISTER_LEGACY_REPORTER( name, reporterType ) #define CATCH_GENERATE( expr) INTERNAL_CATCH_GENERATE( expr ) // "BDD-style" convenience wrappers #ifdef CATCH_CONFIG_VARIADIC_MACROS #define CATCH_SCENARIO( ... ) CATCH_TEST_CASE( "Scenario: " __VA_ARGS__ ) #define CATCH_SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ ) #else #define CATCH_SCENARIO( name, tags ) CATCH_TEST_CASE( "Scenario: " name, tags ) #define CATCH_SCENARIO_METHOD( className, name, tags ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " name, tags ) #endif #define CATCH_GIVEN( desc ) CATCH_SECTION( std::string( "Given: ") + desc, "" ) #define CATCH_WHEN( desc ) CATCH_SECTION( std::string( " When: ") + desc, "" ) #define CATCH_AND_WHEN( desc ) CATCH_SECTION( std::string( " And: ") + desc, "" ) #define CATCH_THEN( desc ) CATCH_SECTION( std::string( " Then: ") + desc, "" ) #define CATCH_AND_THEN( desc ) CATCH_SECTION( std::string( " And: ") + desc, "" ) // If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required #else #define REQUIRE( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::Normal, "REQUIRE" ) #define REQUIRE_FALSE( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, "REQUIRE_FALSE" ) #define REQUIRE_THROWS( expr ) INTERNAL_CATCH_THROWS( expr, Catch::ResultDisposition::Normal, "", "REQUIRE_THROWS" ) #define REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( expr, exceptionType, Catch::ResultDisposition::Normal, "REQUIRE_THROWS_AS" ) #define REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS( expr, Catch::ResultDisposition::Normal, matcher, "REQUIRE_THROWS_WITH" ) #define REQUIRE_NOTHROW( expr ) INTERNAL_CATCH_NO_THROW( expr, Catch::ResultDisposition::Normal, "REQUIRE_NOTHROW" ) #define CHECK( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::ContinueOnFailure, "CHECK" ) #define CHECK_FALSE( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, "CHECK_FALSE" ) #define CHECKED_IF( expr ) INTERNAL_CATCH_IF( expr, Catch::ResultDisposition::ContinueOnFailure, "CHECKED_IF" ) #define CHECKED_ELSE( expr ) INTERNAL_CATCH_ELSE( expr, Catch::ResultDisposition::ContinueOnFailure, "CHECKED_ELSE" ) #define CHECK_NOFAIL( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, "CHECK_NOFAIL" ) #define CHECK_THROWS( expr ) INTERNAL_CATCH_THROWS( expr, Catch::ResultDisposition::ContinueOnFailure, "", "CHECK_THROWS" ) #define CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( expr, exceptionType, Catch::ResultDisposition::ContinueOnFailure, "CHECK_THROWS_AS" ) #define CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS( expr, Catch::ResultDisposition::ContinueOnFailure, matcher, "CHECK_THROWS_WITH" ) #define CHECK_NOTHROW( expr ) INTERNAL_CATCH_NO_THROW( expr, Catch::ResultDisposition::ContinueOnFailure, "CHECK_NOTHROW" ) #define CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( arg, matcher, Catch::ResultDisposition::ContinueOnFailure, "CHECK_THAT" ) #define REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( arg, matcher, Catch::ResultDisposition::Normal, "REQUIRE_THAT" ) #define INFO( msg ) INTERNAL_CATCH_INFO( msg, "INFO" ) #define WARN( msg ) INTERNAL_CATCH_MSG( Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, "WARN", msg ) #define SCOPED_INFO( msg ) INTERNAL_CATCH_INFO( msg, "INFO" ) #define CAPTURE( msg ) INTERNAL_CATCH_INFO( #msg " := " << msg, "CAPTURE" ) #define SCOPED_CAPTURE( msg ) INTERNAL_CATCH_INFO( #msg " := " << msg, "CAPTURE" ) #ifdef CATCH_CONFIG_VARIADIC_MACROS #define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ ) #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ ) #define METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ ) #define REGISTER_TEST_CASE( ... ) INTERNAL_CATCH_REGISTER_TESTCASE( __VA_ARGS__ ) #define SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ ) #define FAIL( ... ) INTERNAL_CATCH_MSG( Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, "FAIL", __VA_ARGS__ ) #define SUCCEED( ... ) INTERNAL_CATCH_MSG( Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, "SUCCEED", __VA_ARGS__ ) #else #define TEST_CASE( name, description ) INTERNAL_CATCH_TESTCASE( name, description ) #define TEST_CASE_METHOD( className, name, description ) INTERNAL_CATCH_TEST_CASE_METHOD( className, name, description ) #define METHOD_AS_TEST_CASE( method, name, description ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, name, description ) #define REGISTER_TEST_CASE( method, name, description ) INTERNAL_CATCH_REGISTER_TESTCASE( method, name, description ) #define SECTION( name, description ) INTERNAL_CATCH_SECTION( name, description ) #define FAIL( msg ) INTERNAL_CATCH_MSG( Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, "FAIL", msg ) #define SUCCEED( msg ) INTERNAL_CATCH_MSG( Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, "SUCCEED", msg ) #endif #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE( "", "" ) #define REGISTER_REPORTER( name, reporterType ) INTERNAL_CATCH_REGISTER_REPORTER( name, reporterType ) #define REGISTER_LEGACY_REPORTER( name, reporterType ) INTERNAL_CATCH_REGISTER_LEGACY_REPORTER( name, reporterType ) #define GENERATE( expr) INTERNAL_CATCH_GENERATE( expr ) #endif #define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature ) // "BDD-style" convenience wrappers #ifdef CATCH_CONFIG_VARIADIC_MACROS #define SCENARIO( ... ) TEST_CASE( "Scenario: " __VA_ARGS__ ) #define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ ) #else #define SCENARIO( name, tags ) TEST_CASE( "Scenario: " name, tags ) #define SCENARIO_METHOD( className, name, tags ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " name, tags ) #endif #define GIVEN( desc ) SECTION( std::string(" Given: ") + desc, "" ) #define WHEN( desc ) SECTION( std::string(" When: ") + desc, "" ) #define AND_WHEN( desc ) SECTION( std::string("And when: ") + desc, "" ) #define THEN( desc ) SECTION( std::string(" Then: ") + desc, "" ) #define AND_THEN( desc ) SECTION( std::string(" And: ") + desc, "" ) using Catch::Detail::Approx; #endif // TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED
[ "dennis.demidov@gmail.com" ]
dennis.demidov@gmail.com
c1ad8bdc1efa4e28fdc06e470cdeb35b1897f1f7
d0c44dd3da2ef8c0ff835982a437946cbf4d2940
/cmake-build-debug/programs_tiling/function13875/function13875_schedule_21/function13875_schedule_21_wrapper.cpp
c97b45521a54e2c74f055b4cd977b6cfb43bf1bc
[]
no_license
IsraMekki/tiramisu_code_generator
8b3f1d63cff62ba9f5242c019058d5a3119184a3
5a259d8e244af452e5301126683fa4320c2047a3
refs/heads/master
2020-04-29T17:27:57.987172
2019-04-23T16:50:32
2019-04-23T16:50:32
176,297,755
1
2
null
null
null
null
UTF-8
C++
false
false
923
cpp
#include "Halide.h" #include "function13875_schedule_21_wrapper.h" #include "tiramisu/utils.h" #include <cstdlib> #include <iostream> #include <time.h> #include <fstream> #include <chrono> #define MAX_RAND 200 int main(int, char **){ Halide::Buffer<int32_t> buf00(512); Halide::Buffer<int32_t> buf0(512, 512, 128); init_buffer(buf0, (int32_t)0); auto t1 = std::chrono::high_resolution_clock::now(); function13875_schedule_21(buf00.raw_buffer(), buf0.raw_buffer()); auto t2 = std::chrono::high_resolution_clock::now(); std::chrono::duration<double> diff = t2 - t1; std::ofstream exec_times_file; exec_times_file.open("../data/programs/function13875/function13875_schedule_21/exec_times.txt", std::ios_base::app); if (exec_times_file.is_open()){ exec_times_file << diff.count() * 1000000 << "us" <<std::endl; exec_times_file.close(); } return 0; }
[ "ei_mekki@esi.dz" ]
ei_mekki@esi.dz
1aff252b749b1d4eab762cb4f1ff79108197c171
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/curl/gumtree/curl_repos_function_713_curl-7.51.0.cpp
52da5e9b5e58e385ba073a080fed4c8b84e95809
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,027
cpp
static curl_socket_t sockdaemon(curl_socket_t sock, unsigned short *listenport) { /* passive daemon style */ srvr_sockaddr_union_t listener; int flag; int rc; int totdelay = 0; int maxretr = 10; int delay= 20; int attempt = 0; int error = 0; do { attempt++; flag = 1; rc = setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void *)&flag, sizeof(flag)); if(rc) { error = SOCKERRNO; logmsg("setsockopt(SO_REUSEADDR) failed with error: (%d) %s", error, strerror(error)); if(maxretr) { rc = wait_ms(delay); if(rc) { /* should not happen */ error = errno; logmsg("wait_ms() failed with error: (%d) %s", error, strerror(error)); sclose(sock); return CURL_SOCKET_BAD; } if(got_exit_signal) { logmsg("signalled to die, exiting..."); sclose(sock); return CURL_SOCKET_BAD; } totdelay += delay; delay *= 2; /* double the sleep for next attempt */ } } } while(rc && maxretr--); if(rc) { logmsg("setsockopt(SO_REUSEADDR) failed %d times in %d ms. Error: (%d) %s", attempt, totdelay, error, strerror(error)); logmsg("Continuing anyway..."); } /* When the specified listener port is zero, it is actually a request to let the system choose a non-zero available port. */ #ifdef ENABLE_IPV6 if(!use_ipv6) { #endif memset(&listener.sa4, 0, sizeof(listener.sa4)); listener.sa4.sin_family = AF_INET; listener.sa4.sin_addr.s_addr = INADDR_ANY; listener.sa4.sin_port = htons(*listenport); rc = bind(sock, &listener.sa, sizeof(listener.sa4)); #ifdef ENABLE_IPV6 } else { memset(&listener.sa6, 0, sizeof(listener.sa6)); listener.sa6.sin6_family = AF_INET6; listener.sa6.sin6_addr = in6addr_any; listener.sa6.sin6_port = htons(*listenport); rc = bind(sock, &listener.sa, sizeof(listener.sa6)); } #endif /* ENABLE_IPV6 */ if(rc) { error = SOCKERRNO; logmsg("Error binding socket on port %hu: (%d) %s", *listenport, error, strerror(error)); sclose(sock); return CURL_SOCKET_BAD; } if(!*listenport) { /* The system was supposed to choose a port number, figure out which port we actually got and update the listener port value with it. */ curl_socklen_t la_size; srvr_sockaddr_union_t localaddr; #ifdef ENABLE_IPV6 if(!use_ipv6) #endif la_size = sizeof(localaddr.sa4); #ifdef ENABLE_IPV6 else la_size = sizeof(localaddr.sa6); #endif memset(&localaddr.sa, 0, (size_t)la_size); if(getsockname(sock, &localaddr.sa, &la_size) < 0) { error = SOCKERRNO; logmsg("getsockname() failed with error: (%d) %s", error, strerror(error)); sclose(sock); return CURL_SOCKET_BAD; } switch (localaddr.sa.sa_family) { case AF_INET: *listenport = ntohs(localaddr.sa4.sin_port); break; #ifdef ENABLE_IPV6 case AF_INET6: *listenport = ntohs(localaddr.sa6.sin6_port); break; #endif default: break; } if(!*listenport) { /* Real failure, listener port shall not be zero beyond this point. */ logmsg("Apparently getsockname() succeeded, with listener port zero."); logmsg("A valid reason for this failure is a binary built without"); logmsg("proper network library linkage. This might not be the only"); logmsg("reason, but double check it before anything else."); sclose(sock); return CURL_SOCKET_BAD; } } /* bindonly option forces no listening */ if(bind_only) { logmsg("instructed to bind port without listening"); return sock; } /* start accepting connections */ rc = listen(sock, 5); if(0 != rc) { error = SOCKERRNO; logmsg("listen(%d, 5) failed with error: (%d) %s", sock, error, strerror(error)); sclose(sock); return CURL_SOCKET_BAD; } return sock; }
[ "993273596@qq.com" ]
993273596@qq.com
51812d9591d17639d5d03182ad9882ea25452f49
7c5a19a71b5bb42808c1483994c133aab3116318
/include/HttpParse.h
dbbcf8866698436e7e4cda62763982db9a294314
[ "MIT" ]
permissive
wcyy0123/WebServer
c7bb798e43622b7013288f21ded2066e8c0fa89e
02ff8a5d59bd3d2de2db73776e57950a97a07bed
refs/heads/master
2023-05-26T21:32:29.091811
2021-03-28T10:36:47
2021-03-28T10:36:47
null
0
0
null
null
null
null
GB18030
C++
false
false
2,007
h
/******************************************************** *@file 封装HttpParse类 *@Author rongweihe *@Data 2019/04/18 *********************************************************/ #ifndef HTTPPARSE_H_INCLUDED #define HTTPPARSE_H_INCLUDED #include <unordered_map> #include <string> #include <iostream> const char CR = '\r' ; const char LF = '\n'; const char LINE_END = '\0'; #define PASS class HttpRequest; std::ostream &operator<<(std::ostream &, const HttpRequest &); class HttpRequestParser { public: //行的读取状态:读取到一个完整的行、行出错和行数据暂且不完整 enum LINE_STATE { LINE_OK=0, LINE_BAD, LINE_MORE }; //解析状态 enum PARSE_STATE { PARSE_REQUESTLINE = 0, PARSE_HEADER, PARSE_BODY }; //服务器处理 HTTP 请求的可能结果 enum HTTP_CODE { NO_REQUEST,/*NO_REQUEST表示请求不完整,需要读取客户数据*/ GET_REQUEST,/*GET_REQUEST表示获得了一个完整的客户请求*/ BAD_REQUEST,/*BAD_REQUEST表示客户请求有语法错误*/ FORBIDDEN_REQUEST,/*表示客户对资源没有足够的访问权限*/ INTERNAL_ERROR,/*表示服务器内部错误*/ CLOSED_CONNECTION/*表示客户端已经关闭连接*/ }; //从状态机,用于解析一行内容 static LINE_STATE parse_line(char *buffer, int &checked_index, int &read_index); //分析请求行 static HTTP_CODE parse_requestline(char *line, PARSE_STATE &parse_state, HttpRequest &request); //分析头部 static HTTP_CODE parse_headers(char *line, PARSE_STATE &parse_state, HttpRequest &request); static HTTP_CODE parse_body(char *body, HttpRequest &request); //分析HTTP请求的入口函数 static HTTP_CODE parse_content(char *buffer, int &check_index, int &read_index, PARSE_STATE &parse_state, int &start_line, HttpRequest &request); }; #endif // HTTPPARSE_H_INCLUDED
[ "rongweihe1995@gmail.com" ]
rongweihe1995@gmail.com
2fdbb8a5b78f88616a27e6e3a4319c4ef9d32ad2
dc03d332fe55e5147e80212bfb3787566bd4c1c2
/codes/Calculator/Calculator/Calculator.h
1d78f41ad714cdd4b5f1dab29fc5fe69f17e428a
[]
no_license
CiCixP/cici
47b79af598b44a03dcb92f6da78fc726eeb45dff
a094ba181964cbef6822259d34f5525e6698fa67
refs/heads/master
2021-01-01T15:54:01.526907
2017-08-17T15:06:17
2017-08-17T15:06:17
97,727,892
0
0
null
null
null
null
UTF-8
C++
false
false
288
h
#ifndef Calculator_h #define Calculator_h #include <iostream> #include <sstream> #include <stdio.h> #include <string> using namespace std; class calculate { public: calculate(); ~calculate(); double expression(); double factor(); double term(); }; #endif /* Calculator_h */
[ "cici.pham@inl.gov" ]
cici.pham@inl.gov
5f6a34ffaddbd9f1ea08a90108005cfaed65d1c2
26ba18f15532023552cf9523feb84a317b47beb0
/JUCE/modules/juce_audio_devices/juce_audio_devices.h
6a3b056438064609b53d9c9895039149e3cd1cd1
[ "GPL-1.0-or-later", "GPL-3.0-only", "ISC", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-proprietary-license", "MIT" ]
permissive
Ultraschall/ultraschall-soundboard
d3fdaf92061f9eacc65351b7b4bc937311f9e7fc
8a7a538831d8dbf7689b47611d218560762ae869
refs/heads/main
2021-12-14T20:19:24.170519
2021-03-17T22:34:11
2021-03-17T22:34:11
27,304,678
27
3
MIT
2021-02-16T20:49:08
2014-11-29T14:36:19
C++
UTF-8
C++
false
false
5,963
h
/* ============================================================================== This file is part of the JUCE library. Copyright (c) 2020 - Raw Material Software Limited JUCE is an open source library subject to commercial or open-source licensing. The code included in this file is provided under the terms of the ISC license http://www.isc.org/downloads/software-support-policy/isc-license. Permission To use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted provided that the above copyright notice and this permission notice appear in all copies. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE DISCLAIMED. ============================================================================== */ /******************************************************************************* The block below describes the properties of this module, and is read by the Projucer to automatically generate project code that uses it. For details about the syntax and how to create or use a module, see the JUCE Module Format.md file. BEGIN_JUCE_MODULE_DECLARATION ID: juce_audio_devices vendor: juce version: 6.0.7 name: JUCE audio and MIDI I/O device classes description: Classes to play and record from audio and MIDI I/O devices website: http://www.juce.com/juce license: ISC dependencies: juce_audio_basics, juce_events OSXFrameworks: CoreAudio CoreMIDI AudioToolbox iOSFrameworks: CoreAudio CoreMIDI AudioToolbox AVFoundation linuxPackages: alsa mingwLibs: winmm END_JUCE_MODULE_DECLARATION *******************************************************************************/ #pragma once #define JUCE_AUDIO_DEVICES_H_INCLUDED #include <juce_events/juce_events.h> #include <juce_audio_basics/juce_audio_basics.h> #if JUCE_MODULE_AVAILABLE_juce_graphics #include <juce_graphics/juce_graphics.h> #endif //============================================================================== /** Config: JUCE_USE_WINRT_MIDI Enables the use of the Windows Runtime API for MIDI, allowing connections to Bluetooth Low Energy devices on Windows 10 version 1809 (October 2018 Update) and later. If you enable this flag then older versions of Windows will automatically fall back to using the regular Win32 MIDI API. You will need version 10.0.14393.0 of the Windows Standalone SDK to compile and you may need to add the path to the WinRT headers. The path to the headers will be something similar to "C:\Program Files (x86)\Windows Kits\10\Include\10.0.14393.0\winrt". */ #ifndef JUCE_USE_WINRT_MIDI #define JUCE_USE_WINRT_MIDI 0 #endif /** Config: JUCE_ASIO Enables ASIO audio devices (MS Windows only). Turning this on means that you'll need to have the Steinberg ASIO SDK installed on your Windows build machine. See the comments in the ASIOAudioIODevice class's header file for more info about this. */ #ifndef JUCE_ASIO #define JUCE_ASIO 0 #endif /** Config: JUCE_WASAPI Enables WASAPI audio devices (Windows Vista and above). */ #ifndef JUCE_WASAPI #define JUCE_WASAPI 1 #endif /** Config: JUCE_DIRECTSOUND Enables DirectSound audio (MS Windows only). */ #ifndef JUCE_DIRECTSOUND #define JUCE_DIRECTSOUND 1 #endif /** Config: JUCE_ALSA Enables ALSA audio devices (Linux only). */ #ifndef JUCE_ALSA #define JUCE_ALSA 1 #endif /** Config: JUCE_JACK Enables JACK audio devices (Linux only). */ #ifndef JUCE_JACK #define JUCE_JACK 0 #endif /** Config: JUCE_BELA Enables Bela audio devices on Bela boards. */ #ifndef JUCE_BELA #define JUCE_BELA 0 #endif /** Config: JUCE_USE_ANDROID_OBOE Enables Oboe devices (Android only, API 16 or above). */ #ifndef JUCE_USE_ANDROID_OBOE #define JUCE_USE_ANDROID_OBOE 1 #endif #if JUCE_USE_ANDROID_OBOE && JUCE_ANDROID_API_VERSION < 16 #undef JUCE_USE_ANDROID_OBOE #define JUCE_USE_ANDROID_OBOE 0 #endif /** Config: JUCE_USE_OBOE_STABILIZED_CALLBACK If JUCE_USE_ANDROID_OBOE is enabled, enabling this will wrap output audio streams in the oboe::StabilizedCallback class. This class attempts to keep the CPU spinning to avoid it being scaled down on certain devices. */ #ifndef JUCE_USE_ANDROID_OBOE_STABILIZED_CALLBACK #define JUCE_USE_ANDROID_OBOE_STABILIZED_CALLBACK 0 #endif /** Config: JUCE_USE_ANDROID_OPENSLES Enables OpenSLES devices (Android only). */ #ifndef JUCE_USE_ANDROID_OPENSLES #if ! JUCE_USE_ANDROID_OBOE && JUCE_ANDROID_API_VERSION >= 9 #define JUCE_USE_ANDROID_OPENSLES 1 #else #define JUCE_USE_ANDROID_OPENSLES 0 #endif #endif /** Config: JUCE_DISABLE_AUDIO_MIXING_WITH_OTHER_APPS Turning this on gives your app exclusive access to the system's audio on platforms which support it (currently iOS only). */ #ifndef JUCE_DISABLE_AUDIO_MIXING_WITH_OTHER_APPS #define JUCE_DISABLE_AUDIO_MIXING_WITH_OTHER_APPS 0 #endif //============================================================================== #include "midi_io/juce_MidiDevices.h" #include "midi_io/juce_MidiMessageCollector.h" namespace juce { /** Available modes for the WASAPI audio device. Pass one of these to the AudioIODeviceType::createAudioIODeviceType_WASAPI() method to create a WASAPI AudioIODeviceType object in this mode. */ enum class WASAPIDeviceMode { shared, exclusive, sharedLowLatency }; } #include "audio_io/juce_AudioIODevice.h" #include "audio_io/juce_AudioIODeviceType.h" #include "audio_io/juce_SystemAudioVolume.h" #include "sources/juce_AudioSourcePlayer.h" #include "sources/juce_AudioTransportSource.h" #include "audio_io/juce_AudioDeviceManager.h" #if JUCE_IOS #include "native/juce_ios_Audio.h" #endif
[ "daniel@lindenfelser.de" ]
daniel@lindenfelser.de
baccbb243e62cf16db81fdaaf93f5575b0871b9f
6b8dce01f9df91077385f93eeb7136604944f1b4
/data/tmp/LinkingTools/linkingtools.h
8cabf5331b4b1ef8ce0155faa038a74400c15184
[]
no_license
twister9893/home
617f869426723a51033882f3ce65682376d8b77b
931ca73c150c546cffc1bf90d696c3484b909050
refs/heads/master
2021-01-21T04:59:53.595803
2016-06-14T11:12:01
2016-06-14T11:12:01
51,158,227
0
0
null
null
null
null
UTF-8
C++
false
false
466
h
#ifndef LINKINGTOOLS_H #define LINKINGTOOLS_H #include <QThread> #include "formulareditor.h" #include "ui_linkingtools.h" class LinkingTools : public QDialog, private Ui::LinkingTools { Q_OBJECT public: explicit LinkingTools(QWidget *parent = 0); public slots: void slot_openFormularEditor(); private: void loadModules(); FormularEditor *m_formularEditor; }; #endif // LINKINGTOOLS_H
[ "twister9893@gmail.com" ]
twister9893@gmail.com
2c4996d8e8dc310a8456f37c90282449cad1226f
d8efaf8e35f7d203d50cb4f87bc7313187d9f6e1
/build/Android/Preview/MyFirstFuseProject/app/src/main/include/Uno.Graphics.VertexAttributeTypeHelpers.h
28f6038f16f6a3764b985a300885303d83d4e624
[]
no_license
eddzmaciel/fproject_fp
fe33dc03b82047e88fad9e82959ee92d6da49025
2760ddb66c749651f163c3c1a3bc7b6820fbebae
refs/heads/master
2020-12-04T12:38:37.955298
2016-09-02T02:23:31
2016-09-02T02:23:31
67,182,558
0
0
null
null
null
null
UTF-8
C++
false
false
651
h
// This file was generated based on C:\ProgramData\Uno\Packages\UnoCore\0.33.1\Source\Uno\Graphics\$.uno. // WARNING: Changes might be lost if you edit this file directly. #pragma once #include <Uno.h> namespace g{namespace Uno{namespace Graphics{struct VertexAttributeTypeHelpers;}}} namespace g{ namespace Uno{ namespace Graphics{ // public static class VertexAttributeTypeHelpers :1591 // { uClassType* VertexAttributeTypeHelpers_typeof(); void VertexAttributeTypeHelpers__GetStrideInBytes_fn(int* type, int* __retval); struct VertexAttributeTypeHelpers : uObject { static int GetStrideInBytes(int type); }; // } }}} // ::g::Uno::Graphics
[ "Edson Maciel" ]
Edson Maciel
0e0c4c70998de62c9771899253c062750089db8e
670cc962162aad7d92f6d9d0721dc41a65209de1
/Strategy y Template method (ej navegador)/src/Malo.cpp
d21b352a94cdce7ea6b6c35f7128944a3c668ffe
[]
no_license
Zarakinoa/Design-Patterns
1d133764ae9b16fb8fecb1c000be533741dccbac
e141146b15d22f09aa670815b9a2c16dbb0c8257
refs/heads/master
2022-02-19T04:02:13.075807
2019-09-25T03:42:33
2019-09-25T03:42:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
186
cpp
#include "Malo.h" Malo::Malo() { //ctor } Malo::~Malo() { //dtor } string Malo::bajarDatos(string url){ return "<Datos de la pagina (con calidad MALA) de " + url + ">"; }
[ "mathias2b@gmail.com" ]
mathias2b@gmail.com
ecc2cabc6095e09a71714327d1ac9f0c9ab93cc1
ca0e7bcfed6672931e5d0ff549de3e4f525142f8
/android-emu/android/base/StringView.h
a6d9a611eba198beb77c9b125cb43c6d1620d366
[ "Apache-2.0" ]
permissive
xiaohua2018/goldfishOpengl
070686de9ab178cf2e37325245a8eca0497a0f65
03aafeef950afd4375d8158dab6fd4fa7206169c
refs/heads/master
2023-06-28T15:55:34.567184
2021-08-04T20:23:55
2021-08-04T20:23:55
392,877,526
0
0
NOASSERTION
2021-08-05T02:37:17
2021-08-05T02:19:43
C++
UTF-8
C++
false
false
10,151
h
// Copyright 2014 The Android Open Source Project // // 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. #pragma once #include "android/base/Optional.h" #include "android/base/TypeTraits.h" #include <algorithm> #include <cstring> #include <string> namespace android { namespace base { // A StringView is a simple (address, size) pair that points to an // existing read-only string. It's a convenience class used to prevent // the creation of std::string() objects un-necessarily. // // Consider the two following functions: // // size_t count1(const std::string& str) { // size_t count = 0; // for (size_t n = 0; n < str.size(); ++n) { // if (str[n] == '1') { // count++; // } // } // return count; // } // // size_t count2(const StringView& str) { // size_t count = 0; // for (size_t n = 0; n < str.size(); ++n) { // if (str[n] == '2') { // count++; // } // } // return count; // } // // Then consider the following calls: // // size_t n1 = count1("There is 1 one in this string!"); // size_t n2 = count2("I can count 2 too"); // // In the first case, the compiler will silently create a temporary // std::string object, copy the input string into it (allocating memory in // the heap), call count1() and destroy the std::string upon its return. // // In the second case, the compiler will create a temporary StringView, // initialize it trivially before calling count2(), this results in // much less generated code, as well as better performance. // // Generally speaking, always use a reference or pointer to StringView // instead of a std::string if your function or method doesn't need to modify // its input. // class StringView { public: constexpr StringView() : mString(""), mSize(0U) {} constexpr StringView(const StringView& other) : mString(other.data()), mSize(other.size()) {} // IMPORTANT: all StringView constructors are intentionally not explict // it is needed to allow seamless creation of StringView from all types // of strings around - as it's intended to be a generic string wrapper // A constexpr constructor from a constant buffer, initializing |mSize| // as well. This allows one to declare a static const StringView instance // and initialize it at compile time, with no runtime overhead: // // static constexpr StringView message = "blah"; // template <size_t size> constexpr StringView(const char (&buf)[size]) : mString(buf), mSize(size - 1) {} // Ctor for non-const arrays, AKA buffers. These usually contain some // string formatted at runtime, so call strlen() instead of using the // buffer size. template <size_t size> constexpr StringView(char (&buf)[size]) : mString(buf), mSize(strlen(buf)) {} // Constructor from a const char pointer. It has to be templated to make // sure the array-based one is chosen for an array - otherwise non-templated // overload always wins // Note: the parameter type is a const reference to a const pointer. This // is to make this overload a poorer choice for the case of an array. For // the 'const char[]' argument both 'reference to an array' and 'pointer' // overloads are tied, so compiler can't choose without help // Note2: for all constructors and set() calls, |end| must be // dereferencable. It is notrequired to be '\0', but there has to be some // data there. One may not construct a StringView passing past-the-end // iterator as |end|! StringView will try to dereference it. template <class Char, class = enable_if<std::is_same<Char, char>>> constexpr StringView(const Char* const & string) : mString(string ? string : ""), mSize(string ? strlen(string) : 0) {} StringView(const std::string& str) : mString(str.c_str()), mSize(str.size()) {} constexpr StringView(const char* str, size_t len) : mString(str ? str : ""), mSize(len) {} constexpr StringView(const char* begin, const char* end) : mString(begin ? begin : ""), mSize(begin ? end - begin : 0) {} constexpr StringView(std::nullptr_t) : mString(""), mSize(0) {} std::string str() const { return std::string(mString, mString + mSize); } constexpr const char* data() const { return mString; } constexpr size_t size() const { return mSize; } typedef const char* iterator; typedef const char* const_iterator; constexpr const_iterator begin() const { return mString; } constexpr const_iterator end() const { return mString + mSize; } constexpr bool empty() const { return !size(); } constexpr bool isNullTerminated() const { return *end() == '\0'; } void clear() { mSize = 0; mString = ""; } constexpr char operator[](size_t index) const { return mString[index]; } void set(const char* data, size_t len) { mString = data ? data : ""; mSize = len; } void set(const char* str) { mString = str ? str : ""; mSize = ::strlen(mString); } void set(const StringView& other) { mString = other.mString; mSize = other.mSize; } // Compare with another StringView. int compare(const StringView& other) const; StringView& operator=(const StringView& other) { set(other); return *this; } // find() first occurrence of |other| with an initial offset. // Returns absolute offset (does not include |off|). size_t find(StringView other, size_t off = 0) { // Trivial case if (!other.mSize) return 0; size_t safeOff = std::min(off, mSize); const char* searchStart = mString + safeOff; const char* searchEnd = searchStart + mSize - safeOff; const char* res = std::search(searchStart, searchEnd, other.mString, other.mString + other.mSize); if (res == searchEnd) return std::string::npos; return (size_t)((uintptr_t)res - (uintptr_t)mString); } // getSubstr(); returns this string starting at the first place |other| // occurs, otherwise a blank string. StringView getSubstr(StringView other, size_t off = 0) { size_t loc = find(other, off); if (loc == std::string::npos) return StringView(""); return { mString + loc, end() }; } // Returns substring starting at |begin| and running for |len|, // or the rest of the string if |len| is std::string::npos. StringView substr(size_t begin, size_t len = std::string::npos) { if (len == std::string::npos) { len = mSize - begin; } size_t safeOff = std::min(begin, mSize); size_t safeLen = std::min(len, mSize - safeOff); return { mString + safeOff, safeLen }; } // Returns substring starting at |begin| ending at |end|, // or the rest of the string if |end is std::string::npos. StringView substrAbs(size_t begin, size_t end = std::string::npos) { if (end == std::string::npos) { end = begin + mSize; } return substr(begin, end - begin); } // Convert to std::string when needed. operator std::string() const { return std::string(mString, mSize); } private: const char* mString; size_t mSize; }; // Comparison operators. Defined as functions to allow automatic type // conversions with C strings and std::string objects. bool operator==(const StringView& x, const StringView& y); inline bool operator!=(const StringView& x, const StringView& y) { return !(x == y); } inline bool operator<(const StringView& x, const StringView& y) { return x.compare(y) < 0; } inline bool operator>=(const StringView& x, const StringView& y) { return !(x < y); } inline bool operator >(const StringView& x, const StringView& y) { return x.compare(y) > 0; } inline bool operator<=(const StringView& x, const StringView& y) { return !(x > y); } // Helper to get a null-terminated const char* from a string view. // Only allocates if the StringView is not null terminated. // // Usage: // // StringView myString = ...; // printf("Contents: %s\n", c_str(myString)); // // c_str(...) constructs a temporary object that may allocate memory if the // StringView is not null termianted. The lifetime of the temporary object will // be until the next sequence point (typically the next semicolon). If the // value needs to exist for longer than that, cache the instance. // // StringView myString = ...; // auto myNullTerminatedString = c_str(myString); // functionAcceptingConstCharPointer(myNullTerminatedString); // class CStrWrapper { public: CStrWrapper(StringView stringView) : mStringView(stringView) {} // Returns a null-terminated char*, potentially creating a copy to add a // null terminator. const char* get() { if (mStringView.isNullTerminated()) { return mStringView.data(); } else { // Create the std::string copy on-demand. if (!mStringCopy) { mStringCopy.emplace(mStringView.str()); } return mStringCopy->c_str(); } } // Enable casting to const char* operator const char*() { return get(); } private: const StringView mStringView; Optional<std::string> mStringCopy; }; inline CStrWrapper c_str(StringView stringView) { return CStrWrapper(stringView); } } // namespace base } // namespace android
[ "lfy@google.com" ]
lfy@google.com
f34dd0cc83be1941ccdbe73b6dec927787d2b2ae
92185e24e4de9eea41f34d9e40abeb3bc32214c5
/Addins/OpenDDS/forwardrateagreementDataReaderListenerImpl.hpp
0ddec631e03879ed57c5190e9592e3aaefa87e69
[]
no_license
hakiri/qldds
f349b85a59222a27d01bcfc26f2749b8442be952
af053553c493564473b2d871905919390dc73aea
refs/heads/master
2021-01-10T11:01:04.077762
2014-01-19T17:47:58
2014-01-19T17:47:58
49,442,005
0
0
null
null
null
null
UTF-8
C++
false
false
3,655
hpp
/* Copyright (C) 2013 Mike Kipnis This file is part of QLDDS, a free-software/open-source library for utilization of QuantLib in the distributed envrionment via DDS. QLDDS is free software: you can redistribute it and/or modify it under the terms of the QLDDS license. You should have received a copy of the license along with this program; if not, please email <dev@qldds.org>. The license is also available online at <http://qldds.org/qldds-license/>. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the license for more details. */ // This file was generated automatically by qldds_gensrc.py. If you edit this file // manually then your changes will be lost the next time gensrc runs. // This source code file was generated from the following stub: // Users/mkipnis/Dev/qldds/gensrc/stubs/stub.opendds.header #include <qlo/qladdindefines.hpp> #include <qlo/handle.hpp> #include <qlo/forwardrateagreement.hpp> #include <qlo/indexes/iborindex.hpp> #include <qlo/yieldtermstructures.hpp> #include <ql/indexes/iborindex.hpp> #include <qlo/valueobjects/vo_forwardrateagreement.hpp> #include <qlo/conversions/all.hpp> #include <oh/property.hpp> #if defined(_MSC_VER) || defined(_WIN32) #include <Addins/Cpp/forwardrateagreement.hpp> #else #include <qlo/Addins/Cpp/forwardrateagreement.hpp> #endif #include "forwardrateagreementTypeSupportC.h" #include <DataReaderListener.hpp> namespace forwardrateagreement { class qlFRADataReaderListenerImpl : public virtual OpenDDS::DCPS::LocalObject<qldds::DataReaderListener< forwardrateagreement::qlFRA, std::string > > { public: qlFRADataReaderListenerImpl( ACE_Mutex& mutex ) : _mutex( mutex ) {}; virtual void on_data_available( DDS::DataReader_ptr reader) throw (CORBA::SystemException); ACE_Mutex& get_ACE_Mutex() { return _mutex; }; virtual void on_requested_deadline_missed ( DDS::DataReader_ptr reader, const DDS::RequestedDeadlineMissedStatus & status) throw (CORBA::SystemException); virtual void on_requested_incompatible_qos ( DDS::DataReader_ptr reader, const DDS::RequestedIncompatibleQosStatus & status) throw (CORBA::SystemException); virtual void on_liveliness_changed ( DDS::DataReader_ptr reader, const DDS::LivelinessChangedStatus & status) throw (CORBA::SystemException); virtual void on_subscription_matched ( DDS::DataReader_ptr reader, const DDS::SubscriptionMatchedStatus & status) throw (CORBA::SystemException); virtual void on_sample_rejected( DDS::DataReader_ptr reader, const DDS::SampleRejectedStatus& status) throw (CORBA::SystemException); virtual void on_sample_lost( DDS::DataReader_ptr reader, const DDS::SampleLostStatus& status) throw (CORBA::SystemException); virtual void on_reading_start( DDS::DataReader_ptr reader ); virtual void on_reading_end( DDS::DataReader_ptr reader, int count ); virtual bool pre_quantlib_addin_call( DDS::DataReader_ptr reader, DDS::SampleInfo&, forwardrateagreement::qlFRA& ); virtual bool post_quantlib_addin_call( DDS::DataReader_ptr reader, forwardrateagreement::qlFRA&, std::string& ); virtual void on_std_exception( DDS::DataReader_ptr reader, forwardrateagreement::qlFRA&, std::exception& e ); virtual void on_dds_reading_error( DDS::DataReader_ptr reader, std::string& err ); virtual void on_dds_exception( DDS::DataReader_ptr reader, CORBA::Exception& exp ); protected: ACE_Mutex& _mutex; }; ; }
[ "mkipnis@Mike-Kipniss-Mac-Pro.local" ]
mkipnis@Mike-Kipniss-Mac-Pro.local