hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
81d99cbe8d4a731f81c7b6a84f788f537ab9d98f
1,120
cc
C++
cpp/solutions/006/solution.cc
StephanBischoff-Digle/dcp
5e0914386ceee5c1aa94a1b2deb8264c7c8bcc3e
[ "Unlicense" ]
null
null
null
cpp/solutions/006/solution.cc
StephanBischoff-Digle/dcp
5e0914386ceee5c1aa94a1b2deb8264c7c8bcc3e
[ "Unlicense" ]
null
null
null
cpp/solutions/006/solution.cc
StephanBischoff-Digle/dcp
5e0914386ceee5c1aa94a1b2deb8264c7c8bcc3e
[ "Unlicense" ]
null
null
null
#include "solution.h" xor_linked_list::xor_linked_list() : memory_(3), size_{0} {} void xor_linked_list::add(std::int32_t value) { if (size_ == 0) { memory_[0] = {0, value}; size_++; return; } // resize internam memory if necessary if (size_ == memory_.size() - 1) { memory_.resize(2 * size_); } // find last std::size_t idx = 0; std::size_t prev = 0; std::size_t next; while ((next = memory_[idx].nxp ^ prev) != 0) { prev = idx; idx = next; } // "allocate memory" memory_[idx + 1] = {idx ^ 0, value}; memory_[idx].nxp = prev ^ (idx + 1); size_++; } std::optional<std::int32_t> xor_linked_list::get(std::size_t target) { if (target >= size_) { return {}; } if (target == 0) { return memory_[0].value; } std::size_t idx = 0; std::size_t prev = 0; std::size_t next; while ((next = memory_[idx].nxp ^ prev) != 0) { prev = idx; idx = next; if (idx == target) { return {memory_[idx].value}; } } return {}; }
20.740741
70
0.507143
StephanBischoff-Digle
81d9ba16900de52ad218827748fd86f2150626a6
639
cpp
C++
src/Expression.cpp
bmarchon/LG_H4311
8a52272a19c13726b8a72b84147d7be27784deb3
[ "Apache-2.0" ]
null
null
null
src/Expression.cpp
bmarchon/LG_H4311
8a52272a19c13726b8a72b84147d7be27784deb3
[ "Apache-2.0" ]
null
null
null
src/Expression.cpp
bmarchon/LG_H4311
8a52272a19c13726b8a72b84147d7be27784deb3
[ "Apache-2.0" ]
null
null
null
#include "Expression.h" Expression::Expression(Expressions typeExp, Symboles type):Symbole(type) { this->typeExp=typeExp; expression = NULL; } Expression::Expression():Symbole(type) { expression = NULL; } Expressions Expression::getExprType() { return this->typeExp; } Expression::~Expression() { //dtor } void Expression::afficher() { cout << "error : call to Expression::afficher()" << endl; } Expression * Expression::getExpression() { return this->expression; } void Expression::setExpression(Expression *expr) { this->expression=expr; } string Expression::afficherExprType() { return exprTypes[this->typeExp]; }
14.860465
72
0.716745
bmarchon
81db734bbc9a6e0f76a87b7a0e2ed2c2ee3ee09e
5,248
hxx
C++
opencascade/GeomInt_ParFunctionOfMyGradientOfTheComputeLineBezierOfWLApprox.hxx
valgur/OCP
2f7d9da73a08e4ffe80883614aedacb27351134f
[ "Apache-2.0" ]
117
2020-03-07T12:07:05.000Z
2022-03-27T07:35:22.000Z
opencascade/GeomInt_ParFunctionOfMyGradientOfTheComputeLineBezierOfWLApprox.hxx
CadQuery/cpp-py-bindgen
66e7376d3a27444393fc99acbdbef40bbc7031ae
[ "Apache-2.0" ]
66
2019-12-20T16:07:36.000Z
2022-03-15T21:56:10.000Z
opencascade/GeomInt_ParFunctionOfMyGradientOfTheComputeLineBezierOfWLApprox.hxx
CadQuery/cpp-py-bindgen
66e7376d3a27444393fc99acbdbef40bbc7031ae
[ "Apache-2.0" ]
76
2020-03-16T01:47:46.000Z
2022-03-21T16:37:07.000Z
// Created on: 1995-01-27 // Created by: Jacques GOUSSARD // Copyright (c) 1995-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _GeomInt_ParFunctionOfMyGradientOfTheComputeLineBezierOfWLApprox_HeaderFile #define _GeomInt_ParFunctionOfMyGradientOfTheComputeLineBezierOfWLApprox_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <Standard_Handle.hxx> #include <Standard_Boolean.hxx> #include <GeomInt_TheMultiLineOfWLApprox.hxx> #include <AppParCurves_MultiCurve.hxx> #include <Standard_Integer.hxx> #include <math_Vector.hxx> #include <Standard_Real.hxx> #include <math_Matrix.hxx> #include <GeomInt_ParLeastSquareOfMyGradientOfTheComputeLineBezierOfWLApprox.hxx> #include <TColStd_HArray1OfInteger.hxx> #include <AppParCurves_HArray1OfConstraintCouple.hxx> #include <math_MultipleVarFunctionWithGradient.hxx> #include <AppParCurves_Constraint.hxx> class GeomInt_TheMultiLineOfWLApprox; class GeomInt_TheMultiLineToolOfWLApprox; class GeomInt_ParLeastSquareOfMyGradientOfTheComputeLineBezierOfWLApprox; class GeomInt_ResConstraintOfMyGradientOfTheComputeLineBezierOfWLApprox; class AppParCurves_MultiCurve; class GeomInt_ParFunctionOfMyGradientOfTheComputeLineBezierOfWLApprox : public math_MultipleVarFunctionWithGradient { public: DEFINE_STANDARD_ALLOC //! initializes the fields of the function. The approximating //! curve has the desired degree Deg. Standard_EXPORT GeomInt_ParFunctionOfMyGradientOfTheComputeLineBezierOfWLApprox(const GeomInt_TheMultiLineOfWLApprox& SSP, const Standard_Integer FirstPoint, const Standard_Integer LastPoint, const Handle(AppParCurves_HArray1OfConstraintCouple)& TheConstraints, const math_Vector& Parameters, const Standard_Integer Deg); //! returns the number of variables of the function. It //! corresponds to the number of MultiPoints. Standard_EXPORT Standard_Integer NbVariables() const; //! this method computes the new approximation of the //! MultiLine //! SSP and calculates F = sum (||Pui - Bi*Pi||2) for each //! point of the MultiLine. Standard_EXPORT Standard_Boolean Value (const math_Vector& X, Standard_Real& F); //! returns the gradient G of the sum above for the //! parameters Xi. Standard_EXPORT Standard_Boolean Gradient (const math_Vector& X, math_Vector& G); //! returns the value F=sum(||Pui - Bi*Pi||)2. //! returns the value G = grad(F) for the parameters Xi. Standard_EXPORT Standard_Boolean Values (const math_Vector& X, Standard_Real& F, math_Vector& G); //! returns the new parameters of the MultiLine. Standard_EXPORT const math_Vector& NewParameters() const; //! returns the MultiCurve approximating the set after //! computing the value F or Grad(F). Standard_EXPORT const AppParCurves_MultiCurve& CurveValue(); //! returns the distance between the MultiPoint of range //! IPoint and the curve CurveIndex. Standard_EXPORT Standard_Real Error (const Standard_Integer IPoint, const Standard_Integer CurveIndex) const; //! returns the maximum distance between the points //! and the MultiCurve. Standard_EXPORT Standard_Real MaxError3d() const; //! returns the maximum distance between the points //! and the MultiCurve. Standard_EXPORT Standard_Real MaxError2d() const; Standard_EXPORT AppParCurves_Constraint FirstConstraint (const Handle(AppParCurves_HArray1OfConstraintCouple)& TheConstraints, const Standard_Integer FirstPoint) const; Standard_EXPORT AppParCurves_Constraint LastConstraint (const Handle(AppParCurves_HArray1OfConstraintCouple)& TheConstraints, const Standard_Integer LastPoint) const; protected: //! this method is used each time Value or Gradient is //! needed. Standard_EXPORT void Perform (const math_Vector& X); private: Standard_Boolean Done; GeomInt_TheMultiLineOfWLApprox MyMultiLine; AppParCurves_MultiCurve MyMultiCurve; Standard_Integer Degre; math_Vector myParameters; Standard_Real FVal; math_Vector ValGrad_F; math_Matrix MyF; math_Matrix PTLX; math_Matrix PTLY; math_Matrix PTLZ; math_Matrix A; math_Matrix DA; GeomInt_ParLeastSquareOfMyGradientOfTheComputeLineBezierOfWLApprox MyLeastSquare; Standard_Boolean Contraintes; Standard_Integer NbP; Standard_Integer NbCu; Standard_Integer Adeb; Standard_Integer Afin; Handle(TColStd_HArray1OfInteger) tabdim; Standard_Real ERR3d; Standard_Real ERR2d; Standard_Integer FirstP; Standard_Integer LastP; Handle(AppParCurves_HArray1OfConstraintCouple) myConstraints; }; #endif // _GeomInt_ParFunctionOfMyGradientOfTheComputeLineBezierOfWLApprox_HeaderFile
35.221477
323
0.804878
valgur
81dc1a3053519a1289dd6bd3195f14443e2fbc58
9,754
cpp
C++
NOLF/ClientShellDLL/BodyFX.cpp
haekb/nolf1-modernizer
25bac3d43c40a83b8e90201a70a14ef63b4240e7
[ "Unlicense" ]
38
2019-09-16T14:46:42.000Z
2022-03-10T20:28:10.000Z
NOLF/ClientShellDLL/BodyFX.cpp
haekb/nolf1-modernizer
25bac3d43c40a83b8e90201a70a14ef63b4240e7
[ "Unlicense" ]
39
2019-08-12T01:35:33.000Z
2022-02-28T16:48:16.000Z
NOLF/ClientShellDLL/BodyFX.cpp
haekb/nolf1-modernizer
25bac3d43c40a83b8e90201a70a14ef63b4240e7
[ "Unlicense" ]
6
2019-09-17T12:49:18.000Z
2022-03-10T20:28:12.000Z
// ----------------------------------------------------------------------- // // // MODULE : BodyFX.cpp // // PURPOSE : Body special FX - Implementation // // CREATED : 8/24/98 // // (c) 1998-1999 Monolith Productions, Inc. All Rights Reserved // // ----------------------------------------------------------------------- // #include "stdafx.h" #include "BodyFX.h" #include "GameClientShell.h" #include "SFXMsgIds.h" #include "ClientUtilities.h" #include "SoundMgr.h" #include "BaseScaleFX.h" #include "SurfaceFunctions.h" extern CGameClientShell* g_pGameClientShell; extern VarTrack g_vtBigHeadMode; // ----------------------------------------------------------------------- // // // ROUTINE: CBodyFX::CBodyFX() // // PURPOSE: Constructor // // ----------------------------------------------------------------------- // CBodyFX::CBodyFX() { m_fFaderTime = 3.0f; m_fFaderTimer = 3.0f; m_hMarker = LTNULL; m_bHasNodeControl = LTFALSE; } // ----------------------------------------------------------------------- // // // ROUTINE: CBodyFX::~CBodyFX() // // PURPOSE: Destructor // // ----------------------------------------------------------------------- // CBodyFX::~CBodyFX() { RemoveMarker(); if ( m_hServerObject ) { g_pModelLT->RemoveTracker(m_hServerObject, &m_TwitchTracker); } } // ----------------------------------------------------------------------- // // // ROUTINE: CBodyFX::Init // // PURPOSE: Init the Body fx // // ----------------------------------------------------------------------- // LTBOOL CBodyFX::Init(HLOCALOBJ hServObj, HMESSAGEREAD hMessage) { if (!CSpecialFX::Init(hServObj, hMessage)) return LTFALSE; if (!hMessage) return LTFALSE; BODYCREATESTRUCT bcs; bcs.hServerObj = hServObj; bcs.Read(g_pLTClient, hMessage); return Init(&bcs); } // ----------------------------------------------------------------------- // // // ROUTINE: CBodyFX::Init // // PURPOSE: Init the Body fx // // ----------------------------------------------------------------------- // LTBOOL CBodyFX::Init(SFXCREATESTRUCT* psfxCreateStruct) { if (!CSpecialFX::Init(psfxCreateStruct)) return LTFALSE; m_bs = *((BODYCREATESTRUCT*)psfxCreateStruct); g_pModelLT->AddTracker(m_bs.hServerObj, &m_TwitchTracker); return LTTRUE; } // ----------------------------------------------------------------------- // // // ROUTINE: CBodyFX::CreateObject // // PURPOSE: Create the various fx // // ----------------------------------------------------------------------- // LTBOOL CBodyFX::CreateObject(ILTClient* pClientDE) { if (!CSpecialFX::CreateObject(pClientDE) || !m_hServerObject) return LTFALSE; uint32 dwCFlags = m_pClientDE->GetObjectClientFlags(m_hServerObject); m_pClientDE->SetObjectClientFlags(m_hServerObject, dwCFlags | CF_NOTIFYMODELKEYS | CF_INSIDERADIUS); // uint32 dwCFlags = m_pClientDE->GetObjectClientFlags(m_hServerObject); // m_pClientDE->SetObjectClientFlags(m_hServerObject, dwCFlags | CF_NOTIFYMODELKEYS); return LTTRUE; } // ----------------------------------------------------------------------- // // // ROUTINE: CBodyFX::Update // // PURPOSE: Update the fx // // ----------------------------------------------------------------------- // LTBOOL CBodyFX::Update() { if (!m_pClientDE || !m_hServerObject || m_bWantRemove) return LTFALSE; // Only register/deregister once if (!m_bHasNodeControl && g_vtBigHeadMode.GetFloat()) { m_bHasNodeControl = LTTRUE; g_pLTClient->ModelNodeControl(m_hServerObject, CBodyFX::HandleBigHeadModeFn, this); } else if(m_bHasNodeControl && !g_vtBigHeadMode.GetFloat()) { m_bHasNodeControl = LTFALSE; g_pLTClient->ModelNodeControl(m_hServerObject, LTNULL, LTNULL); } switch ( m_bs.eBodyState ) { case eBodyStateFade: UpdateFade(); break; } if (g_pGameClientShell->GetGameType() != SINGLE && m_bs.nClientId != (uint8)-1) { UpdateMarker(); } return LTTRUE; } // ----------------------------------------------------------------------- // // // ROUTINE: CBodyFX::UpdateFade // // PURPOSE: Update the fx // // ----------------------------------------------------------------------- // void CBodyFX::UpdateFade() { HLOCALOBJ attachList[20]; uint32 dwListSize = 0; uint32 dwNumAttach = 0; g_pLTClient->GetAttachments(m_hServerObject, attachList, 20, &dwListSize, &dwNumAttach); int nNum = dwNumAttach <= dwListSize ? dwNumAttach : dwListSize; m_fFaderTime = Max<LTFLOAT>(0.0f, m_fFaderTime - g_pGameClientShell->GetFrameTime()); g_pLTClient->SetObjectColor(m_hServerObject, 1, 1, 1, m_fFaderTime/m_fFaderTimer); for (int i=0; i < nNum; i++) { g_pLTClient->SetObjectColor(attachList[i], 1, 1, 1, m_fFaderTime/m_fFaderTimer); } } // ----------------------------------------------------------------------- // // // ROUTINE: CBodyFX::OnServerMessage // // PURPOSE: Handle any messages from our server object... // // ----------------------------------------------------------------------- // LTBOOL CBodyFX::OnServerMessage(HMESSAGEREAD hMessage) { if (!CSpecialFX::OnServerMessage(hMessage)) return LTFALSE; uint8 nMsgId = g_pLTClient->ReadFromMessageByte(hMessage); switch(nMsgId) { case BFX_FADE_MSG: { m_bs.eBodyState = eBodyStateFade; } break; } return LTTRUE; } LTBOOL GroundFilterFn(HOBJECT hObj, void *pUserData) { return ( IsMainWorld(hObj) || (OT_WORLDMODEL == g_pLTClient->GetObjectType(hObj)) ); } void CBodyFX::OnModelKey(HLOCALOBJ hObj, ArgList *pArgs) { if (!m_hServerObject || !hObj || !pArgs || !pArgs->argv || pArgs->argc == 0) return; char* pKey = pArgs->argv[0]; if (!pKey) return; LTBOOL bSlump = !_stricmp(pKey, "NOISE"); LTBOOL bLand = !_stricmp(pKey, "LAND"); if ( bSlump || bLand ) { LTVector vPos; g_pLTClient->GetObjectPos(m_hServerObject, &vPos); IntersectQuery IQuery; IntersectInfo IInfo; IQuery.m_From = vPos; IQuery.m_To = vPos - LTVector(0,96,0); IQuery.m_Flags = INTERSECT_OBJECTS | INTERSECT_HPOLY | IGNORE_NONSOLID; IQuery.m_FilterFn = GroundFilterFn; SurfaceType eSurface; if (g_pLTClient->IntersectSegment(&IQuery, &IInfo)) { if (IInfo.m_hPoly && IInfo.m_hPoly != INVALID_HPOLY) { eSurface = (SurfaceType)GetSurfaceType(IInfo.m_hPoly); } else if (IInfo.m_hObject) // Get the texture flags from the object... { eSurface = (SurfaceType)GetSurfaceType(IInfo.m_hObject); } else { return; } } else { return; } // Play the noise SURFACE* pSurf = g_pSurfaceMgr->GetSurface(eSurface); _ASSERT(pSurf); if (!pSurf) return; if (bSlump && pSurf->szBodyFallSnd[0]) { g_pClientSoundMgr->PlaySoundFromPos(vPos, pSurf->szBodyFallSnd, pSurf->fBodyFallSndRadius, SOUNDPRIORITY_MISC_LOW); } else if (bLand && pSurf->szBodyLedgeFallSnd[0]) { g_pClientSoundMgr->PlaySoundFromPos(vPos, pSurf->szBodyLedgeFallSnd, pSurf->fBodyLedgeFallSndRadius, SOUNDPRIORITY_MISC_LOW); } } } // ----------------------------------------------------------------------- // // // ROUTINE: CBodyFX::UpdateMarker // // PURPOSE: Update the marker fx // // ----------------------------------------------------------------------- // void CBodyFX::UpdateMarker() { if (!m_pClientDE || !m_hServerObject) return; CClientInfoMgr *pClientMgr = g_pInterfaceMgr->GetClientInfoMgr(); if (!pClientMgr) return; CLIENT_INFO* pLocalInfo = pClientMgr->GetLocalClient(); CLIENT_INFO* pInfo = pClientMgr->GetClientByID(m_bs.nClientId); if (!pInfo || !pLocalInfo) return; LTBOOL bSame = (pInfo->team == pLocalInfo->team); if (bSame) { if (m_hMarker) RemoveMarker(); return; } uint32 dwFlags = g_pLTClient->GetObjectFlags(m_hServerObject); if (!(dwFlags & FLAG_VISIBLE)) { RemoveMarker(); return; } LTVector vU, vR, vF, vTemp, vDims, vPos; LTRotation rRot; ILTPhysics* pPhysics = m_pClientDE->Physics(); m_pClientDE->GetObjectPos(m_hServerObject, &vPos); pPhysics->GetObjectDims(m_hServerObject, &vDims); vPos.y += (vDims.y + 20.0f); if (!m_hMarker) { CreateMarker(vPos,bSame); } if (m_hMarker) { m_pClientDE->SetObjectPos(m_hMarker, &vPos); } } // ----------------------------------------------------------------------- // // // ROUTINE: CBodyFX::CreateMarker // // PURPOSE: Create marker special fx // // ----------------------------------------------------------------------- // void CBodyFX::CreateMarker(LTVector & vPos, LTBOOL bSame) { if (!m_pClientDE || !g_pGameClientShell || !m_hServerObject) return; if (!bSame) return; ObjectCreateStruct createStruct; INIT_OBJECTCREATESTRUCT(createStruct); CString str = g_pClientButeMgr->GetSpecialFXAttributeString("TeamSprite"); LTFLOAT fScaleMult = g_pClientButeMgr->GetSpecialFXAttributeFloat("TeamScale"); LTFLOAT fAlpha = g_pClientButeMgr->GetSpecialFXAttributeFloat("TeamAlpha"); LTVector vScale(1.0f,1.0f,1.0f); VEC_MULSCALAR(vScale, vScale, fScaleMult); SAFE_STRCPY(createStruct.m_Filename, (char *)(LPCSTR)str); createStruct.m_ObjectType = OT_SPRITE; createStruct.m_Flags = FLAG_VISIBLE | FLAG_FOGDISABLE | FLAG_NOLIGHT; createStruct.m_Pos = vPos; m_hMarker = m_pClientDE->CreateObject(&createStruct); if (!m_hMarker) return; m_pClientDE->SetObjectScale(m_hMarker, &vScale); LTFLOAT r, g, b, a; m_pClientDE->GetObjectColor(m_hServerObject, &r, &g, &b, &a); m_pClientDE->SetObjectColor(m_hObject, r, g, b, (fAlpha * a)); } // ----------------------------------------------------------------------- // // // ROUTINE: CBodyFX::RemoveMarker // // PURPOSE: Remove the marker fx // // ----------------------------------------------------------------------- // void CBodyFX::RemoveMarker() { if (!m_hMarker) return; g_pLTClient->DeleteObject(m_hMarker); m_hMarker = LTNULL; }
24.693671
128
0.574841
haekb
81dc81bbfec0415572e5d7334486fcc66220c540
1,584
cpp
C++
IfcPlusPlus/src/ifcpp/IFC4/lib/IfcPositiveRatioMeasure.cpp
shelltdf/ifcplusplus
120ef686c4002c1cc77e3808fe00b8653cfcabd7
[ "MIT" ]
null
null
null
IfcPlusPlus/src/ifcpp/IFC4/lib/IfcPositiveRatioMeasure.cpp
shelltdf/ifcplusplus
120ef686c4002c1cc77e3808fe00b8653cfcabd7
[ "MIT" ]
null
null
null
IfcPlusPlus/src/ifcpp/IFC4/lib/IfcPositiveRatioMeasure.cpp
shelltdf/ifcplusplus
120ef686c4002c1cc77e3808fe00b8653cfcabd7
[ "MIT" ]
1
2021-04-26T14:56:09.000Z
2021-04-26T14:56:09.000Z
/* Code generated by IfcQuery EXPRESS generator, www.ifcquery.com */ #include <sstream> #include <limits> #include <map> #include "ifcpp/reader/ReaderUtil.h" #include "ifcpp/writer/WriterUtil.h" #include "ifcpp/model/BasicTypes.h" #include "ifcpp/model/BuildingException.h" #include "ifcpp/IFC4/include/IfcMeasureValue.h" #include "ifcpp/IFC4/include/IfcSizeSelect.h" #include "ifcpp/IFC4/include/IfcPositiveRatioMeasure.h" // TYPE IfcPositiveRatioMeasure = IfcRatioMeasure; shared_ptr<BuildingObject> IfcPositiveRatioMeasure::getDeepCopy( BuildingCopyOptions& options ) { shared_ptr<IfcPositiveRatioMeasure> copy_self( new IfcPositiveRatioMeasure() ); copy_self->m_value = m_value; return copy_self; } void IfcPositiveRatioMeasure::getStepParameter( std::stringstream& stream, bool is_select_type ) const { if( is_select_type ) { stream << "IFCPOSITIVERATIOMEASURE("; } stream << m_value; if( is_select_type ) { stream << ")"; } } const std::wstring IfcPositiveRatioMeasure::toString() const { std::wstringstream strs; strs << m_value; return strs.str(); } shared_ptr<IfcPositiveRatioMeasure> IfcPositiveRatioMeasure::createObjectFromSTEP( const std::wstring& arg, const std::map<int,shared_ptr<BuildingEntity> >& map ) { if( arg.compare( L"$" ) == 0 ) { return shared_ptr<IfcPositiveRatioMeasure>(); } if( arg.compare( L"*" ) == 0 ) { return shared_ptr<IfcPositiveRatioMeasure>(); } shared_ptr<IfcPositiveRatioMeasure> type_object( new IfcPositiveRatioMeasure() ); readReal( arg, type_object->m_value ); return type_object; }
38.634146
163
0.748106
shelltdf
81dd0fc1dac78844220e9e9d309f26e5fb3b6c78
6,750
cpp
C++
Source/AllProjects/Tests2/TestEvents/TestEvents_Scheduled.cpp
MarkStega/CQC
c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07
[ "MIT" ]
51
2020-12-26T18:17:16.000Z
2022-03-15T04:29:35.000Z
Source/AllProjects/Tests2/TestEvents/TestEvents_Scheduled.cpp
MarkStega/CQC
c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07
[ "MIT" ]
null
null
null
Source/AllProjects/Tests2/TestEvents/TestEvents_Scheduled.cpp
MarkStega/CQC
c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07
[ "MIT" ]
4
2020-12-28T07:24:39.000Z
2021-12-29T12:09:37.000Z
// // FILE NAME: TestEvents_Scheduled.cpp // // AUTHOR: Dean Roddey // // CREATED: 09/21/2009 // // COPYRIGHT: Charmed Quark Systems, Ltd @ 2020 // // This software is copyrighted by 'Charmed Quark Systems, Ltd' and // the author (Dean Roddey.) It is licensed under the MIT Open Source // license: // // https://opensource.org/licenses/MIT // // DESCRIPTION: // // This file implements the tests for the scheduled events. // // CAVEATS/GOTCHAS: // // LOG: // // $Log$ // // --------------------------------------------------------------------------- // Include underlying headers // --------------------------------------------------------------------------- #include "TestEvents.hpp" // --------------------------------------------------------------------------- // Magic macros // --------------------------------------------------------------------------- RTTIDecls(TTest_Scheduled1,TTestFWTest) // --------------------------------------------------------------------------- // Local types and constants // --------------------------------------------------------------------------- namespace TestEvents_Scheduled { // Some faux lat/long values const tCIDLib::TFloat8 f8Lat = 37.3; const tCIDLib::TFloat8 f8Long = -121.88; } // --------------------------------------------------------------------------- // CLASS: TTest_BasicActVar // PREFIX: tfwt // --------------------------------------------------------------------------- // --------------------------------------------------------------------------- // TTest_Scheduled1: Constructor and Destructor // --------------------------------------------------------------------------- TTest_Scheduled1::TTest_Scheduled1() : TTestFWTest ( L"Scheduled Events 1", L"Basic tests of scheduled events", 3 ) { } TTest_Scheduled1::~TTest_Scheduled1() { } // --------------------------------------------------------------------------- // TTest_Scheduled1: Public, inherited methods // --------------------------------------------------------------------------- tTestFWLib::ETestRes TTest_Scheduled1::eRunTest( TTextStringOutStream& strmOut , tCIDLib::TBoolean& bWarning) { tTestFWLib::ETestRes eRes = tTestFWLib::ETestRes::Success; tCIDLib::TCard4 c4Hour; tCIDLib::TCard4 c4Millis; tCIDLib::TCard4 c4Min; tCIDLib::TCard4 c4Sec; tCIDLib::TCard4 c4Year; tCIDLib::EMonths eMonth; tCIDLib::TCard4 c4Day; // Do a basic one shot test { tCIDLib::TEncodedTime enctAt(TTime::enctNowPlusMins(2)); TCQCSchEvent csrcOneShot(L"Test one shot"); csrcOneShot.SetOneShot(enctAt); if (!csrcOneShot.bIsOneShot()) { strmOut << TFWCurLn << L"Event did not come back as one shot\n\n"; eRes = tTestFWLib::ETestRes::Failed; } if (!bCheckInfo(strmOut, TFWCurLn, csrcOneShot, tCQCKit::ESchTypes::Once, enctAt)) eRes = tTestFWLib::ETestRes::Failed; // Calculating the next time should do nothing CalcNext(csrcOneShot); if (!bCheckInfo(strmOut, TFWCurLn, csrcOneShot, tCQCKit::ESchTypes::Once, enctAt)) eRes = tTestFWLib::ETestRes::Failed; } // Do a daily one { // Set the start time to now tCIDLib::TEncodedTime enctStartAt = TTime::enctNow(); TCQCSchEvent csrcDaily(L"Daily event"); csrcDaily.SetScheduled ( tCQCKit::ESchTypes::Daily , 0 , 13 , 30 , 0 , enctStartAt ); // The initial starting time is now, so if the hour/minute is past // the one we set, then it should run today, else it will be tomorrow. // TTime tmNext(enctStartAt); tCIDLib::TEncodedTime enctTmp; tmNext.eExpandDetails ( c4Year , eMonth , c4Day , c4Hour , c4Min , c4Sec , c4Millis , enctTmp ); tmNext.FromDetails(c4Year, eMonth, c4Day, 13, 30); if ((c4Hour > 13) || (c4Hour == 13) && (c4Min > 30)) { // // It should run tomorrow. Note that this isn't the best way // to do this, since if we hit a day where there's a leap // minute or something, it could fail. But not too much risk // in reality. // tmNext += kCIDLib::enctOneDay; } if (!bCheckInfo(strmOut, TFWCurLn, csrcDaily, tCQCKit::ESchTypes::Daily, tmNext.enctTime())) eRes = tTestFWLib::ETestRes::Failed; } // Do a weekly one { // Set the start time to now tCIDLib::TEncodedTime enctStartAt = TTime::enctNow(); TCQCSchEvent csrcWeekly(L"Weekly event"); csrcWeekly.SetScheduled ( tCQCKit::ESchTypes::Weekly , 0 , 10 , 30 , 0x7F , enctStartAt ); } return eRes; } // --------------------------------------------------------------------------- // TTest_Scheduled1: Private, non-virtual methods // --------------------------------------------------------------------------- tCIDLib::TBoolean TTest_Scheduled1::bCheckInfo( TTextStringOutStream& strmOut , const TTFWCurLn& tfwclAt , const TCQCSchEvent& csrcToCheck , const tCQCKit::ESchTypes eType , const tCIDLib::TEncodedTime enctNext) { if (csrcToCheck.eType() != eType) { strmOut << tfwclAt << L"Wrong schedule type\n\n"; return kCIDLib::False; } // // Currently all times are rounded down to the previous minute, so // the actual value the caller set and passed in won't match. // // Probably we should just stop doing that and let them stagger out // through the minute to avoid peak activity. So, for now we just // round it here, so that it can be removed easily if we stop this // rounding. // tCIDLib::TEncodedTime enctActual = enctNext / kCIDLib::enctOneMinute; enctActual *= kCIDLib::enctOneMinute; if (csrcToCheck.enctAt() != enctActual) { strmOut << tfwclAt << L"Wrong next scheduled time\n\n"; return kCIDLib::False; } return kCIDLib::True; } // // Calculate the next time for the passed event, using the faux lat/long // positions. // tCIDLib::TVoid TTest_Scheduled1::CalcNext(TCQCSchEvent& csrcTar) { csrcTar.CalcNextTime(TestEvents_Scheduled::f8Lat, TestEvents_Scheduled::f8Long); }
29.220779
100
0.491259
MarkStega
81de4c19a335e3ca7d86cd3105998e654e0319f7
2,406
cpp
C++
Passes/Misc/ReanimatorPass.cpp
vorpal-research/borealis
247ca1bb26690e2d605ffc57785151e86dccd5bb
[ "MIT" ]
null
null
null
Passes/Misc/ReanimatorPass.cpp
vorpal-research/borealis
247ca1bb26690e2d605ffc57785151e86dccd5bb
[ "MIT" ]
null
null
null
Passes/Misc/ReanimatorPass.cpp
vorpal-research/borealis
247ca1bb26690e2d605ffc57785151e86dccd5bb
[ "MIT" ]
1
2019-09-02T12:56:27.000Z
2019-09-02T12:56:27.000Z
// // Created by ice-phoenix on 5/27/15. // #include <llvm/Pass.h> #include "Passes/Defect/DefectManager.h" #include "Passes/PredicateStateAnalysis/PredicateStateAnalysis.h" #include "Passes/Tracker/SlotTrackerPass.h" #include "Reanimator/Reanimator.h" #include "State/Transformer/AggregateTransformer.h" #include "State/Transformer/ArrayBoundsCollector.h" #include "State/Transformer/TermCollector.h" #include "Util/passes.hpp" #include "Util/macros.h" namespace borealis { class ReanimatorPass : public llvm::ModulePass, public borealis::logging::ClassLevelLogging<ReanimatorPass> { public: static char ID; ReanimatorPass() : llvm::ModulePass(ID) {}; virtual bool runOnModule(llvm::Module&) override { auto&& DM = GetAnalysis<DefectManager>::doit(this); auto&& STP = GetAnalysis<SlotTrackerPass>::doit(this); for (auto&& di : DM.getData()) { auto&& adi = DM.getAdditionalInfo(di); if (not adi.satModel) continue; auto&& PSA = GetAnalysis<PredicateStateAnalysis>::doit(this, *adi.atFunc); auto&& ps = PSA.getInstructionState(adi.atInst); auto&& FN = FactoryNest(adi.atFunc->getDataLayout(), STP.getSlotTracker(adi.atFunc)); auto&& TC = TermCollector<>(FN); auto&& AC = ArrayBoundsCollector(FN); (TC + AC).transform(ps); auto&& reanim = Reanimator(adi.satModel.getUnsafe(), AC.getArrayBounds()); auto&& dbg = dbgs(); dbg << ps << endl; dbg << adi.satModel << endl; dbg << reanim.getArrayBoundsMap() << endl; for (auto&& v : util::viewContainer(TC.getTerms()) .filter(APPLY(llvm::is_one_of<ArgumentTerm, ValueTerm>))) { dbg << raise(reanim, v); } } return false; } virtual void getAnalysisUsage(llvm::AnalysisUsage& AU) const override { AU.setPreservesAll(); AUX<DefectManager>::addRequiredTransitive(AU); AUX<SlotTrackerPass>::addRequiredTransitive(AU); AUX<PredicateStateAnalysis>::addRequiredTransitive(AU); } virtual ~ReanimatorPass() = default; }; char ReanimatorPass::ID; static RegisterPass<ReanimatorPass> X("reanimator", "Pass that reanimates `variables` at defect sites"); } // namespace borealis #include "Util/unmacros.h"
28.987952
97
0.63591
vorpal-research
81de8f9990a206bc30adfd35bddc9388d5ec7fdf
601
hpp
C++
include/extractor/guidance/turn_lane_augmentation.hpp
peterkist-tinker/osrm-backend-appveyor-test
1891d7379c1d524ea6dc5a8d95e93f4023481a07
[ "BSD-2-Clause" ]
null
null
null
include/extractor/guidance/turn_lane_augmentation.hpp
peterkist-tinker/osrm-backend-appveyor-test
1891d7379c1d524ea6dc5a8d95e93f4023481a07
[ "BSD-2-Clause" ]
null
null
null
include/extractor/guidance/turn_lane_augmentation.hpp
peterkist-tinker/osrm-backend-appveyor-test
1891d7379c1d524ea6dc5a8d95e93f4023481a07
[ "BSD-2-Clause" ]
null
null
null
#ifndef OSRM_EXTRACTOR_GUIDANCE_TURN_LANE_AUGMENTATION_HPP_ #define OSRM_EXTRACTOR_GUIDANCE_TURN_LANE_AUGMENTATION_HPP_ #include "extractor/guidance/intersection.hpp" #include "extractor/guidance/turn_lane_data.hpp" namespace osrm { namespace extractor { namespace guidance { namespace lanes { LaneDataVector handleNoneValueAtSimpleTurn(LaneDataVector lane_data, const Intersection &intersection); } // namespace lanes } // namespace guidance } // namespace extractor } // namespace osrm #endif /* OSRM_EXTRACTOR_GUIDANCE_TURN_LANE_AUGMENTATION_HPP_ */
24.04
77
0.777038
peterkist-tinker
81defce025f673146fb076b3c67dd6f24fc5d927
1,529
cpp
C++
atcoder/agc006/D.cpp
swwind/code
25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0
[ "WTFPL" ]
3
2017-09-17T09:12:50.000Z
2018-04-06T01:18:17.000Z
atcoder/agc006/D.cpp
swwind/code
25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0
[ "WTFPL" ]
null
null
null
atcoder/agc006/D.cpp
swwind/code
25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0
[ "WTFPL" ]
null
null
null
#include <bits/stdc++.h> #define N 200020 #define ll long long using namespace std; inline int read(){ int x=0,f=1;char ch=getchar(); while(ch>'9'||ch<'0')ch=='-'&&(f=0)||(ch=getchar()); while(ch<='9'&&ch>='0')x=(x<<3)+(x<<1)+ch-'0',ch=getchar(); return f?x:-x; } int a[N]; bool b[N]; int n, sz; bool check(int x) { for (int i = 1; i <= sz; ++ i) { b[i] = a[i] <= x; } int rp = 0; for (int i = n + 1; i <= sz; ++ i) { if (b[i] == b[i - 1]) { rp = i - n; break; } } int lp = 0; for (int i = n - 1; i; -- i) { if (b[i] == b[i + 1]) { lp = n - i; break; } } if (!rp && !lp) return b[1]; if (!rp) return b[n - lp]; if (!lp) return b[n + rp]; if (rp == lp) return b[n - lp]; // printf("%d %d\n", lp, rp); if (rp < lp) { return b[n + rp]; } else { return b[n - lp]; } } int main(int argc, char const *argv[]) { n = read(); sz = 2 * n - 1; for (int i = 1; i <= sz; ++ i) { a[i] = read(); } int l = 1, r = sz; while (l <= r) { int mid = (l + r) >> 1; if (check(mid)) r = mid - 1; else l = mid + 1; } printf("%d\n", r + 1); return 0; } /* 二分答案,将每个小于等于 mid 的都看成 1,其余看成 0。 与 B 题同样的思想,有两个相邻的 0 或者相邻的 1,会一直冲到最顶上。 判断离中线最近的一根柱子即可。 1 6 3 7 4 5 2 1: 1 0 0 0 0 0 0 false 2: 1 0 0 0 0 0 1 false 3: 1 0 1 0 0 0 1 false 4: 1 0 1 0 1 0 1 true 5: 1 0 1 0 1 1 1 true 6: 1 1 1 0 1 1 1 true 7: 1 1 1 1 1 1 1 true 如果没有相邻的数字,那么答案就是第一个元素。 1 1 0 1 1 0 1 0 1 1 0 1 0 1 0 1 复杂度 O(nlogn) */
15.927083
61
0.456508
swwind
81dfaff9617ef04a799d6168fb671e82f45bae41
363
cpp
C++
RandomNumbersLibrary/RandomNumbers/RandomGeneratorBase.cpp
PiotrGardocki/RandomNumbersLibrary
4657ea288109381538a041ad765d02104414cd3c
[ "Unlicense" ]
null
null
null
RandomNumbersLibrary/RandomNumbers/RandomGeneratorBase.cpp
PiotrGardocki/RandomNumbersLibrary
4657ea288109381538a041ad765d02104414cd3c
[ "Unlicense" ]
null
null
null
RandomNumbersLibrary/RandomNumbers/RandomGeneratorBase.cpp
PiotrGardocki/RandomNumbersLibrary
4657ea288109381538a041ad765d02104414cd3c
[ "Unlicense" ]
null
null
null
#include <chrono> #include "RandomGeneratorBase.hpp" namespace { long long createSeed() { auto seed = std::chrono::system_clock::now().time_since_epoch().count(); return seed; } } thread_local std::mt19937 RandomGeneratorBase::mEngine(static_cast<unsigned int>(createSeed()) ); std::mt19937 & RandomGeneratorBase::getEngine() const { return mEngine; }
19.105263
97
0.738292
PiotrGardocki
81e093b03296306e50da0486be0ffc86b2f40401
21,481
cc
C++
third_party/blink/renderer/bindings/core/v8/generated_code_helper.cc
Ron423c/chromium
2edf7b980065b648f8b2a6e52193d83832fe36b7
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
third_party/blink/renderer/bindings/core/v8/generated_code_helper.cc
Ron423c/chromium
2edf7b980065b648f8b2a6e52193d83832fe36b7
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
third_party/blink/renderer/bindings/core/v8/generated_code_helper.cc
Ron423c/chromium
2edf7b980065b648f8b2a6e52193d83832fe36b7
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2021-03-07T14:20:02.000Z
2021-03-07T14:20:02.000Z
// Copyright 2016 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 "third_party/blink/renderer/bindings/core/v8/generated_code_helper.h" #include "third_party/blink/renderer/bindings/core/v8/native_value_traits_impl.h" #include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.h" #include "third_party/blink/renderer/bindings/core/v8/v8_css_style_declaration.h" #include "third_party/blink/renderer/bindings/core/v8/v8_element.h" #include "third_party/blink/renderer/bindings/core/v8/v8_set_return_value_for_core.h" #include "third_party/blink/renderer/core/dom/document.h" #include "third_party/blink/renderer/core/dom/range.h" #include "third_party/blink/renderer/core/execution_context/execution_context.h" #include "third_party/blink/renderer/core/frame/local_dom_window.h" #include "third_party/blink/renderer/core/html/custom/ce_reactions_scope.h" #include "third_party/blink/renderer/core/inspector/console_message.h" #include "third_party/blink/renderer/core/xml/dom_parser.h" #include "third_party/blink/renderer/platform/bindings/v8_binding.h" #include "third_party/blink/renderer/platform/bindings/v8_per_context_data.h" namespace blink { void V8ConstructorAttributeGetter( v8::Local<v8::Name> property_name, const v8::PropertyCallbackInfo<v8::Value>& info, const WrapperTypeInfo* wrapper_type_info) { RUNTIME_CALL_TIMER_SCOPE_DISABLED_BY_DEFAULT( info.GetIsolate(), "Blink_V8ConstructorAttributeGetter"); V8PerContextData* per_context_data = V8PerContextData::From(info.Holder()->CreationContext()); if (!per_context_data) return; V8SetReturnValue(info, per_context_data->ConstructorForType(wrapper_type_info)); } namespace { enum class IgnorePause { kDontIgnore, kIgnore }; // 'beforeunload' event listeners are runnable even when execution contexts are // paused. Use |RespectPause::kPrioritizeOverPause| in such a case. bool IsCallbackFunctionRunnableInternal( const ScriptState* callback_relevant_script_state, const ScriptState* incumbent_script_state, IgnorePause ignore_pause) { if (!callback_relevant_script_state->ContextIsValid()) return false; const ExecutionContext* relevant_execution_context = ExecutionContext::From(callback_relevant_script_state); if (!relevant_execution_context || relevant_execution_context->IsContextDestroyed()) { return false; } if (relevant_execution_context->IsContextPaused()) { if (ignore_pause == IgnorePause::kDontIgnore) return false; } // TODO(yukishiino): Callback function type value must make the incumbent // environment alive, i.e. the reference to v8::Context must be strong. v8::HandleScope handle_scope(incumbent_script_state->GetIsolate()); v8::Local<v8::Context> incumbent_context = incumbent_script_state->GetContext(); ExecutionContext* incumbent_execution_context = incumbent_context.IsEmpty() ? nullptr : ToExecutionContext(incumbent_context); // The incumbent realm schedules the currently-running callback although it // may not correspond to the currently-running function object. So we check // the incumbent context which originally schedules the currently-running // callback to see whether the script setting is disabled before invoking // the callback. // TODO(crbug.com/608641): move IsMainWorld check into // ExecutionContext::CanExecuteScripts() if (!incumbent_execution_context || incumbent_execution_context->IsContextDestroyed()) { return false; } if (incumbent_execution_context->IsContextPaused()) { if (ignore_pause == IgnorePause::kDontIgnore) return false; } return !incumbent_script_state->World().IsMainWorld() || incumbent_execution_context->CanExecuteScripts(kAboutToExecuteScript); } } // namespace bool IsCallbackFunctionRunnable( const ScriptState* callback_relevant_script_state, const ScriptState* incumbent_script_state) { return IsCallbackFunctionRunnableInternal(callback_relevant_script_state, incumbent_script_state, IgnorePause::kDontIgnore); } bool IsCallbackFunctionRunnableIgnoringPause( const ScriptState* callback_relevant_script_state, const ScriptState* incumbent_script_state) { return IsCallbackFunctionRunnableInternal(callback_relevant_script_state, incumbent_script_state, IgnorePause::kIgnore); } void V8SetReflectedBooleanAttribute( const v8::FunctionCallbackInfo<v8::Value>& info, const char* interface_name, const char* idl_attribute_name, const QualifiedName& content_attr) { v8::Isolate* isolate = info.GetIsolate(); Element* impl = V8Element::ToImpl(info.Holder()); ExceptionState exception_state(isolate, ExceptionState::kSetterContext, interface_name, idl_attribute_name); CEReactionsScope ce_reactions_scope; // Prepare the value to be set. bool cpp_value = NativeValueTraits<IDLBoolean>::NativeValue(isolate, info[0], exception_state); if (exception_state.HadException()) return; impl->SetBooleanAttribute(content_attr, cpp_value); } void V8SetReflectedDOMStringAttribute( const v8::FunctionCallbackInfo<v8::Value>& info, const QualifiedName& content_attr) { Element* impl = V8Element::ToImpl(info.Holder()); CEReactionsScope ce_reactions_scope; // Prepare the value to be set. V8StringResource<> cpp_value{info[0]}; if (!cpp_value.Prepare()) return; impl->setAttribute(content_attr, cpp_value); } void V8SetReflectedNullableDOMStringAttribute( const v8::FunctionCallbackInfo<v8::Value>& info, const QualifiedName& content_attr) { Element* impl = V8Element::ToImpl(info.Holder()); CEReactionsScope ce_reactions_scope; // Prepare the value to be set. V8StringResource<kTreatNullAndUndefinedAsNullString> cpp_value{info[0]}; if (!cpp_value.Prepare()) return; impl->setAttribute(content_attr, cpp_value); } namespace bindings { void SetupIDLInterfaceTemplate( v8::Isolate* isolate, const WrapperTypeInfo* wrapper_type_info, v8::Local<v8::ObjectTemplate> instance_template, v8::Local<v8::ObjectTemplate> prototype_template, v8::Local<v8::FunctionTemplate> interface_template, v8::Local<v8::FunctionTemplate> parent_interface_template) { v8::Local<v8::String> class_string = V8AtomicString(isolate, wrapper_type_info->interface_name); if (!parent_interface_template.IsEmpty()) interface_template->Inherit(parent_interface_template); interface_template->ReadOnlyPrototype(); interface_template->SetClassName(class_string); prototype_template->Set( v8::Symbol::GetToStringTag(isolate), class_string, static_cast<v8::PropertyAttribute>(v8::ReadOnly | v8::DontEnum)); instance_template->SetInternalFieldCount(kV8DefaultWrapperInternalFieldCount); } void SetupIDLNamespaceTemplate( v8::Isolate* isolate, const WrapperTypeInfo* wrapper_type_info, v8::Local<v8::ObjectTemplate> interface_template) { v8::Local<v8::String> class_string = V8AtomicString(isolate, wrapper_type_info->interface_name); interface_template->Set( v8::Symbol::GetToStringTag(isolate), class_string, static_cast<v8::PropertyAttribute>(v8::ReadOnly | v8::DontEnum)); } void SetupIDLCallbackInterfaceTemplate( v8::Isolate* isolate, const WrapperTypeInfo* wrapper_type_info, v8::Local<v8::FunctionTemplate> interface_template) { interface_template->RemovePrototype(); interface_template->SetClassName( V8AtomicString(isolate, wrapper_type_info->interface_name)); } base::Optional<size_t> FindIndexInEnumStringTable( v8::Isolate* isolate, v8::Local<v8::Value> value, base::span<const char* const> enum_value_table, const char* enum_type_name, ExceptionState& exception_state) { const String& str_value = NativeValueTraits<IDLStringV2>::NativeValue( isolate, value, exception_state); if (exception_state.HadException()) return base::nullopt; base::Optional<size_t> index = FindIndexInEnumStringTable(str_value, enum_value_table); if (!index.has_value()) { exception_state.ThrowTypeError("The provided value '" + str_value + "' is not a valid enum value of type " + enum_type_name + "."); } return index; } base::Optional<size_t> FindIndexInEnumStringTable( const String& str_value, base::span<const char* const> enum_value_table) { for (size_t i = 0; i < enum_value_table.size(); ++i) { if (Equal(str_value.Impl(), enum_value_table[i])) return i; } return base::nullopt; } void ReportInvalidEnumSetToAttribute(v8::Isolate* isolate, const String& value, const String& enum_type_name, ExceptionState& exception_state) { ScriptState* script_state = ScriptState::From(isolate->GetCurrentContext()); ExecutionContext* execution_context = ExecutionContext::From(script_state); exception_state.ThrowTypeError("The provided value '" + value + "' is not a valid enum value of type " + enum_type_name + "."); String message = exception_state.Message(); exception_state.ClearException(); execution_context->AddConsoleMessage(MakeGarbageCollected<ConsoleMessage>( mojom::blink::ConsoleMessageSource::kJavaScript, mojom::blink::ConsoleMessageLevel::kWarning, message, SourceLocation::Capture(execution_context))); } bool IsEsIterableObject(v8::Isolate* isolate, v8::Local<v8::Value> value, ExceptionState& exception_state) { // https://heycam.github.io/webidl/#es-overloads // step 9. Otherwise: if Type(V) is Object and ... if (!value->IsObject()) return false; // step 9.1. Let method be ? GetMethod(V, @@iterator). // https://tc39.es/ecma262/#sec-getmethod v8::TryCatch try_catch(isolate); v8::Local<v8::Value> iterator_key = v8::Symbol::GetIterator(isolate); v8::Local<v8::Value> iterator_value; if (!value.As<v8::Object>() ->Get(isolate->GetCurrentContext(), iterator_key) .ToLocal(&iterator_value)) { exception_state.RethrowV8Exception(try_catch.Exception()); return false; } if (iterator_value->IsNullOrUndefined()) return false; if (!iterator_value->IsFunction()) { exception_state.ThrowTypeError("@@iterator must be a function"); return false; } return true; } Document* ToDocumentFromExecutionContext(ExecutionContext* execution_context) { return DynamicTo<LocalDOMWindow>(execution_context)->document(); } ExecutionContext* ExecutionContextFromV8Wrappable(const Range* range) { return range->startContainer()->GetExecutionContext(); } ExecutionContext* ExecutionContextFromV8Wrappable(const DOMParser* parser) { return parser->GetWindow(); } v8::MaybeLocal<v8::Value> CreateNamedConstructorFunction( ScriptState* script_state, v8::FunctionCallback callback, const char* func_name, int func_length, const WrapperTypeInfo* wrapper_type_info) { v8::Isolate* isolate = script_state->GetIsolate(); const DOMWrapperWorld& world = script_state->World(); V8PerIsolateData* per_isolate_data = V8PerIsolateData::From(isolate); const void* callback_key = reinterpret_cast<const void*>(callback); if (!script_state->ContextIsValid()) { return v8::Undefined(isolate); } v8::Local<v8::FunctionTemplate> function_template = per_isolate_data->FindV8Template(world, callback_key) .As<v8::FunctionTemplate>(); if (function_template.IsEmpty()) { function_template = v8::FunctionTemplate::New( isolate, callback, v8::Local<v8::Value>(), v8::Local<v8::Signature>(), func_length, v8::ConstructorBehavior::kAllow, v8::SideEffectType::kHasSideEffect); v8::Local<v8::FunctionTemplate> interface_template = wrapper_type_info->GetV8ClassTemplate(isolate, world) .As<v8::FunctionTemplate>(); function_template->Inherit(interface_template); function_template->SetClassName(V8AtomicString(isolate, func_name)); function_template->InstanceTemplate()->SetInternalFieldCount( kV8DefaultWrapperInternalFieldCount); per_isolate_data->AddV8Template(world, callback_key, function_template); } v8::Local<v8::Context> context = script_state->GetContext(); V8PerContextData* per_context_data = V8PerContextData::From(context); v8::Local<v8::Function> function; if (!function_template->GetFunction(context).ToLocal(&function)) { return v8::MaybeLocal<v8::Value>(); } v8::Local<v8::Object> prototype_object = per_context_data->PrototypeForType(wrapper_type_info); bool did_define; if (!function ->DefineOwnProperty( context, V8AtomicString(isolate, "prototype"), prototype_object, static_cast<v8::PropertyAttribute>(v8::ReadOnly | v8::DontEnum | v8::DontDelete)) .To(&did_define)) { return v8::MaybeLocal<v8::Value>(); } CHECK(did_define); return function; } void InstallUnscopablePropertyNames( v8::Isolate* isolate, v8::Local<v8::Context> context, v8::Local<v8::Object> prototype_object, base::span<const char* const> property_name_table) { // 3.6.3. Interface prototype object // https://heycam.github.io/webidl/#interface-prototype-object // step 8. If interface has any member declared with the [Unscopable] // extended attribute, then: // step 8.1. Let unscopableObject be the result of performing // ! ObjectCreate(null). v8::Local<v8::Object> unscopable_object = v8::Object::New(isolate, v8::Null(isolate), nullptr, nullptr, 0); for (const char* const property_name : property_name_table) { // step 8.2.2. Perform ! CreateDataProperty(unscopableObject, id, true). unscopable_object ->CreateDataProperty(context, V8AtomicString(isolate, property_name), v8::True(isolate)) .ToChecked(); } // step 8.3. Let desc be the PropertyDescriptor{[[Value]]: unscopableObject, // [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true}. // step 8.4. Perform ! DefinePropertyOrThrow(interfaceProtoObj, // @@unscopables, desc). prototype_object ->DefineOwnProperty( context, v8::Symbol::GetUnscopables(isolate), unscopable_object, static_cast<v8::PropertyAttribute>(v8::ReadOnly | v8::DontEnum)) .ToChecked(); } v8::Local<v8::Array> EnumerateIndexedProperties(v8::Isolate* isolate, uint32_t length) { Vector<v8::Local<v8::Value>> elements; elements.ReserveCapacity(length); for (uint32_t i = 0; i < length; ++i) elements.UncheckedAppend(v8::Integer::New(isolate, i)); return v8::Array::New(isolate, elements.data(), elements.size()); } #if defined(USE_BLINK_V8_BINDING_NEW_IDL_INTERFACE) void InstallCSSPropertyAttributes( v8::Isolate* isolate, const DOMWrapperWorld& world, v8::Local<v8::Template> instance_template, v8::Local<v8::Template> prototype_template, v8::Local<v8::Template> interface_template, v8::Local<v8::Signature> signature, base::span<const char* const> css_property_names) { const String kGetPrefix = "get "; const String kSetPrefix = "set "; for (const char* const property_name : css_property_names) { v8::Local<v8::Value> v8_property_name = v8::External::New( isolate, const_cast<void*>(reinterpret_cast<const void*>(property_name))); v8::Local<v8::FunctionTemplate> get_func = v8::FunctionTemplate::New( isolate, CSSPropertyAttributeGet, v8_property_name, signature, 0, v8::ConstructorBehavior::kThrow, v8::SideEffectType::kHasNoSideEffect); v8::Local<v8::FunctionTemplate> set_func = v8::FunctionTemplate::New( isolate, CSSPropertyAttributeSet, v8_property_name, signature, 1, v8::ConstructorBehavior::kThrow, v8::SideEffectType::kHasSideEffect); get_func->SetAcceptAnyReceiver(false); set_func->SetAcceptAnyReceiver(false); get_func->SetClassName( V8AtomicString(isolate, String(kGetPrefix + property_name))); set_func->SetClassName( V8AtomicString(isolate, String(kSetPrefix + property_name))); prototype_template->SetAccessorProperty( V8AtomicString(isolate, property_name), get_func, set_func); } } void CSSPropertyAttributeGet(const v8::FunctionCallbackInfo<v8::Value>& info) { CSSStyleDeclaration* blink_receiver = V8CSSStyleDeclaration::ToWrappableUnsafe(info.This()); const char* property_name = reinterpret_cast<const char*>(info.Data().As<v8::External>()->Value()); auto&& return_value = blink_receiver->GetPropertyAttribute(property_name); bindings::V8SetReturnValue(info, return_value, info.GetIsolate(), bindings::V8ReturnValue::kNonNullable); } void CSSPropertyAttributeSet(const v8::FunctionCallbackInfo<v8::Value>& info) { v8::Isolate* isolate = info.GetIsolate(); const char* const class_like_name = "CSSStyleDeclaration"; const char* property_name = reinterpret_cast<const char*>(info.Data().As<v8::External>()->Value()); ExceptionState exception_state(isolate, ExceptionState::kSetterContext, class_like_name, property_name); // [CEReactions] CEReactionsScope ce_reactions_scope; v8::Local<v8::Object> v8_receiver = info.This(); CSSStyleDeclaration* blink_receiver = V8CSSStyleDeclaration::ToWrappableUnsafe(v8_receiver); v8::Local<v8::Value> v8_property_value = info[0]; auto&& arg1_value = NativeValueTraits<IDLStringTreatNullAsEmptyStringV2>::NativeValue( isolate, v8_property_value, exception_state); if (exception_state.HadException()) { return; } v8::Local<v8::Context> receiver_context = v8_receiver->CreationContext(); ExecutionContext* execution_context = ExecutionContext::From(receiver_context); blink_receiver->SetPropertyAttribute(execution_context, property_name, arg1_value, exception_state); } template <typename IDLType, typename ArgType, void (Element::*MemFunc)(const QualifiedName&, ArgType)> void PerformAttributeSetCEReactionsReflect( const v8::FunctionCallbackInfo<v8::Value>& info, const QualifiedName& content_attribute, const char* interface_name, const char* attribute_name) { v8::Isolate* isolate = info.GetIsolate(); ExceptionState exception_state(isolate, ExceptionState::kSetterContext, interface_name, attribute_name); if (UNLIKELY(info.Length() < 1)) { exception_state.ThrowTypeError( ExceptionMessages::NotEnoughArguments(1, info.Length())); return; } CEReactionsScope ce_reactions_scope; Element* blink_receiver = V8Element::ToWrappableUnsafe(info.This()); auto&& arg_value = NativeValueTraits<IDLType>::NativeValue(isolate, info[0], exception_state); if (exception_state.HadException()) return; (blink_receiver->*MemFunc)(content_attribute, arg_value); } void PerformAttributeSetCEReactionsReflectTypeBoolean( const v8::FunctionCallbackInfo<v8::Value>& info, const QualifiedName& content_attribute, const char* interface_name, const char* attribute_name) { PerformAttributeSetCEReactionsReflect<IDLBoolean, bool, &Element::SetBooleanAttribute>( info, content_attribute, interface_name, attribute_name); } void PerformAttributeSetCEReactionsReflectTypeString( const v8::FunctionCallbackInfo<v8::Value>& info, const QualifiedName& content_attribute, const char* interface_name, const char* attribute_name) { PerformAttributeSetCEReactionsReflect<IDLStringV2, const AtomicString&, &Element::setAttribute>( info, content_attribute, interface_name, attribute_name); } void PerformAttributeSetCEReactionsReflectTypeStringLegacyNullToEmptyString( const v8::FunctionCallbackInfo<v8::Value>& info, const QualifiedName& content_attribute, const char* interface_name, const char* attribute_name) { PerformAttributeSetCEReactionsReflect<IDLStringTreatNullAsEmptyStringV2, const AtomicString&, &Element::setAttribute>( info, content_attribute, interface_name, attribute_name); } void PerformAttributeSetCEReactionsReflectTypeStringOrNull( const v8::FunctionCallbackInfo<v8::Value>& info, const QualifiedName& content_attribute, const char* interface_name, const char* attribute_name) { PerformAttributeSetCEReactionsReflect< IDLNullable<IDLStringV2>, const AtomicString&, &Element::setAttribute>( info, content_attribute, interface_name, attribute_name); } #endif // USE_BLINK_V8_BINDING_NEW_IDL_INTERFACE } // namespace bindings } // namespace blink
40.151402
85
0.713561
Ron423c
81e3ed422724ffb91dc0100ff185cc6a3592d9d8
8,344
cc
C++
lib/libbase-chromium/base/threading/platform_thread_posix.cc
ducalpha/android_tools
5a660b6d4b4e963054a8fea380b7184d908bdd7a
[ "MIT" ]
null
null
null
lib/libbase-chromium/base/threading/platform_thread_posix.cc
ducalpha/android_tools
5a660b6d4b4e963054a8fea380b7184d908bdd7a
[ "MIT" ]
null
null
null
lib/libbase-chromium/base/threading/platform_thread_posix.cc
ducalpha/android_tools
5a660b6d4b4e963054a8fea380b7184d908bdd7a
[ "MIT" ]
null
null
null
// 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 "base/threading/platform_thread.h" #include <errno.h> #include <pthread.h> #include <sched.h> #include <stddef.h> #include <stdint.h> #include <sys/resource.h> #include <sys/time.h> #include <memory> // ducalpha: remove unnecessary dependency // #include "base/lazy_instance.h" #include "base/logging.h" #include "base/threading/platform_thread_internal_posix.h" // ducalpha: remove dependency on thread_id_name_manager //#include "base/threading/thread_id_name_manager.h" #include "base/threading/thread_restrictions.h" #include "build/build_config.h" #if defined(OS_LINUX) #include <sys/syscall.h> #elif defined(OS_ANDROID) #include <sys/types.h> #endif namespace base { void InitThreading(); void TerminateOnThread(); size_t GetDefaultThreadStackSize(const pthread_attr_t& attributes); namespace { struct ThreadParams { ThreadParams() : delegate(NULL), joinable(false), priority(ThreadPriority::NORMAL) {} PlatformThread::Delegate* delegate; bool joinable; ThreadPriority priority; }; void* ThreadFunc(void* params) { PlatformThread::Delegate* delegate = nullptr; { std::unique_ptr<ThreadParams> thread_params( static_cast<ThreadParams*>(params)); delegate = thread_params->delegate; if (!thread_params->joinable) base::ThreadRestrictions::SetSingletonAllowed(false); #if !defined(OS_NACL) // Threads on linux/android may inherit their priority from the thread // where they were created. This explicitly sets the priority of all new // threads. PlatformThread::SetCurrentThreadPriority(thread_params->priority); #endif } /* ducalpha: remove dependency on thread_id_name_manager ThreadIdNameManager::GetInstance()->RegisterThread( PlatformThread::CurrentHandle().platform_handle(), PlatformThread::CurrentId()); */ delegate->ThreadMain(); /* ducalpha: remove dependency on thread_id_name_manager ThreadIdNameManager::GetInstance()->RemoveName( PlatformThread::CurrentHandle().platform_handle(), PlatformThread::CurrentId()); */ base::TerminateOnThread(); return NULL; } bool CreateThread(size_t stack_size, bool joinable, PlatformThread::Delegate* delegate, PlatformThreadHandle* thread_handle, ThreadPriority priority) { DCHECK(thread_handle); base::InitThreading(); pthread_attr_t attributes; pthread_attr_init(&attributes); // Pthreads are joinable by default, so only specify the detached // attribute if the thread should be non-joinable. if (!joinable) pthread_attr_setdetachstate(&attributes, PTHREAD_CREATE_DETACHED); // Get a better default if available. if (stack_size == 0) stack_size = base::GetDefaultThreadStackSize(attributes); if (stack_size > 0) pthread_attr_setstacksize(&attributes, stack_size); std::unique_ptr<ThreadParams> params(new ThreadParams); params->delegate = delegate; params->joinable = joinable; params->priority = priority; pthread_t handle; int err = pthread_create(&handle, &attributes, ThreadFunc, params.get()); bool success = !err; if (success) { // ThreadParams should be deleted on the created thread after used. ignore_result(params.release()); } else { // Value of |handle| is undefined if pthread_create fails. handle = 0; errno = err; PLOG(ERROR) << "pthread_create"; } *thread_handle = PlatformThreadHandle(handle); pthread_attr_destroy(&attributes); return success; } } // namespace // static PlatformThreadId PlatformThread::CurrentId() { // Pthreads doesn't have the concept of a thread ID, so we have to reach down // into the kernel. #if defined(OS_MACOSX) return pthread_mach_thread_np(pthread_self()); #elif defined(OS_LINUX) return syscall(__NR_gettid); #elif defined(OS_ANDROID) return gettid(); #elif defined(OS_SOLARIS) || defined(OS_QNX) return pthread_self(); #elif defined(OS_NACL) && defined(__GLIBC__) return pthread_self(); #elif defined(OS_NACL) && !defined(__GLIBC__) // Pointers are 32-bits in NaCl. return reinterpret_cast<int32_t>(pthread_self()); #elif defined(OS_POSIX) return reinterpret_cast<int64_t>(pthread_self()); #endif } // static PlatformThreadRef PlatformThread::CurrentRef() { return PlatformThreadRef(pthread_self()); } // static PlatformThreadHandle PlatformThread::CurrentHandle() { return PlatformThreadHandle(pthread_self()); } // static void PlatformThread::YieldCurrentThread() { sched_yield(); } // static void PlatformThread::Sleep(TimeDelta duration) { struct timespec sleep_time, remaining; // Break the duration into seconds and nanoseconds. // NOTE: TimeDelta's microseconds are int64s while timespec's // nanoseconds are longs, so this unpacking must prevent overflow. sleep_time.tv_sec = duration.InSeconds(); duration -= TimeDelta::FromSeconds(sleep_time.tv_sec); sleep_time.tv_nsec = duration.InMicroseconds() * 1000; // nanoseconds while (nanosleep(&sleep_time, &remaining) == -1 && errno == EINTR) sleep_time = remaining; } // static /* ducalpha: remove dependency on thread_id_name_manager const char* PlatformThread::GetName() { return ThreadIdNameManager::GetInstance()->GetName(CurrentId()); } */ // static bool PlatformThread::CreateWithPriority(size_t stack_size, Delegate* delegate, PlatformThreadHandle* thread_handle, ThreadPriority priority) { return CreateThread(stack_size, true, // joinable thread delegate, thread_handle, priority); } // static bool PlatformThread::CreateNonJoinable(size_t stack_size, Delegate* delegate) { PlatformThreadHandle unused; bool result = CreateThread(stack_size, false /* non-joinable thread */, delegate, &unused, ThreadPriority::NORMAL); return result; } // static void PlatformThread::Join(PlatformThreadHandle thread_handle) { // Joining another thread may block the current thread for a long time, since // the thread referred to by |thread_handle| may still be running long-lived / // blocking tasks. base::ThreadRestrictions::AssertIOAllowed(); CHECK_EQ(0, pthread_join(thread_handle.platform_handle(), NULL)); } // Mac has its own Set/GetCurrentThreadPriority() implementations. #if !defined(OS_MACOSX) // static void PlatformThread::SetCurrentThreadPriority(ThreadPriority priority) { #if defined(OS_NACL) NOTIMPLEMENTED(); #else if (internal::SetCurrentThreadPriorityForPlatform(priority)) return; // setpriority(2) should change the whole thread group's (i.e. process) // priority. However, as stated in the bugs section of // http://man7.org/linux/man-pages/man2/getpriority.2.html: "under the current // Linux/NPTL implementation of POSIX threads, the nice value is a per-thread // attribute". Also, 0 is prefered to the current thread id since it is // equivalent but makes sandboxing easier (https://crbug.com/399473). const int nice_setting = internal::ThreadPriorityToNiceValue(priority); if (setpriority(PRIO_PROCESS, 0, nice_setting)) { DVPLOG(1) << "Failed to set nice value of thread (" << PlatformThread::CurrentId() << ") to " << nice_setting; } #endif // defined(OS_NACL) } // static ThreadPriority PlatformThread::GetCurrentThreadPriority() { #if defined(OS_NACL) NOTIMPLEMENTED(); return ThreadPriority::NORMAL; #else // Mirrors SetCurrentThreadPriority()'s implementation. ThreadPriority platform_specific_priority; if (internal::GetCurrentThreadPriorityForPlatform( &platform_specific_priority)) { return platform_specific_priority; } // Need to clear errno before calling getpriority(): // http://man7.org/linux/man-pages/man2/getpriority.2.html errno = 0; int nice_value = getpriority(PRIO_PROCESS, 0); if (errno != 0) { DVPLOG(1) << "Failed to get nice value of thread (" << PlatformThread::CurrentId() << ")"; return ThreadPriority::NORMAL; } return internal::NiceValueToThreadPriority(nice_value); #endif // !defined(OS_NACL) } #endif // !defined(OS_MACOSX) } // namespace base
30.676471
80
0.723634
ducalpha
81e43a2f9aa0d4deedde81d90e47d78a3dc333ad
681
cpp
C++
test/unit/math/prim/meta/disjunction_test.cpp
LaudateCorpus1/math
990a66b3cccd27a5fd48626360bb91093a48278b
[ "BSD-3-Clause" ]
1
2020-06-14T14:33:37.000Z
2020-06-14T14:33:37.000Z
test/unit/math/prim/meta/disjunction_test.cpp
LaudateCorpus1/math
990a66b3cccd27a5fd48626360bb91093a48278b
[ "BSD-3-Clause" ]
2
2019-07-23T12:45:30.000Z
2020-05-01T20:43:03.000Z
test/unit/math/prim/meta/disjunction_test.cpp
LaudateCorpus1/math
990a66b3cccd27a5fd48626360bb91093a48278b
[ "BSD-3-Clause" ]
1
2020-05-10T12:55:07.000Z
2020-05-10T12:55:07.000Z
#include <stan/math/prim/meta.hpp> #include <gtest/gtest.h> TEST(MathMetaPrim, or_type) { bool temp = stan::math::disjunction<std::true_type, std::true_type, std::true_type>::value; EXPECT_TRUE(temp); temp = stan::math::disjunction<std::false_type, std::false_type, std::false_type>::value; EXPECT_FALSE(temp); temp = stan::math::disjunction<std::false_type, std::true_type, std::true_type>::value; EXPECT_TRUE(temp); temp = stan::math::disjunction<std::true_type, std::true_type, std::false_type>::value; EXPECT_TRUE(temp); }
37.833333
69
0.577093
LaudateCorpus1
81e4b7f88888d2272cf3af84dadb9ff704aa1078
9,953
cpp
C++
Graphics Offline 1/Graphics-Offline-1/codes/Wheel.cpp
shamiul94/Graphics-OpenGL-Lab-Assignments
7cbaa91634fe0f254222c42bb147e47979ce2329
[ "MIT" ]
null
null
null
Graphics Offline 1/Graphics-Offline-1/codes/Wheel.cpp
shamiul94/Graphics-OpenGL-Lab-Assignments
7cbaa91634fe0f254222c42bb147e47979ce2329
[ "MIT" ]
null
null
null
Graphics Offline 1/Graphics-Offline-1/codes/Wheel.cpp
shamiul94/Graphics-OpenGL-Lab-Assignments
7cbaa91634fe0f254222c42bb147e47979ce2329
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> #include <windows.h> #include <glut.h> #define pi (2*acos(0.0)) using namespace std; double cameraHeight; double cameraAngle; int drawgrid; int drawaxes; double angle; double cylinderHeight = 20, cylinderRadius = 30, sphereRadius = 20; double movementOnZaxes = 40, sphereZaxisMovement = 40, movementOnYaxes = 40, movementOnXaxes = 40; double distanceCoveredPerRotation, distanceCoveredPerRotationX, distanceCoveredPerRotationY; double distanceCoveredPerRotationZ, angleY, angleZ, angleChange, period = 60; struct Point { double x, y, z; Point() {} Point(double X, double Y, double Z) { x = X; y = Y; z = Z; } Point(const Point &p) : x(p.x), y(p.y), z(p.z) {} }; class Position { public: double dx, dy, dz, dtheta; Position() {} Position(double x, double y, double z, double theta) : dx(x), dy(y), dz(z), dtheta(theta) {} }; Position movement, currPos; Point crossProduct(const Point &a, const Point &b) { Point ret; ret.x = a.y * b.z - a.z * b.y; ret.y = -(a.x * b.z - a.z * b.x); ret.z = a.x * b.y - a.y * b.x; return ret; } Point cameraPos, cameraUp, cameraLook, cameraRight; double degreesToRadians(double angle_in_degrees) { return angle_in_degrees * (pi / 180.0); } void drawAxes() { if (drawaxes == 1) { glColor3f(1.0, 1.0, 1.0); glBegin(GL_LINES); { glColor3f(1, 0, 0); glVertex3f(100, 0, 0); glVertex3f(-100, 0, 0); glColor3f(0, 1, 0); glVertex3f(0, -100, 0); glVertex3f(0, 100, 0); glColor3f(0, 0, 1); glVertex3f(0, 0, 100); glVertex3f(0, 0, -100); } glEnd(); } } void drawGrid() { int i; glColor3f(0.6, 0.6, 0.6); //grey glBegin(GL_LINES); { for (i = -28; i <= 28; i++) { // if (i == 0) // continue; //SKIP the MAIN axes //lines parallel to Y-axis glVertex3f(i * 10, -300, 0); glVertex3f(i * 10, 300, 0); //lines parallel to X-axis glVertex3f(-300, i * 10, 0); glVertex3f(300, i * 10, 0); } } glEnd(); } void drawCylinder(double height, double radius, int slices) { struct point { double x, y, z; }; int i; struct point pointsUp[1000]; struct point pointsDown[1000]; glColor3f(0.7, 0.7, 0.7); //generate points for (i = 0; i <= slices; i++) { pointsUp[i].x = pointsDown[i].x = radius * cos(((double) i / (double) slices) * 2 * pi); pointsUp[i].y = pointsDown[i].y = radius * sin(((double) i / (double) slices) * 2 * pi); pointsUp[i].z = height / 2; pointsDown[i].z = -1.0 * pointsUp[i].z; } //draw segments using generated points for (i = 0; i < slices; i++) { glBegin(GL_LINES); { glVertex3f(static_cast<GLfloat>(pointsUp[i].x), static_cast<GLfloat>(pointsUp[i].y), static_cast<GLfloat>(pointsUp[i].z)); glVertex3f(static_cast<GLfloat>(pointsUp[i + 1].x), static_cast<GLfloat>(pointsUp[i + 1].y), static_cast<GLfloat>(pointsUp[i + 1].z)); glVertex3f(static_cast<GLfloat>(pointsDown[i].x), static_cast<GLfloat>(pointsDown[i].y), static_cast<GLfloat>(pointsDown[i].z)); glVertex3f(static_cast<GLfloat>(pointsDown[i + 1].x), static_cast<GLfloat>(pointsDown[i + 1].y), static_cast<GLfloat>(pointsDown[i + 1].z)); } glEnd(); // glColor3f(0, 1, 0); glColor3f(0*(double) i / (double) slices, 2*(double) i / (double) slices, 0*(double) i / (double) slices); glBegin(GL_QUADS); { glVertex3f(static_cast<GLfloat>(pointsUp[i].x), static_cast<GLfloat>(pointsUp[i].y), static_cast<GLfloat>(pointsUp[i].z)); glVertex3f(static_cast<GLfloat>(pointsDown[i].x), static_cast<GLfloat>(pointsDown[i].y), static_cast<GLfloat>(pointsDown[i].z)); glVertex3f(static_cast<GLfloat>(pointsDown[i + 1].x), static_cast<GLfloat>(pointsDown[i + 1].y), static_cast<GLfloat>(pointsDown[i + 1].z)); glVertex3f(static_cast<GLfloat>(pointsUp[i + 1].x), static_cast<GLfloat>(pointsUp[i + 1].y), static_cast<GLfloat>(pointsUp[i + 1].z)); } glEnd(); } } void drawInnerRectangle() { glBegin(GL_QUADS); { glVertex3f(-cylinderRadius, cylinderHeight / 4, 0); glVertex3f(-cylinderRadius, -cylinderHeight / 4, 0); glVertex3f(cylinderRadius, -cylinderHeight / 4, 0); glVertex3f(cylinderRadius, cylinderHeight / 4, 0); } glEnd(); } void drawWheelStructure() { glPushMatrix(); { glRotatef(90, 0, 0, 1); glRotatef(90, 0, 1, 0); drawCylinder(cylinderHeight, cylinderRadius, 30); } glPopMatrix(); glPushMatrix(); { glColor3f(1, 0, 0); drawInnerRectangle(); } glPopMatrix(); glPushMatrix(); { glRotatef(90, 0, 1, 0); glColor3f(0, 0, 1); drawInnerRectangle(); } glPopMatrix(); } void drawWheel() { glPushMatrix(); { glTranslatef(movement.dx, movement.dy, movement.dz); glTranslatef(0, 0, cylinderRadius); glRotatef(angleZ, 0, 0, 1); glRotatef(angleY, 0, 1, 0); drawWheelStructure(); } glPopMatrix(); } void keyboardListener(unsigned char key, int x, int y) { switch (key) { case 'a': angleZ += (2 * 180 / period); break; case 'd': angleZ -= (2 * 180 / period); break; case 'w': movement.dx -= distanceCoveredPerRotation * cos(degreesToRadians(angleZ)); movement.dy -= distanceCoveredPerRotation * sin(degreesToRadians(angleZ)); angleY -= (2 * 180 / period); break; case 's': movement.dx += distanceCoveredPerRotation * cos(degreesToRadians(angleZ)); movement.dy += distanceCoveredPerRotation * sin(degreesToRadians(angleZ)); angleY += (2 * 180 / period); break; default: break; } } void specialKeyListener(int key, int x, int y) { double mov = 3; switch (key) { case GLUT_KEY_RIGHT: cameraAngle += .05; break; case GLUT_KEY_LEFT: cameraAngle -= .05; break; case GLUT_KEY_UP: cameraHeight += 5; break; case GLUT_KEY_DOWN: cameraHeight -= 5; break; case GLUT_KEY_HOME: break; case GLUT_KEY_END: break; default: break; } } void mouseListener(int button, int state, int x, int y) //x, y is the x-y of the screen (2D) { switch (button) { case GLUT_LEFT_BUTTON: if (state == GLUT_DOWN) // 2 times?? in ONE click? -- solution is checking DOWN or UP { drawaxes = 1 - drawaxes; } break; case GLUT_RIGHT_BUTTON: //........ break; case GLUT_MIDDLE_BUTTON: //........ break; default: break; } } void display() { //clear the display glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glClearColor(0, 0, 0, 0); //color black glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); /********************* # set-up camera here # *********************/ //load the correct matrix -- MODEL-VIEW matrix glMatrixMode(GL_MODELVIEW); //initialize the matrix glLoadIdentity(); gluLookAt(200 * cos(cameraAngle), 200 * sin(cameraAngle), cameraHeight, 0, 0, 0, 0, 0, 1); //again select MODEL-VIEW glMatrixMode(GL_MODELVIEW); glColor3f(1, 0, 0); drawAxes(); drawGrid(); drawWheel(); glutSwapBuffers(); } void animate() { angle += 0.05; //codes for any changes in Models, Camera glutPostRedisplay(); } void init() { //codes for initialization drawgrid = 1; drawaxes = 1; cameraHeight = 150.0; cameraAngle = 1.0; angle = 0; /*** position movement initialization ***/ movement = Position(0, 0, 0, 0); currPos = Position(0, 0, 0, 0); distanceCoveredPerRotation = 2 * pi * cylinderRadius / period; angleZ = 0; angleY = 0; angleChange = 0; /** Camera initialization **/ drawgrid = 0; drawaxes = 1; cameraHeight = 80; cameraAngle = pi / 4; //clear the screen glClearColor(0, 0, 0, 0); /************************ / set-up projection here ************************/ //load the PROJECTION matrix glMatrixMode(GL_PROJECTION); //initialize the matrix glLoadIdentity(); //give PERSPECTIVE parameters gluPerspective(80, 1, 1, 1000.0); //field of view in the Y (vertically) //aspect ratio that determines the field of view in the X direction (horizontally) //near distance //far distance } int main(int argc, char **argv) { glutInit(&argc, argv); glutInitWindowSize(500, 500); glutInitWindowPosition(300, 100); glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGB); //Depth, Double buffer, RGB color glutCreateWindow("My OpenGL Program"); init(); glEnable(GL_DEPTH_TEST); //enable Depth Testing glutDisplayFunc(display); //display callback function glutIdleFunc(animate); //what you want to do in the idle time (when no drawing is occuring) glutKeyboardFunc(keyboardListener); glutSpecialFunc(specialKeyListener); glutMouseFunc(mouseListener); glutMainLoop(); //The main loop of OpenGL return 0; }
24.636139
114
0.555511
shamiul94
81e6a655366f5b01affb9add00a1bf2d59ed9c1d
873
cpp
C++
connected_components.cpp
GautamSachdeva/Number_of_connected_components
d2f7cefaf956660f027e05836a075653390f66c3
[ "MIT" ]
null
null
null
connected_components.cpp
GautamSachdeva/Number_of_connected_components
d2f7cefaf956660f027e05836a075653390f66c3
[ "MIT" ]
null
null
null
connected_components.cpp
GautamSachdeva/Number_of_connected_components
d2f7cefaf956660f027e05836a075653390f66c3
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> using namespace std; using std::vector; using std::pair; void depth(vector<vector<int> > &adj ,vector<bool> &visited , int curr_node){ visited[curr_node] = true; for(int i = 0; i < adj[curr_node].size() ; i++){ int v = adj[curr_node][i]; if(!visited[v]) depth(adj,visited,v); } } int number_of_components(vector<vector<int> > &adj) { int res = 0; //write your code here vector<bool> visited(adj.size(),false); for(int i = 0 ; i < adj.size() ; i++){ if(!visited[i]){ depth(adj,visited,i); res++; } } return res; } int main() { size_t n, m; std::cin >> n >> m; vector<vector<int> > adj(n, vector<int>()); for (size_t i = 0; i < m; i++) { int x, y; std::cin >> x >> y; adj[x - 1].push_back(y - 1); adj[y - 1].push_back(x - 1); } std::cout << number_of_components(adj); }
20.302326
77
0.578465
GautamSachdeva
81e7e0b37b80a1a8a6534fd7a1f96e58c27d798d
16,712
cc
C++
src/ufo/filters/obsfunctions/CLWRetMW.cc
fmahebert/ufo
2af9b91433553ca473c72fcd131400a01c3aabdb
[ "Apache-2.0" ]
4
2020-12-04T08:26:06.000Z
2021-11-20T01:18:47.000Z
src/ufo/filters/obsfunctions/CLWRetMW.cc
fmahebert/ufo
2af9b91433553ca473c72fcd131400a01c3aabdb
[ "Apache-2.0" ]
21
2020-10-30T08:57:16.000Z
2021-05-17T15:11:20.000Z
src/ufo/filters/obsfunctions/CLWRetMW.cc
fmahebert/ufo
2af9b91433553ca473c72fcd131400a01c3aabdb
[ "Apache-2.0" ]
31
2021-06-24T18:07:53.000Z
2021-10-08T15:40:39.000Z
/* * (C) Copyright 2019 UCAR * * This software is licensed under the terms of the Apache Licence Version 2.0 * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. */ #include "ufo/filters/obsfunctions/CLWRetMW.h" #include <algorithm> #include <cmath> #include <iomanip> #include <iostream> #include <set> #include <string> #include <vector> #include "ioda/ObsDataVector.h" #include "oops/util/IntSetParser.h" #include "ufo/filters/Variable.h" #include "ufo/utils/Constants.h" namespace ufo { static ObsFunctionMaker<CLWRetMW> makerCLWRetMW_("CLWRetMW"); CLWRetMW::CLWRetMW(const eckit::LocalConfiguration & conf) : invars_() { // Initialize options options_.deserialize(conf); // Check required parameters // Get variable group types for CLW retrieval from option ASSERT(options_.varGroup.value().size() == 1 || options_.varGroup.value().size() == 2); ASSERT((options_.ch238.value() != boost::none && options_.ch314.value() != boost::none) || (options_.ch37v.value() != boost::none && options_.ch37h.value() != boost::none) || (options_.ch18v.value() != boost::none && options_.ch18h.value() != boost::none && options_.ch36v.value() != boost::none && options_.ch36h.value() != boost::none)); if (options_.ch238.value() != boost::none && options_.ch314.value() != boost::none) { // For AMSUA and ATMS retrievals // Get channels for CLW retrieval from options const std::vector<int> channels = {options_.ch238.value().get(), options_.ch314.value().get()}; ASSERT(options_.ch238.value().get() != 0 && options_.ch314.value().get() != 0 && channels.size() == 2); // Include list of required data from ObsSpace for (size_t igrp = 0; igrp < options_.varGroup.value().size(); ++igrp) { invars_ += Variable("brightness_temperature@" + options_.varGroup.value()[igrp], channels); } invars_ += Variable("brightness_temperature@" + options_.testBias.value(), channels); invars_ += Variable("sensor_zenith_angle@MetaData"); // Include list of required data from GeoVaLs invars_ += Variable("average_surface_temperature_within_field_of_view@GeoVaLs"); invars_ += Variable("water_area_fraction@GeoVaLs"); invars_ += Variable("surface_temperature_where_sea@GeoVaLs"); } else if (options_.ch37v.value() != boost::none && options_.ch37h.value() != boost::none) { // For cloud index like GMI's. // Get channels for CLW retrieval from options const std::vector<int> channels = {options_.ch37v.value().get(), options_.ch37h.value().get()}; ASSERT(options_.ch37v.value().get() != 0 && options_.ch37h.value().get() != 0 && channels.size() == 2); // Include list of required data from ObsSpace for (size_t igrp = 0; igrp < options_.varGroup.value().size(); ++igrp) { invars_ += Variable("brightness_temperature@" + options_.varGroup.value()[igrp], channels); } invars_ += Variable("brightness_temperature@" + options_.testBias.value(), channels); // Include list of required data from ObsDiag invars_ += Variable("brightness_temperature_assuming_clear_sky@ObsDiag" , channels); // Include list of required data from GeoVaLs invars_ += Variable("water_area_fraction@GeoVaLs"); } else if (options_.ch18v.value() != boost::none && options_.ch18h.value() != boost::none && options_.ch36v.value() != boost::none && options_.ch36h.value() != boost::none) { const std::vector<int> channels = {options_.ch18v.value().get(), options_.ch18h.value().get(), options_.ch36v.value().get(), options_.ch36h.value().get()}; ASSERT(options_.ch18v.value().get() != 0 && options_.ch18h.value().get() != 0 && options_.ch36v.value().get() != 0 && options_.ch36h.value().get() != 0 && channels.size() == 4); const std::vector<float> &sys_bias = options_.origbias.value().get(); ASSERT(options_.origbias.value() != boost::none); // Include list of required data from ObsSpace for (size_t igrp = 0; igrp < options_.varGroup.value().size(); ++igrp) { invars_ += Variable("brightness_temperature@" + options_.varGroup.value()[igrp], channels); } invars_ += Variable("brightness_temperature@" + options_.testBias.value(), channels); // Include list of required data from GeoVaLs invars_ += Variable("water_area_fraction@GeoVaLs"); } } // ----------------------------------------------------------------------------- CLWRetMW::~CLWRetMW() {} // ----------------------------------------------------------------------------- void CLWRetMW::compute(const ObsFilterData & in, ioda::ObsDataVector<float> & out) const { // Get required parameters const std::vector<std::string> &vargrp = options_.varGroup.value(); // Get dimension const size_t nlocs = in.nlocs(); const size_t ngrps = vargrp.size(); // Get area fraction of each surface type std::vector<float> water_frac(nlocs); in.get(Variable("water_area_fraction@GeoVaLs"), water_frac); // --------------- amsua or atms -------------------------- if (options_.ch238.value() != boost::none && options_.ch314.value() != boost::none) { const std::vector<int> channels = {options_.ch238.value().get(), options_.ch314.value().get()}; // Get variables from ObsSpace // Get sensor zenith angle std::vector<float> szas(nlocs); in.get(Variable("sensor_zenith_angle@MetaData"), szas); // Get variables from GeoVaLs // Get average surface temperature in FOV std::vector<float> tsavg(nlocs); in.get(Variable("average_surface_temperature_within_field_of_view@GeoVaLs"), tsavg); // Calculate retrieved cloud liquid water std::vector<float> bt238(nlocs), bt314(nlocs); for (size_t igrp = 0; igrp < ngrps; ++igrp) { // Get data based on group type in.get(Variable("brightness_temperature@" + vargrp[igrp], channels)[0], bt238); in.get(Variable("brightness_temperature@" + vargrp[igrp], channels)[1], bt314); // Get bias based on group type if (options_.addBias.value() == vargrp[igrp]) { std::vector<float> bias238(nlocs), bias314(nlocs); if (in.has(Variable("brightness_temperature@" + options_.testBias.value(), channels)[0])) { in.get(Variable("brightness_temperature@" + options_.testBias.value(), channels)[0], bias238); in.get(Variable("brightness_temperature@" + options_.testBias.value(), channels)[1], bias314); } else { bias238.assign(nlocs, 0.0f); bias314.assign(nlocs, 0.0f); } // Add bias correction to the assigned group (only for ObsValue; H(x) already includes bias // correction if (options_.addBias.value() == "ObsValue") { for (size_t iloc = 0; iloc < nlocs; ++iloc) { bt238[iloc] = bt238[iloc] - bias238[iloc]; bt314[iloc] = bt314[iloc] - bias314[iloc]; } } } // Compute the cloud liquid water cloudLiquidWater(szas, tsavg, water_frac, bt238, bt314, out[igrp]); } // -------------------- GMI --------------------------- } else if (options_.ch37v.value() != boost::none && options_.ch37h.value() != boost::none) { const std::vector<int> channels = {options_.ch37v.value().get(), options_.ch37h.value().get()}; // Indices of data at channeles 37v and 37h in the above array "channels" const int jch37v = 0; const int jch37h = 1; std::vector<float> bt_clr_37v(nlocs), bt_clr_37h(nlocs); in.get(Variable("brightness_temperature_assuming_clear_sky@ObsDiag" , channels) [jch37v], bt_clr_37v); in.get(Variable("brightness_temperature_assuming_clear_sky@ObsDiag" , channels) [jch37h], bt_clr_37h); // Calculate retrieved cloud liquid water std::vector<float> bt37v(nlocs), bt37h(nlocs); for (size_t igrp = 0; igrp < ngrps; ++igrp) { // Get data based on group type in.get(Variable("brightness_temperature@" + vargrp[igrp], channels) [jch37v], bt37v); in.get(Variable("brightness_temperature@" + vargrp[igrp], channels) [jch37h], bt37h); // Get bias based on group type if (options_.addBias.value() == vargrp[igrp]) { std::vector<float> bias37v(nlocs), bias37h(nlocs); if (in.has(Variable("brightness_temperature@" + options_.testBias.value(), channels) [jch37v])) { in.get(Variable("brightness_temperature@" + options_.testBias.value(), channels) [jch37v], bias37v); in.get(Variable("brightness_temperature@" + options_.testBias.value(), channels) [jch37h], bias37h); } else { bias37v.assign(nlocs, 0.0f); bias37h.assign(nlocs, 0.0f); } // Add bias correction to the assigned group (only for ObsValue; H(x) already includes bias // correction if (options_.addBias.value() == "ObsValue") { for (size_t iloc = 0; iloc < nlocs; ++iloc) { bt37v[iloc] = bt37v[iloc] - bias37v[iloc]; bt37h[iloc] = bt37h[iloc] - bias37h[iloc]; } } } // Compute cloud index CIret_37v37h_diff(bt_clr_37v, bt_clr_37h, water_frac, bt37v, bt37h, out[igrp]); } // -------------------- amsr2 --------------------------- } else if (options_.ch18v.value() != boost::none && options_.ch18h.value() != boost::none && options_.ch36v.value() != boost::none && options_.ch36h.value() != boost::none) { const std::vector<int> channels = {options_.ch18v.value().get(), options_.ch18h.value().get(), options_.ch36v.value().get(), options_.ch36h.value().get()}; const int jch18v = 0; const int jch18h = 1; const int jch36v = 2; const int jch36h = 3; // systematic bias for channels 1-14. const std::vector<float> &sys_bias = options_.origbias.value().get(); // Calculate retrieved cloud liquid water std::vector<float> bt18v(nlocs), bt18h(nlocs), bt36v(nlocs), bt36h(nlocs); for (size_t igrp = 0; igrp < ngrps; ++igrp) { // Get data based on group type const Variable btVar("brightness_temperature@" + vargrp[igrp], channels); in.get(btVar[jch18v], bt18v); in.get(btVar[jch18h], bt18h); in.get(btVar[jch36v], bt36v); in.get(btVar[jch36h], bt36h); // Get bias based on group type if (options_.addBias.value() == vargrp[igrp]) { std::vector<float> bias18v(nlocs), bias18h(nlocs); std::vector<float> bias36v(nlocs), bias36h(nlocs); if (in.has(Variable("brightness_temperature@" + options_.testBias.value(), channels) [jch36v])) { const Variable testBias("brightness_temperature@" + options_.testBias.value(), channels); in.get(testBias[jch18v], bias18v); in.get(testBias[jch18h], bias18h); in.get(testBias[jch36v], bias36v); in.get(testBias[jch36h], bias36h); } else { bias18v.assign(nlocs, 0.0f); bias18h.assign(nlocs, 0.0f); bias36v.assign(nlocs, 0.0f); bias36h.assign(nlocs, 0.0f); } // Add bias correction to the assigned group (only for ObsValue; H(x) already includes bias // correction if (options_.addBias.value() == "ObsValue") { for (size_t iloc = 0; iloc < nlocs; ++iloc) { bt18v[iloc] = bt18v[iloc] - bias18v[iloc]; bt18h[iloc] = bt18h[iloc] - bias18h[iloc]; bt36v[iloc] = bt36v[iloc] - bias36v[iloc]; bt36h[iloc] = bt36h[iloc] - bias36h[iloc]; } } } // correct systematic bias. for (size_t iloc = 0; iloc < nlocs; ++iloc) { bt18v[iloc] = bt18v[iloc] - sys_bias[6]; bt18h[iloc] = bt18h[iloc] - sys_bias[7]; bt36v[iloc] = bt36v[iloc] - sys_bias[10]; bt36h[iloc] = bt36h[iloc] - sys_bias[11]; } // Compute cloud index clw_retr_amsr2(bt18v, bt18h, bt36v, bt36h, out[igrp]); } } } // ----------------------------------------------------------------------------- void CLWRetMW::cloudLiquidWater(const std::vector<float> & szas, const std::vector<float> & tsavg, const std::vector<float> & water_frac, const std::vector<float> & bt238, const std::vector<float> & bt314, std::vector<float> & out) { /// /// \brief Retrieve cloud liquid water from AMSU-A 23.8 GHz and 31.4 GHz channels. /// /// Reference: Grody et al. (2001) /// Determination of precipitable water and cloud liquid water over oceans from /// the NOAA 15 advanced microwave sounding unit /// const float t0c = Constants::t0c; const float d1 = 0.754, d2 = -2.265; const float c1 = 8.240, c2 = 2.622, c3 = 1.846; for (size_t iloc = 0; iloc < water_frac.size(); ++iloc) { if (water_frac[iloc] >= 0.99) { float cossza = cos(Constants::deg2rad * szas[iloc]); float d0 = c1 - (c2 - c3 * cossza) * cossza; if (tsavg[iloc] > t0c - 1.0 && bt238[iloc] <= 284.0 && bt314[iloc] <= 284.0 && bt238[iloc] > 0.0 && bt314[iloc] > 0.0) { out[iloc] = cossza * (d0 + d1 * std::log(285.0 - bt238[iloc]) + d2 * std::log(285.0 - bt314[iloc])); out[iloc] = std::max(0.f, out[iloc]); } else { out[iloc] = getBadValue(); } } } } // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- void CLWRetMW::CIret_37v37h_diff(const std::vector<float> & bt_clr_37v, const std::vector<float> & bt_clr_37h, const std::vector<float> & water_frac, const std::vector<float> & bt37v, const std::vector<float> & bt37h, std::vector<float> & out) { /// /// \brief Retrieve cloud index from GMI 37V and 37H channels. /// /// GMI cloud index: 1.0 - (Tb_37v - Tb_37h)/(Tb_37v_clr - Tb_37h_clr), in which /// Tb_37v_clr and Tb_37h_clr for calculated Tb at 37 V and 37H GHz from module values /// assuming in clear-sky condition. Tb_37v and Tb_37h are Tb observations at 37 V and 37H GHz. /// for (size_t iloc = 0; iloc < water_frac.size(); ++iloc) { if (water_frac[iloc] >= 0.99) { if (bt37h[iloc] <= bt37v[iloc]) { out[iloc] = 1.0 - (bt37v[iloc] - bt37h[iloc])/(bt_clr_37v[iloc] - bt_clr_37h[iloc]); out[iloc] = std::max(0.f, out[iloc]); } else { out[iloc] = getBadValue(); } } else { out[iloc] = getBadValue(); } } } // ----------------------------------------------------------------------------- /// \brief Retrieve AMSR2_GCOM-W1 cloud liquid water. /// This retrieval function is taken from the subroutine "retrieval_amsr2()" in GSI. void CLWRetMW::clw_retr_amsr2(const std::vector<float> & bt18v, const std::vector<float> & bt18h, const std::vector<float> & bt36v, const std::vector<float> & bt36h, std::vector<float> & out) { float clw; std::vector<float> pred_var_clw(2); // intercepts const float a0_clw = -0.65929; // regression coefficients float regr_coeff_clw[3] = {-0.00013, 1.64692, -1.51916}; for (size_t iloc = 0; iloc < bt18v.size(); ++iloc) { if (bt18v[iloc] <= bt18h[iloc]) { out[iloc] = getBadValue(); } else if (bt36v[iloc] <= bt36h[iloc]) { out[iloc] = getBadValue(); } else { // Calculate predictors pred_var_clw[0] = log(bt18v[iloc] - bt18h[iloc]); pred_var_clw[1] = log(bt36v[iloc] - bt36h[iloc]); clw = a0_clw + bt36h[iloc]*regr_coeff_clw[0]; for (size_t nvar_clw=0; nvar_clw < pred_var_clw.size(); ++nvar_clw) { clw = clw + (pred_var_clw[nvar_clw] * regr_coeff_clw[nvar_clw+1]); } clw = std::max(0.0f, clw); clw = std::min(6.0f, clw); out[iloc] = clw; } } } // ----------------------------------------------------------------------------- const ufo::Variables & CLWRetMW::requiredVariables() const { return invars_; } // ----------------------------------------------------------------------------- } // namespace ufo
45.045822
99
0.57366
fmahebert
81e8caa080f0e05f4896cf588c709a8e75e495f4
76
hpp
C++
examples/example2/user1.hpp
ldrozdz93/cpp-visitor-pattern
542dd041178be665c94b9364a3595ff7cb60e40a
[ "MIT" ]
1
2022-01-13T07:04:41.000Z
2022-01-13T07:04:41.000Z
examples/example2/user1.hpp
ldrozdz93/cpp-visitor-pattern
542dd041178be665c94b9364a3595ff7cb60e40a
[ "MIT" ]
null
null
null
examples/example2/user1.hpp
ldrozdz93/cpp-visitor-pattern
542dd041178be665c94b9364a3595ff7cb60e40a
[ "MIT" ]
null
null
null
#pragma once #include "base.hpp" int user1_value_by_visitation(Base& base);
19
42
0.789474
ldrozdz93
81ea1d4f7ee99284ee21a9fb7e0e834aaf8adce4
2,437
cpp
C++
test/test_reversed.cpp
memgraph/cppitertools
d990df92820c3493eb1dbdd92fd23463a7089b6b
[ "BSD-2-Clause" ]
2
2017-08-19T08:12:19.000Z
2022-02-23T20:34:33.000Z
test/test_reversed.cpp
memgraph/cppitertools
d990df92820c3493eb1dbdd92fd23463a7089b6b
[ "BSD-2-Clause" ]
null
null
null
test/test_reversed.cpp
memgraph/cppitertools
d990df92820c3493eb1dbdd92fd23463a7089b6b
[ "BSD-2-Clause" ]
null
null
null
#include <reversed.hpp> #include <array> #include <string> #include <utility> #include <vector> #include "catch.hpp" #define DECLARE_REVERSE_ITERATOR #include "helpers.hpp" #undef DECLARE_REVERSE_ITERATOR using iter::reversed; using Vec = const std::vector<int>; TEST_CASE("reversed: can reverse a vector", "[reversed]") { Vec ns = {10, 20, 30, 40}; std::vector<int> v; SECTION("Normal call") { auto r = reversed(ns); v.assign(std::begin(r), std::end(r)); } SECTION("Pipe") { auto r = ns | reversed; v.assign(std::begin(r), std::end(r)); } Vec vc = {40, 30, 20, 10}; REQUIRE(v == vc); } #if 0 TEST_CASE("reversed: Works with different begin and end types", "[reversed]") { CharRange cr{'d'}; auto r = reversed(cr); Vec v(r.begin(), r.end()); Vec vc{'c', 'b', 'a'}; REQUIRE(v == vc); } #endif TEST_CASE("reversed: can reverse an array", "[reversed]") { int ns[] = {10, 20, 30, 40}; auto r = reversed(ns); Vec v(std::begin(r), std::end(r)); Vec vc = {40, 30, 20, 10}; REQUIRE(v == vc); } TEST_CASE("reversed: empty when iterable is empty", "[reversed]") { Vec emp{}; auto r = reversed(emp); REQUIRE(std::begin(r) == std::end(r)); } TEST_CASE("reversed: moves rvalues and binds to lvalues", "[reversed]") { itertest::BasicIterable<int> bi{1, 2}; itertest::BasicIterable<int> bi2{1, 2}; reversed(bi); REQUIRE_FALSE(bi.was_moved_from()); reversed(std::move(bi2)); REQUIRE(bi2.was_moved_from()); } TEST_CASE("reversed: doesn't move or copy elements of array", "[reversed]") { constexpr itertest::SolidInt arr[] = {{6}, {7}, {8}}; for (auto&& i : reversed(arr)) { (void)i; } } TEST_CASE("reversed: with iterable doesn't move or copy elems", "[reversed]") { constexpr std::array<itertest::SolidInt, 3> arr{{{6}, {7}, {8}}}; for (auto&& i : reversed(arr)) { (void)i; } } TEST_CASE("reversed: iterator meets requirements", "[reversed]") { Vec v; auto r = reversed(v); REQUIRE(itertest::IsIterator<decltype(std::begin(r))>::value); int a[1]; auto ra = reversed(a); REQUIRE(itertest::IsIterator<decltype(std::begin(ra))>::value); } template <typename T> using ImpT = decltype(reversed(std::declval<T>())); TEST_CASE("reversed: has correct ctor and assign ops", "[reversed]") { REQUIRE(itertest::IsMoveConstructibleOnly<ImpT<std::string&>>::value); REQUIRE(itertest::IsMoveConstructibleOnly<ImpT<std::string>>::value); }
24.128713
79
0.63808
memgraph
81ec34342b8d7fca921401c10aa3c77c8d4e6ee5
4,438
cpp
C++
src/lib/tide/javascript/js_method.cpp
badlee/TideSDK
fe6f6c93c6cab3395121696f48d3b55d43e1eddd
[ "Apache-2.0" ]
1
2021-09-18T10:10:39.000Z
2021-09-18T10:10:39.000Z
src/lib/tide/javascript/js_method.cpp
hexmode/TideSDK
2c0276de08d7b760b53416bbd8038d79b8474fc5
[ "Apache-2.0" ]
1
2022-02-08T08:45:29.000Z
2022-02-08T08:45:29.000Z
src/lib/tide/javascript/js_method.cpp
hexmode/TideSDK
2c0276de08d7b760b53416bbd8038d79b8474fc5
[ "Apache-2.0" ]
null
null
null
/** * Copyright (c) 2012 - 2014 TideSDK contributors * http://www.tidesdk.org * Includes modified sources under the Apache 2 License * Copyright (c) 2008 - 2012 Appcelerator Inc * Refer to LICENSE for details of distribution and use. **/ #include "javascript_module.h" namespace tide { KKJSMethod::KKJSMethod(JSContextRef context, JSObjectRef jsobject, JSObjectRef thisObject) : TiMethod("JavaScript.KKJSMethod"), context(NULL), jsobject(jsobject), thisObject(thisObject) { /* KJS methods run in the global context that they originated from * this seems to prevent nasty crashes from trying to access invalid * contexts later. Global contexts need to be registered by all modules * that use a KJS context. */ JSObjectRef globalObject = JSContextGetGlobalObject(context); JSGlobalContextRef globalContext = JSUtil::GetGlobalContext(globalObject); // This context hasn't been registered. Something has gone pretty // terribly wrong and TideSDK will likely crash soon. Nonetheless, keep // the user up-to-date to keep their hopes up. if (globalContext == NULL) std::cerr << "Could not locate global context for a KJS method." << " One of the modules is misbehaving." << std::endl; this->context = globalContext; JSUtil::ProtectGlobalContext(this->context); JSValueProtect(this->context, jsobject); if (thisObject != NULL) JSValueProtect(this->context, thisObject); this->tiObject = new KKJSObject(this->context, jsobject); } KKJSMethod::~KKJSMethod() { JSValueUnprotect(this->context, this->jsobject); if (this->thisObject != NULL) JSValueUnprotect(this->context, this->thisObject); JSUtil::UnprotectGlobalContext(this->context); } ValueRef KKJSMethod::Get(const char *name) { return tiObject->Get(name); } void KKJSMethod::Set(const char *name, ValueRef value) { return tiObject->Set(name, value); } bool KKJSMethod::Equals(TiObjectRef other) { return this->tiObject->Equals(other); } SharedStringList KKJSMethod::GetPropertyNames() { return tiObject->GetPropertyNames(); } bool KKJSMethod::HasProperty(const char* name) { return tiObject->HasProperty(name); } bool KKJSMethod::SameContextGroup(JSContextRef c) { return tiObject->SameContextGroup(c); } JSObjectRef KKJSMethod::GetJSObject() { return this->jsobject; } ValueRef KKJSMethod::Call(JSObjectRef thisObject, const ValueList& args) { JSValueRef* jsArgs = new JSValueRef[args.size()]; for (int i = 0; i < (int) args.size(); i++) { ValueRef arg = args.at(i); jsArgs[i] = JSUtil::ToJSValue(arg, this->context); } JSValueRef exception = NULL; JSValueRef jsValue = JSObjectCallAsFunction(this->context, thisObject, this->thisObject, args.size(), jsArgs, &exception); delete [] jsArgs; // clean up args if (jsValue == NULL && exception != NULL) //exception thrown { ValueRef exceptionValue = JSUtil::ToTiValue(exception, this->context, NULL); throw ValueException(exceptionValue); } return JSUtil::ToTiValue(jsValue, this->context, NULL); } ValueRef KKJSMethod::Call(const ValueList& args) { return this->Call(this->jsobject, args); } ValueRef KKJSMethod::Call(TiObjectRef thisObject, const ValueList& args) { JSValueRef thisObjectValue = JSUtil::ToJSValue(Value::NewObject(thisObject), this->context); if (!JSValueIsObject(this->context, thisObjectValue)) { SharedString ss(thisObject->DisplayString()); throw ValueException::FromFormat("Could not convert %s to JSObjectRef for KKJSMethod::Call", ss->c_str()); } JSObjectRef jsThisObject = JSValueToObject(this->context, thisObjectValue, NULL); if (!jsThisObject) { SharedString ss(thisObject->DisplayString()); throw ValueException::FromFormat("Could not convert %s to JSObjectRef for KKJSMethod::Call", ss->c_str()); } return this->Call(jsThisObject, args); } }
32.15942
104
0.632267
badlee
81ec746e39c96792fecb45725eb7a543a1cd2e87
2,765
hpp
C++
lite/fpga/KD/layout.hpp
banbishan/Paddle-Lite
02517c12c31609f413a1c47a83e25d3fbff07074
[ "Apache-2.0" ]
1
2019-08-21T05:54:42.000Z
2019-08-21T05:54:42.000Z
lite/fpga/KD/layout.hpp
banbishan/Paddle-Lite
02517c12c31609f413a1c47a83e25d3fbff07074
[ "Apache-2.0" ]
null
null
null
lite/fpga/KD/layout.hpp
banbishan/Paddle-Lite
02517c12c31609f413a1c47a83e25d3fbff07074
[ "Apache-2.0" ]
1
2019-10-11T09:34:49.000Z
2019-10-11T09:34:49.000Z
/* 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. */ #pragma once #include <vector> #include "lite/fpga/KD/alignment.h" namespace paddle { namespace zynqmp { enum LayoutType { N, NC, NCHW, NHWC, NHW, }; class Layout { public: virtual int numIndex() = 0; virtual int channelIndex() { return -1; } virtual int heightIndex() { return -1; } virtual int widthIndex() { return -1; } virtual int alignedElementCount(const std::vector<int>& dims) = 0; virtual int elementCount(const std::vector<int>& dims) = 0; }; struct NCHW : Layout { int numIndex() { return 0; } int channelIndex() { return 1; } int heightIndex() { return 2; } int widthIndex() { return 3; } int alignedElementCount(const std::vector<int>& dims) { return dims[0] * dims[2] * align_image(dims[1] * dims[3]); } virtual int elementCount(const std::vector<int>& dims) { return dims[0] * dims[1] * dims[2] * dims[3]; } }; struct NHWC : Layout { int numIndex() { return 0; } int heightIndex() { return 1; } int widthIndex() { return 2; } int channelIndex() { return 3; } int alignedElementCount(const std::vector<int>& dims) { return dims[0] * dims[1] * align_image(dims[2] * dims[3]); } virtual int elementCount(const std::vector<int>& dims) { return dims[0] * dims[1] * dims[2] * dims[3]; } }; struct NC : Layout { int numIndex() { return 0; } int channelIndex() { return 1; } int alignedElementCount(const std::vector<int>& dims) { return dims[0] * dims[1]; } virtual int elementCount(const std::vector<int>& dims) { return dims[0] * dims[1]; } }; struct N : Layout { int numIndex() { return 0; } int alignedElementCount(const std::vector<int>& dims) { return dims[0]; } virtual int elementCount(const std::vector<int>& dims) { return dims[0]; } }; struct NHW : Layout { int numIndex() { return 0; } int heightIndex() { return 1; } int widthIndex() { return 2; } int alignedElementCount(const std::vector<int>& dims) { // TODO(chonwhite) align it; return dims[0] * dims[1] * dims[2]; } virtual int elementCount(const std::vector<int>& dims) { return dims[0] * dims[1] * dims[2]; } }; } // namespace zynqmp } // namespace paddle
27.65
76
0.666908
banbishan
81f03799cb719d11f4c00ae5c5f60e01313a0903
854
cpp
C++
August_2020_challange/Day 7.cpp
jv640/LeetCode
af07ebf2f4cc5f28a61f78d952febe10782b0e93
[ "MIT" ]
null
null
null
August_2020_challange/Day 7.cpp
jv640/LeetCode
af07ebf2f4cc5f28a61f78d952febe10782b0e93
[ "MIT" ]
null
null
null
August_2020_challange/Day 7.cpp
jv640/LeetCode
af07ebf2f4cc5f28a61f78d952febe10782b0e93
[ "MIT" ]
null
null
null
/* Problem : Vertical Order Traversal of a Binary Tree */ // Approach make variable x and y and attach them with every node x for horizontal distance and y for vertical distance // Code map<int,set<pair<int,int>>> ans; void pre( TreeNode *root, int horizontal_Level, int vertical_Level ){ if(!root) return ; ans[horizontal_Level].insert({vertical_Level,root->val}); pre(root->left,horizontal_Level-1,vertical_Level+1); pre(root->right,horizontal_Level+1,vertical_Level+1); } public: vector<vector<int>> verticalTraversal(TreeNode* root) { pre(root,0 , 0 ); vector<vector<int>> v; for( auto e : ans ){ vector<int> c; for( auto x : e.second ) c.push_back(x.second); v.push_back(c); } return v; }
32.846154
121
0.59719
jv640
81f1b89a3bced4fa9428e1eab4d8b19028256f04
268
cpp
C++
1.cpp
baicaihenxiao/LeetCode-Myself
f88fa5b5e76a913d6d9395d75571c8d7c46d37f5
[ "MIT" ]
null
null
null
1.cpp
baicaihenxiao/LeetCode-Myself
f88fa5b5e76a913d6d9395d75571c8d7c46d37f5
[ "MIT" ]
6
2021-03-31T02:43:24.000Z
2022-01-04T16:40:26.000Z
1.cpp
baicaihenxiao/LeetCode-Myself
f88fa5b5e76a913d6d9395d75571c8d7c46d37f5
[ "MIT" ]
null
null
null
#include <iostream> #include <stdio.h> #include <string> #include <fstream> #include <vector> #include <unordered_map> #include <stack> #include <deque> #include <algorithm> using namespace std; int main() { cout << "Hello World!" << endl; return 0; }
13.4
35
0.660448
baicaihenxiao
81f22282779ab4d0066af37af146da671c028333
312
hpp
C++
rmvmath/types/quaternion_double_type.hpp
vitali-kurlovich/RMMath
a982b89e5db08e9cd16cb08e92839a315b6198dc
[ "MIT" ]
null
null
null
rmvmath/types/quaternion_double_type.hpp
vitali-kurlovich/RMMath
a982b89e5db08e9cd16cb08e92839a315b6198dc
[ "MIT" ]
null
null
null
rmvmath/types/quaternion_double_type.hpp
vitali-kurlovich/RMMath
a982b89e5db08e9cd16cb08e92839a315b6198dc
[ "MIT" ]
null
null
null
// // Created by Vitali Kurlovich on 4/13/16. // #ifndef RMVECTORMATH_QUATERNION_DOUBLE_TYPE_HPP #define RMVECTORMATH_QUATERNION_DOUBLE_TYPE_HPP #include "../quaternion/TQuaternion.hpp" namespace rmmath { typedef quaternion::TQuaternion<double> dquat; } #endif //RMVECTORMATH_QUATERNION_DOUBLE_TYPE_HPP
19.5
50
0.801282
vitali-kurlovich
81f28547a74d8f334bab2fb9b6f11cd76da21412
2,679
cc
C++
chrome/browser/importer/toolbar_importer_utils.cc
pozdnyakov/chromium-crosswalk
0fb25c7278bf1d93e53a3b0bcb75aa8b99d4b26e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
9
2018-09-21T05:36:12.000Z
2021-11-15T15:14:36.000Z
chrome/browser/importer/toolbar_importer_utils.cc
pozdnyakov/chromium-crosswalk
0fb25c7278bf1d93e53a3b0bcb75aa8b99d4b26e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/importer/toolbar_importer_utils.cc
pozdnyakov/chromium-crosswalk
0fb25c7278bf1d93e53a3b0bcb75aa8b99d4b26e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
3
2018-11-28T14:54:13.000Z
2020-07-02T07:36:07.000Z
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/importer/toolbar_importer_utils.h" #include <string> #include <vector> #include "base/bind.h" #include "base/strings/string_split.h" #include "chrome/browser/profiles/profile.h" #include "content/public/browser/browser_thread.h" #include "googleurl/src/gurl.h" #include "net/cookies/cookie_store.h" #include "net/url_request/url_request_context.h" #include "net/url_request/url_request_context_getter.h" using content::BrowserThread; namespace { const char kGoogleDomainUrl[] = "http://.google.com/"; const char kGoogleDomainSecureCookieId[] = "SID="; const char kSplitStringToken = ';'; } namespace toolbar_importer_utils { void OnGetCookies(const base::Callback<void(bool)>& callback, const std::string& cookies) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); std::vector<std::string> cookie_list; base::SplitString(cookies, kSplitStringToken, &cookie_list); for (std::vector<std::string>::iterator current = cookie_list.begin(); current != cookie_list.end(); ++current) { size_t position = (*current).find(kGoogleDomainSecureCookieId); if (position == 0) { callback.Run(true); return; } } callback.Run(false); } void OnFetchComplete(const base::Callback<void(bool)>& callback, const std::string& cookies) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&OnGetCookies, callback, cookies)); } void FetchCookiesOnIOThread( const base::Callback<void(bool)>& callback, net::URLRequestContextGetter* context_getter) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); net::CookieStore* store = context_getter-> GetURLRequestContext()->cookie_store(); GURL url(kGoogleDomainUrl); net::CookieOptions options; options.set_include_httponly(); // The SID cookie might be httponly. store->GetCookiesWithOptionsAsync( url, options, base::Bind(&toolbar_importer_utils::OnFetchComplete, callback)); } void IsGoogleGAIACookieInstalled(const base::Callback<void(bool)>& callback, Profile* profile) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); if (!callback.is_null()) { BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::Bind(&FetchCookiesOnIOThread, callback, base::Unretained(profile->GetRequestContext()))); } } } // namespace toolbar_importer_utils
33.4875
78
0.711459
pozdnyakov
81f2a8043fea1e31ec5aca13a1808b6898969c0e
382
cpp
C++
sledge/test/analyze/FN_ptr_arith_bad.cpp
sujin0529/infer
f08a09d6896ac2a22081ead4830eb86c64af8813
[ "MIT" ]
2
2021-12-17T13:38:34.000Z
2021-12-17T14:06:53.000Z
sledge/test/analyze/FN_ptr_arith_bad.cpp
sujin0529/infer
f08a09d6896ac2a22081ead4830eb86c64af8813
[ "MIT" ]
7
2017-12-03T16:09:45.000Z
2018-01-08T15:15:34.000Z
sledge/test/analyze/FN_ptr_arith_bad.cpp
sujin0529/infer
f08a09d6896ac2a22081ead4830eb86c64af8813
[ "MIT" ]
2
2020-06-23T00:43:10.000Z
2022-03-24T06:24:50.000Z
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ int main() { auto x = new int[8]; auto y = new int[8]; y[0] = 42; auto x_ptr = x + 8; // one past the end if (x_ptr == &y[0]) // valid *x_ptr = 23; // UB return y[0]; }
20.105263
66
0.586387
sujin0529
81f84de16b7ddce4b6c0ae26e79c0b2ed543fa4b
907
hh
C++
src/pks/flow/FracturePermModel_Linear.hh
fmyuan/amanzi
edb7b815ae6c22956c8519acb9d87b92a9915ed4
[ "RSA-MD" ]
37
2017-04-26T16:27:07.000Z
2022-03-01T07:38:57.000Z
src/pks/flow/FracturePermModel_Linear.hh
fmyuan/amanzi
edb7b815ae6c22956c8519acb9d87b92a9915ed4
[ "RSA-MD" ]
494
2016-09-14T02:31:13.000Z
2022-03-13T18:57:05.000Z
src/pks/flow/FracturePermModel_Linear.hh
fmyuan/amanzi
edb7b815ae6c22956c8519acb9d87b92a9915ed4
[ "RSA-MD" ]
43
2016-09-26T17:58:40.000Z
2022-03-25T02:29:59.000Z
/* Flow PK Copyright 2010-201x held jointly by LANS/LANL, LBNL, and PNNL. Amanzi is released under the three-clause BSD License. The terms of use and "as is" disclaimer for this license are provided in the top-level COPYRIGHT file. Author: Konstantin Lipnikov (lipnikov@lanl.gov) Linear model for effective permeability in fracutres. */ #ifndef AMANZI_FRACTURE_PERM_MODEL_LINEAR_HH_ #define AMANZI_FRACTURE_PERM_MODEL_LINEAR_HH_ #include "Teuchos_ParameterList.hpp" #include "FracturePermModel.hh" namespace Amanzi { namespace Flow { class FracturePermModel_Linear : public FracturePermModel { public: explicit FracturePermModel_Linear(Teuchos::ParameterList& plist) {} ~FracturePermModel_Linear() {}; // required methods from the base class inline double Permeability(double aperture) { return aperture / 12; } }; } // namespace Flow } // namespace Amanzi #endif
24.513514
71
0.76516
fmyuan
81fa269334856aaedcbfbc00cbb504cf710def21
970
cpp
C++
3rdParty/boost/1.71.0/libs/hana/example/set/searchable.cpp
rajeev02101987/arangodb
817e6c04cb82777d266f3b444494140676da98e2
[ "Apache-2.0" ]
12,278
2015-01-29T17:11:33.000Z
2022-03-31T21:12:00.000Z
3rdParty/boost/1.71.0/libs/hana/example/set/searchable.cpp
rajeev02101987/arangodb
817e6c04cb82777d266f3b444494140676da98e2
[ "Apache-2.0" ]
9,469
2015-01-30T05:33:07.000Z
2022-03-31T16:17:21.000Z
3rdParty/boost/1.71.0/libs/hana/example/set/searchable.cpp
rajeev02101987/arangodb
817e6c04cb82777d266f3b444494140676da98e2
[ "Apache-2.0" ]
1,343
2017-12-08T19:47:19.000Z
2022-03-26T11:31:36.000Z
// Copyright Louis Dionne 2013-2017 // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) #include <boost/hana/assert.hpp> #include <boost/hana/at_key.hpp> #include <boost/hana/equal.hpp> #include <boost/hana/find.hpp> #include <boost/hana/integral_constant.hpp> #include <boost/hana/optional.hpp> #include <boost/hana/set.hpp> namespace hana = boost::hana; int main() { constexpr auto xs = hana::make_set(hana::int_c<0>, hana::int_c<1>, hana::int_c<2>); BOOST_HANA_CONSTANT_CHECK(hana::find(xs, hana::int_c<0>) == hana::just(hana::int_c<0>)); BOOST_HANA_CONSTANT_CHECK(hana::find(xs, hana::int_c<3>) == hana::nothing); // operator[] is equivalent to at_key BOOST_HANA_CONSTANT_CHECK(xs[hana::int_c<2>] == hana::int_c<2>); // long_c<0> == int_<0>, and therefore int_<0> is found BOOST_HANA_CONSTANT_CHECK(xs[hana::long_c<0>] == hana::int_c<0>); }
37.307692
92
0.705155
rajeev02101987
3b4fe2e7cd59041d8fe62c572e6f3f466ea7a61c
2,736
cpp
C++
Engine/Source/Runtime/Engine/Private/Animation/AnimNode_TransitionPoseEvaluator.cpp
PopCap/GameIdea
201e1df50b2bc99afc079ce326aa0a44b178a391
[ "BSD-2-Clause" ]
null
null
null
Engine/Source/Runtime/Engine/Private/Animation/AnimNode_TransitionPoseEvaluator.cpp
PopCap/GameIdea
201e1df50b2bc99afc079ce326aa0a44b178a391
[ "BSD-2-Clause" ]
2
2015-06-21T17:38:11.000Z
2015-06-22T20:54:42.000Z
Engine/Source/Runtime/Engine/Private/Animation/AnimNode_TransitionPoseEvaluator.cpp
PopCap/GameIdea
201e1df50b2bc99afc079ce326aa0a44b178a391
[ "BSD-2-Clause" ]
null
null
null
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved. #include "EnginePrivate.h" #include "Animation/AnimNode_TransitionPoseEvaluator.h" ///////////////////////////////////////////////////// // FAnimNode_TransitionPoseEvaluator FAnimNode_TransitionPoseEvaluator::FAnimNode_TransitionPoseEvaluator() : DataSource(EEvaluatorDataSource::EDS_SourcePose) , EvaluatorMode(EEvaluatorMode::EM_Standard) , FramesToCachePose(1) , CacheFramesRemaining(1) { } void FAnimNode_TransitionPoseEvaluator::Initialize(const FAnimationInitializeContext& Context) { if (EvaluatorMode == EEvaluatorMode::EM_Freeze) { // EM_Freeze must evaluate 1 frame to get the initial pose. This cached frame will not call update, only evaluate CacheFramesRemaining = 1; } else if (EvaluatorMode == EEvaluatorMode::EM_DelayedFreeze) { // EM_DelayedFreeze can evaluate multiple frames, but must evaluate at least one. CacheFramesRemaining = FMath::Max(FramesToCachePose, 1); } } void FAnimNode_TransitionPoseEvaluator::CacheBones(const FAnimationCacheBonesContext& Context) { CachedPose.SetBoneContainer(&Context.AnimInstance->RequiredBones); CachedCurve.InitFrom(Context.AnimInstance); } void FAnimNode_TransitionPoseEvaluator::Update(const FAnimationUpdateContext& Context) { // updating is all handled in state machine } void FAnimNode_TransitionPoseEvaluator::Evaluate(FPoseContext& Output) { // the cached pose is evaluated in the state machine and set via CachePose(). // This is because we need information about the transition that is not available at this level Output.Pose.CopyBonesFrom(CachedPose); Output.Curve.CopyFrom(CachedCurve); if ((EvaluatorMode != EEvaluatorMode::EM_Standard) && (CacheFramesRemaining > 0)) { CacheFramesRemaining = FMath::Max(CacheFramesRemaining - 1, 0); } } void FAnimNode_TransitionPoseEvaluator::GatherDebugData(FNodeDebugData& DebugData) { FString DebugLine = DebugData.GetNodeName(this); DebugLine += FString::Printf(TEXT("(Cached Frames Remaining: %i)"), CacheFramesRemaining); DebugData.AddDebugItem(DebugLine); } bool FAnimNode_TransitionPoseEvaluator::InputNodeNeedsUpdate() const { // EM_Standard mode always updates and EM_DelayedFreeze mode only updates if there are cache frames remaining return (EvaluatorMode == EEvaluatorMode::EM_Standard) || ((EvaluatorMode == EEvaluatorMode::EM_DelayedFreeze) && (CacheFramesRemaining > 0)); } bool FAnimNode_TransitionPoseEvaluator::InputNodeNeedsEvaluate() const { return (EvaluatorMode == EEvaluatorMode::EM_Standard) || (CacheFramesRemaining > 0); } void FAnimNode_TransitionPoseEvaluator::CachePose(FPoseContext& PoseToCache) { CachedPose.CopyBonesFrom(PoseToCache.Pose); CachedCurve.CopyFrom(PoseToCache.Curve); }
35.076923
142
0.783991
PopCap
3b506a36b07018b302038cfb8c986422bcefecaf
14,713
hxx
C++
linux_packages/source/hypre-2.9.0b/src/babel/bHYPREClient-CX/bHYPRE_IJParCSRVector.hxx
pangkeji/warp3d
8b273b337e557f734298940a63291697cd561d02
[ "NCSA" ]
75
2015-07-06T18:14:20.000Z
2022-01-24T02:54:32.000Z
linux_packages/source/hypre-2.9.0b/src/babel/bHYPREClient-CX/bHYPRE_IJParCSRVector.hxx
pangkeji/warp3d
8b273b337e557f734298940a63291697cd561d02
[ "NCSA" ]
15
2017-04-07T18:09:58.000Z
2022-02-28T01:48:33.000Z
linux_packages/source/hypre-2.9.0b/src/babel/bHYPREClient-CX/bHYPRE_IJParCSRVector.hxx
pangkeji/warp3d
8b273b337e557f734298940a63291697cd561d02
[ "NCSA" ]
41
2015-05-24T23:24:54.000Z
2021-12-13T22:07:45.000Z
// // File: bHYPRE_IJParCSRVector.hxx // Symbol: bHYPRE.IJParCSRVector-v1.0.0 // Symbol Type: class // Babel Version: 1.0.4 // Description: Client-side glue code for bHYPRE.IJParCSRVector // // WARNING: Automatically generated; changes will be lost // // #ifndef included_bHYPRE_IJParCSRVector_hxx #define included_bHYPRE_IJParCSRVector_hxx #ifndef included_sidl_cxx_hxx #include "sidl_cxx.hxx" #endif // declare class before main #includes // (this alleviates circular #include guard problems)[BUG#393] namespace bHYPRE { class IJParCSRVector; } // end namespace bHYPRE // Some compilers need to define array template before the specializations namespace sidl { template<> class array< ::bHYPRE::IJParCSRVector >; } // // Forward declarations for method dependencies. // namespace bHYPRE { class IJParCSRVector; } // end namespace bHYPRE namespace bHYPRE { class MPICommunicator; } // end namespace bHYPRE namespace bHYPRE { class Vector; } // end namespace bHYPRE namespace sidl { class RuntimeException; } // end namespace sidl #ifndef included_sidl_cxx_hxx #include "sidl_cxx.hxx" #endif #ifndef included_bHYPRE_IJParCSRVector_IOR_h #include "bHYPRE_IJParCSRVector_IOR.h" #endif #ifndef included_bHYPRE_IJVectorView_hxx #include "bHYPRE_IJVectorView.hxx" #endif #ifndef included_bHYPRE_Vector_hxx #include "bHYPRE_Vector.hxx" #endif #ifndef included_sidl_BaseClass_hxx #include "sidl_BaseClass.hxx" #endif namespace sidl { namespace rmi { class Call; class Return; class Ticket; } namespace rmi { class InstanceHandle; } } namespace bHYPRE { /** * Symbol "bHYPRE.IJParCSRVector" (version 1.0.0) * * The IJParCSR vector class. * * Objects of this type can be cast to IJVectorView or Vector * objects using the {\tt \_\_cast} methods. */ class IJParCSRVector: public virtual ::bHYPRE::IJVectorView, public virtual ::bHYPRE::Vector, public virtual ::sidl::BaseClass { ////////////////////////////////////////////////// // // Special methods for throwing exceptions // private: static void throwException0( struct sidl_BaseInterface__object *_exception ) // throws: ; ////////////////////////////////////////////////// // // User Defined Methods // public: /** * This function is the preferred way to create an IJParCSR Vector. */ static ::bHYPRE::IJParCSRVector Create ( /* in */::bHYPRE::MPICommunicator mpi_comm, /* in */int32_t jlower, /* in */int32_t jupper ) ; /** * Set the local range for a vector object. Each process owns * some unique consecutive range of vector unknowns, indicated * by the global indices {\tt jlower} and {\tt jupper}. The * data is required to be such that the value of {\tt jlower} on * any process $p$ be exactly one more than the value of {\tt * jupper} on process $p-1$. Note that the first index of the * global vector may start with any integer value. In * particular, one may use zero- or one-based indexing. * * Collective. */ int32_t SetLocalRange ( /* in */int32_t jlower, /* in */int32_t jupper ) ; /** * Sets values in vector. The arrays {\tt values} and {\tt * indices} are of dimension {\tt nvalues} and contain the * vector values to be set and the corresponding global vector * indices, respectively. Erases any previous values at the * specified locations and replaces them with new ones. * * Not collective. */ int32_t SetValues ( /* in */int32_t nvalues, /* in rarray[nvalues] */int32_t* indices, /* in rarray[nvalues] */double* values ) ; /** * Sets values in vector. The arrays {\tt values} and {\tt * indices} are of dimension {\tt nvalues} and contain the * vector values to be set and the corresponding global vector * indices, respectively. Erases any previous values at the * specified locations and replaces them with new ones. * * Not collective. */ int32_t SetValues ( /* in rarray[nvalues] */::sidl::array<int32_t> indices, /* in rarray[nvalues] */::sidl::array<double> values ) ; /** * Adds to values in vector. Usage details are analogous to * {\tt SetValues}. * * Not collective. */ int32_t AddToValues ( /* in */int32_t nvalues, /* in rarray[nvalues] */int32_t* indices, /* in rarray[nvalues] */double* values ) ; /** * Adds to values in vector. Usage details are analogous to * {\tt SetValues}. * * Not collective. */ int32_t AddToValues ( /* in rarray[nvalues] */::sidl::array<int32_t> indices, /* in rarray[nvalues] */::sidl::array<double> values ) ; /** * Returns range of the part of the vector owned by this * processor. */ int32_t GetLocalRange ( /* out */int32_t& jlower, /* out */int32_t& jupper ) ; /** * Gets values in vector. Usage details are analogous to {\tt * SetValues}. * * Not collective. */ int32_t GetValues ( /* in */int32_t nvalues, /* in rarray[nvalues] */int32_t* indices, /* inout rarray[nvalues] */double* values ) ; /** * Gets values in vector. Usage details are analogous to {\tt * SetValues}. * * Not collective. */ int32_t GetValues ( /* in rarray[nvalues] */::sidl::array<int32_t> indices, /* inout rarray[nvalues] */::sidl::array<double>& values ) ; /** * Print the vector to file. This is mainly for debugging * purposes. */ int32_t Print ( /* in */const ::std::string& filename ) ; /** * Read the vector from file. This is mainly for debugging * purposes. */ int32_t Read ( /* in */const ::std::string& filename, /* in */::bHYPRE::MPICommunicator comm ) ; /** * Set the MPI Communicator. DEPRECATED, Use Create() */ int32_t SetCommunicator ( /* in */::bHYPRE::MPICommunicator mpi_comm ) ; /** * The Destroy function doesn't necessarily destroy anything. * It is just another name for deleteRef. Thus it decrements the * object's reference count. The Babel memory management system will * destroy the object if the reference count goes to zero. */ void Destroy() ; /** * Prepare an object for setting coefficient values, whether for * the first time or subsequently. */ int32_t Initialize() ; /** * Finalize the construction of an object before using, either * for the first time or on subsequent uses. {\tt Initialize} * and {\tt Assemble} always appear in a matched set, with * Initialize preceding Assemble. Values can only be set in * between a call to Initialize and Assemble. */ int32_t Assemble() ; /** * Set {\tt self} to 0. */ int32_t Clear() ; /** * Copy data from x into {\tt self}. */ int32_t Copy ( /* in */::bHYPRE::Vector x ) ; /** * Create an {\tt x} compatible with {\tt self}. * The new vector's data is not specified. * * NOTE: When this method is used in an inherited class, the * cloned {\tt Vector} object can be cast to an object with the * inherited class type. */ int32_t Clone ( /* out */::bHYPRE::Vector& x ) ; /** * Scale {\tt self} by {\tt a}. */ int32_t Scale ( /* in */double a ) ; /** * Compute {\tt d}, the inner-product of {\tt self} and {\tt x}. */ int32_t Dot ( /* in */::bHYPRE::Vector x, /* out */double& d ) ; /** * Add {\tt a}{\tt x} to {\tt self}. */ int32_t Axpy ( /* in */double a, /* in */::bHYPRE::Vector x ) ; ////////////////////////////////////////////////// // // End User Defined Methods // (everything else in this file is specific to // Babel's C++ bindings) // public: typedef struct bHYPRE_IJParCSRVector__object ior_t; typedef struct bHYPRE_IJParCSRVector__external ext_t; typedef struct bHYPRE_IJParCSRVector__sepv sepv_t; // default constructor IJParCSRVector() { } // static constructor static ::bHYPRE::IJParCSRVector _create(); // RMI constructor static ::bHYPRE::IJParCSRVector _create( /*in*/ const std::string& url ); // RMI connect static inline ::bHYPRE::IJParCSRVector _connect( /*in*/ const std::string& url ) { return _connect(url, true); } // RMI connect 2 static ::bHYPRE::IJParCSRVector _connect( /*in*/ const std::string& url, /*in*/ const bool ar ); // default destructor virtual ~IJParCSRVector () { } // copy constructor IJParCSRVector ( const IJParCSRVector& original ); // assignment operator IJParCSRVector& operator= ( const IJParCSRVector& rhs ); protected: // Internal data wrapping method static ior_t* _wrapObj(void* private_data); public: // conversion from ior to C++ class IJParCSRVector ( IJParCSRVector::ior_t* ior ); // Alternate constructor: does not call addRef() // (sets d_weak_reference=isWeak) // For internal use by Impls (fixes bug#275) IJParCSRVector ( IJParCSRVector::ior_t* ior, bool isWeak ); inline ior_t* _get_ior() const throw() { return reinterpret_cast< ior_t*>(d_self); } void _set_ior( ior_t* ptr ) throw () { d_self = reinterpret_cast< void*>(ptr); } bool _is_nil() const throw () { return (d_self==0); } bool _not_nil() const throw () { return (d_self!=0); } bool operator !() const throw () { return (d_self==0); } static inline const char * type_name() throw () { return "bHYPRE.IJParCSRVector";} static struct bHYPRE_IJParCSRVector__object* _cast(const void* src); // execute member function by name void _exec(const std::string& methodName, ::sidl::rmi::Call& inArgs, ::sidl::rmi::Return& outArgs); // exec static member function by name static void _sexec(const std::string& methodName, ::sidl::rmi::Call& inArgs, ::sidl::rmi::Return& outArgs); /** * Get the URL of the Implementation of this object (for RMI) */ ::std::string _getURL() // throws: // ::sidl::RuntimeException ; /** * Method to set whether or not method hooks should be invoked. */ void _set_hooks ( /* in */bool on ) // throws: // ::sidl::RuntimeException ; /** * Static Method to set whether or not method hooks should be invoked. */ static void _set_hooks_static ( /* in */bool on ) // throws: // ::sidl::RuntimeException ; // return true iff object is remote bool _isRemote() const { ior_t* self = const_cast<ior_t*>(_get_ior() ); struct sidl_BaseInterface__object *throwaway_exception; return (*self->d_epv->f__isRemote)(self, &throwaway_exception) == TRUE; } // return true iff object is local bool _isLocal() const { return !_isRemote(); } protected: // Pointer to external (DLL loadable) symbols (shared among instances) static const ext_t * s_ext; public: static const ext_t * _get_ext() throw ( ::sidl::NullIORException ); static const sepv_t * _get_sepv() { return (*(_get_ext()->getStaticEPV))(); } }; // end class IJParCSRVector } // end namespace bHYPRE extern "C" { #pragma weak bHYPRE_IJParCSRVector__connectI #pragma weak bHYPRE_IJParCSRVector__rmicast /** * Cast method for interface and class type conversions. */ struct bHYPRE_IJParCSRVector__object* bHYPRE_IJParCSRVector__rmicast( void* obj, struct sidl_BaseInterface__object **_ex); /** * RMI connector function for the class. (no addref) */ struct bHYPRE_IJParCSRVector__object* bHYPRE_IJParCSRVector__connectI(const char * url, sidl_bool ar, struct sidl_BaseInterface__object **_ex); } // end extern "C" namespace sidl { // traits specialization template<> struct array_traits< ::bHYPRE::IJParCSRVector > { typedef array< ::bHYPRE::IJParCSRVector > cxx_array_t; typedef ::bHYPRE::IJParCSRVector cxx_item_t; typedef struct bHYPRE_IJParCSRVector__array ior_array_t; typedef sidl_interface__array ior_array_internal_t; typedef struct bHYPRE_IJParCSRVector__object ior_item_t; typedef cxx_item_t value_type; typedef value_type reference; typedef value_type* pointer; typedef const value_type const_reference; typedef const value_type* const_pointer; typedef array_iter< array_traits< ::bHYPRE::IJParCSRVector > > iterator; typedef const_array_iter< array_traits< ::bHYPRE::IJParCSRVector > > const_iterator; }; // array specialization template<> class array< ::bHYPRE::IJParCSRVector >: public interface_array< array_traits< ::bHYPRE::IJParCSRVector > > { public: typedef interface_array< array_traits< ::bHYPRE::IJParCSRVector > > Base; typedef array_traits< ::bHYPRE::IJParCSRVector >::cxx_array_t cxx_array_t; typedef array_traits< ::bHYPRE::IJParCSRVector >::cxx_item_t cxx_item_t; typedef array_traits< ::bHYPRE::IJParCSRVector >::ior_array_t ior_array_t; typedef array_traits< ::bHYPRE::IJParCSRVector >::ior_array_internal_t ior_array_internal_t; typedef array_traits< ::bHYPRE::IJParCSRVector >::ior_item_t ior_item_t; /** * conversion from ior to C++ class * (constructor/casting operator) */ array( struct bHYPRE_IJParCSRVector__array* src = 0) : Base(src) {} /** * copy constructor */ array( const array< ::bHYPRE::IJParCSRVector >&src) : Base(src) {} /** * assignment */ array< ::bHYPRE::IJParCSRVector >& operator =( const array< ::bHYPRE::IJParCSRVector >&rhs ) { if (d_array != rhs._get_baseior()) { if (d_array) deleteRef(); d_array = const_cast<sidl__array *>(rhs._get_baseior()); if (d_array) addRef(); } return *this; } }; } #ifndef included_bHYPRE_MPICommunicator_hxx #include "bHYPRE_MPICommunicator.hxx" #endif #endif
23.5408
79
0.613947
pangkeji
3b51973e261c9f2e13c3e999c9cdfd2146978689
8,986
cc
C++
snapshot/test/test_cpu_context.cc
venge-vimeo/crashpad
7c30a508eb1c5fba3533a1e5570e79b9b2ad37d5
[ "Apache-2.0" ]
null
null
null
snapshot/test/test_cpu_context.cc
venge-vimeo/crashpad
7c30a508eb1c5fba3533a1e5570e79b9b2ad37d5
[ "Apache-2.0" ]
null
null
null
snapshot/test/test_cpu_context.cc
venge-vimeo/crashpad
7c30a508eb1c5fba3533a1e5570e79b9b2ad37d5
[ "Apache-2.0" ]
null
null
null
// Copyright 2014 The Crashpad 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 "snapshot/test/test_cpu_context.h" #include <string.h> #include <sys/types.h> #include <iterator> namespace crashpad { namespace test { namespace { // This is templatized because the CPUContextX86::Fxsave and // CPUContextX86_64::Fxsave are nearly identical but have different sizes for // the members |xmm|, |reserved_4|, and |available|. template <typename FxsaveType> void InitializeCPUContextFxsave(FxsaveType* fxsave, uint32_t* seed) { uint32_t value = *seed; fxsave->fcw = static_cast<uint16_t>(value++); fxsave->fsw = static_cast<uint16_t>(value++); fxsave->ftw = static_cast<uint8_t>(value++); fxsave->reserved_1 = static_cast<uint8_t>(value++); fxsave->fop = static_cast<uint16_t>(value++); fxsave->fpu_ip = value++; fxsave->fpu_cs = static_cast<uint16_t>(value++); fxsave->reserved_2 = static_cast<uint16_t>(value++); fxsave->fpu_dp = value++; fxsave->fpu_ds = static_cast<uint16_t>(value++); fxsave->reserved_3 = static_cast<uint16_t>(value++); fxsave->mxcsr = value++; fxsave->mxcsr_mask = value++; for (size_t st_mm_index = 0; st_mm_index < std::size(fxsave->st_mm); ++st_mm_index) { for (size_t byte = 0; byte < std::size(fxsave->st_mm[st_mm_index].st); ++byte) { fxsave->st_mm[st_mm_index].st[byte] = static_cast<uint8_t>(value++); } for (size_t byte = 0; byte < std::size(fxsave->st_mm[st_mm_index].st_reserved); ++byte) { fxsave->st_mm[st_mm_index].st_reserved[byte] = static_cast<uint8_t>(value); } } for (size_t xmm_index = 0; xmm_index < std::size(fxsave->xmm); ++xmm_index) { for (size_t byte = 0; byte < std::size(fxsave->xmm[xmm_index]); ++byte) { fxsave->xmm[xmm_index][byte] = static_cast<uint8_t>(value++); } } for (size_t byte = 0; byte < std::size(fxsave->reserved_4); ++byte) { fxsave->reserved_4[byte] = static_cast<uint8_t>(value++); } for (size_t byte = 0; byte < std::size(fxsave->available); ++byte) { fxsave->available[byte] = static_cast<uint8_t>(value++); } *seed = value; } } // namespace void InitializeCPUContextX86Fxsave(CPUContextX86::Fxsave* fxsave, uint32_t* seed) { return InitializeCPUContextFxsave(fxsave, seed); } void InitializeCPUContextX86_64Fxsave(CPUContextX86_64::Fxsave* fxsave, uint32_t* seed) { return InitializeCPUContextFxsave(fxsave, seed); } void InitializeCPUContextX86(CPUContext* context, uint32_t seed) { context->architecture = kCPUArchitectureX86; if (seed == 0) { memset(context->x86, 0, sizeof(*context->x86)); return; } uint32_t value = seed; context->x86->eax = value++; context->x86->ebx = value++; context->x86->ecx = value++; context->x86->edx = value++; context->x86->edi = value++; context->x86->esi = value++; context->x86->ebp = value++; context->x86->esp = value++; context->x86->eip = value++; context->x86->eflags = value++; context->x86->cs = static_cast<uint16_t>(value++); context->x86->ds = static_cast<uint16_t>(value++); context->x86->es = static_cast<uint16_t>(value++); context->x86->fs = static_cast<uint16_t>(value++); context->x86->gs = static_cast<uint16_t>(value++); context->x86->ss = static_cast<uint16_t>(value++); InitializeCPUContextX86Fxsave(&context->x86->fxsave, &value); context->x86->dr0 = value++; context->x86->dr1 = value++; context->x86->dr2 = value++; context->x86->dr3 = value++; context->x86->dr4 = value++; context->x86->dr5 = value++; context->x86->dr6 = value++; context->x86->dr7 = value++; } void InitializeCPUContextX86_64(CPUContext* context, uint32_t seed) { context->architecture = kCPUArchitectureX86_64; if (seed == 0) { memset(context->x86_64, 0, sizeof(*context->x86_64)); return; } uint32_t value = seed; context->x86_64->rax = value++; context->x86_64->rbx = value++; context->x86_64->rcx = value++; context->x86_64->rdx = value++; context->x86_64->rdi = value++; context->x86_64->rsi = value++; context->x86_64->rbp = value++; context->x86_64->rsp = value++; context->x86_64->r8 = value++; context->x86_64->r9 = value++; context->x86_64->r10 = value++; context->x86_64->r11 = value++; context->x86_64->r12 = value++; context->x86_64->r13 = value++; context->x86_64->r14 = value++; context->x86_64->r15 = value++; context->x86_64->rip = value++; context->x86_64->rflags = value++; context->x86_64->cs = static_cast<uint16_t>(value++); context->x86_64->fs = static_cast<uint16_t>(value++); context->x86_64->gs = static_cast<uint16_t>(value++); InitializeCPUContextX86_64Fxsave(&context->x86_64->fxsave, &value); context->x86_64->dr0 = value++; context->x86_64->dr1 = value++; context->x86_64->dr2 = value++; context->x86_64->dr3 = value++; context->x86_64->dr4 = value++; context->x86_64->dr5 = value++; context->x86_64->dr6 = value++; context->x86_64->dr7 = value++; // Make sure this is sensible. When supplied the size/state come from the OS. memset(&context->x86_64->xstate, 0, sizeof(context->x86_64->xstate)); } void InitializeCPUContextARM(CPUContext* context, uint32_t seed) { context->architecture = kCPUArchitectureARM; CPUContextARM* arm = context->arm; if (seed == 0) { memset(arm, 0, sizeof(*arm)); return; } uint32_t value = seed; for (size_t index = 0; index < std::size(arm->regs); ++index) { arm->regs[index] = value++; } arm->fp = value++; arm->ip = value++; arm->ip = value++; arm->sp = value++; arm->lr = value++; arm->pc = value++; arm->cpsr = value++; for (size_t index = 0; index < std::size(arm->vfp_regs.vfp); ++index) { arm->vfp_regs.vfp[index] = value++; } arm->vfp_regs.fpscr = value++; arm->have_fpa_regs = false; arm->have_vfp_regs = true; } void InitializeCPUContextARM64(CPUContext* context, uint32_t seed) { context->architecture = kCPUArchitectureARM64; CPUContextARM64* arm64 = context->arm64; if (seed == 0) { memset(arm64, 0, sizeof(*arm64)); return; } uint32_t value = seed; for (size_t index = 0; index < std::size(arm64->regs); ++index) { arm64->regs[index] = value++; } arm64->sp = value++; arm64->pc = value++; arm64->spsr = value++; for (size_t index = 0; index < std::size(arm64->fpsimd); ++index) { arm64->fpsimd[index].lo = value++; arm64->fpsimd[index].hi = value++; } arm64->fpsr = value++; arm64->fpcr = value++; } void InitializeCPUContextMIPS(CPUContext* context, uint32_t seed) { context->architecture = kCPUArchitectureMIPSEL; CPUContextMIPS* mipsel = context->mipsel; if (seed == 0) { memset(mipsel, 0, sizeof(*mipsel)); return; } uint32_t value = seed; for (size_t index = 0; index < std::size(mipsel->regs); ++index) { mipsel->regs[index] = value++; } mipsel->mdlo = value++; mipsel->mdhi = value++; mipsel->cp0_epc = value++; mipsel->cp0_badvaddr = value++; mipsel->cp0_status = value++; mipsel->cp0_cause = value++; for (size_t index = 0; index < std::size(mipsel->fpregs.fregs); ++index) { mipsel->fpregs.fregs[index]._fp_fregs = static_cast<float>(value++); } mipsel->fpcsr = value++; mipsel->fir = value++; for (size_t index = 0; index < 3; ++index) { mipsel->hi[index] = value++; mipsel->lo[index] = value++; } mipsel->dsp_control = value++; } void InitializeCPUContextMIPS64(CPUContext* context, uint32_t seed) { context->architecture = kCPUArchitectureMIPS64EL; CPUContextMIPS64* mips64 = context->mips64; if (seed == 0) { memset(mips64, 0, sizeof(*mips64)); return; } uint64_t value = seed; for (size_t index = 0; index < std::size(mips64->regs); ++index) { mips64->regs[index] = value++; } mips64->mdlo = value++; mips64->mdhi = value++; mips64->cp0_epc = value++; mips64->cp0_badvaddr = value++; mips64->cp0_status = value++; mips64->cp0_cause = value++; for (size_t index = 0; index < std::size(mips64->fpregs.dregs); ++index) { mips64->fpregs.dregs[index] = static_cast<double>(value++); } mips64->fpcsr = value++; mips64->fir = value++; for (size_t index = 0; index < 3; ++index) { mips64->hi[index] = value++; mips64->lo[index] = value++; } mips64->dsp_control = value++; } } // namespace test } // namespace crashpad
29.953333
79
0.649232
venge-vimeo
3b52fb8755de47c005dada8e8640116f3566d69b
61,418
cpp
C++
src/qt/src/gui/painting/qblendfunctions.cpp
ant0ine/phantomjs
8114d44a28134b765ab26b7e13ce31594fa81253
[ "BSD-3-Clause" ]
46
2015-01-08T14:32:34.000Z
2022-02-05T16:48:26.000Z
src/qt/src/gui/painting/qblendfunctions.cpp
ant0ine/phantomjs
8114d44a28134b765ab26b7e13ce31594fa81253
[ "BSD-3-Clause" ]
7
2015-01-20T14:28:12.000Z
2017-01-18T17:21:44.000Z
src/qt/src/gui/painting/qblendfunctions.cpp
ant0ine/phantomjs
8114d44a28134b765ab26b7e13ce31594fa81253
[ "BSD-3-Clause" ]
14
2015-10-27T06:17:48.000Z
2020-03-03T06:15:50.000Z
/**************************************************************************** ** ** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** 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 Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <qmath.h> #include "qblendfunctions_p.h" QT_BEGIN_NAMESPACE struct SourceOnlyAlpha { inline uchar alpha(uchar src) const { return src; } inline quint16 bytemul(quint16 spix) const { return spix; } }; struct SourceAndConstAlpha { SourceAndConstAlpha(int a) : m_alpha256(a) { m_alpha255 = (m_alpha256 * 255) >> 8; }; inline uchar alpha(uchar src) const { return (src * m_alpha256) >> 8; } inline quint16 bytemul(quint16 x) const { uint t = (((x & 0x07e0)*m_alpha255) >> 8) & 0x07e0; t |= (((x & 0xf81f)*(m_alpha255>>2)) >> 6) & 0xf81f; return t; } int m_alpha255; int m_alpha256; }; /************************************************************************ RGB16 (565) format target format ************************************************************************/ static inline quint16 convert_argb32_to_rgb16(quint32 spix) { quint32 b = spix; quint32 g = spix; b >>= 8; g >>= 5; b &= 0x0000f800; g &= 0x000007e0; spix >>= 3; b |= g; spix &= 0x0000001f; b |= spix; return b; } struct Blend_RGB16_on_RGB16_NoAlpha { inline void write(quint16 *dst, quint16 src) { *dst = src; } inline void flush(void *) {} }; struct Blend_RGB16_on_RGB16_ConstAlpha { inline Blend_RGB16_on_RGB16_ConstAlpha(quint32 alpha) { m_alpha = (alpha * 255) >> 8; m_ialpha = 255 - m_alpha; } inline void write(quint16 *dst, quint16 src) { *dst = BYTE_MUL_RGB16(src, m_alpha) + BYTE_MUL_RGB16(*dst, m_ialpha); } inline void flush(void *) {} quint32 m_alpha; quint32 m_ialpha; }; struct Blend_ARGB24_on_RGB16_SourceAlpha { inline void write(quint16 *dst, const qargb8565 &src) { const uint alpha = src.alpha(); if (alpha) { quint16 s = src.rawValue16(); if (alpha < 255) s += BYTE_MUL_RGB16(*dst, 255 - alpha); *dst = s; } } inline void flush(void *) {} }; struct Blend_ARGB24_on_RGB16_SourceAndConstAlpha { inline Blend_ARGB24_on_RGB16_SourceAndConstAlpha(quint32 alpha) { m_alpha = (alpha * 255) >> 8; } inline void write(quint16 *dst, qargb8565 src) { src = src.byte_mul(src.alpha(m_alpha)); const uint alpha = src.alpha(); if (alpha) { quint16 s = src.rawValue16(); if (alpha < 255) s += BYTE_MUL_RGB16(*dst, 255 - alpha); *dst = s; } } inline void flush(void *) {} quint32 m_alpha; }; struct Blend_ARGB32_on_RGB16_SourceAlpha { inline void write(quint16 *dst, quint32 src) { const quint8 alpha = qAlpha(src); if(alpha) { quint16 s = convert_argb32_to_rgb16(src); if(alpha < 255) s += BYTE_MUL_RGB16(*dst, 255 - alpha); *dst = s; } } inline void flush(void *) {} }; struct Blend_ARGB32_on_RGB16_SourceAndConstAlpha { inline Blend_ARGB32_on_RGB16_SourceAndConstAlpha(quint32 alpha) { m_alpha = (alpha * 255) >> 8; } inline void write(quint16 *dst, quint32 src) { src = BYTE_MUL(src, m_alpha); const quint8 alpha = qAlpha(src); if(alpha) { quint16 s = convert_argb32_to_rgb16(src); if(alpha < 255) s += BYTE_MUL_RGB16(*dst, 255 - alpha); *dst = s; } } inline void flush(void *) {} quint32 m_alpha; }; void qt_scale_image_rgb16_on_rgb16(uchar *destPixels, int dbpl, const uchar *srcPixels, int sbpl, const QRectF &targetRect, const QRectF &sourceRect, const QRect &clip, int const_alpha) { #ifdef QT_DEBUG_DRAW printf("qt_scale_rgb16_on_rgb16: dst=(%p, %d), src=(%p, %d), target=(%d, %d), [%d x %d], src=(%d, %d) [%d x %d] alpha=%d\n", destPixels, dbpl, srcPixels, sbpl, targetRect.x(), targetRect.y(), targetRect.width(), targetRect.height(), sourceRect.x(), sourceRect.y(), sourceRect.width(), sourceRect.height(), const_alpha); #endif if (const_alpha == 256) { Blend_RGB16_on_RGB16_NoAlpha noAlpha; qt_scale_image_16bit<quint16>(destPixels, dbpl, srcPixels, sbpl, targetRect, sourceRect, clip, noAlpha); } else { Blend_RGB16_on_RGB16_ConstAlpha constAlpha(const_alpha); qt_scale_image_16bit<quint16>(destPixels, dbpl, srcPixels, sbpl, targetRect, sourceRect, clip, constAlpha); } } void qt_scale_image_argb24_on_rgb16(uchar *destPixels, int dbpl, const uchar *srcPixels, int sbpl, const QRectF &targetRect, const QRectF &sourceRect, const QRect &clip, int const_alpha) { #ifdef QT_DEBUG_DRAW printf("qt_scale_argb24_on_rgb16: dst=(%p, %d), src=(%p, %d), target=(%d, %d), [%d x %d], src=(%d, %d) [%d x %d] alpha=%d\n", destPixels, dbpl, srcPixels, sbpl, targetRect.x(), targetRect.y(), targetRect.width(), targetRect.height(), sourceRect.x(), sourceRect.y(), sourceRect.width(), sourceRect.height(), const_alpha); #endif if (const_alpha == 256) { Blend_ARGB24_on_RGB16_SourceAlpha noAlpha; qt_scale_image_16bit<qargb8565>(destPixels, dbpl, srcPixels, sbpl, targetRect, sourceRect, clip, noAlpha); } else { Blend_ARGB24_on_RGB16_SourceAndConstAlpha constAlpha(const_alpha); qt_scale_image_16bit<qargb8565>(destPixels, dbpl, srcPixels, sbpl, targetRect, sourceRect, clip, constAlpha); } } void qt_scale_image_argb32_on_rgb16(uchar *destPixels, int dbpl, const uchar *srcPixels, int sbpl, const QRectF &targetRect, const QRectF &sourceRect, const QRect &clip, int const_alpha) { #ifdef QT_DEBUG_DRAW printf("qt_scale_argb32_on_rgb16: dst=(%p, %d), src=(%p, %d), target=(%d, %d), [%d x %d], src=(%d, %d) [%d x %d] alpha=%d\n", destPixels, dbpl, srcPixels, sbpl, targetRect.x(), targetRect.y(), targetRect.width(), targetRect.height(), sourceRect.x(), sourceRect.y(), sourceRect.width(), sourceRect.height(), const_alpha); #endif if (const_alpha == 256) { Blend_ARGB32_on_RGB16_SourceAlpha noAlpha; qt_scale_image_16bit<quint32>(destPixels, dbpl, srcPixels, sbpl, targetRect, sourceRect, clip, noAlpha); } else { Blend_ARGB32_on_RGB16_SourceAndConstAlpha constAlpha(const_alpha); qt_scale_image_16bit<quint32>(destPixels, dbpl, srcPixels, sbpl, targetRect, sourceRect, clip, constAlpha); } } void qt_blend_rgb16_on_rgb16(uchar *dst, int dbpl, const uchar *src, int sbpl, int w, int h, int const_alpha) { #ifdef QT_DEBUG_DRAW printf("qt_blend_rgb16_on_rgb16: dst=(%p, %d), src=(%p, %d), dim=(%d, %d) alpha=%d\n", dst, dbpl, src, sbpl, w, h, const_alpha); #endif if (const_alpha == 256) { if (w <= 64) { while (h--) { QT_MEMCPY_USHORT(dst, src, w); dst += dbpl; src += sbpl; } } else { int length = w << 1; while (h--) { memcpy(dst, src, length); dst += dbpl; src += sbpl; } } } else if (const_alpha != 0) { SourceAndConstAlpha alpha(const_alpha); // expects the 0-256 range quint16 *d = (quint16 *) dst; const quint16 *s = (const quint16 *) src; quint8 a = (255 * const_alpha) >> 8; quint8 ia = 255 - a; while (h--) { for (int x=0; x<w; ++x) { d[x] = BYTE_MUL_RGB16(s[x], a) + BYTE_MUL_RGB16(d[x], ia); } d = (quint16 *)(((uchar *) d) + dbpl); s = (const quint16 *)(((const uchar *) s) + sbpl); } } } template <typename T> void qt_blend_argb24_on_rgb16(uchar *destPixels, int dbpl, const uchar *srcPixels, int sbpl, int w, int h, const T &alphaFunc) { int srcOffset = w*3; int dstJPL = dbpl / 2; quint16 *dst = (quint16 *) destPixels; int dstExtraStride = dstJPL - w; for (int y=0; y<h; ++y) { const uchar *src = srcPixels + y * sbpl; const uchar *srcEnd = src + srcOffset; while (src < srcEnd) { #if defined(QT_ARCH_ARMV5) || defined(QT_ARCH_POWERPC) || defined(QT_ARCH_SH) || defined(QT_ARCH_AVR32) || (defined(QT_ARCH_WINDOWSCE) && !defined(_X86_)) || (defined(QT_ARCH_SPARC) && defined(Q_CC_GNU)) || (defined(QT_ARCH_INTEGRITY) && !defined(_X86_)) // non-16-bit aligned memory access is not possible on PowerPC, // ARM <v6 (QT_ARCH_ARMV5) & SH & AVR32 & SPARC w/GCC quint16 spix = (quint16(src[2])<<8) + src[1]; #else quint16 spix = *(quint16 *) (src + 1); #endif uchar alpha = alphaFunc.alpha(*src); if (alpha == 255) { *dst = spix; } else if (alpha != 0) { quint16 dpix = *dst; quint32 sia = 255 - alpha; quint16 dr = (dpix & 0x0000f800); quint16 dg = (dpix & 0x000007e0); quint16 db = (dpix & 0x0000001f); quint32 siar = dr * sia; quint32 siag = dg * sia; quint32 siab = db * sia; quint32 rr = ((siar + (siar>>8) + (0x80 << 8)) >> 8) & 0xf800; quint32 rg = ((siag + (siag>>8) + (0x80 << 3)) >> 8) & 0x07e0; quint32 rb = ((siab + (siab>>8) + (0x80 >> 3)) >> 8) & 0x001f; *dst = alphaFunc.bytemul(spix) + rr + rg + rb; } ++dst; src += 3; } dst += dstExtraStride; } } static void qt_blend_argb24_on_rgb16(uchar *destPixels, int dbpl, const uchar *srcPixels, int sbpl, int w, int h, int const_alpha) { #ifdef QT_DEBUG_DRAW printf("qt_blend_argb24_on_rgb16: dst=(%p, %d), src=(%p, %d), dim=(%d, %d) alpha=%d\n", destPixels, dbpl, srcPixels, sbpl, w, h, const_alpha); #endif if (const_alpha != 256) { SourceAndConstAlpha alphaFunc(const_alpha); qt_blend_argb24_on_rgb16(destPixels, dbpl, srcPixels, sbpl, w, h, alphaFunc); } else { SourceOnlyAlpha alphaFunc; qt_blend_argb24_on_rgb16(destPixels, dbpl, srcPixels, sbpl, w, h, alphaFunc); } } void qt_blend_argb32_on_rgb16_const_alpha(uchar *destPixels, int dbpl, const uchar *srcPixels, int sbpl, int w, int h, int const_alpha) { quint16 *dst = (quint16 *) destPixels; const quint32 *src = (const quint32 *) srcPixels; const_alpha = (const_alpha * 255) >> 8; for (int y=0; y<h; ++y) { for (int i = 0; i < w; ++i) { uint s = src[i]; s = BYTE_MUL(s, const_alpha); int alpha = qAlpha(s); s = convert_argb32_to_rgb16(s); s += BYTE_MUL_RGB16(dst[i], 255 - alpha); dst[i] = s; } dst = (quint16 *)(((uchar *) dst) + dbpl); src = (const quint32 *)(((const uchar *) src) + sbpl); } } static void qt_blend_argb32_on_rgb16(uchar *destPixels, int dbpl, const uchar *srcPixels, int sbpl, int w, int h, int const_alpha) { if (const_alpha != 256) { qt_blend_argb32_on_rgb16_const_alpha(destPixels, dbpl, srcPixels, sbpl, w, h, const_alpha); return; } quint16 *dst = (quint16 *) destPixels; quint32 *src = (quint32 *) srcPixels; for (int y=0; y<h; ++y) { for (int x=0; x<w; ++x) { quint32 spix = src[x]; quint32 alpha = spix >> 24; if (alpha == 255) { dst[x] = convert_argb32_to_rgb16(spix); } else if (alpha != 0) { quint32 dpix = dst[x]; quint32 sia = 255 - alpha; quint32 sr = (spix >> 8) & 0xf800; quint32 sg = (spix >> 5) & 0x07e0; quint32 sb = (spix >> 3) & 0x001f; quint32 dr = (dpix & 0x0000f800); quint32 dg = (dpix & 0x000007e0); quint32 db = (dpix & 0x0000001f); quint32 siar = dr * sia; quint32 siag = dg * sia; quint32 siab = db * sia; quint32 rr = sr + ((siar + (siar>>8) + (0x80 << 8)) >> 8); quint32 rg = sg + ((siag + (siag>>8) + (0x80 << 3)) >> 8); quint32 rb = sb + ((siab + (siab>>8) + (0x80 >> 3)) >> 8); dst[x] = (rr & 0xf800) | (rg & 0x07e0) | (rb); } } dst = (quint16 *) (((uchar *) dst) + dbpl); src = (quint32 *) (((uchar *) src) + sbpl); } } static void qt_blend_rgb32_on_rgb16(uchar *destPixels, int dbpl, const uchar *srcPixels, int sbpl, int w, int h, int const_alpha) { #ifdef QT_DEBUG_DRAW printf("qt_blend_rgb32_on_rgb16: dst=(%p, %d), src=(%p, %d), dim=(%d, %d) alpha=%d\n", destPixels, dbpl, srcPixels, sbpl, w, h, const_alpha); #endif if (const_alpha != 256) { qt_blend_argb32_on_rgb16(destPixels, dbpl, srcPixels, sbpl, w, h, const_alpha); return; } const quint32 *src = (const quint32 *) srcPixels; int srcExtraStride = (sbpl >> 2) - w; int dstJPL = dbpl / 2; quint16 *dst = (quint16 *) destPixels; quint16 *dstEnd = dst + dstJPL * h; int dstExtraStride = dstJPL - w; while (dst < dstEnd) { const quint32 *srcEnd = src + w; while (src < srcEnd) { *dst = convert_argb32_to_rgb16(*src); ++dst; ++src; } dst += dstExtraStride; src += srcExtraStride; } } /************************************************************************ RGB32 (-888) format target format ************************************************************************/ static void qt_blend_argb32_on_argb32(uchar *destPixels, int dbpl, const uchar *srcPixels, int sbpl, int w, int h, int const_alpha) { #ifdef QT_DEBUG_DRAW fprintf(stdout, "qt_blend_argb32_on_argb32: dst=(%p, %d), src=(%p, %d), dim=(%d, %d) alpha=%d\n", destPixels, dbpl, srcPixels, sbpl, w, h, const_alpha); fflush(stdout); #endif const uint *src = (const uint *) srcPixels; uint *dst = (uint *) destPixels; if (const_alpha == 256) { for (int y=0; y<h; ++y) { for (int x=0; x<w; ++x) { uint s = src[x]; if (s >= 0xff000000) dst[x] = s; else if (s != 0) dst[x] = s + BYTE_MUL(dst[x], qAlpha(~s)); } dst = (quint32 *)(((uchar *) dst) + dbpl); src = (const quint32 *)(((const uchar *) src) + sbpl); } } else if (const_alpha != 0) { const_alpha = (const_alpha * 255) >> 8; for (int y=0; y<h; ++y) { for (int x=0; x<w; ++x) { uint s = BYTE_MUL(src[x], const_alpha); dst[x] = s + BYTE_MUL(dst[x], qAlpha(~s)); } dst = (quint32 *)(((uchar *) dst) + dbpl); src = (const quint32 *)(((const uchar *) src) + sbpl); } } } void qt_blend_rgb32_on_rgb32(uchar *destPixels, int dbpl, const uchar *srcPixels, int sbpl, int w, int h, int const_alpha) { #ifdef QT_DEBUG_DRAW fprintf(stdout, "qt_blend_rgb32_on_rgb32: dst=(%p, %d), src=(%p, %d), dim=(%d, %d) alpha=%d\n", destPixels, dbpl, srcPixels, sbpl, w, h, const_alpha); fflush(stdout); #endif if (const_alpha != 256) { qt_blend_argb32_on_argb32(destPixels, dbpl, srcPixels, sbpl, w, h, const_alpha); return; } const uint *src = (const uint *) srcPixels; uint *dst = (uint *) destPixels; if (w <= 64) { for (int y=0; y<h; ++y) { qt_memconvert(dst, src, w); dst = (quint32 *)(((uchar *) dst) + dbpl); src = (const quint32 *)(((const uchar *) src) + sbpl); } } else { int len = w * 4; for (int y=0; y<h; ++y) { memcpy(dst, src, len); dst = (quint32 *)(((uchar *) dst) + dbpl); src = (const quint32 *)(((const uchar *) src) + sbpl); } } } struct Blend_RGB32_on_RGB32_NoAlpha { inline void write(quint32 *dst, quint32 src) { *dst = src; } inline void flush(void *) {} }; struct Blend_RGB32_on_RGB32_ConstAlpha { inline Blend_RGB32_on_RGB32_ConstAlpha(quint32 alpha) { m_alpha = (alpha * 255) >> 8; m_ialpha = 255 - m_alpha; } inline void write(quint32 *dst, quint32 src) { *dst = BYTE_MUL(src, m_alpha) + BYTE_MUL(*dst, m_ialpha); } inline void flush(void *) {} quint32 m_alpha; quint32 m_ialpha; }; struct Blend_ARGB32_on_ARGB32_SourceAlpha { inline void write(quint32 *dst, quint32 src) { *dst = src + BYTE_MUL(*dst, qAlpha(~src)); } inline void flush(void *) {} }; struct Blend_ARGB32_on_ARGB32_SourceAndConstAlpha { inline Blend_ARGB32_on_ARGB32_SourceAndConstAlpha(quint32 alpha) { m_alpha = (alpha * 255) >> 8; m_ialpha = 255 - m_alpha; } inline void write(quint32 *dst, quint32 src) { src = BYTE_MUL(src, m_alpha); *dst = src + BYTE_MUL(*dst, qAlpha(~src)); } inline void flush(void *) {} quint32 m_alpha; quint32 m_ialpha; }; void qt_scale_image_rgb32_on_rgb32(uchar *destPixels, int dbpl, const uchar *srcPixels, int sbpl, const QRectF &targetRect, const QRectF &sourceRect, const QRect &clip, int const_alpha) { #ifdef QT_DEBUG_DRAW printf("qt_scale_rgb32_on_rgb32: dst=(%p, %d), src=(%p, %d), target=(%d, %d), [%d x %d], src=(%d, %d) [%d x %d] alpha=%d\n", destPixels, dbpl, srcPixels, sbpl, targetRect.x(), targetRect.y(), targetRect.width(), targetRect.height(), sourceRect.x(), sourceRect.y(), sourceRect.width(), sourceRect.height(), const_alpha); #endif if (const_alpha == 256) { Blend_RGB32_on_RGB32_NoAlpha noAlpha; qt_scale_image_32bit(destPixels, dbpl, srcPixels, sbpl, targetRect, sourceRect, clip, noAlpha); } else { Blend_RGB32_on_RGB32_ConstAlpha constAlpha(const_alpha); qt_scale_image_32bit(destPixels, dbpl, srcPixels, sbpl, targetRect, sourceRect, clip, constAlpha); } } void qt_scale_image_argb32_on_argb32(uchar *destPixels, int dbpl, const uchar *srcPixels, int sbpl, const QRectF &targetRect, const QRectF &sourceRect, const QRect &clip, int const_alpha) { #ifdef QT_DEBUG_DRAW printf("qt_scale_argb32_on_argb32: dst=(%p, %d), src=(%p, %d), target=(%d, %d), [%d x %d], src=(%d, %d) [%d x %d] alpha=%d\n", destPixels, dbpl, srcPixels, sbpl, targetRect.x(), targetRect.y(), targetRect.width(), targetRect.height(), sourceRect.x(), sourceRect.y(), sourceRect.width(), sourceRect.height(), const_alpha); #endif if (const_alpha == 256) { Blend_ARGB32_on_ARGB32_SourceAlpha sourceAlpha; qt_scale_image_32bit(destPixels, dbpl, srcPixels, sbpl, targetRect, sourceRect, clip, sourceAlpha); } else { Blend_ARGB32_on_ARGB32_SourceAndConstAlpha constAlpha(const_alpha); qt_scale_image_32bit(destPixels, dbpl, srcPixels, sbpl, targetRect, sourceRect, clip, constAlpha); } } void qt_transform_image_rgb16_on_rgb16(uchar *destPixels, int dbpl, const uchar *srcPixels, int sbpl, const QRectF &targetRect, const QRectF &sourceRect, const QRect &clip, const QTransform &targetRectTransform, int const_alpha) { if (const_alpha == 256) { Blend_RGB16_on_RGB16_NoAlpha noAlpha; qt_transform_image(reinterpret_cast<quint16 *>(destPixels), dbpl, reinterpret_cast<const quint16 *>(srcPixels), sbpl, targetRect, sourceRect, clip, targetRectTransform, noAlpha); } else { Blend_RGB16_on_RGB16_ConstAlpha constAlpha(const_alpha); qt_transform_image(reinterpret_cast<quint16 *>(destPixels), dbpl, reinterpret_cast<const quint16 *>(srcPixels), sbpl, targetRect, sourceRect, clip, targetRectTransform, constAlpha); } } void qt_transform_image_argb24_on_rgb16(uchar *destPixels, int dbpl, const uchar *srcPixels, int sbpl, const QRectF &targetRect, const QRectF &sourceRect, const QRect &clip, const QTransform &targetRectTransform, int const_alpha) { if (const_alpha == 256) { Blend_ARGB24_on_RGB16_SourceAlpha noAlpha; qt_transform_image(reinterpret_cast<quint16 *>(destPixels), dbpl, reinterpret_cast<const qargb8565 *>(srcPixels), sbpl, targetRect, sourceRect, clip, targetRectTransform, noAlpha); } else { Blend_ARGB24_on_RGB16_SourceAndConstAlpha constAlpha(const_alpha); qt_transform_image(reinterpret_cast<quint16 *>(destPixels), dbpl, reinterpret_cast<const qargb8565 *>(srcPixels), sbpl, targetRect, sourceRect, clip, targetRectTransform, constAlpha); } } void qt_transform_image_argb32_on_rgb16(uchar *destPixels, int dbpl, const uchar *srcPixels, int sbpl, const QRectF &targetRect, const QRectF &sourceRect, const QRect &clip, const QTransform &targetRectTransform, int const_alpha) { if (const_alpha == 256) { Blend_ARGB32_on_RGB16_SourceAlpha noAlpha; qt_transform_image(reinterpret_cast<quint16 *>(destPixels), dbpl, reinterpret_cast<const quint32 *>(srcPixels), sbpl, targetRect, sourceRect, clip, targetRectTransform, noAlpha); } else { Blend_ARGB32_on_RGB16_SourceAndConstAlpha constAlpha(const_alpha); qt_transform_image(reinterpret_cast<quint16 *>(destPixels), dbpl, reinterpret_cast<const quint32 *>(srcPixels), sbpl, targetRect, sourceRect, clip, targetRectTransform, constAlpha); } } void qt_transform_image_rgb32_on_rgb32(uchar *destPixels, int dbpl, const uchar *srcPixels, int sbpl, const QRectF &targetRect, const QRectF &sourceRect, const QRect &clip, const QTransform &targetRectTransform, int const_alpha) { if (const_alpha == 256) { Blend_RGB32_on_RGB32_NoAlpha noAlpha; qt_transform_image(reinterpret_cast<quint32 *>(destPixels), dbpl, reinterpret_cast<const quint32 *>(srcPixels), sbpl, targetRect, sourceRect, clip, targetRectTransform, noAlpha); } else { Blend_RGB32_on_RGB32_ConstAlpha constAlpha(const_alpha); qt_transform_image(reinterpret_cast<quint32 *>(destPixels), dbpl, reinterpret_cast<const quint32 *>(srcPixels), sbpl, targetRect, sourceRect, clip, targetRectTransform, constAlpha); } } void qt_transform_image_argb32_on_argb32(uchar *destPixels, int dbpl, const uchar *srcPixels, int sbpl, const QRectF &targetRect, const QRectF &sourceRect, const QRect &clip, const QTransform &targetRectTransform, int const_alpha) { if (const_alpha == 256) { Blend_ARGB32_on_ARGB32_SourceAlpha sourceAlpha; qt_transform_image(reinterpret_cast<quint32 *>(destPixels), dbpl, reinterpret_cast<const quint32 *>(srcPixels), sbpl, targetRect, sourceRect, clip, targetRectTransform, sourceAlpha); } else { Blend_ARGB32_on_ARGB32_SourceAndConstAlpha constAlpha(const_alpha); qt_transform_image(reinterpret_cast<quint32 *>(destPixels), dbpl, reinterpret_cast<const quint32 *>(srcPixels), sbpl, targetRect, sourceRect, clip, targetRectTransform, constAlpha); } } SrcOverScaleFunc qScaleFunctions[QImage::NImageFormats][QImage::NImageFormats] = { { // Format_Invalid 0, // Format_Invalid, 0, // Format_Mono, 0, // Format_MonoLSB, 0, // Format_Indexed8, 0, // Format_RGB32, 0, // Format_ARGB32, 0, // Format_ARGB32_Premultiplied, 0, // Format_RGB16, 0, // Format_ARGB8565_Premultiplied, 0, // Format_RGB666, 0, // Format_ARGB6666_Premultiplied, 0, // Format_RGB555, 0, // Format_ARGB8555_Premultiplied, 0, // Format_RGB888, 0, // Format_RGB444, 0 // Format_ARGB4444_Premultiplied, }, { // Format_Mono 0, // Format_Invalid, 0, // Format_Mono, 0, // Format_MonoLSB, 0, // Format_Indexed8, 0, // Format_RGB32, 0, // Format_ARGB32, 0, // Format_ARGB32_Premultiplied, 0, // Format_RGB16, 0, // Format_ARGB8565_Premultiplied, 0, // Format_RGB666, 0, // Format_ARGB6666_Premultiplied, 0, // Format_RGB555, 0, // Format_ARGB8555_Premultiplied, 0, // Format_RGB888, 0, // Format_RGB444, 0 // Format_ARGB4444_Premultiplied, }, { // Format_MonoLSB 0, // Format_Invalid, 0, // Format_Mono, 0, // Format_MonoLSB, 0, // Format_Indexed8, 0, // Format_RGB32, 0, // Format_ARGB32, 0, // Format_ARGB32_Premultiplied, 0, // Format_RGB16, 0, // Format_ARGB8565_Premultiplied, 0, // Format_RGB666, 0, // Format_ARGB6666_Premultiplied, 0, // Format_RGB555, 0, // Format_ARGB8555_Premultiplied, 0, // Format_RGB888, 0, // Format_RGB444, 0 // Format_ARGB4444_Premultiplied, }, { // Format_Indexed8 0, // Format_Invalid, 0, // Format_Mono, 0, // Format_MonoLSB, 0, // Format_Indexed8, 0, // Format_RGB32, 0, // Format_ARGB32, 0, // Format_ARGB32_Premultiplied, 0, // Format_RGB16, 0, // Format_ARGB8565_Premultiplied, 0, // Format_RGB666, 0, // Format_ARGB6666_Premultiplied, 0, // Format_RGB555, 0, // Format_ARGB8555_Premultiplied, 0, // Format_RGB888, 0, // Format_RGB444, 0 // Format_ARGB4444_Premultiplied, }, { // Format_RGB32 0, // Format_Invalid, 0, // Format_Mono, 0, // Format_MonoLSB, 0, // Format_Indexed8, qt_scale_image_rgb32_on_rgb32, // Format_RGB32, 0, // Format_ARGB32, qt_scale_image_argb32_on_argb32, // Format_ARGB32_Premultiplied, 0, // Format_RGB16, 0, // Format_ARGB8565_Premultiplied, 0, // Format_RGB666, 0, // Format_ARGB6666_Premultiplied, 0, // Format_RGB555, 0, // Format_ARGB8555_Premultiplied, 0, // Format_RGB888, 0, // Format_RGB444, 0 // Format_ARGB4444_Premultiplied, }, { // Format_ARGB32 0, // Format_Invalid, 0, // Format_Mono, 0, // Format_MonoLSB, 0, // Format_Indexed8, 0, // Format_RGB32, 0, // Format_ARGB32, 0, // Format_ARGB32_Premultiplied, 0, // Format_RGB16, 0, // Format_ARGB8565_Premultiplied, 0, // Format_RGB666, 0, // Format_ARGB6666_Premultiplied, 0, // Format_RGB555, 0, // Format_ARGB8555_Premultiplied, 0, // Format_RGB888, 0, // Format_RGB444, 0 // Format_ARGB4444_Premultiplied, }, { // Format_ARGB32_Premultiplied 0, // Format_Invalid, 0, // Format_Mono, 0, // Format_MonoLSB, 0, // Format_Indexed8, qt_scale_image_rgb32_on_rgb32, // Format_RGB32, 0, // Format_ARGB32, qt_scale_image_argb32_on_argb32, // Format_ARGB32_Premultiplied, 0, // Format_RGB16, 0, // Format_ARGB8565_Premultiplied, 0, // Format_RGB666, 0, // Format_ARGB6666_Premultiplied, 0, // Format_RGB555, 0, // Format_ARGB8555_Premultiplied, 0, // Format_RGB888, 0, // Format_RGB444, 0 // Format_ARGB4444_Premultiplied, }, { // Format_RGB16 0, // Format_Invalid, 0, // Format_Mono, 0, // Format_MonoLSB, 0, // Format_Indexed8, 0, // Format_RGB32, 0, // Format_ARGB32, qt_scale_image_argb32_on_rgb16, // Format_ARGB32_Premultiplied, qt_scale_image_rgb16_on_rgb16, // Format_RGB16, qt_scale_image_argb24_on_rgb16, // Format_ARGB8565_Premultiplied, 0, // Format_RGB666, 0, // Format_ARGB6666_Premultiplied, 0, // Format_RGB555, 0, // Format_ARGB8555_Premultiplied, 0, // Format_RGB888, 0, // Format_RGB444, 0 // Format_ARGB4444_Premultiplied, }, { // Format_ARGB8565_Premultiplied 0, // Format_Invalid, 0, // Format_Mono, 0, // Format_MonoLSB, 0, // Format_Indexed8, 0, // Format_RGB32, 0, // Format_ARGB32, 0, // Format_ARGB32_Premultiplied, 0, // Format_RGB16, 0, // Format_ARGB8565_Premultiplied, 0, // Format_RGB666, 0, // Format_ARGB6666_Premultiplied, 0, // Format_RGB555, 0, // Format_ARGB8555_Premultiplied, 0, // Format_RGB888, 0, // Format_RGB444, 0 // Format_ARGB4444_Premultiplied, }, { // Format_RGB666 0, // Format_Invalid, 0, // Format_Mono, 0, // Format_MonoLSB, 0, // Format_Indexed8, 0, // Format_RGB32, 0, // Format_ARGB32, 0, // Format_ARGB32_Premultiplied, 0, // Format_RGB16, 0, // Format_ARGB8565_Premultiplied, 0, // Format_RGB666, 0, // Format_ARGB6666_Premultiplied, 0, // Format_RGB555, 0, // Format_ARGB8555_Premultiplied, 0, // Format_RGB888, 0, // Format_RGB444, 0 // Format_ARGB4444_Premultiplied, }, { // Format_ARGB6666_Premultiplied 0, // Format_Invalid, 0, // Format_Mono, 0, // Format_MonoLSB, 0, // Format_Indexed8, 0, // Format_RGB32, 0, // Format_ARGB32, 0, // Format_ARGB32_Premultiplied, 0, // Format_RGB16, 0, // Format_ARGB8565_Premultiplied, 0, // Format_RGB666, 0, // Format_ARGB6666_Premultiplied, 0, // Format_RGB555, 0, // Format_ARGB8555_Premultiplied, 0, // Format_RGB888, 0, // Format_RGB444, 0 // Format_ARGB4444_Premultiplied, }, { // Format_RGB555 0, // Format_Invalid, 0, // Format_Mono, 0, // Format_MonoLSB, 0, // Format_Indexed8, 0, // Format_RGB32, 0, // Format_ARGB32, 0, // Format_ARGB32_Premultiplied, 0, // Format_RGB16, 0, // Format_ARGB8565_Premultiplied, 0, // Format_RGB666, 0, // Format_ARGB6666_Premultiplied, 0, // Format_RGB555, 0, // Format_ARGB8555_Premultiplied, 0, // Format_RGB888, 0, // Format_RGB444, 0 // Format_ARGB4444_Premultiplied, }, { // Format_ARGB8555_Premultiplied 0, // Format_Invalid, 0, // Format_Mono, 0, // Format_MonoLSB, 0, // Format_Indexed8, 0, // Format_RGB32, 0, // Format_ARGB32, 0, // Format_ARGB32_Premultiplied, 0, // Format_RGB16, 0, // Format_ARGB8565_Premultiplied, 0, // Format_RGB666, 0, // Format_ARGB6666_Premultiplied, 0, // Format_RGB555, 0, // Format_ARGB8555_Premultiplied, 0, // Format_RGB888, 0, // Format_RGB444, 0 // Format_ARGB4444_Premultiplied, }, { // Format_RGB888 0, // Format_Invalid, 0, // Format_Mono, 0, // Format_MonoLSB, 0, // Format_Indexed8, 0, // Format_RGB32, 0, // Format_ARGB32, 0, // Format_ARGB32_Premultiplied, 0, // Format_RGB16, 0, // Format_ARGB8565_Premultiplied, 0, // Format_RGB666, 0, // Format_ARGB6666_Premultiplied, 0, // Format_RGB555, 0, // Format_ARGB8555_Premultiplied, 0, // Format_RGB888, 0, // Format_RGB444, 0 // Format_ARGB4444_Premultiplied, }, { // Format_RGB444 0, // Format_Invalid, 0, // Format_Mono, 0, // Format_MonoLSB, 0, // Format_Indexed8, 0, // Format_RGB32, 0, // Format_ARGB32, 0, // Format_ARGB32_Premultiplied, 0, // Format_RGB16, 0, // Format_ARGB8565_Premultiplied, 0, // Format_RGB666, 0, // Format_ARGB6666_Premultiplied, 0, // Format_RGB555, 0, // Format_ARGB8555_Premultiplied, 0, // Format_RGB888, 0, // Format_RGB444, 0 // Format_ARGB4444_Premultiplied, }, { // Format_ARGB4444_Premultiplied 0, // Format_Invalid, 0, // Format_Mono, 0, // Format_MonoLSB, 0, // Format_Indexed8, 0, // Format_RGB32, 0, // Format_ARGB32, 0, // Format_ARGB32_Premultiplied, 0, // Format_RGB16, 0, // Format_ARGB8565_Premultiplied, 0, // Format_RGB666, 0, // Format_ARGB6666_Premultiplied, 0, // Format_RGB555, 0, // Format_ARGB8555_Premultiplied, 0, // Format_RGB888, 0, // Format_RGB444, 0 // Format_ARGB4444_Premultiplied, } }; SrcOverBlendFunc qBlendFunctions[QImage::NImageFormats][QImage::NImageFormats] = { { // Format_Invalid 0, // Format_Invalid, 0, // Format_Mono, 0, // Format_MonoLSB, 0, // Format_Indexed8, 0, // Format_RGB32, 0, // Format_ARGB32, 0, // Format_ARGB32_Premultiplied, 0, // Format_RGB16, 0, // Format_ARGB8565_Premultiplied, 0, // Format_RGB666, 0, // Format_ARGB6666_Premultiplied, 0, // Format_RGB555, 0, // Format_ARGB8555_Premultiplied, 0, // Format_RGB888, 0, // Format_RGB444, 0 // Format_ARGB4444_Premultiplied, }, { // Format_Mono 0, // Format_Invalid, 0, // Format_Mono, 0, // Format_MonoLSB, 0, // Format_Indexed8, 0, // Format_RGB32, 0, // Format_ARGB32, 0, // Format_ARGB32_Premultiplied, 0, // Format_RGB16, 0, // Format_ARGB8565_Premultiplied, 0, // Format_RGB666, 0, // Format_ARGB6666_Premultiplied, 0, // Format_RGB555, 0, // Format_ARGB8555_Premultiplied, 0, // Format_RGB888, 0, // Format_RGB444, 0 // Format_ARGB4444_Premultiplied, }, { // Format_MonoLSB 0, // Format_Invalid, 0, // Format_Mono, 0, // Format_MonoLSB, 0, // Format_Indexed8, 0, // Format_RGB32, 0, // Format_ARGB32, 0, // Format_ARGB32_Premultiplied, 0, // Format_RGB16, 0, // Format_ARGB8565_Premultiplied, 0, // Format_RGB666, 0, // Format_ARGB6666_Premultiplied, 0, // Format_RGB555, 0, // Format_ARGB8555_Premultiplied, 0, // Format_RGB888, 0, // Format_RGB444, 0 // Format_ARGB4444_Premultiplied, }, { // Format_Indexed8 0, // Format_Invalid, 0, // Format_Mono, 0, // Format_MonoLSB, 0, // Format_Indexed8, 0, // Format_RGB32, 0, // Format_ARGB32, 0, // Format_ARGB32_Premultiplied, 0, // Format_RGB16, 0, // Format_ARGB8565_Premultiplied, 0, // Format_RGB666, 0, // Format_ARGB6666_Premultiplied, 0, // Format_RGB555, 0, // Format_ARGB8555_Premultiplied, 0, // Format_RGB888, 0, // Format_RGB444, 0 // Format_ARGB4444_Premultiplied, }, { // Format_RGB32 0, // Format_Invalid, 0, // Format_Mono, 0, // Format_MonoLSB, 0, // Format_Indexed8, qt_blend_rgb32_on_rgb32, // Format_RGB32, 0, // Format_ARGB32, qt_blend_argb32_on_argb32, // Format_ARGB32_Premultiplied, 0, // Format_RGB16, 0, // Format_ARGB8565_Premultiplied, 0, // Format_RGB666, 0, // Format_ARGB6666_Premultiplied, 0, // Format_RGB555, 0, // Format_ARGB8555_Premultiplied, 0, // Format_RGB888, 0, // Format_RGB444, 0 // Format_ARGB4444_Premultiplied, }, { // Format_ARGB32 0, // Format_Invalid, 0, // Format_Mono, 0, // Format_MonoLSB, 0, // Format_Indexed8, 0, // Format_RGB32, 0, // Format_ARGB32, 0, // Format_ARGB32_Premultiplied, 0, // Format_RGB16, 0, // Format_ARGB8565_Premultiplied, 0, // Format_RGB666, 0, // Format_ARGB6666_Premultiplied, 0, // Format_RGB555, 0, // Format_ARGB8555_Premultiplied, 0, // Format_RGB888, 0, // Format_RGB444, 0 // Format_ARGB4444_Premultiplied, }, { // Format_ARGB32_Premultiplied 0, // Format_Invalid, 0, // Format_Mono, 0, // Format_MonoLSB, 0, // Format_Indexed8, qt_blend_rgb32_on_rgb32, // Format_RGB32, 0, // Format_ARGB32, qt_blend_argb32_on_argb32, // Format_ARGB32_Premultiplied, 0, // Format_RGB16, 0, // Format_ARGB8565_Premultiplied, 0, // Format_RGB666, 0, // Format_ARGB6666_Premultiplied, 0, // Format_RGB555, 0, // Format_ARGB8555_Premultiplied, 0, // Format_RGB888, 0, // Format_RGB444, 0 // Format_ARGB4444_Premultiplied, }, { // Format_RGB16 0, // Format_Invalid, 0, // Format_Mono, 0, // Format_MonoLSB, 0, // Format_Indexed8, qt_blend_rgb32_on_rgb16, // Format_RGB32, 0, // Format_ARGB32, qt_blend_argb32_on_rgb16, // Format_ARGB32_Premultiplied, qt_blend_rgb16_on_rgb16, // Format_RGB16, qt_blend_argb24_on_rgb16, // Format_ARGB8565_Premultiplied, 0, // Format_RGB666, 0, // Format_ARGB6666_Premultiplied, 0, // Format_RGB555, 0, // Format_ARGB8555_Premultiplied, 0, // Format_RGB888, 0, // Format_RGB444, 0 // Format_ARGB4444_Premultiplied, }, { // Format_ARGB8565_Premultiplied 0, // Format_Invalid, 0, // Format_Mono, 0, // Format_MonoLSB, 0, // Format_Indexed8, 0, // Format_RGB32, 0, // Format_ARGB32, 0, // Format_ARGB32_Premultiplied, 0, // Format_RGB16, 0, // Format_ARGB8565_Premultiplied, 0, // Format_RGB666, 0, // Format_ARGB6666_Premultiplied, 0, // Format_RGB555, 0, // Format_ARGB8555_Premultiplied, 0, // Format_RGB888, 0, // Format_RGB444, 0 // Format_ARGB4444_Premultiplied, }, { // Format_RGB666 0, // Format_Invalid, 0, // Format_Mono, 0, // Format_MonoLSB, 0, // Format_Indexed8, 0, // Format_RGB32, 0, // Format_ARGB32, 0, // Format_ARGB32_Premultiplied, 0, // Format_RGB16, 0, // Format_ARGB8565_Premultiplied, 0, // Format_RGB666, 0, // Format_ARGB6666_Premultiplied, 0, // Format_RGB555, 0, // Format_ARGB8555_Premultiplied, 0, // Format_RGB888, 0, // Format_RGB444, 0 // Format_ARGB4444_Premultiplied, }, { // Format_ARGB6666_Premultiplied 0, // Format_Invalid, 0, // Format_Mono, 0, // Format_MonoLSB, 0, // Format_Indexed8, 0, // Format_RGB32, 0, // Format_ARGB32, 0, // Format_ARGB32_Premultiplied, 0, // Format_RGB16, 0, // Format_ARGB8565_Premultiplied, 0, // Format_RGB666, 0, // Format_ARGB6666_Premultiplied, 0, // Format_RGB555, 0, // Format_ARGB8555_Premultiplied, 0, // Format_RGB888, 0, // Format_RGB444, 0 // Format_ARGB4444_Premultiplied, }, { // Format_RGB555 0, // Format_Invalid, 0, // Format_Mono, 0, // Format_MonoLSB, 0, // Format_Indexed8, 0, // Format_RGB32, 0, // Format_ARGB32, 0, // Format_ARGB32_Premultiplied, 0, // Format_RGB16, 0, // Format_ARGB8565_Premultiplied, 0, // Format_RGB666, 0, // Format_ARGB6666_Premultiplied, 0, // Format_RGB555, 0, // Format_ARGB8555_Premultiplied, 0, // Format_RGB888, 0, // Format_RGB444, 0 // Format_ARGB4444_Premultiplied, }, { // Format_ARGB8555_Premultiplied 0, // Format_Invalid, 0, // Format_Mono, 0, // Format_MonoLSB, 0, // Format_Indexed8, 0, // Format_RGB32, 0, // Format_ARGB32, 0, // Format_ARGB32_Premultiplied, 0, // Format_RGB16, 0, // Format_ARGB8565_Premultiplied, 0, // Format_RGB666, 0, // Format_ARGB6666_Premultiplied, 0, // Format_RGB555, 0, // Format_ARGB8555_Premultiplied, 0, // Format_RGB888, 0, // Format_RGB444, 0 // Format_ARGB4444_Premultiplied, }, { // Format_RGB888 0, // Format_Invalid, 0, // Format_Mono, 0, // Format_MonoLSB, 0, // Format_Indexed8, 0, // Format_RGB32, 0, // Format_ARGB32, 0, // Format_ARGB32_Premultiplied, 0, // Format_RGB16, 0, // Format_ARGB8565_Premultiplied, 0, // Format_RGB666, 0, // Format_ARGB6666_Premultiplied, 0, // Format_RGB555, 0, // Format_ARGB8555_Premultiplied, 0, // Format_RGB888, 0, // Format_RGB444, 0 // Format_ARGB4444_Premultiplied, }, { // Format_RGB444 0, // Format_Invalid, 0, // Format_Mono, 0, // Format_MonoLSB, 0, // Format_Indexed8, 0, // Format_RGB32, 0, // Format_ARGB32, 0, // Format_ARGB32_Premultiplied, 0, // Format_RGB16, 0, // Format_ARGB8565_Premultiplied, 0, // Format_RGB666, 0, // Format_ARGB6666_Premultiplied, 0, // Format_RGB555, 0, // Format_ARGB8555_Premultiplied, 0, // Format_RGB888, 0, // Format_RGB444, 0 // Format_ARGB4444_Premultiplied, }, { // Format_ARGB4444_Premultiplied 0, // Format_Invalid, 0, // Format_Mono, 0, // Format_MonoLSB, 0, // Format_Indexed8, 0, // Format_RGB32, 0, // Format_ARGB32, 0, // Format_ARGB32_Premultiplied, 0, // Format_RGB16, 0, // Format_ARGB8565_Premultiplied, 0, // Format_RGB666, 0, // Format_ARGB6666_Premultiplied, 0, // Format_RGB555, 0, // Format_ARGB8555_Premultiplied, 0, // Format_RGB888, 0, // Format_RGB444, 0 // Format_ARGB4444_Premultiplied, } }; SrcOverTransformFunc qTransformFunctions[QImage::NImageFormats][QImage::NImageFormats] = { { // Format_Invalid 0, // Format_Invalid, 0, // Format_Mono, 0, // Format_MonoLSB, 0, // Format_Indexed8, 0, // Format_RGB32, 0, // Format_ARGB32, 0, // Format_ARGB32_Premultiplied, 0, // Format_RGB16, 0, // Format_ARGB8565_Premultiplied, 0, // Format_RGB666, 0, // Format_ARGB6666_Premultiplied, 0, // Format_RGB555, 0, // Format_ARGB8555_Premultiplied, 0, // Format_RGB888, 0, // Format_RGB444, 0 // Format_ARGB4444_Premultiplied, }, { // Format_Mono 0, // Format_Invalid, 0, // Format_Mono, 0, // Format_MonoLSB, 0, // Format_Indexed8, 0, // Format_RGB32, 0, // Format_ARGB32, 0, // Format_ARGB32_Premultiplied, 0, // Format_RGB16, 0, // Format_ARGB8565_Premultiplied, 0, // Format_RGB666, 0, // Format_ARGB6666_Premultiplied, 0, // Format_RGB555, 0, // Format_ARGB8555_Premultiplied, 0, // Format_RGB888, 0, // Format_RGB444, 0 // Format_ARGB4444_Premultiplied, }, { // Format_MonoLSB 0, // Format_Invalid, 0, // Format_Mono, 0, // Format_MonoLSB, 0, // Format_Indexed8, 0, // Format_RGB32, 0, // Format_ARGB32, 0, // Format_ARGB32_Premultiplied, 0, // Format_RGB16, 0, // Format_ARGB8565_Premultiplied, 0, // Format_RGB666, 0, // Format_ARGB6666_Premultiplied, 0, // Format_RGB555, 0, // Format_ARGB8555_Premultiplied, 0, // Format_RGB888, 0, // Format_RGB444, 0 // Format_ARGB4444_Premultiplied, }, { // Format_Indexed8 0, // Format_Invalid, 0, // Format_Mono, 0, // Format_MonoLSB, 0, // Format_Indexed8, 0, // Format_RGB32, 0, // Format_ARGB32, 0, // Format_ARGB32_Premultiplied, 0, // Format_RGB16, 0, // Format_ARGB8565_Premultiplied, 0, // Format_RGB666, 0, // Format_ARGB6666_Premultiplied, 0, // Format_RGB555, 0, // Format_ARGB8555_Premultiplied, 0, // Format_RGB888, 0, // Format_RGB444, 0 // Format_ARGB4444_Premultiplied, }, { // Format_RGB32 0, // Format_Invalid, 0, // Format_Mono, 0, // Format_MonoLSB, 0, // Format_Indexed8, qt_transform_image_rgb32_on_rgb32, // Format_RGB32, 0, // Format_ARGB32, qt_transform_image_argb32_on_argb32, // Format_ARGB32_Premultiplied, 0, // Format_RGB16, 0, // Format_ARGB8565_Premultiplied, 0, // Format_RGB666, 0, // Format_ARGB6666_Premultiplied, 0, // Format_RGB555, 0, // Format_ARGB8555_Premultiplied, 0, // Format_RGB888, 0, // Format_RGB444, 0 // Format_ARGB4444_Premultiplied, }, { // Format_ARGB32 0, // Format_Invalid, 0, // Format_Mono, 0, // Format_MonoLSB, 0, // Format_Indexed8, 0, // Format_RGB32, 0, // Format_ARGB32, 0, // Format_ARGB32_Premultiplied, 0, // Format_RGB16, 0, // Format_ARGB8565_Premultiplied, 0, // Format_RGB666, 0, // Format_ARGB6666_Premultiplied, 0, // Format_RGB555, 0, // Format_ARGB8555_Premultiplied, 0, // Format_RGB888, 0, // Format_RGB444, 0 // Format_ARGB4444_Premultiplied, }, { // Format_ARGB32_Premultiplied 0, // Format_Invalid, 0, // Format_Mono, 0, // Format_MonoLSB, 0, // Format_Indexed8, qt_transform_image_rgb32_on_rgb32, // Format_RGB32, 0, // Format_ARGB32, qt_transform_image_argb32_on_argb32, // Format_ARGB32_Premultiplied, 0, // Format_RGB16, 0, // Format_ARGB8565_Premultiplied, 0, // Format_RGB666, 0, // Format_ARGB6666_Premultiplied, 0, // Format_RGB555, 0, // Format_ARGB8555_Premultiplied, 0, // Format_RGB888, 0, // Format_RGB444, 0 // Format_ARGB4444_Premultiplied, }, { // Format_RGB16 0, // Format_Invalid, 0, // Format_Mono, 0, // Format_MonoLSB, 0, // Format_Indexed8, 0, // Format_RGB32, 0, // Format_ARGB32, qt_transform_image_argb32_on_rgb16, // Format_ARGB32_Premultiplied, qt_transform_image_rgb16_on_rgb16, // Format_RGB16, qt_transform_image_argb24_on_rgb16, // Format_ARGB8565_Premultiplied, 0, // Format_RGB666, 0, // Format_ARGB6666_Premultiplied, 0, // Format_RGB555, 0, // Format_ARGB8555_Premultiplied, 0, // Format_RGB888, 0, // Format_RGB444, 0 // Format_ARGB4444_Premultiplied, }, { // Format_ARGB8565_Premultiplied 0, // Format_Invalid, 0, // Format_Mono, 0, // Format_MonoLSB, 0, // Format_Indexed8, 0, // Format_RGB32, 0, // Format_ARGB32, 0, // Format_ARGB32_Premultiplied, 0, // Format_RGB16, 0, // Format_ARGB8565_Premultiplied, 0, // Format_RGB666, 0, // Format_ARGB6666_Premultiplied, 0, // Format_RGB555, 0, // Format_ARGB8555_Premultiplied, 0, // Format_RGB888, 0, // Format_RGB444, 0 // Format_ARGB4444_Premultiplied, }, { // Format_RGB666 0, // Format_Invalid, 0, // Format_Mono, 0, // Format_MonoLSB, 0, // Format_Indexed8, 0, // Format_RGB32, 0, // Format_ARGB32, 0, // Format_ARGB32_Premultiplied, 0, // Format_RGB16, 0, // Format_ARGB8565_Premultiplied, 0, // Format_RGB666, 0, // Format_ARGB6666_Premultiplied, 0, // Format_RGB555, 0, // Format_ARGB8555_Premultiplied, 0, // Format_RGB888, 0, // Format_RGB444, 0 // Format_ARGB4444_Premultiplied, }, { // Format_ARGB6666_Premultiplied 0, // Format_Invalid, 0, // Format_Mono, 0, // Format_MonoLSB, 0, // Format_Indexed8, 0, // Format_RGB32, 0, // Format_ARGB32, 0, // Format_ARGB32_Premultiplied, 0, // Format_RGB16, 0, // Format_ARGB8565_Premultiplied, 0, // Format_RGB666, 0, // Format_ARGB6666_Premultiplied, 0, // Format_RGB555, 0, // Format_ARGB8555_Premultiplied, 0, // Format_RGB888, 0, // Format_RGB444, 0 // Format_ARGB4444_Premultiplied, }, { // Format_RGB555 0, // Format_Invalid, 0, // Format_Mono, 0, // Format_MonoLSB, 0, // Format_Indexed8, 0, // Format_RGB32, 0, // Format_ARGB32, 0, // Format_ARGB32_Premultiplied, 0, // Format_RGB16, 0, // Format_ARGB8565_Premultiplied, 0, // Format_RGB666, 0, // Format_ARGB6666_Premultiplied, 0, // Format_RGB555, 0, // Format_ARGB8555_Premultiplied, 0, // Format_RGB888, 0, // Format_RGB444, 0 // Format_ARGB4444_Premultiplied, }, { // Format_ARGB8555_Premultiplied 0, // Format_Invalid, 0, // Format_Mono, 0, // Format_MonoLSB, 0, // Format_Indexed8, 0, // Format_RGB32, 0, // Format_ARGB32, 0, // Format_ARGB32_Premultiplied, 0, // Format_RGB16, 0, // Format_ARGB8565_Premultiplied, 0, // Format_RGB666, 0, // Format_ARGB6666_Premultiplied, 0, // Format_RGB555, 0, // Format_ARGB8555_Premultiplied, 0, // Format_RGB888, 0, // Format_RGB444, 0 // Format_ARGB4444_Premultiplied, }, { // Format_RGB888 0, // Format_Invalid, 0, // Format_Mono, 0, // Format_MonoLSB, 0, // Format_Indexed8, 0, // Format_RGB32, 0, // Format_ARGB32, 0, // Format_ARGB32_Premultiplied, 0, // Format_RGB16, 0, // Format_ARGB8565_Premultiplied, 0, // Format_RGB666, 0, // Format_ARGB6666_Premultiplied, 0, // Format_RGB555, 0, // Format_ARGB8555_Premultiplied, 0, // Format_RGB888, 0, // Format_RGB444, 0 // Format_ARGB4444_Premultiplied, }, { // Format_RGB444 0, // Format_Invalid, 0, // Format_Mono, 0, // Format_MonoLSB, 0, // Format_Indexed8, 0, // Format_RGB32, 0, // Format_ARGB32, 0, // Format_ARGB32_Premultiplied, 0, // Format_RGB16, 0, // Format_ARGB8565_Premultiplied, 0, // Format_RGB666, 0, // Format_ARGB6666_Premultiplied, 0, // Format_RGB555, 0, // Format_ARGB8555_Premultiplied, 0, // Format_RGB888, 0, // Format_RGB444, 0 // Format_ARGB4444_Premultiplied, }, { // Format_ARGB4444_Premultiplied 0, // Format_Invalid, 0, // Format_Mono, 0, // Format_MonoLSB, 0, // Format_Indexed8, 0, // Format_RGB32, 0, // Format_ARGB32, 0, // Format_ARGB32_Premultiplied, 0, // Format_RGB16, 0, // Format_ARGB8565_Premultiplied, 0, // Format_RGB666, 0, // Format_ARGB6666_Premultiplied, 0, // Format_RGB555, 0, // Format_ARGB8555_Premultiplied, 0, // Format_RGB888, 0, // Format_RGB444, 0 // Format_ARGB4444_Premultiplied, } }; QT_END_NAMESPACE
37.33617
254
0.511283
ant0ine
3b536e10d490f9a00b5ca1787c108c2a3f088e25
1,191
cpp
C++
competitive_programming/programming_contests/uri/motoboy.cpp
LeandroTk/Algorithms
569ed68eba3eeff902f8078992099c28ce4d7cd6
[ "MIT" ]
205
2018-12-01T17:49:49.000Z
2021-12-22T07:02:27.000Z
competitive_programming/programming_contests/uri/motoboy.cpp
LeandroTk/Algorithms
569ed68eba3eeff902f8078992099c28ce4d7cd6
[ "MIT" ]
2
2020-01-01T16:34:29.000Z
2020-04-26T19:11:13.000Z
competitive_programming/programming_contests/uri/motoboy.cpp
LeandroTk/Algorithms
569ed68eba3eeff902f8078992099c28ce4d7cd6
[ "MIT" ]
50
2018-11-28T20:51:36.000Z
2021-11-29T04:08:25.000Z
// https://www.urionlinejudge.com.br/judge/pt/problems/view/1286 #include <iostream> #include <vector> #include <algorithm> using namespace std; int max(int a, int b) { return a > b? a : b; } struct Obj { int time, pizza; }; bool sortByPizza(Obj obj1, Obj obj2) { if (obj1.pizza < obj2.pizza) return true; else if (obj1.pizza > obj2.pizza) return false; else return obj1.time < obj2.time; } int main() { int N, P, time, pizza; while (cin >> N && N) { vector<Obj> objects; cin >> P; for (int i = 0; i < N; i++) { cin >> time >> pizza; Obj object; object.time = time; object.pizza = pizza; objects.push_back(object); } sort(objects.begin(), objects.end(), sortByPizza); int dp[N][P+1]; for (int i = 0; i <= P; i++) { if (objects[0].pizza <= i) dp[0][i] = objects[0].time; else dp[0][i] = 0; } for (int i = 1; i < N; i++) { for (int j = 0; j < P; j++) { if (j - objects[i].pizza >= 0) dp[i][j] = max(dp[i-1][j - objects[i].pizza] + objects[i].time, dp[i-1][j]); else dp[i][j] = dp[i-1][j]; } } cout << dp[N-1][P-1] << " min."<< endl; } return 0; }
20.186441
115
0.525609
LeandroTk
3b586f4a9bf403ae9a5a5c7d52f417ecf11a5bd8
13,160
cpp
C++
mplapack/reference/Chetrf_aa.cpp
Ndersam/mplapack
f2ef54d7ce95e4028d3f101a901c75d18d3f1327
[ "BSD-3-Clause-Open-MPI" ]
26
2019-03-20T04:06:03.000Z
2022-03-02T10:21:01.000Z
mplapack/reference/Chetrf_aa.cpp
Ndersam/mplapack
f2ef54d7ce95e4028d3f101a901c75d18d3f1327
[ "BSD-3-Clause-Open-MPI" ]
5
2019-03-04T03:32:41.000Z
2021-12-01T07:47:25.000Z
mplapack/reference/Chetrf_aa.cpp
Ndersam/mplapack
f2ef54d7ce95e4028d3f101a901c75d18d3f1327
[ "BSD-3-Clause-Open-MPI" ]
5
2019-03-09T17:50:26.000Z
2022-03-10T19:46:20.000Z
/* * Copyright (c) 2008-2021 * Nakata, Maho * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #include <mpblas.h> #include <mplapack.h> void Chetrf_aa(const char *uplo, INTEGER const n, COMPLEX *a, INTEGER const lda, INTEGER *ipiv, COMPLEX *work, INTEGER const lwork, INTEGER &info) { INTEGER nb = 0; bool upper = false; bool lquery = false; INTEGER lwkopt = 0; INTEGER j = 0; INTEGER j1 = 0; INTEGER jb = 0; INTEGER k1 = 0; INTEGER j2 = 0; COMPLEX alpha = 0.0; const COMPLEX one = COMPLEX(1.0, 0.0); INTEGER k2 = 0; INTEGER nj = 0; INTEGER j3 = 0; INTEGER mj = 0; // // -- LAPACK computational routine -- // -- LAPACK is a software package provided by Univ. of Tennessee, -- // -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- // // .. Scalar Arguments .. // .. // .. Array Arguments .. // .. // // ===================================================================== // .. Parameters .. // // .. Local Scalars .. // .. // .. External Functions .. // .. // .. External Subroutines .. // .. // .. Intrinsic Functions .. // .. // .. Executable Statements .. // // Determine the block size // nb = iMlaenv(1, "Chetrf_aa", uplo, n, -1, -1, -1); // // Test the input parameters. // info = 0; upper = Mlsame(uplo, "U"); lquery = (lwork == -1); if (!upper && !Mlsame(uplo, "L")) { info = -1; } else if (n < 0) { info = -2; } else if (lda < max((INTEGER)1, n)) { info = -4; } else if (lwork < max((INTEGER)1, 2 * n) && !lquery) { info = -7; } // if (info == 0) { lwkopt = (nb + 1) * n; work[1 - 1] = lwkopt; } // if (info != 0) { Mxerbla("Chetrf_aa", -info); return; } else if (lquery) { return; } // // Quick return // if (n == 0) { return; } ipiv[1 - 1] = 1; if (n == 1) { a[(1 - 1)] = a[(1 - 1)].real(); return; } // // Adjust block size based on the workspace size // if (lwork < ((1 + nb) * n)) { nb = (lwork - n) / n; } // if (upper) { // // ..................................................... // Factorize A as U**H*D*U using the upper triangle of A // ..................................................... // // copy first row A(1, 1:N) into H(1:n) (stored in WORK(1:N)) // Ccopy(n, &a[(1 - 1)], lda, &work[1 - 1], 1); // // J is the main loop index, increasing from 1 to N in steps of // JB, where JB is the number of columns factorized by Clahef; // JB is either NB, or N-J+1 for the last block // j = 0; statement_10: if (j >= n) { goto statement_20; } // // each step of the main loop // J is the last column of the previous panel // J1 is the first column of the current panel // K1 identifies if the previous column of the panel has been // explicitly stored, e.g., K1=1 for the first panel, and // K1=0 for the rest // j1 = j + 1; jb = min(n - j1 + 1, nb); k1 = max((INTEGER)1, j) - j; // // Panel factorization // Clahef_aa(uplo, 2 - k1, n - j, jb, &a[(max((INTEGER)1, j) - 1) + ((j + 1) - 1) * lda], lda, &ipiv[(j + 1) - 1], work, n, &work[(n * nb + 1) - 1]); // // Adjust IPIV and apply it back (J-th step picks (J+1)-th pivot) // for (j2 = j + 2; j2 <= min(n, j + jb + 1); j2 = j2 + 1) { ipiv[j2 - 1] += j; if ((j2 != ipiv[j2 - 1]) && ((j1 - k1) > 2)) { Cswap(j1 - k1 - 2, &a[(j2 - 1) * lda], 1, &a[(ipiv[j2 - 1] - 1) * lda], 1); } } j += jb; // // Trailing submatrix update, where // the row A(J1-1, J2-1:N) stores U(J1, J2+1:N) and // WORK stores the current block of the auxiriarly matrix H // if (j < n) { // // if the first panel and JB=1 (NB=1), then nothing to do // if (j1 > 1 || jb > 1) { // // Merge rank-1 update with BLAS-3 update // alpha = conj(a[(j - 1) + ((j + 1) - 1) * lda]); a[(j - 1) + ((j + 1) - 1) * lda] = one; Ccopy(n - j, &a[((j - 1) - 1) + ((j + 1) - 1) * lda], lda, &work[((j + 1 - j1 + 1) + jb * n) - 1], 1); Cscal(n - j, alpha, &work[((j + 1 - j1 + 1) + jb * n) - 1], 1); // // K1 identifies if the previous column of the panel has been // explicitly stored, e.g., K1=0 and K2=1 for the first panel, // and K1=1 and K2=0 for the rest // if (j1 > 1) { // // Not first panel // k2 = 1; } else { // // First panel // k2 = 0; // // First update skips the first column // jb = jb - 1; } // for (j2 = j + 1; j2 <= n; j2 = j2 + nb) { nj = min(nb, n - j2 + 1); // // Update (J2, J2) diagonal block with Cgemv // j3 = j2; for (mj = nj - 1; mj >= 1; mj = mj - 1) { Cgemm("Conjugate transpose", "Transpose", 1, mj, jb + 1, -one, &a[((j1 - k2) - 1) + (j3 - 1) * lda], lda, &work[((j3 - j1 + 1) + k1 * n) - 1], n, one, &a[(j3 - 1) + (j3 - 1) * lda], lda); j3++; } // // Update off-diagonal block of J2-th block row with Cgemm // Cgemm("Conjugate transpose", "Transpose", nj, n - j3 + 1, jb + 1, -one, &a[((j1 - k2) - 1) + (j2 - 1) * lda], lda, &work[((j3 - j1 + 1) + k1 * n) - 1], n, one, &a[(j2 - 1) + (j3 - 1) * lda], lda); } // // Recover T( J, J+1 ) // a[(j - 1) + ((j + 1) - 1) * lda] = conj(alpha); } // // WORK(J+1, 1) stores H(J+1, 1) // Ccopy(n - j, &a[((j + 1) - 1) + ((j + 1) - 1) * lda], lda, &work[1 - 1], 1); } goto statement_10; } else { // // ..................................................... // Factorize A as L*D*L**H using the lower triangle of A // ..................................................... // // copy first column A(1:N, 1) into H(1:N, 1) // (stored in WORK(1:N)) // Ccopy(n, &a[(1 - 1)], 1, &work[1 - 1], 1); // // J is the main loop index, increasing from 1 to N in steps of // JB, where JB is the number of columns factorized by Clahef; // JB is either NB, or N-J+1 for the last block // j = 0; statement_11: if (j >= n) { goto statement_20; } // // each step of the main loop // J is the last column of the previous panel // J1 is the first column of the current panel // K1 identifies if the previous column of the panel has been // explicitly stored, e.g., K1=1 for the first panel, and // K1=0 for the rest // j1 = j + 1; jb = min(n - j1 + 1, nb); k1 = max((INTEGER)1, j) - j; // // Panel factorization // Clahef_aa(uplo, 2 - k1, n - j, jb, &a[((j + 1) - 1) + (max((INTEGER)1, j) - 1) * lda], lda, &ipiv[(j + 1) - 1], work, n, &work[(n * nb + 1) - 1]); // // Adjust IPIV and apply it back (J-th step picks (J+1)-th pivot) // for (j2 = j + 2; j2 <= min(n, j + jb + 1); j2 = j2 + 1) { ipiv[j2 - 1] += j; if ((j2 != ipiv[j2 - 1]) && ((j1 - k1) > 2)) { Cswap(j1 - k1 - 2, &a[(j2 - 1)], lda, &a[(ipiv[j2 - 1] - 1)], lda); } } j += jb; // // Trailing submatrix update, where // A(J2+1, J1-1) stores L(J2+1, J1) and // WORK(J2+1, 1) stores H(J2+1, 1) // if (j < n) { // // if the first panel and JB=1 (NB=1), then nothing to do // if (j1 > 1 || jb > 1) { // // Merge rank-1 update with BLAS-3 update // alpha = conj(a[((j + 1) - 1) + (j - 1) * lda]); a[((j + 1) - 1) + (j - 1) * lda] = one; Ccopy(n - j, &a[((j + 1) - 1) + ((j - 1) - 1) * lda], 1, &work[((j + 1 - j1 + 1) + jb * n) - 1], 1); Cscal(n - j, alpha, &work[((j + 1 - j1 + 1) + jb * n) - 1], 1); // // K1 identifies if the previous column of the panel has been // explicitly stored, e.g., K1=0 and K2=1 for the first panel, // and K1=1 and K2=0 for the rest // if (j1 > 1) { // // Not first panel // k2 = 1; } else { // // First panel // k2 = 0; // // First update skips the first column // jb = jb - 1; } // for (j2 = j + 1; j2 <= n; j2 = j2 + nb) { nj = min(nb, n - j2 + 1); // // Update (J2, J2) diagonal block with Cgemv // j3 = j2; for (mj = nj - 1; mj >= 1; mj = mj - 1) { Cgemm("No transpose", "Conjugate transpose", mj, 1, jb + 1, -one, &work[((j3 - j1 + 1) + k1 * n) - 1], n, &a[(j3 - 1) + ((j1 - k2) - 1) * lda], lda, one, &a[(j3 - 1) + (j3 - 1) * lda], lda); j3++; } // // Update off-diagonal block of J2-th block column with Cgemm // Cgemm("No transpose", "Conjugate transpose", n - j3 + 1, nj, jb + 1, -one, &work[((j3 - j1 + 1) + k1 * n) - 1], n, &a[(j2 - 1) + ((j1 - k2) - 1) * lda], lda, one, &a[(j3 - 1) + (j2 - 1) * lda], lda); } // // Recover T( J+1, J ) // a[((j + 1) - 1) + (j - 1) * lda] = conj(alpha); } // // WORK(J+1, 1) stores H(J+1, 1) // Ccopy(n - j, &a[((j + 1) - 1) + ((j + 1) - 1) * lda], 1, &work[1 - 1], 1); } goto statement_11; } // statement_20:; // // End of Chetrf_aa // }
38.367347
219
0.38579
Ndersam
3b5925b76ac1fcfbc1cf4036da4a15deda5565f1
3,196
hpp
C++
modules/scene_manager/include/urdf/visibility_control.hpp
Omnirobotic/godot
d50b5d047bbf6c68fc458c1ad097321ca627185d
[ "CC-BY-3.0", "Apache-2.0", "MIT" ]
null
null
null
modules/scene_manager/include/urdf/visibility_control.hpp
Omnirobotic/godot
d50b5d047bbf6c68fc458c1ad097321ca627185d
[ "CC-BY-3.0", "Apache-2.0", "MIT" ]
3
2019-11-14T12:20:06.000Z
2020-08-07T13:51:10.000Z
modules/scene_manager/include/urdf/visibility_control.hpp
Omnirobotic/godot
d50b5d047bbf6c68fc458c1ad097321ca627185d
[ "CC-BY-3.0", "Apache-2.0", "MIT" ]
null
null
null
/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2017, Open Source Robotics Foundation, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *********************************************************************/ /* This header must be included by all urdf headers which declare symbols * which are defined in the urdf library. When not building the urdf * library, i.e. when using the headers in other package's code, the contents * of this header change the visibility of certain symbols which the urdf * library cannot have, but the consuming code must have inorder to link. */ #ifndef URDF__VISIBILITY_CONTROL_HPP_ #define URDF__VISIBILITY_CONTROL_HPP_ // This logic was borrowed (then namespaced) from the examples on the gcc wiki: // https://gcc.gnu.org/wiki/Visibility #if defined _WIN32 || defined __CYGWIN__ #ifdef __GNUC__ #define URDF_EXPORT __attribute__ ((dllexport)) #define URDF_IMPORT __attribute__ ((dllimport)) #else #define URDF_EXPORT __declspec(dllexport) #define URDF_IMPORT __declspec(dllimport) #endif #ifdef URDF_BUILDING_LIBRARY #define URDF_PUBLIC URDF_EXPORT #else #define URDF_PUBLIC URDF_IMPORT #endif #define URDF_PUBLIC_TYPE URDF_PUBLIC #define URDF_LOCAL #else #define URDF_EXPORT __attribute__ ((visibility("default"))) #define URDF_IMPORT #if __GNUC__ >= 4 #define URDF_PUBLIC __attribute__ ((visibility("default"))) #define URDF_LOCAL __attribute__ ((visibility("hidden"))) #else #define URDF_PUBLIC #define URDF_LOCAL #endif #define URDF_PUBLIC_TYPE #endif #endif // URDF__VISIBILITY_CONTROL_HPP_
41.506494
79
0.727472
Omnirobotic
3b59512a3a38616191043a443da2b41c89fb5aae
10,365
cpp
C++
test/xeus_client.cpp
JohanMabille/xeus-python
f7319d1d4e814f8842b8f12376301ce38dfed1e7
[ "BSD-3-Clause" ]
269
2019-12-29T23:50:45.000Z
2022-03-31T06:11:02.000Z
test/xeus_client.cpp
JohanMabille/xeus-python
f7319d1d4e814f8842b8f12376301ce38dfed1e7
[ "BSD-3-Clause" ]
199
2019-12-27T12:45:32.000Z
2022-03-14T17:06:32.000Z
test/xeus_client.cpp
JohanMabille/xeus-python
f7319d1d4e814f8842b8f12376301ce38dfed1e7
[ "BSD-3-Clause" ]
43
2020-01-09T22:37:45.000Z
2022-02-27T01:28:31.000Z
/*************************************************************************** * Copyright (c) 2018, Martin Renou, Johan Mabille, Sylvain Corlay, and * * Wolf Vollprecht * * Copyright (c) 2018, QuantStack * * * * Distributed under the terms of the BSD 3-Clause License. * * * * The full license is in the file LICENSE, distributed with this software. * ****************************************************************************/ #include <chrono> #include <fstream> #include <iostream> #include <thread> #include "zmq_addon.hpp" #include "xeus_client.hpp" #include "xeus/xguid.hpp" #include "xeus/xmessage.hpp" #include "xeus/xmiddleware.hpp" #include "xeus/xzmq_serializer.hpp" using namespace std::chrono_literals; /*********************************** * xeus-client_base implementation * ***********************************/ xeus_client_base::xeus_client_base(zmq::context_t& context, const std::string& user_name, const xeus::xconfiguration& config) : p_shell_authentication(xeus::make_xauthentication(config.m_signature_scheme, config.m_key)) , p_control_authentication(xeus::make_xauthentication(config.m_signature_scheme, config.m_key)) , p_iopub_authentication(xeus::make_xauthentication(config.m_signature_scheme, config.m_key)) , m_shell(context, zmq::socket_type::dealer) , m_control(context, zmq::socket_type::dealer) , m_iopub(context, zmq::socket_type::sub) , m_shell_end_point("") , m_control_end_point("") , m_iopub_end_point("") , m_user_name(user_name) , m_session_id(xeus::new_xguid()) { m_shell_end_point = xeus::get_end_point(config.m_transport, config.m_ip, config.m_shell_port); m_control_end_point = xeus::get_end_point(config.m_transport, config.m_ip, config.m_control_port); m_iopub_end_point = xeus::get_end_point(config.m_transport, config.m_ip, config.m_iopub_port); m_shell.connect(m_shell_end_point); m_control.connect(m_control_end_point); m_iopub.connect(m_iopub_end_point); } xeus_client_base::~xeus_client_base() { m_shell.disconnect(m_shell_end_point); m_control.disconnect(m_control_end_point); m_iopub.disconnect(m_iopub_end_point); } void xeus_client_base::send_on_shell(nl::json header, nl::json parent_header, nl::json metadata, nl::json content) { send_message(std::move(header), std::move(parent_header), std::move(metadata), std::move(content), m_shell, *p_shell_authentication); } nl::json xeus_client_base::receive_on_shell() { return receive_message(m_shell, *p_shell_authentication); } void xeus_client_base::send_on_control(nl::json header, nl::json parent_header, nl::json metadata, nl::json content) { send_message(std::move(header), std::move(parent_header), std::move(metadata), std::move(content), m_control, *p_control_authentication); } nl::json xeus_client_base::receive_on_control() { return receive_message(m_control, *p_control_authentication); } void xeus_client_base::subscribe_iopub(const std::string& filter) { m_iopub.setsockopt(ZMQ_SUBSCRIBE, filter.c_str(), filter.length()); } void xeus_client_base::unsubscribe_iopub(const std::string& filter) { m_iopub.setsockopt(ZMQ_UNSUBSCRIBE, filter.c_str(), filter.length()); } nl::json xeus_client_base::receive_on_iopub() { zmq::multipart_t wire_msg; wire_msg.recv(m_iopub); xeus::xpub_message msg = xeus::xzmq_serializer::deserialize_iopub(wire_msg, *p_iopub_authentication); nl::json res = aggregate(msg.header(), msg.parent_header(), msg.metadata(), msg.content()); res["topic"] = msg.topic(); return res; } nl::json xeus_client_base::make_header(const std::string& msg_type) const { return xeus::make_header(msg_type, m_user_name, m_session_id); } void xeus_client_base::send_message(nl::json header, nl::json parent_header, nl::json metadata, nl::json content, zmq::socket_t& socket, const xeus::xauthentication& auth) { xeus::xmessage msg(xeus::xmessage::guid_list(), std::move(header), std::move(parent_header), std::move(metadata), std::move(content), xeus::buffer_sequence()); zmq::multipart_t wire_msg = xeus::xzmq_serializer::serialize(std::move(msg), auth); wire_msg.send(socket); } nl::json xeus_client_base::receive_message(zmq::socket_t& socket, const xeus::xauthentication& auth) { zmq::multipart_t wire_msg; wire_msg.recv(socket); xeus::xmessage msg = xeus::xzmq_serializer::deserialize(wire_msg, auth); return aggregate(msg.header(), msg.parent_header(), msg.metadata(), msg.content()); } nl::json xeus_client_base::aggregate(const nl::json& header, const nl::json& parent_header, const nl::json& metadata, const nl::json& content) const { nl::json result; result["header"] = header; result["parent_header"] = parent_header; result["metadata"] = metadata; result["content"] = content; return result; } /************************************* * xeus_logger_client implementation * *************************************/ xeus_logger_client::xeus_logger_client(zmq::context_t& context, const std::string& user_name, const xeus::xconfiguration& config, const std::string& file_name) : xeus_client_base(context, user_name, config) , m_file_name(file_name) , m_iopub_stopped(false) { std::ofstream out(m_file_name); out << "STARTING CLIENT" << std::endl; base_type::subscribe_iopub(""); std::thread iopub_thread(&xeus_logger_client::poll_iopub, this); iopub_thread.detach(); } xeus_logger_client::~xeus_logger_client() { while(!m_iopub_stopped) { std::this_thread::sleep_for(100ms); } } void xeus_logger_client::send_on_shell(const std::string& msg_type, nl::json content) { nl::json header = base_type::make_header(msg_type); log_message(base_type::aggregate(header, nl::json::object(), nl::json::object(), content)); base_type::send_on_shell(std::move(header), nl::json::object(), nl::json::object(), std::move(content)); } void xeus_logger_client::send_on_control(const std::string& msg_type, nl::json content) { nl::json header = base_type::make_header(msg_type); log_message(base_type::aggregate(header, nl::json::object(), nl::json::object(), content)); base_type::send_on_control(std::move(header), nl::json::object(), nl::json::object(), std::move(content)); } nl::json xeus_logger_client::receive_on_shell() { nl::json msg = base_type::receive_on_shell(); log_message(msg); return msg; } nl::json xeus_logger_client::receive_on_control() { nl::json msg = base_type::receive_on_control(); log_message(msg); return msg; } std::size_t xeus_logger_client::iopub_queue_size() const { std::lock_guard<std::mutex> guard(m_queue_mutex); return m_message_queue.size(); } nl::json xeus_logger_client::pop_iopub_message() { std::lock_guard<std::mutex> guard(m_queue_mutex); nl::json res = m_message_queue.back(); m_message_queue.pop(); return res; } nl::json xeus_logger_client::wait_for_debug_event(const std::string& event) { bool event_found = false; nl::json msg; while(!event_found) { std::size_t s = iopub_queue_size(); if(s != 0) { msg = pop_iopub_message(); if(msg["topic"] == "debug_event" && msg["content"]["event"] == event) { event_found = true; } } else { std::unique_lock<std::mutex> lk(m_notify_mutex); if(iopub_queue_size()) { continue; } m_notify_cond.wait(lk); } } return msg; } void xeus_logger_client::poll_iopub() { while(true) { nl::json msg = base_type::receive_on_iopub(); { std::unique_lock<std::mutex> lk(m_notify_mutex); std::unique_lock<std::mutex> guard(m_queue_mutex); m_message_queue.push(msg); guard.unlock(); lk.unlock(); m_notify_cond.notify_one(); } std::string topic = msg["topic"]; std::size_t topic_size = topic.size(); log_message(std::move(msg)); if(topic.substr(topic_size - 8, topic_size) == "shutdown") { std::cout << "Received shutdown, exiting" << std::endl; break; } } m_iopub_stopped = true; } void xeus_logger_client::log_message(nl::json msg) { std::lock_guard<std::mutex> guard(m_file_mutex); std::ofstream out(m_file_name, std::ios_base::app); out << msg.dump(4) << std::endl; }
33.543689
105
0.54877
JohanMabille
3b5966ae0e3db24afa6799df4c5b4dc80b53692c
240
cpp
C++
list1010.cpp
zhangqiangoffice/Explain-C
d804978556ea3000f1718126765606e43223925e
[ "Apache-2.0" ]
null
null
null
list1010.cpp
zhangqiangoffice/Explain-C
d804978556ea3000f1718126765606e43223925e
[ "Apache-2.0" ]
null
null
null
list1010.cpp
zhangqiangoffice/Explain-C
d804978556ea3000f1718126765606e43223925e
[ "Apache-2.0" ]
null
null
null
#include <stdio.h> int main(void) { int i; int vc[5] = {10, 20, 30, 40, 50}; int *ptr = &vc[0]; for (i = 0; i < 5; i++) printf("vc[%d] = %d ptr[%d] = %d *(ptr + %d) = %d\n", i, vc[i], i, ptr[i], i, *(ptr + i)); return (0); }
20
57
0.429167
zhangqiangoffice
3b5dfce7bba25ebda8010d0f04f5f660e7627608
892
cpp
C++
qprogressbar_hook_c.cpp
mariuszmaximus/qt5pas-aarch64-linux-gnu
c60bbcfa5b0d7c4fe18bb21e5f2f424a5b658c1b
[ "Apache-2.0" ]
null
null
null
qprogressbar_hook_c.cpp
mariuszmaximus/qt5pas-aarch64-linux-gnu
c60bbcfa5b0d7c4fe18bb21e5f2f424a5b658c1b
[ "Apache-2.0" ]
null
null
null
qprogressbar_hook_c.cpp
mariuszmaximus/qt5pas-aarch64-linux-gnu
c60bbcfa5b0d7c4fe18bb21e5f2f424a5b658c1b
[ "Apache-2.0" ]
null
null
null
//****************************************************************************** // Copyright (c) 2005-2013 by Jan Van hijfte // // See the included file COPYING.TXT for details about the copyright. // // 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. //****************************************************************************** #include "qprogressbar_hook_c.h" QProgressBar_hookH QProgressBar_hook_Create(QObjectH handle) { return (QProgressBar_hookH) new QProgressBar_hook((QObject*)handle); } void QProgressBar_hook_Destroy(QProgressBar_hookH handle) { delete (QProgressBar_hook *)handle; } void QProgressBar_hook_hook_valueChanged(QProgressBar_hookH handle, QHookH hook) { ((QProgressBar_hook *)handle)->hook_valueChanged(hook); }
30.758621
80
0.643498
mariuszmaximus
3b5e19002f51f8095c627fcfb44c89a83d29aae5
15,875
cpp
C++
Tools/STM32FW/STM32Cube_FW_F7_V1.16.2/Projects/STM32F769I_EVAL/Demonstrations/TouchGFX/Gui/gui/src/common/LoginWidget.cpp
ramkumarkoppu/NUCLEO-F767ZI-ESW
85e129d71ee8eccbd0b94b5e07e75b6b91679ee8
[ "MIT" ]
null
null
null
Tools/STM32FW/STM32Cube_FW_F7_V1.16.2/Projects/STM32F769I_EVAL/Demonstrations/TouchGFX/Gui/gui/src/common/LoginWidget.cpp
ramkumarkoppu/NUCLEO-F767ZI-ESW
85e129d71ee8eccbd0b94b5e07e75b6b91679ee8
[ "MIT" ]
null
null
null
Tools/STM32FW/STM32Cube_FW_F7_V1.16.2/Projects/STM32F769I_EVAL/Demonstrations/TouchGFX/Gui/gui/src/common/LoginWidget.cpp
ramkumarkoppu/NUCLEO-F767ZI-ESW
85e129d71ee8eccbd0b94b5e07e75b6b91679ee8
[ "MIT" ]
null
null
null
/** ****************************************************************************** * This file is part of the TouchGFX 4.10.0 distribution. * * @attention * * Copyright (c) 2018 STMicroelectronics. * All rights reserved. * * This software is licensed under terms that can be found in the LICENSE file * in the root directory of this software component. * If no LICENSE file comes with this software, it is provided AS-IS. * ****************************************************************************** */ #include <gui/common/LoginWidget.hpp> #include <touchgfx/Color.hpp> #include <touchgfx/hal/Types.hpp> #include <texts/TextKeysAndLanguages.hpp> #include <BitmapDatabase.hpp> LoginWidget::LoginWidget() : Container(), patternStarted(false), solutionFailed(false), success(false), tracing(false), solutionMinLength(0), failedAttempts(0), maxAllowedAttempts(0), tickCounter(0), completedEdges(0), animationEndedCallback(this, &LoginWidget::animationEnded) { setTouchable(true); //default solution solution.add(0); solution.add(1); solution.add(2); solution.add(3); solutionMinLength = solution.size(); background.setBitmap(Bitmap(BITMAP_HOME_LOGIN_BACKGROUND_ID)); background.setXY(0, 0); add(background); setWidth(background.getWidth()); setHeight(background.getHeight()); //Set up canvas myColorPainter.setColor(Color::getColorFrom24BitRGB(51, 189, 253)); //Add header and banner headerTxt.setTypedText(TypedText(T_LOGIN_HEADLINE)); headerTxt.setPosition(0, 20, getWidth(), 50); headerTxt.setColor(Color::getColorFrom24BitRGB(0xff, 0xff, 0xff)); add(headerTxt); bannerTxt.setPosition(0, getHeight() - 50, getWidth(), 50); bannerTxt.setColor(Color::getColorFrom24BitRGB(255, 0, 0)); bannerTxt.setVisible(false); add(bannerTxt); reset(); } void LoginWidget::handleDragEvent(const touchgfx::DragEvent &evt) { // Pattern cannot be started if solution failed if ( (patternStarted && !solutionFailed && !success)) { line[completedEdges].updateEnd(evt.getNewX(), evt.getNewY()); if (!line[completedEdges].isVisible()) { line[completedEdges].setVisible(true); } //If no elements in input, that means we started away from a marker for (int i = 0; i < NR_OF_MARKERS; i++) { if (hitBoxes[i].getRect().intersect(evt.getNewX(), evt.getNewY()) && !input.contains(i)) { //Draw additional lines along diagonals and if (input.size() >= 1) { uint8_t prevVal = input[input.size() - 1]; if ((i == 0 || i == 2) && (prevVal == 0 || prevVal == 2)) { activateNode(1, true); } if ((i == 0 || i == 6) && (prevVal == 0 || prevVal == 6)) { activateNode(3, true); } if ((i == 2 || i == 8) && (prevVal == 2 || prevVal == 8)) { activateNode(5, true); } if ((i == 6 || i == 8) && (prevVal == 6 || prevVal == 8)) { activateNode(7, true); } //Activation of skipped contact if (((i == 3 || i == 5) && (prevVal == 3 || prevVal == 5)) || ((i == 0 || i == 8) && (prevVal == 0 || prevVal == 8)) || ((i == 1 || i == 7) && (prevVal == 1 || prevVal == 7)) || ((i == 2 || i == 6) && (prevVal == 6 || prevVal == 2)) ) { activateNode(4, true); } //activate activateNode(i); } } } } } void LoginWidget::handleClickEvent(const touchgfx::ClickEvent &evt) { //todo: If moving success to activateSingle() RELEASED will never contain a valid solution if (evt.getType() == touchgfx::ClickEvent::RELEASED && !success && !tracing) { if (input.size() > 0) { if (input.size() < MIN_ACCEPTED_INPUT_SIZE) { //CANCEL CURRENT LINE IF NOT CONNECTED //completed edges is off by one, so we can use it for a comparison if (input.size() == completedEdges) { line[completedEdges].setVisible(false); line[completedEdges].invalidate(); } //solution failed (too short) solutionFailed = true; touchgfx::Application::getInstance()->registerTimerWidget(this); showPatternTooSmallBanner(); return; } else { processAnswer(); if (!success) { //CANCEL CURRENT LINE IF NOT CONNECTED - completed edges is off by one, so we can use it for a comparison if (input.size() == completedEdges) { line[completedEdges].setVisible(false); } solutionFailed = true; failedAttempts++; //Show failure banner and begin fail timer showSolutionFailureBanner(); touchgfx::Application::getInstance()->registerTimerWidget(this); return; } } } } else if (evt.getType() == touchgfx::ClickEvent::PRESSED && (!solutionFailed && !success && !tracing)/* || misclick*/) { //Begin tracking for (int i = 0; i < NR_OF_MARKERS; i++) { if (hitBoxes[i].getRect().intersect(evt.getX(), evt.getY()) && !input.contains(i)) //we havent' already been there: we never will have, since we either failed (clear) or continued (change screen) { //begin first line line[0].updateStart((hitBoxes[i].getX() + hitBoxes[i].getWidth() / 2), (hitBoxes[i].getY() + hitBoxes[i].getHeight() / 2)); line[0].updateEnd((hitBoxes[i].getX() + hitBoxes[i].getWidth() / 2), (hitBoxes[i].getY() + hitBoxes[i].getHeight() / 2)); line[0].setVisible(true); //activate activateNode(i); patternStarted = true; } } } } void LoginWidget::reset() { for (int i = 0; i < NR_OF_MARKERS; i++) { hitBoxes[i].setColor(touchgfx::Color::getColorFrom24BitRGB(255, 0, 0)); //clear lines line[i].setVisible(false); line[i].setAlpha(255); //reset animations images[i].stopAnimation(); images[i].setAlpha(255); } myColorPainter.setColor(touchgfx::Color::getColorFrom24BitRGB(51, 189, 253)); bannerTxt.setColor(Color::getColorFrom24BitRGB(255, 0, 0)); bannerTxt.setVisible(false); bannerTxt.invalidate(); //reset stuff input.clear(); completedEdges = 0; patternStarted = false; solutionFailed = false; success = false; tracing = false; invalidate(); } void LoginWidget::activateNode(uint8_t id, bool completeNext) //should be able to start a new line { //Only process solution if completeNext == false. if (!input.contains(id)) { hitBoxes[id].setColor(touchgfx::Color::getColorFrom24BitRGB(0, 255, 0)); //todo: invis, so color is unused hitBoxes[id].invalidate(); images[id].startAnimation(false, true, false); images[id].invalidate(); if (tracing) { images[id].setAlpha(175); } //Fixate line - Must be gray when starting the next line myColorPainter.setColor(touchgfx::Color::getColorFrom24BitRGB(51, 189, 253)); line[completedEdges].updateEnd((hitBoxes[id].getX() + hitBoxes[id].getWidth() / 2), (hitBoxes[id].getY() + hitBoxes[id].getHeight() / 2)); line[completedEdges].invalidate(); input.add(id); //Inspect if solution correct only if we're not filling out missing dots. if (!completeNext && !tracing) { processAnswer(); if (success) { return; } } //begin next line (last possible activation will never be a skip) if (completedEdges < NR_OF_MARKERS - 1) { completedEdges++; //Fix start of next line to this myColorPainter.setColor(touchgfx::Color::getColorFrom24BitRGB(51, 189, 253)); line[completedEdges].updateStart((hitBoxes[id].getX() + hitBoxes[id].getWidth() / 2), (hitBoxes[id].getY() + hitBoxes[id].getHeight() / 2)); if (completeNext) /*complete missing dot instantly*/ { //If filling in missingdots, also fill in the missing line starting from end of previous line[completedEdges].updateEnd(hitBoxes[input[input.size() - 1]].getX(), hitBoxes[input[input.size() - 1]].getY()); //? this should give wrong result visually line[completedEdges].setVisible(true); } } else { //No edges left to complete, force a release? or move the code from release so that we can call it manually. patternStarted = false; } } } void LoginWidget::handleTickEvent() { if (!tracing && (solutionFailed)) { tickCounter++; if (tickCounter % BANNER_DISPLAY_TIME == 0) { //reset banner if we want to have another go (success = end of the road) //If we want a delay before sending a message to user (view), send callback from here. Make this configurable. //callback win. Move this to handleTicke if we need to wait a while if (failureCallback && failureCallback->isValid()) { failureCallback->execute(); } // if (!success) // { // reset(); //prolly don't need to reset if we're not staying on screen? // } resetTimer(); } } else if (tracing) { tickCounter++; if (tickCounter % TRACE_DISPLAY_TIME == 0) { reset(); resetTimer(); } } } void LoginWidget::setSolution(touchgfx::Vector<uint8_t, 9> solution_) { for (int i = 0; i < solution_.size(); i++) { //add method to identify uniqueness uint8_t temp = solution_[i]; for (int j = i + 1; j < solution_.size(); j++) { if (temp == solution_[j]) { assert(false && "Solution must be unique"); } } } //Set solution and update length. solution = solution_; solutionMinLength = solution.size(); } void LoginWidget::showSolutionFailureBanner() { updateBannerText(T_LOGIN_SOLUTION_INCORRECT); } void LoginWidget::showPatternTooSmallBanner() { updateBannerText(T_LOGIN_PATTERN_TOO_SHORT); } void LoginWidget::showHintBanner() { updateBannerText(T_LOGIN_HINT); } void LoginWidget::showSolutionSuccessBanner() { bannerTxt.setColor(Color::getColorFrom24BitRGB(51, 189, 253)); updateBannerText(T_LOGIN_SOLUTION_CORRECT); } void LoginWidget::setBitmapsAndHitBoxes(BitmapId begin, BitmapId end, uint16_t hitboxWidth, uint16_t hitboxHeight) { uint8_t index = 0; for (int i = 0; i < NR_OF_MARKERS / 3; i++) { for (int j = 0; j < NR_OF_MARKERS / 3; j++) { hitBoxes[index].setPosition(CANVAS_X_BEGIN + j * DISTANCE_BETWEEN_MARKERS, CANVAS_Y_BEGIN + i * DISTANCE_BETWEEN_MARKERS, hitboxWidth, hitboxHeight); add(hitBoxes[index]); hitBoxes[index].setVisible(false); index++; } } //Hitbox setup. The pos for these should be based on the position of the images. And if the hit boxes are larger then the images... index = 0; for (int i = 0; i < NR_OF_MARKERS / 3; i++) { for (int j = 0; j < NR_OF_MARKERS / 3; j++) { images[index].setBitmaps(begin, end); images[index].setUpdateTicksInterval(1); images[index].setDoneAction(animationEndedCallback); images[index].setXY(CANVAS_X_BEGIN + j * DISTANCE_BETWEEN_MARKERS, CANVAS_Y_BEGIN + i * DISTANCE_BETWEEN_MARKERS); add(images[index]); index++; } } //add lines on top for (int i = 0; i < NR_OF_MARKERS; i++) { line[i].setPosition(0, 0, 2 * DISTANCE_BETWEEN_MARKERS + HITBOX_SIZE + CANVAS_X_BEGIN + 50, 2 * DISTANCE_BETWEEN_MARKERS + HITBOX_SIZE + CANVAS_Y_BEGIN + 50); line[i].setLineWidth(TRACE_LINE_THICKNESS); line[i].setPainter(myColorPainter); line[i].setLineEndingStyle(touchgfx::Line::BUTT_CAP_ENDING); line[i].setVisible(false); add(line[i]); } } void LoginWidget::showTrace(touchgfx::Vector<uint8_t, 9> solution_) { reset(); tracing = true; failedAttempts = 0; for (int i = 0; i < solution_.size(); i++) { //activate nodes activateNode(solution_[i]); //only draw lines when necessary. if (solution_.size() > 1 && i < solution_.size() - 1) { line[i].updateStart((hitBoxes[solution_[i]].getX() + hitBoxes[solution_[i]].getWidth() / 2), (hitBoxes[solution_[i]].getY() + hitBoxes[solution_[i]].getHeight() / 2)); line[i].updateEnd((hitBoxes[solution_[i + 1]].getX() + hitBoxes[solution_[i + 1]].getWidth() / 2), (hitBoxes[solution_[i + 1]].getY() + hitBoxes[solution_[i + 1]].getHeight() / 2)); line[i].setVisible(true); line[i].setAlpha(50); } } showHintBanner(); //begin timer touchgfx::Application::getInstance()->registerTimerWidget(this); } void LoginWidget::setMaxAllowedAttempts(uint8_t attempts) { maxAllowedAttempts = attempts; } void LoginWidget::showBannerContent(const char *text, uint8_t ms) { //This method copies incoming string to buffer for x ms. } void LoginWidget::animationEnded(const AnimatedImage &source) { //This method is called when markers are done animating. //No implementation } void LoginWidget::updateBannerText(TypedTextId textId) { bannerTxt.setTypedText(TypedText(textId)); bannerTxt.moveTo(getTextCenterXCoord(bannerTxt), bannerTxt.getY()); bannerTxt.setVisible(true); bannerTxt.invalidate(); } uint16_t LoginWidget::getTextCenterXCoord(TextArea &ta) { return ((getWidth() / 2) - (ta.getWidth() / 2)); } void LoginWidget::processAnswer() { ///////////////////////////////////////////////////// // PROCESS SOLUTION for correct answer // success = true; if (input.size() != solution.size()) { success = false; } else if (input.size() == solution.size()) { for (int i = 0; i < input.size(); i++) { if (input[i] != solution[i]) { success = false; break; } } } //If pattern approved, display static banner if (success) { failedAttempts = 0; showSolutionSuccessBanner(); if (successCallback && successCallback->isValid()) { successCallback->execute(); } } } void LoginWidget::resetTimer() { tickCounter = 0; touchgfx::Application::getInstance()->unregisterTimerWidget(this); } void LoginWidget::setBannerPosition(uint16_t x, uint16_t y) { //This method sets the position of the banner //No implementation }
31.560636
207
0.553701
ramkumarkoppu
3b5ebd385bb7b7e6513b1cd178a958ebeb5eda6c
7,169
cpp
C++
REDSI_1160929_1161573/boost_1_67_0/libs/geometry/test/formulas/intersection.cpp
Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo
eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8
[ "MIT" ]
null
null
null
REDSI_1160929_1161573/boost_1_67_0/libs/geometry/test/formulas/intersection.cpp
Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo
eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8
[ "MIT" ]
null
null
null
REDSI_1160929_1161573/boost_1_67_0/libs/geometry/test/formulas/intersection.cpp
Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo
eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8
[ "MIT" ]
null
null
null
// Boost.Geometry // Unit Test // Copyright (c) 2016-2017 Oracle and/or its affiliates. // Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle // Use, modification and distribution is subject to the Boost Software License, // Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include "test_formula.hpp" #include "intersection_cases.hpp" #include <boost/geometry/formulas/andoyer_inverse.hpp> #include <boost/geometry/formulas/geographic.hpp> #include <boost/geometry/formulas/gnomonic_intersection.hpp> #include <boost/geometry/formulas/sjoberg_intersection.hpp> #include <boost/geometry/formulas/thomas_direct.hpp> #include <boost/geometry/formulas/thomas_inverse.hpp> #include <boost/geometry/formulas/vincenty_direct.hpp> #include <boost/geometry/formulas/vincenty_inverse.hpp> #include <boost/geometry/srs/spheroid.hpp> void check_result(expected_result const& result, expected_result const& expected, expected_result const& reference, double reference_error, bool check_reference_only) { //BOOST_CHECK_MESSAGE((false), "(" << result.lon << " " << result.lat << ") vs (" << expected.lon << " " << expected.lat << ")"); check_one(result.lon, expected.lon, reference.lon, reference_error, false, check_reference_only); check_one(result.lat, expected.lat, reference.lat, reference_error, false, check_reference_only); } void test_formulas(expected_results const& results, bool check_reference_only) { // reference result if (results.sjoberg_vincenty.lon == ND) { return; } double const d2r = bg::math::d2r<double>(); double const r2d = bg::math::r2d<double>(); double lona1r = results.p1.lon * d2r; double lata1r = results.p1.lat * d2r; double lona2r = results.p2.lon * d2r; double lata2r = results.p2.lat * d2r; double lonb1r = results.q1.lon * d2r; double latb1r = results.q1.lat * d2r; double lonb2r = results.q2.lon * d2r; double latb2r = results.q2.lat * d2r; expected_result result; // WGS84 bg::srs::spheroid<double> spheroid(6378137.0, 6356752.3142451793); if (results.gnomonic_vincenty.lon != ND) { bg::formula::gnomonic_intersection<double, bg::formula::vincenty_inverse, bg::formula::vincenty_direct> ::apply(lona1r, lata1r, lona2r, lata2r, lonb1r, latb1r, lonb2r, latb2r, result.lon, result.lat, spheroid); result.lon *= r2d; result.lat *= r2d; check_result(result, results.gnomonic_vincenty, results.sjoberg_vincenty, 0.00000001, check_reference_only); } if (results.gnomonic_thomas.lon != ND) { bg::formula::gnomonic_intersection<double, bg::formula::thomas_inverse, bg::formula::thomas_direct> ::apply(lona1r, lata1r, lona2r, lata2r, lonb1r, latb1r, lonb2r, latb2r, result.lon, result.lat, spheroid); result.lon *= r2d; result.lat *= r2d; check_result(result, results.gnomonic_thomas, results.sjoberg_vincenty, 0.0000001, check_reference_only); } if (results.sjoberg_vincenty.lon != ND) { bg::formula::sjoberg_intersection<double, bg::formula::vincenty_inverse, 4> ::apply(lona1r, lata1r, lona2r, lata2r, lonb1r, latb1r, lonb2r, latb2r, result.lon, result.lat, spheroid); result.lon *= r2d; result.lat *= r2d; check_result(result, results.sjoberg_vincenty, results.sjoberg_vincenty, 0.00000001, check_reference_only); } if (results.sjoberg_thomas.lon != ND) { bg::formula::sjoberg_intersection<double, bg::formula::thomas_inverse, 2> ::apply(lona1r, lata1r, lona2r, lata2r, lonb1r, latb1r, lonb2r, latb2r, result.lon, result.lat, spheroid); result.lon *= r2d; result.lat *= r2d; check_result(result, results.sjoberg_thomas, results.sjoberg_vincenty, 0.0000001, check_reference_only); } if (results.sjoberg_andoyer.lon != ND) { bg::formula::sjoberg_intersection<double, bg::formula::andoyer_inverse, 1> ::apply(lona1r, lata1r, lona2r, lata2r, lonb1r, latb1r, lonb2r, latb2r, result.lon, result.lat, spheroid); result.lon *= r2d; result.lat *= r2d; check_result(result, results.sjoberg_andoyer, results.sjoberg_vincenty, 0.0001, check_reference_only); } if (results.great_elliptic.lon != ND) { typedef bg::model::point<double, 2, bg::cs::geographic<bg::degree> > point_geo; typedef bg::model::point<double, 3, bg::cs::cartesian> point_3d; point_geo a1(results.p1.lon, results.p1.lat); point_geo a2(results.p2.lon, results.p2.lat); point_geo b1(results.q1.lon, results.q1.lat); point_geo b2(results.q2.lon, results.q2.lat); point_3d a1v = bg::formula::geo_to_cart3d<point_3d>(a1, spheroid); point_3d a2v = bg::formula::geo_to_cart3d<point_3d>(a2, spheroid); point_3d b1v = bg::formula::geo_to_cart3d<point_3d>(b1, spheroid); point_3d b2v = bg::formula::geo_to_cart3d<point_3d>(b2, spheroid); point_3d resv(0, 0, 0); point_geo res(0, 0); bg::formula::great_elliptic_intersection(a1v, a2v, b1v, b2v, resv, spheroid); res = bg::formula::cart3d_to_geo<point_geo>(resv, spheroid); result.lon = bg::get<0>(res); result.lat = bg::get<1>(res); check_result(result, results.great_elliptic, results.sjoberg_vincenty, 0.01, check_reference_only); } } void test_4_input_combinations(expected_results const& results, bool check_reference_only) { test_formulas(results, check_reference_only); #ifdef BOOST_GEOMETRY_TEST_GEO_INTERSECTION_TEST_SIMILAR { expected_results results_alt = results; std::swap(results_alt.p1, results_alt.p2); test_formulas(results_alt, true); } { expected_results results_alt = results; std::swap(results_alt.q1, results_alt.q2); test_formulas(results_alt, true); } { expected_results results_alt = results; std::swap(results_alt.p1, results_alt.p2); std::swap(results_alt.q1, results_alt.q2); test_formulas(results_alt, true); } #endif } void test_all(expected_results const& results) { test_4_input_combinations(results, false); #ifdef BOOST_GEOMETRY_TEST_GEO_INTERSECTION_TEST_SIMILAR expected_results results_alt = results; results_alt.p1.lat *= -1; results_alt.p2.lat *= -1; results_alt.q1.lat *= -1; results_alt.q2.lat *= -1; results_alt.gnomonic_vincenty.lat *= -1; results_alt.gnomonic_thomas.lat *= -1; results_alt.sjoberg_vincenty.lat *= -1; results_alt.sjoberg_thomas.lat *= -1; results_alt.sjoberg_andoyer.lat *= -1; results_alt.great_elliptic.lat *= -1; test_4_input_combinations(results_alt, true); #endif } int test_main(int, char*[]) { for (size_t i = 0; i < expected_size; ++i) { test_all(expected[i]); } return 0; }
39.827778
134
0.667318
Wultyc
3b605aebaac58b71a48e68f078aed36a94602d4a
8,211
cpp
C++
src/VAC/IO/XmlStreamConverters/XmlStreamConverter_1_0_to_1_6.cpp
Qt-Widgets/vpaint
6b1bf57e3c239194443f7284adfd5c5326cd1bf2
[ "ECL-2.0", "Apache-2.0" ]
697
2015-08-08T09:27:02.000Z
2022-03-25T04:38:29.000Z
src/VAC/IO/XmlStreamConverters/XmlStreamConverter_1_0_to_1_6.cpp
Qt-Widgets/vpaint
6b1bf57e3c239194443f7284adfd5c5326cd1bf2
[ "ECL-2.0", "Apache-2.0" ]
125
2015-08-09T08:45:42.000Z
2022-03-31T11:26:16.000Z
src/VAC/IO/XmlStreamConverters/XmlStreamConverter_1_0_to_1_6.cpp
Qt-Widgets/vpaint
6b1bf57e3c239194443f7284adfd5c5326cd1bf2
[ "ECL-2.0", "Apache-2.0" ]
64
2015-08-09T10:34:34.000Z
2022-01-03T18:01:57.000Z
// Copyright (C) 2012-2019 The VPaint Developers. // See the COPYRIGHT file at the top-level directory of this distribution // and at https://github.com/dalboris/vpaint/blob/master/COPYRIGHT // // 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 "XmlStreamConverter_1_0_to_1_6.h" #include "../../XmlStreamReader.h" #include "../../XmlStreamWriter.h" #include <QString> #include <QRegularExpression> namespace { void changeAttributeValue(QXmlStreamAttributes & attributes, const QString & qualifiedName, const QString & newValue) { for (int i=0; i<attributes.size(); ++i) { if (attributes[i].qualifiedName() == qualifiedName) { attributes[i] = QXmlStreamAttribute(qualifiedName, newValue); } } } void removeAttribute(QXmlStreamAttributes & attributes, const QString & qualifiedName) { QXmlStreamAttributes newAttributes; for (int i=0; i<attributes.size(); ++i) { if (attributes[i].qualifiedName() != qualifiedName) { newAttributes << attributes[i]; } } attributes = newAttributes; } void insertAttribute(QXmlStreamAttributes & attributes, int i, const QString & qualifiedName, const QString & value) { attributes.insert(i, QXmlStreamAttribute(qualifiedName, value)); } void prependAttribute(QXmlStreamAttributes & attributes, const QString & qualifiedName, const QString & value) { attributes.prepend(QXmlStreamAttribute(qualifiedName, value)); } void appendAttribute(QXmlStreamAttributes & attributes, const QString & qualifiedName, const QString & value) { attributes.append(QXmlStreamAttribute(qualifiedName, value)); } void convertColorStyleToAttribute(QXmlStreamAttributes & attributes) { for (int i=0; i<attributes.size(); ++i) { if (attributes[i].qualifiedName() == "style") { QString colorValue; // Extract color QString styleValue = attributes[i].value().toString(); QRegularExpression re("(;|^)color:([^;]*)(;|$)"); QRegularExpressionMatch match = re.match(styleValue); if (match.hasMatch()) { colorValue = match.captured(2); } attributes[i] = QXmlStreamAttribute("color", colorValue); } } } } XmlStreamConverter_1_0_to_1_6::XmlStreamConverter_1_0_to_1_6(XmlStreamReader & in, XmlStreamWriter & out) : XmlStreamConverter(in, out) { } void XmlStreamConverter_1_0_to_1_6::begin() { // Start XML Document out().writeStartDocument(); // Header out().writeComment(" Created with VPaint (http://www.vpaint.org) "); out().writeCharacters("\n\n"); } void XmlStreamConverter_1_0_to_1_6::end() { // End XML Document out().writeEndDocument(); } void XmlStreamConverter_1_0_to_1_6::pre() { QString name = in().name().toString(); QXmlStreamAttributes attrs = in().attributes(); if (name == "vec") { QXmlStreamAttributes attrs = in().attributes(); changeAttributeValue(attrs, "version", "1.6"); out().writeStartElement(name); out().writeAttributes(attrs); } else if (name == "playback") { QString framerangeValue; if (attrs.hasAttribute("firstframe")) framerangeValue += attrs.value("firstframe").toString(); else framerangeValue += "0"; framerangeValue += " "; if (attrs.hasAttribute("lastframe")) framerangeValue += attrs.value("lastframe").toString(); else framerangeValue += "0"; removeAttribute(attrs, "firstframe"); removeAttribute(attrs, "lastframe"); prependAttribute(attrs, "framerange", framerangeValue); out().writeStartElement(name); out().writeAttributes(attrs); } else if (name == "canvas") { QString positionValue; if (attrs.hasAttribute("left")) positionValue += attrs.value("left").toString(); else positionValue += "0"; positionValue += " "; if (attrs.hasAttribute("top")) positionValue += attrs.value("top").toString(); else positionValue += "0"; QString sizeValue; if (attrs.hasAttribute("width")) sizeValue += attrs.value("width").toString(); else sizeValue += "0"; sizeValue += " "; if (attrs.hasAttribute("height")) sizeValue += attrs.value("height").toString(); else sizeValue += "0"; removeAttribute(attrs, "left"); removeAttribute(attrs, "top"); removeAttribute(attrs, "width"); removeAttribute(attrs, "height"); appendAttribute(attrs, "position", positionValue); appendAttribute(attrs, "size", sizeValue); out().writeStartElement(name); out().writeAttributes(attrs); } else if (name == "layer") { QString backgroundColorValue; if (attrs.hasAttribute("style")) { // Extract background color QString styleValue = attrs.value("style").toString(); QRegularExpression re("(;|^)background-color:([^;]*)(;|$)"); QRegularExpressionMatch match = re.match(styleValue); if (match.hasMatch()) { backgroundColorValue = match.captured(2); } // Remove style attribute removeAttribute(attrs, "style"); } out().writeStartElement(name); out().writeAttributes(attrs); // Add background as child element if (backgroundColorValue.length() > 0) { out().writeStartElement("background"); out().writeAttribute("color", backgroundColorValue); out().writeEndElement(); } out().writeStartElement("objects"); } else if (name == "vertex") { QString oldPositionValue = attrs.value("position").toString(); QStringList list = oldPositionValue.split(","); QString newPositionValue = list[0] + " " + list[1]; changeAttributeValue(attrs, "position", newPositionValue); convertColorStyleToAttribute(attrs); out().writeStartElement(name); out().writeAttributes(attrs); } else if (name == "edge") { QString newCurveValue; QString oldCurveValue = attrs.value("curve").toString(); QRegularExpression re("xyw-dense: (.*)"); QRegularExpressionMatch match = re.match(oldCurveValue); if (match.hasMatch()) { newCurveValue = "xywdense(" + match.captured(1) + ")"; } changeAttributeValue(attrs, "curve", newCurveValue); convertColorStyleToAttribute(attrs); out().writeStartElement(name); out().writeAttributes(attrs); } else if (name == "face" || name == "inbetweenvertex" || name == "inbetweenedge" || name == "inbetweenface") { convertColorStyleToAttribute(attrs); out().writeStartElement(name); out().writeAttributes(attrs); } else { out().writeStartElement(name); out().writeAttributes(attrs); } } void XmlStreamConverter_1_0_to_1_6::post() { QString name = in().name().toString(); if (name == "layer") { out().writeEndElement(); // end objects out().writeEndElement(); // end layer } else { out().writeEndElement(); } }
29.325
107
0.596273
Qt-Widgets
3b61ee22750667eb92981b7e8e0a85b42ad9f45d
6,668
cpp
C++
lab8/src/2/src/kernel/memory.cpp
YatSenOS/YatSenOS-Tutorial-Volume-1
dc69d576b2cdcece58744eeab4798bd6f1260bb5
[ "MulanPSL-1.0" ]
400
2021-05-30T04:07:44.000Z
2022-03-16T04:47:52.000Z
lab8/src/2/src/kernel/memory.cpp
YatSenOS/YatSenOS-Tutorial-Volume-1
dc69d576b2cdcece58744eeab4798bd6f1260bb5
[ "MulanPSL-1.0" ]
2
2021-10-10T23:55:02.000Z
2021-10-11T06:09:36.000Z
lab8/src/2/src/kernel/memory.cpp
YatSenOS/YatSenOS-Tutorial-Volume-1
dc69d576b2cdcece58744eeab4798bd6f1260bb5
[ "MulanPSL-1.0" ]
38
2021-05-30T04:22:44.000Z
2022-03-14T04:41:52.000Z
#include "memory.h" #include "os_constant.h" #include "stdlib.h" #include "asm_utils.h" #include "stdio.h" #include "program.h" #include "os_modules.h" MemoryManager::MemoryManager() { initialize(); } void MemoryManager::initialize() { this->totalMemory = 0; this->totalMemory = getTotalMemory(); // 预留的内存 int usedMemory = 256 * PAGE_SIZE + 0x100000; if (this->totalMemory < usedMemory) { printf("memory is too small, halt.\n"); asm_halt(); } // 剩余的空闲的内存 int freeMemory = this->totalMemory - usedMemory; int freePages = freeMemory / PAGE_SIZE; int kernelPages = freePages / 2; int userPages = freePages - kernelPages; int kernelPhysicalStartAddress = usedMemory; int userPhysicalStartAddress = usedMemory + kernelPages * PAGE_SIZE; int kernelPhysicalBitMapStart = BITMAP_START_ADDRESS; int userPhysicalBitMapStart = kernelPhysicalBitMapStart + ceil(kernelPages, 8); int kernelVirtualBitMapStart = userPhysicalBitMapStart + ceil(userPages, 8); kernelPhysical.initialize( (char *)kernelPhysicalBitMapStart, kernelPages, kernelPhysicalStartAddress); userPhysical.initialize( (char *)userPhysicalBitMapStart, userPages, userPhysicalStartAddress); kernelVirtual.initialize( (char *)kernelVirtualBitMapStart, kernelPages, KERNEL_VIRTUAL_START); printf("total memory: %d bytes ( %d MB )\n", this->totalMemory, this->totalMemory / 1024 / 1024); printf("kernel pool\n" " start address: 0x%x\n" " total pages: %d ( %d MB )\n" " bitmap start address: 0x%x\n", kernelPhysicalStartAddress, kernelPages, kernelPages * PAGE_SIZE / 1024 / 1024, kernelPhysicalBitMapStart); printf("user pool\n" " start address: 0x%x\n" " total pages: %d ( %d MB )\n" " bit map start address: 0x%x\n", userPhysicalStartAddress, userPages, userPages * PAGE_SIZE / 1024 / 1024, userPhysicalBitMapStart); printf("kernel virtual pool\n" " start address: 0x%x\n" " total pages: %d ( %d MB ) \n" " bit map start address: 0x%x\n", KERNEL_VIRTUAL_START, userPages, kernelPages * PAGE_SIZE / 1024 / 1024, kernelVirtualBitMapStart); } int MemoryManager::allocatePhysicalPages(enum AddressPoolType type, const int count) { int start = -1; if (type == AddressPoolType::KERNEL) { start = kernelPhysical.allocate(count); } else if (type == AddressPoolType::USER) { start = userPhysical.allocate(count); } return (start == -1) ? 0 : start; } void MemoryManager::releasePhysicalPages(enum AddressPoolType type, const int paddr, const int count) { if (type == AddressPoolType::KERNEL) { kernelPhysical.release(paddr, count); } else if (type == AddressPoolType::USER) { userPhysical.release(paddr, count); } } int MemoryManager::getTotalMemory() { if (!this->totalMemory) { int memory = *((int *)MEMORY_SIZE_ADDRESS); // ax寄存器保存的内容 int low = memory & 0xffff; // bx寄存器保存的内容 int high = (memory >> 16) & 0xffff; this->totalMemory = low * 1024 + high * 64 * 1024; } return this->totalMemory; } int MemoryManager::allocatePages(enum AddressPoolType type, const int count) { // 第一步:从虚拟地址池中分配若干虚拟页 int virtualAddress = allocateVirtualPages(type, count); if (!virtualAddress) { return 0; } bool flag; int physicalPageAddress; int vaddress = virtualAddress; // 依次为每一个虚拟页指定物理页 for (int i = 0; i < count; ++i, vaddress += PAGE_SIZE) { flag = false; // 第二步:从物理地址池中分配一个物理页 physicalPageAddress = allocatePhysicalPages(type, 1); if (physicalPageAddress) { //printf("allocate physical page 0x%x\n", physicalPageAddress); // 第三步:为虚拟页建立页目录项和页表项,使虚拟页内的地址经过分页机制变换到物理页内。 flag = connectPhysicalVirtualPage(vaddress, physicalPageAddress); } else { flag = false; } // 分配失败,释放前面已经分配的虚拟页和物理页表 if (!flag) { // 前i个页表已经指定了物理页 releasePages(type, virtualAddress, i); // 剩余的页表未指定物理页 releaseVirtualPages(type, virtualAddress + i * PAGE_SIZE, count - i); return 0; } } return virtualAddress; } int MemoryManager::allocateVirtualPages(enum AddressPoolType type, const int count) { int start = -1; if (type == AddressPoolType::KERNEL) { start = kernelVirtual.allocate(count); } return (start == -1) ? 0 : start; } bool MemoryManager::connectPhysicalVirtualPage(const int virtualAddress, const int physicalPageAddress) { // 计算虚拟地址对应的页目录项和页表项 int *pde = (int *)toPDE(virtualAddress); int *pte = (int *)toPTE(virtualAddress); // 页目录项无对应的页表,先分配一个页表 if(!(*pde & 0x00000001)) { // 从内核物理地址空间中分配一个页表 int page = allocatePhysicalPages(AddressPoolType::KERNEL, 1); if (!page) return false; // 使页目录项指向页表 *pde = page | 0x7; // 初始化页表 char *pagePtr = (char *)(((int)pte) & 0xfffff000); memset(pagePtr, 0, PAGE_SIZE); } // 使页表项指向物理页 *pte = physicalPageAddress | 0x7; return true; } int MemoryManager::toPDE(const int virtualAddress) { return (0xfffff000 + (((virtualAddress & 0xffc00000) >> 22) * 4)); } int MemoryManager::toPTE(const int virtualAddress) { return (0xffc00000 + ((virtualAddress & 0xffc00000) >> 10) + (((virtualAddress & 0x003ff000) >> 12) * 4)); } void MemoryManager::releasePages(enum AddressPoolType type, const int virtualAddress, const int count) { int vaddr = virtualAddress; int *pte; for (int i = 0; i < count; ++i, vaddr += PAGE_SIZE) { // 第一步,对每一个虚拟页,释放为其分配的物理页 releasePhysicalPages(type, vaddr2paddr(vaddr), 1); // 设置页表项为不存在,防止释放后被再次使用 pte = (int *)toPTE(vaddr); *pte = 0; } // 第二步,释放虚拟页 releaseVirtualPages(type, virtualAddress, count); } int MemoryManager::vaddr2paddr(int vaddr) { int *pte = (int *)toPTE(vaddr); int page = (*pte) & 0xfffff000; int offset = vaddr & 0xfff; return (page + offset); } void MemoryManager::releaseVirtualPages(enum AddressPoolType type, const int vaddr, const int count) { if (type == AddressPoolType::KERNEL) { kernelVirtual.release(vaddr, count); } }
26.046875
110
0.613077
YatSenOS
3b621e74b984a64b65282d7af484f2fef4badf25
13,031
cc
C++
file/s3_file.cc
dendisuhubdy/gaia
a988b7f08a4080a3209eba6cb378718486947a68
[ "BSD-2-Clause" ]
72
2019-01-25T09:03:41.000Z
2022-01-16T01:01:55.000Z
file/s3_file.cc
dendisuhubdy/gaia
a988b7f08a4080a3209eba6cb378718486947a68
[ "BSD-2-Clause" ]
35
2019-09-20T05:02:22.000Z
2022-02-14T17:28:58.000Z
file/s3_file.cc
dendisuhubdy/gaia
a988b7f08a4080a3209eba6cb378718486947a68
[ "BSD-2-Clause" ]
15
2018-08-12T13:43:31.000Z
2022-02-09T08:04:27.000Z
// Copyright 2013, Beeri 15. All rights reserved. // Author: Roman Gershman (romange@gmail.com) // #include <fnmatch.h> #include <libs3.h> #include <mutex> #include <unordered_map> #include "base/logging.h" #include "file/s3_file.h" #include "file/file.h" #include "file/file_util.h" #include "strings/strcat.h" namespace file { using base::Status; using base::StatusCode; using strings::Slice; using std::string; namespace { const char kS3NamespacePrefix[] = "s3://"; typedef std::unordered_map<string, S3BucketContext> BucketMap; struct S3GlobalData; std::once_flag s3data_once; S3GlobalData* global_data = nullptr; inline BucketMap& bucket_map() { static BucketMap internal_map; return internal_map; } inline string safe_cstr(const char* s) { return s ? s : ""; } struct CallbackData { volatile S3Status status = S3StatusOK; // Read. volatile size_t length = 0; char* dest_buf = nullptr; FILE *infile = nullptr; // For S3_list_bucket; const S3BucketContext* bcontext = nullptr; std::vector<StatShort>* file_arr = nullptr; bool is_truncated = false; string marker; }; class S3File : public ReadonlyFile { const S3BucketContext* context_ = nullptr; std::string key_; size_t file_size_ = 0; public: S3File(size_t file_size, StringPiece key, const S3BucketContext* context) : context_(context), key_(key.as_string()), file_size_(file_size) {} Status Close() override { return Status::OK;} // Reads data and returns it in OUTPUT. Set total count of bytes read into read_size. virtual Status Read(size_t offset, size_t length, Slice* result, uint8* buffer) override; size_t Size() const override { return file_size_; } static S3Status PropertiesCallback(const S3ResponseProperties* properties, void* callbackData) { VLOG(1) << "PropertiesCallback " << properties->contentType << " " << properties->contentLength << " " << properties->metaDataCount; CallbackData* data = reinterpret_cast<CallbackData*>(callbackData); data->length = properties->contentLength; return S3StatusOK; } static void CompleteCallback(S3Status status, const S3ErrorDetails* errorDetails, void* callbackData) { CallbackData* data = reinterpret_cast<CallbackData*>(callbackData); CHECK_NOTNULL(data); if (status != S3StatusOK) { /*string msg; if (errorDetails) { msg = safe_cstr(errorDetails->message) + ", more: " + safe_cstr(errorDetails->furtherDetails); }*/ LOG(WARNING) << "Status : " << S3_get_status_name(status); } data->status = status; } static S3Status DataCallback(int bufferSize, const char *buffer, void* callbackData); protected: ~S3File() {} }; struct S3GlobalData { string access_key; string secret_key; }; void InitS3Data() { CHECK(global_data == nullptr); CHECK_EQ(S3StatusOK, S3_initialize(NULL, S3_INIT_ALL, NULL)); const char* sk = getenv("AWS_SECRET_KEY"); if (sk) { global_data = new S3GlobalData(); const char* ak = CHECK_NOTNULL(getenv("AWS_ACCESS_KEY")); global_data->access_key.assign(ak); global_data->secret_key.assign(sk); } else { // Initialize from IAM tokens of the server. CHECK_EQ(S3StatusOK, S3_init_iam_role()); LOG(INFO) << "Initializing iam tokens"; } } inline S3BucketContext NewBucket() { const char* a = global_data ? global_data->access_key.c_str() : nullptr; const char* s = global_data ? global_data->secret_key.c_str() : nullptr; return S3BucketContext{nullptr, nullptr, S3ProtocolHTTP, S3UriStylePath, a, s}; } // Returns suffix after the bucket name and S3BucketContext. std::pair<StringPiece, const S3BucketContext*> GetKeyAndBucket(StringPiece name) { DCHECK(name.starts_with(kS3NamespacePrefix)) << name; std::call_once(s3data_once, InitS3Data); StringPiece tmp = name; tmp.remove_prefix(sizeof(kS3NamespacePrefix) - 1); size_t pos = tmp.find('/'); CHECK_NE(StringPiece::npos, pos) << "Invalid filename " << name; string bucket_str = tmp.substr(0, pos).as_string(); BucketMap& bmap = bucket_map(); auto res = bmap.emplace(bucket_str, NewBucket()); if (res.second) { res.first->second.bucketName = res.first->first.c_str(); } tmp.remove_prefix(pos + 1); return std::pair<StringPiece, const S3BucketContext*>(tmp, &res.first->second); } Status S3File::Read(size_t offset, size_t length, Slice* result, uint8* buffer) { if (offset > file_size_ || length == 0) { *result = Slice(); return Status(StatusCode::RUNTIME_ERROR, "Invalid read range"); } if (offset + length > file_size_) { length = file_size_ - offset; } VLOG(1) << "S3File::Read " << offset << " " << length; S3GetObjectHandler handler{{nullptr, S3File::CompleteCallback}, S3File::DataCallback}; CallbackData data; data.dest_buf = reinterpret_cast<char*>(buffer); size_t try_length = length; size_t read_length = 0; for (unsigned attempts = 0; attempts < 5; ++attempts) { data.status = S3StatusOK; data.length = 0; S3_get_object(context_, key_.c_str(), nullptr, offset, try_length, nullptr, &handler, &data); read_length += data.length; if (data.status == S3StatusOK) { result->set(reinterpret_cast<char*>(buffer), read_length); return Status::OK; } LOG(WARNING) << "Attempt " << attempts << " failed: " << data.status << ", " << data.length; if (data.length >= length) { return Status(StatusCode::INTERNAL_ERROR, "Data length is too large"); } offset += data.length; try_length -= data.length; LOG(WARNING) << "Attempt " << attempts << " failed"; } return Status(StatusCode::IO_ERROR, S3_get_status_name(data.status)); } S3Status S3File::DataCallback(int bufferSize, const char *buffer, void* callbackData) { VLOG(2) << "S3 Read " << bufferSize << " bytes"; CallbackData* data = reinterpret_cast<CallbackData*>(callbackData); memcpy(data->dest_buf, buffer, bufferSize); data->dest_buf += bufferSize; data->length += bufferSize; return S3StatusOK; } int PutObjectDataCallback(int buffer_size, char *buffer, void *callbackData) { CallbackData *data = static_cast<CallbackData*>(callbackData); int ret = 0; if (data->length) { int to_read = std::min<size_t>(size_t(data->length), buffer_size); ret = fread(buffer, 1, to_read, data->infile); } data->length -= ret; return ret; } } // namespace base::StatusObject<ReadonlyFile*> OpenS3File(StringPiece name) { auto res = GetKeyAndBucket(name); const S3BucketContext* context = res.second; CHECK(!res.first.empty()) << "Missing file name after the bucket"; StringPiece key = res.first; S3ResponseHandler handler{S3File::PropertiesCallback, S3File::CompleteCallback}; CallbackData data; for (unsigned attempts = 0; attempts < 5; ++attempts) { S3_head_object(context, key.data(), nullptr, &handler, &data); if (data.status == S3StatusOK) { return new S3File(data.length, key, context); } LOG(WARNING) << "Failed to open file from s3 " << name << ". Attempt " << attempts << " failed"; } return Status(StatusCode::IO_ERROR, S3_get_status_name(data.status)); } bool IsInS3Namespace(StringPiece name) { return name.starts_with(kS3NamespacePrefix); } bool ExistsS3File(StringPiece name) { S3ResponseHandler handler{nullptr, S3File::CompleteCallback}; CallbackData data; auto res = GetKeyAndBucket(name); for (unsigned attempts = 0; attempts < 5; ++attempts) { S3_head_object(res.second, res.first.data(), nullptr, &handler, &data); if (data.status == S3StatusOK) { return true; } else if (data.status == S3StatusHttpErrorNotFound) { return false; } LOG(WARNING) << "Failed to find if s3 file exists " << name << ". Attempt " << attempts << " failed"; } return (data.status == S3StatusOK); } Status CopyFileToS3(StringPiece file_path, StringPiece s3_dir) { StringPiece file_name = file_util::GetNameFromPath(file_path); if (file_name.empty()) { return Status(StrCat("Invalid path: ", file_path)); } string s3_path = file_util::JoinPath(s3_dir, file_name); auto res = GetKeyAndBucket(s3_path); int64_t file_length = file_util::LocalFileSize(file_path); if (file_length == -1) { return Status(StrCat("Failed to fetch file size: ", file_path)); } CallbackData data; data.length = file_length; if (!(data.infile = fopen(file_path.data(), "r"))) { return Status(StrCat("Failed to open source file: ", file_path)); } S3ResponseHandler response_handler{S3File::PropertiesCallback, S3File::CompleteCallback}; S3PutObjectHandler obj_handler = { response_handler, &PutObjectDataCallback }; for (unsigned attempts = 0; attempts < 5; ++attempts) { S3_put_object(res.second, res.first.data(), file_length, nullptr, nullptr, &obj_handler, &data); if (data.status == S3StatusOK) { break; } LOG(WARNING) << "Failed to put file to s3 " << file_name << ". Attempt " << attempts << " failed"; } CHECK(data.infile != 0); if (fclose(data.infile) != 0) { LOG(WARNING) << "Failed to close file: " << file_path; } if (data.status != S3StatusOK) { return Status(StatusCode::IO_ERROR, S3_get_status_name(data.status)); } return Status::OK; } static S3Status MyListFileCb(int isTruncated, const char *nextMarker, int contentsCount, const S3ListBucketContent *contents, int commonPrefixesCount, const char **commonPrefixes, void *callbackData) { VLOG(2) << "MyListFileCb: " << isTruncated << " " << contentsCount << " " << nextMarker << " " << commonPrefixesCount; CallbackData* data = static_cast<CallbackData*>(callbackData); data->is_truncated = isTruncated; if (isTruncated) { data->marker.assign(nextMarker); } for (int i = 0; i < contentsCount; ++i) { string tmp = StrCat(kS3NamespacePrefix, data->bcontext->bucketName, "/", contents[i].key); VLOG(2) << "Key: " << tmp << " " << contents[i].size; if (tmp.back() != '/') { data->file_arr->push_back( StatShort{std::move(tmp), contents[i].lastModified, off_t(contents[i].size) }); } } for (int i = 0; i < commonPrefixesCount; ++i) { VLOG(3) << "commonPrefixes: " << commonPrefixes[i]; } return S3StatusOK; } static Status ListFilesInternal(StringPiece path, unsigned max_items, std::vector<StatShort>* file_names) { if (!IsInS3Namespace(path)) { return Status("Non-S3 path"); } auto res = GetKeyAndBucket(path); const S3BucketContext* context = res.second; CallbackData callback_data; callback_data.file_arr = file_names; callback_data.bcontext = context; S3ResponseHandler response_handler{S3File::PropertiesCallback, S3File::CompleteCallback}; S3ListBucketHandler handler{response_handler, &MyListFileCb}; string prefix = res.first.as_string(); VLOG(1) << prefix << " " << max_items; const char* marker = nullptr; do { for (unsigned attempts = 0; attempts < 5; ++attempts) { S3_list_bucket(context, prefix.c_str(), marker, "/", max_items, (S3RequestContext*)nullptr, &handler, &callback_data); if (callback_data.status == S3StatusOK) { break; } LOG(WARNING) << "Failed to list s3 bucket " << prefix << ". Attempt " << attempts << " failed"; } if (callback_data.status != S3StatusOK) { return Status(StatusCode::IO_ERROR, S3_get_status_name(callback_data.status)); } marker = callback_data.marker.c_str(); } while (callback_data.is_truncated); return Status::OK; } Status ListFiles(StringPiece path, unsigned max_items, std::vector<StatShort>* file_names) { auto pos = path.find('*', 0); if (pos != std::string::npos) { // If path contains '*'. StringPiece pattern = StringPiece(path, pos, path.length()); StringPiece path_without_star = StringPiece(path, 0, pos); RETURN_IF_ERROR(ListFilesInternal(path_without_star, max_items, file_names)); // Remove files that do not match pattern. auto out_it = file_names->begin(); auto pattern_str = pattern.as_string().c_str(); for (auto inp_it = file_names->begin(); inp_it != file_names->end();) { if (0 != fnmatch(pattern_str, inp_it->name.c_str(), FNM_EXTMATCH)) { ++inp_it; } else { *out_it++ = *inp_it++; } } auto new_length = out_it - file_names->begin(); file_names->resize(new_length); } else { RETURN_IF_ERROR(ListFilesInternal(path, max_items, file_names)); } return Status::OK; } base::Status ListFiles(StringPiece path, unsigned max_items, std::vector<std::string>* file_names) { std::vector<StatShort> res; RETURN_IF_ERROR(ListFiles(path, max_items, &res)); for (auto& val : res) { file_names->push_back(std::move(val.name)); } return Status::OK; } } // namespace file
32.5775
107
0.670862
dendisuhubdy
3b6251aa2907606b779fd4115b9f2f0d38a22ac3
288
hpp
C++
pythran/pythonic/__builtin__/UserWarning.hpp
xmar/pythran
dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592
[ "BSD-3-Clause" ]
null
null
null
pythran/pythonic/__builtin__/UserWarning.hpp
xmar/pythran
dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592
[ "BSD-3-Clause" ]
null
null
null
pythran/pythonic/__builtin__/UserWarning.hpp
xmar/pythran
dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592
[ "BSD-3-Clause" ]
null
null
null
#ifndef PYTHONIC_BUILTIN_USERWARNING_HPP #define PYTHONIC_BUILTIN_USERWARNING_HPP #include "pythonic/include/__builtin__/UserWarning.hpp" #include "pythonic/types/exceptions.hpp" namespace pythonic { namespace __builtin__ { PYTHONIC_EXCEPTION_IMPL(UserWarning) } } #endif
15.157895
55
0.805556
xmar
3b643983e602fd8539a7b121c967ecf189789816
804
cc
C++
RAVL2/Image/Base/RealDVSYUVValue.cc
isuhao/ravl2
317e0ae1cb51e320b877c3bad6a362447b5e52ec
[ "BSD-Source-Code" ]
null
null
null
RAVL2/Image/Base/RealDVSYUVValue.cc
isuhao/ravl2
317e0ae1cb51e320b877c3bad6a362447b5e52ec
[ "BSD-Source-Code" ]
null
null
null
RAVL2/Image/Base/RealDVSYUVValue.cc
isuhao/ravl2
317e0ae1cb51e320b877c3bad6a362447b5e52ec
[ "BSD-Source-Code" ]
null
null
null
// This file is part of RAVL, Recognition And Vision Library // Copyright (C) 2001, University of Surrey // This code may be redistributed under the terms of the GNU Lesser // General Public License (LGPL). See the lgpl.licence file for details or // see http://www.gnu.org/copyleft/lesser.html // file-header-ends-here //! rcsid="$Id: RealYUVValue.cc 130 2001-05-24 22:50:53Z ees1se $" //! lib=RavlImage //! file="Ravl/Image/Base/RealDVSYUVValue.cc" #include "Ravl/BinStream.hh" #include "Ravl/Image/Image.hh" #include "Ravl/Image/RealYUVValue.hh" #include "Ravl/Image/RealDVSYUVValue.hh" #include "Ravl/TypeName.hh" namespace RavlImageN { static TypeNameC type2(typeid(RealDVSYUVValueC),"RealDVSYUVValueC"); static TypeNameC type3(typeid(ImageC<RealDVSYUVValueC>),"ImageC<RealDVSYUVValueC>"); }
38.285714
86
0.756219
isuhao
3b678a0addf2b3959f949dc84cf3f76fbea1ae2f
8,651
cpp
C++
YorozuyaGSLib/source/VoterDetail.cpp
lemkova/Yorozuya
f445d800078d9aba5de28f122cedfa03f26a38e4
[ "MIT" ]
29
2017-07-01T23:08:31.000Z
2022-02-19T10:22:45.000Z
YorozuyaGSLib/source/VoterDetail.cpp
kotopes/Yorozuya
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
[ "MIT" ]
90
2017-10-18T21:24:51.000Z
2019-06-06T02:30:33.000Z
YorozuyaGSLib/source/VoterDetail.cpp
kotopes/Yorozuya
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
[ "MIT" ]
44
2017-12-19T08:02:59.000Z
2022-02-24T23:15:01.000Z
#include <VoterDetail.hpp> #include <common/ATFCore.hpp> START_ATF_NAMESPACE namespace Detail { Info::VoterDoit2_ptr VoterDoit2_next(nullptr); Info::VoterDoit2_clbk VoterDoit2_user(nullptr); Info::VoterInitialize4_ptr VoterInitialize4_next(nullptr); Info::VoterInitialize4_clbk VoterInitialize4_user(nullptr); Info::VoterIsRegistedVotePaper6_ptr VoterIsRegistedVotePaper6_next(nullptr); Info::VoterIsRegistedVotePaper6_clbk VoterIsRegistedVotePaper6_user(nullptr); Info::Voterctor_Voter8_ptr Voterctor_Voter8_next(nullptr); Info::Voterctor_Voter8_clbk Voterctor_Voter8_user(nullptr); Info::Voter_MakeVotePaper10_ptr Voter_MakeVotePaper10_next(nullptr); Info::Voter_MakeVotePaper10_clbk Voter_MakeVotePaper10_user(nullptr); Info::Voter_SendVotePaper12_ptr Voter_SendVotePaper12_next(nullptr); Info::Voter_SendVotePaper12_clbk Voter_SendVotePaper12_user(nullptr); Info::Voter_SendVotePaperAll14_ptr Voter_SendVotePaperAll14_next(nullptr); Info::Voter_SendVotePaperAll14_clbk Voter_SendVotePaperAll14_user(nullptr); Info::Voter_SendVoteScore16_ptr Voter_SendVoteScore16_next(nullptr); Info::Voter_SendVoteScore16_clbk Voter_SendVoteScore16_user(nullptr); Info::Voter_SendVoteScoreAll18_ptr Voter_SendVoteScoreAll18_next(nullptr); Info::Voter_SendVoteScoreAll18_clbk Voter_SendVoteScoreAll18_user(nullptr); Info::Voter_SetVoteScoreInfo20_ptr Voter_SetVoteScoreInfo20_next(nullptr); Info::Voter_SetVoteScoreInfo20_clbk Voter_SetVoteScoreInfo20_user(nullptr); Info::Voter_Vote22_ptr Voter_Vote22_next(nullptr); Info::Voter_Vote22_clbk Voter_Vote22_user(nullptr); Info::Voterdtor_Voter27_ptr Voterdtor_Voter27_next(nullptr); Info::Voterdtor_Voter27_clbk Voterdtor_Voter27_user(nullptr); int VoterDoit2_wrapper(struct Voter* _this, Cmd eCmd, struct CPlayer* pOne, char* pdata) { return VoterDoit2_user(_this, eCmd, pOne, pdata, VoterDoit2_next); }; bool VoterInitialize4_wrapper(struct Voter* _this) { return VoterInitialize4_user(_this, VoterInitialize4_next); }; bool VoterIsRegistedVotePaper6_wrapper(struct Voter* _this, char byRace, char* pwszName) { return VoterIsRegistedVotePaper6_user(_this, byRace, pwszName, VoterIsRegistedVotePaper6_next); }; void Voterctor_Voter8_wrapper(struct Voter* _this) { Voterctor_Voter8_user(_this, Voterctor_Voter8_next); }; void Voter_MakeVotePaper10_wrapper(struct Voter* _this) { Voter_MakeVotePaper10_user(_this, Voter_MakeVotePaper10_next); }; int Voter_SendVotePaper12_wrapper(struct Voter* _this, struct CPlayer* pOne) { return Voter_SendVotePaper12_user(_this, pOne, Voter_SendVotePaper12_next); }; void Voter_SendVotePaperAll14_wrapper(struct Voter* _this) { Voter_SendVotePaperAll14_user(_this, Voter_SendVotePaperAll14_next); }; void Voter_SendVoteScore16_wrapper(struct Voter* _this, struct CPlayer* pOne) { Voter_SendVoteScore16_user(_this, pOne, Voter_SendVoteScore16_next); }; void Voter_SendVoteScoreAll18_wrapper(struct Voter* _this, char byRace) { Voter_SendVoteScoreAll18_user(_this, byRace, Voter_SendVoteScoreAll18_next); }; void Voter_SetVoteScoreInfo20_wrapper(struct Voter* _this, char byRace, char* wszName, bool bAbstention) { Voter_SetVoteScoreInfo20_user(_this, byRace, wszName, bAbstention, Voter_SetVoteScoreInfo20_next); }; int Voter_Vote22_wrapper(struct Voter* _this, struct CPlayer* pOne, char* pdata) { return Voter_Vote22_user(_this, pOne, pdata, Voter_Vote22_next); }; void Voterdtor_Voter27_wrapper(struct Voter* _this) { Voterdtor_Voter27_user(_this, Voterdtor_Voter27_next); }; ::std::array<hook_record, 12> Voter_functions = { _hook_record { (LPVOID)0x1402bea50L, (LPVOID *)&VoterDoit2_user, (LPVOID *)&VoterDoit2_next, (LPVOID)cast_pointer_function(VoterDoit2_wrapper), (LPVOID)cast_pointer_function((int(Voter::*)(Cmd, struct CPlayer*, char*))&Voter::Doit) }, _hook_record { (LPVOID)0x1402be940L, (LPVOID *)&VoterInitialize4_user, (LPVOID *)&VoterInitialize4_next, (LPVOID)cast_pointer_function(VoterInitialize4_wrapper), (LPVOID)cast_pointer_function((bool(Voter::*)())&Voter::Initialize) }, _hook_record { (LPVOID)0x1402bfa90L, (LPVOID *)&VoterIsRegistedVotePaper6_user, (LPVOID *)&VoterIsRegistedVotePaper6_next, (LPVOID)cast_pointer_function(VoterIsRegistedVotePaper6_wrapper), (LPVOID)cast_pointer_function((bool(Voter::*)(char, char*))&Voter::IsRegistedVotePaper) }, _hook_record { (LPVOID)0x1402be860L, (LPVOID *)&Voterctor_Voter8_user, (LPVOID *)&Voterctor_Voter8_next, (LPVOID)cast_pointer_function(Voterctor_Voter8_wrapper), (LPVOID)cast_pointer_function((void(Voter::*)())&Voter::ctor_Voter) }, _hook_record { (LPVOID)0x1402bf610L, (LPVOID *)&Voter_MakeVotePaper10_user, (LPVOID *)&Voter_MakeVotePaper10_next, (LPVOID)cast_pointer_function(Voter_MakeVotePaper10_wrapper), (LPVOID)cast_pointer_function((void(Voter::*)())&Voter::_MakeVotePaper) }, _hook_record { (LPVOID)0x1402c0140L, (LPVOID *)&Voter_SendVotePaper12_user, (LPVOID *)&Voter_SendVotePaper12_next, (LPVOID)cast_pointer_function(Voter_SendVotePaper12_wrapper), (LPVOID)cast_pointer_function((int(Voter::*)(struct CPlayer*))&Voter::_SendVotePaper) }, _hook_record { (LPVOID)0x1402beb20L, (LPVOID *)&Voter_SendVotePaperAll14_user, (LPVOID *)&Voter_SendVotePaperAll14_next, (LPVOID)cast_pointer_function(Voter_SendVotePaperAll14_wrapper), (LPVOID)cast_pointer_function((void(Voter::*)())&Voter::_SendVotePaperAll) }, _hook_record { (LPVOID)0x1402bede0L, (LPVOID *)&Voter_SendVoteScore16_user, (LPVOID *)&Voter_SendVoteScore16_next, (LPVOID)cast_pointer_function(Voter_SendVoteScore16_wrapper), (LPVOID)cast_pointer_function((void(Voter::*)(struct CPlayer*))&Voter::_SendVoteScore) }, _hook_record { (LPVOID)0x1402beec0L, (LPVOID *)&Voter_SendVoteScoreAll18_user, (LPVOID *)&Voter_SendVoteScoreAll18_next, (LPVOID)cast_pointer_function(Voter_SendVoteScoreAll18_wrapper), (LPVOID)cast_pointer_function((void(Voter::*)(char))&Voter::_SendVoteScoreAll) }, _hook_record { (LPVOID)0x1402bf3d0L, (LPVOID *)&Voter_SetVoteScoreInfo20_user, (LPVOID *)&Voter_SetVoteScoreInfo20_next, (LPVOID)cast_pointer_function(Voter_SetVoteScoreInfo20_wrapper), (LPVOID)cast_pointer_function((void(Voter::*)(char, char*, bool))&Voter::_SetVoteScoreInfo) }, _hook_record { (LPVOID)0x1402befd0L, (LPVOID *)&Voter_Vote22_user, (LPVOID *)&Voter_Vote22_next, (LPVOID)cast_pointer_function(Voter_Vote22_wrapper), (LPVOID)cast_pointer_function((int(Voter::*)(struct CPlayer*, char*))&Voter::_Vote) }, _hook_record { (LPVOID)0x1402c0100L, (LPVOID *)&Voterdtor_Voter27_user, (LPVOID *)&Voterdtor_Voter27_next, (LPVOID)cast_pointer_function(Voterdtor_Voter27_wrapper), (LPVOID)cast_pointer_function((void(Voter::*)())&Voter::dtor_Voter) }, }; }; // end namespace Detail END_ATF_NAMESPACE
46.510753
112
0.635765
lemkova
3b6908b7dbf5f6f66cac9172cca25d52bab9a4d7
2,784
hpp
C++
Siv3D/include/Siv3D/BinaryWriter.hpp
tas9n/OpenSiv3D
c561cba1d88eb9cd9606ba983fcc1120192d5615
[ "MIT" ]
2
2021-11-22T00:52:48.000Z
2021-12-24T09:33:55.000Z
Siv3D/include/Siv3D/BinaryWriter.hpp
tas9n/OpenSiv3D
c561cba1d88eb9cd9606ba983fcc1120192d5615
[ "MIT" ]
32
2021-10-09T10:04:11.000Z
2022-02-25T06:10:13.000Z
Siv3D/include/Siv3D/BinaryWriter.hpp
tas9n/OpenSiv3D
c561cba1d88eb9cd9606ba983fcc1120192d5615
[ "MIT" ]
1
2021-12-31T05:08:00.000Z
2021-12-31T05:08:00.000Z
//----------------------------------------------- // // This file is part of the Siv3D Engine. // // Copyright (c) 2008-2022 Ryo Suzuki // Copyright (c) 2016-2022 OpenSiv3D Project // // Licensed under the MIT License. // //----------------------------------------------- # pragma once # include <memory> # include "Common.hpp" # include "IWriter.hpp" # include "StringView.hpp" # include "OpenMode.hpp" namespace s3d { class String; using FilePath = String; /// @brief 書き込み用バイナリファイル class BinaryWriter : public IWriter { public: /// @brief デフォルトコンストラクタ SIV3D_NODISCARD_CXX20 BinaryWriter(); /// @brief ファイルを開きます。 /// @param path ファイルパス /// @param openMode オープンモード (`OpenMode` の組み合わせ) SIV3D_NODISCARD_CXX20 explicit BinaryWriter(FilePathView path, OpenMode openMode = OpenMode::Trunc); /// @brief ファイルを開きます。 /// @param path ファイルパス /// @param openMode オープンモード (`OpenMode` の組み合わせ) /// @return ファイルのオープンに成功した場合 true, それ以外の場合は false bool open(FilePathView path, OpenMode openMode = OpenMode::Trunc); /// @brief ファイルを閉じます。 /// @remark ファイルがオープンしていない場合は何もしません。 void close(); /// @brief ファイルが開いているかを返します。 /// @return ファイルが開いている場合 true, それ以外の場合は false [[nodiscard]] bool isOpen() const noexcept override; /// @brief ファイルが開いているかを返します。 /// @return ファイルが開いている場合 true, それ以外の場合は false [[nodiscard]] explicit operator bool() const noexcept; /// @brief 書き込んだデータのバッファをフラッシュして、確実にファイルに書き込みます。 void flush(); /// @brief 開いているファイルの内容をすべて消去し、サイズが 0 のファイルにします。 void clear(); /// @brief 開いているファイルの現在のサイズ(バイト)を返します。 /// @return 開いているファイルの現在のサイズ(バイト) [[nodiscard]] int64 size() const override; /// @brief 現在の書き込み位置を返します。 /// @return 現在の書き込み位置 [[nodiscard]] int64 getPos() const override; /// @brief 書き込み位置を変更します。 /// @param pos 新しい書き込み位置(バイト) /// @return 書き込み位置の変更に成功した場合 true, それ以外の場合は false bool setPos(int64 pos) override; /// @brief 書き込み位置をファイルの終端に移動させます。 /// @return 新しい書き込み位置(バイト) int64 seekToEnd(); /// @brief 現在の書き込み位置にデータを書き込みます。 /// @param src 書き込むデータ /// @param sizeBytes 書き込むサイズ(バイト) /// @remark 書き込み位置がファイルの終端の場合、書き込んだ分だけファイルのサイズが拡張されます。 /// @return 実際に書き込んだサイズ(バイト) int64 write(const void* src, int64 sizeBytes) override; /// @brief 現在の書き込み位置にデータを書き込みます。 /// @tparam TriviallyCopyable 書き込む値の型 /// @param src 書き込むデータ /// @remark 書き込み位置がファイルの終端の場合、書き込んだ分だけファイルのサイズが拡張されます。 /// @return 書き込みに成功した場合 true, それ以外の場合は false SIV3D_CONCEPT_TRIVIALLY_COPYABLE bool write(const TriviallyCopyable& src); /// @brief 開いているファイルのパスを返します。 /// @return 開いているファイルのパス。ファイルが開いていない場合は空の文字列 [[nodiscard]] const FilePath& path() const noexcept; private: class BinaryWriterDetail; std::shared_ptr<BinaryWriterDetail> pImpl; }; } # include "detail/BinaryWriter.ipp"
24.637168
80
0.681394
tas9n
3b6d257f9bc5af1f60e7de9e2cef005529eff75d
3,960
cpp
C++
native/androidaudioplugin/android/src/audio-plugin-host-android.cpp
atsushieno/android-audio-plugin-framework
f382d5964af24498972e51cbe52af34361a02dc3
[ "MIT" ]
34
2020-03-05T23:40:44.000Z
2022-03-23T04:50:43.000Z
native/androidaudioplugin/android/src/audio-plugin-host-android.cpp
atsushieno/android-audio-plugin-framework
f382d5964af24498972e51cbe52af34361a02dc3
[ "MIT" ]
87
2020-01-04T14:47:55.000Z
2022-03-31T16:42:11.000Z
native/androidaudioplugin/android/src/audio-plugin-host-android.cpp
atsushieno/android-audio-plugin-framework
f382d5964af24498972e51cbe52af34361a02dc3
[ "MIT" ]
1
2021-01-31T11:16:40.000Z
2021-01-31T11:16:40.000Z
// // Created by atsushi on 2020/01/21. // #include <jni.h> #include <android/log.h> #include <stdlib.h> #include <sys/mman.h> #include <memory> #include "aidl/org/androidaudioplugin/BnAudioPluginInterface.h" #include "aidl/org/androidaudioplugin/BpAudioPluginInterface.h" #include "aap/audio-plugin-host.h" #include "aap/audio-plugin-host-android.h" #include "AudioPluginInterfaceImpl.h" #include "aap/android-application-context.h" namespace aap { std::vector<std::string> AndroidPluginHostPAL::getPluginPaths() { // Due to the way how Android service query works (asynchronous), // it has to wait until AudioPluginHost service query completes. for (int i = 0; i < SERVICE_QUERY_TIMEOUT_IN_SECONDS; i++) if (plugin_list_cache.empty()) sleep(1); std::vector<std::string> ret{}; for (auto p : plugin_list_cache) { if (std::find(ret.begin(), ret.end(), p->getPluginPackageName()) == ret.end()) ret.emplace_back(p->getPluginPackageName()); } return ret; } std::vector<PluginInformation*> AndroidPluginHostPAL::getPluginsFromMetadataPaths(std::vector<std::string>& aapMetadataPaths) { std::vector<PluginInformation *> results{}; for (auto p : plugin_list_cache) if (std::find(aapMetadataPaths.begin(), aapMetadataPaths.end(), p->getPluginPackageName()) != aapMetadataPaths.end()) results.emplace_back(p); return results; } AIBinder* AndroidPluginHostPAL::getBinderForServiceConnection(std::string packageName, std::string className) { for (int i = 0; i < serviceConnections.size(); i++) { auto s = serviceConnections[i].get(); if (s->packageName == packageName && s->className == className) return serviceConnections[i]->aibinder; } return nullptr; } AIBinder* AndroidPluginHostPAL::getBinderForServiceConnectionForPlugin(std::string pluginId) { auto pl = plugin_list_cache; for (int i = 0; pl[i] != nullptr; i++) if (pl[i]->getPluginID() == pluginId) return getBinderForServiceConnection(pl[i]->getPluginPackageName(), pl[i]->getPluginLocalName()); return nullptr; } extern "C" aap::PluginInformation * pluginInformation_fromJava(JNIEnv *env, jobject pluginInformation); // in AudioPluginHost_native.cpp std::vector<PluginInformation*> AndroidPluginHostPAL::convertPluginList(jobjectArray jPluginInfos) { assert(jPluginInfos != nullptr); plugin_list_cache.clear(); auto env = getJNIEnv(); jsize infoSize = env->GetArrayLength(jPluginInfos); for (int i = 0; i < infoSize; i++) { auto jPluginInfo = (jobject) env->GetObjectArrayElement(jPluginInfos, i); plugin_list_cache.emplace_back(pluginInformation_fromJava(env, jPluginInfo)); } return plugin_list_cache; } extern "C" jobjectArray queryInstalledPluginsJNI(); // in AudioPluginHost_native.cpp void AndroidPluginHostPAL::initializeKnownPlugins(jobjectArray jPluginInfos) { jPluginInfos = jPluginInfos != nullptr ? jPluginInfos : queryInstalledPluginsJNI(); setPluginListCache(convertPluginList(jPluginInfos)); } std::vector<aap::PluginInformation*> AndroidPluginHostPAL::queryInstalledPlugins() { return convertPluginList(queryInstalledPluginsJNI()); } std::unique_ptr<AndroidPluginHostPAL> android_pal_instance{}; PluginHostPAL* getPluginHostPAL() { if (android_pal_instance == nullptr) android_pal_instance = std::make_unique<AndroidPluginHostPAL>(); return android_pal_instance.get(); } JNIEnv* AndroidPluginHostPAL::getJNIEnv() { JavaVM* vm = aap::get_android_jvm(); assert(vm); JNIEnv* env; vm->AttachCurrentThread(&env, nullptr); return env; } void AndroidPluginHostPAL::initialize(JNIEnv *env, jobject applicationContext) { aap::set_application_context(env, applicationContext); } void AndroidPluginHostPAL::terminate(JNIEnv *env) { aap::unset_application_context(env); } } // namespace aap
32.727273
127
0.717677
atsushieno
3b7171baaf7025f92b310950c21729d04d011e69
727
cpp
C++
TAO/orbsvcs/examples/LoadBalancing/StockFactory.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
36
2015-01-10T07:27:33.000Z
2022-03-07T03:32:08.000Z
TAO/orbsvcs/examples/LoadBalancing/StockFactory.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
2
2018-08-13T07:30:51.000Z
2019-02-25T03:04:31.000Z
TAO/orbsvcs/examples/LoadBalancing/StockFactory.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
38
2015-01-08T14:12:06.000Z
2022-01-19T08:33:00.000Z
// // $Id: StockFactory.cpp 78900 2007-07-15 13:05:48Z sowayaa $ // #include "StockFactory.h" #include "ace/streams.h" StockFactory::StockFactory (CORBA::ORB_ptr orb, int number) : orb_ (CORBA::ORB::_duplicate (orb)), rhat_ ("RHAT", "RedHat, Inc.", 210), msft_ ("MSFT", "Microsoft, Inc.", 91), number_ (number) { } Test::Stock_ptr StockFactory::get_stock (const char *symbol) { cout << "Server Number is " << number_ << endl; if (ACE_OS::strcmp (symbol, "RHAT") == 0) { return this->rhat_._this (); } else if (ACE_OS::strcmp (symbol, "MSFT") == 0) { return this->msft_._this (); } throw Test::Invalid_Stock_Symbol (); } void StockFactory::shutdown (void) { this->orb_->shutdown (0); }
22.030303
61
0.629986
cflowe
3b71cd7c8f4d104658fa98bf693f6a494dc504af
24,957
cc
C++
src/transform/vertex_pulling_transform_test.cc
dorba/tint
f81c1081ea7d27ea55f373c0bfaf651e491da7e6
[ "Apache-2.0" ]
null
null
null
src/transform/vertex_pulling_transform_test.cc
dorba/tint
f81c1081ea7d27ea55f373c0bfaf651e491da7e6
[ "Apache-2.0" ]
null
null
null
src/transform/vertex_pulling_transform_test.cc
dorba/tint
f81c1081ea7d27ea55f373c0bfaf651e491da7e6
[ "Apache-2.0" ]
null
null
null
// Copyright 2020 The Tint Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "src/transform/vertex_pulling_transform.h" #include "gtest/gtest.h" #include "src/ast/decorated_variable.h" #include "src/ast/function.h" #include "src/ast/pipeline_stage.h" #include "src/ast/stage_decoration.h" #include "src/ast/type/array_type.h" #include "src/ast/type/f32_type.h" #include "src/ast/type/i32_type.h" #include "src/ast/type/void_type.h" #include "src/type_determiner.h" #include "src/validator.h" namespace tint { namespace transform { namespace { class VertexPullingTransformHelper { public: VertexPullingTransformHelper() { mod_ = std::make_unique<ast::Module>(); transform_ = std::make_unique<VertexPullingTransform>(&ctx_, mod_.get()); } // Create basic module with an entry point and vertex function void InitBasicModule() { auto func = std::make_unique<ast::Function>( "main", ast::VariableList{}, ctx_.type_mgr().Get(std::make_unique<ast::type::VoidType>())); func->add_decoration( std::make_unique<ast::StageDecoration>(ast::PipelineStage ::kVertex)); mod()->AddFunction(std::move(func)); } // Set up the transformation, after building the module void InitTransform(VertexStateDescriptor vertex_state) { EXPECT_TRUE(mod_->IsValid()); TypeDeterminer td(&ctx_, mod_.get()); EXPECT_TRUE(td.Determine()); transform_->SetVertexState( std::make_unique<VertexStateDescriptor>(std::move(vertex_state))); transform_->SetEntryPoint("main"); } // Inserts a variable which will be converted to vertex pulling void AddVertexInputVariable(uint32_t location, std::string name, ast::type::Type* type) { auto var = std::make_unique<ast::DecoratedVariable>( std::make_unique<ast::Variable>(name, ast::StorageClass::kInput, type)); ast::VariableDecorationList decorations; decorations.push_back(std::make_unique<ast::LocationDecoration>(location)); var->set_decorations(std::move(decorations)); mod_->AddGlobalVariable(std::move(var)); } Context* ctx() { return &ctx_; } ast::Module* mod() { return mod_.get(); } VertexPullingTransform* transform() { return transform_.get(); } private: Context ctx_; std::unique_ptr<ast::Module> mod_; std::unique_ptr<VertexPullingTransform> transform_; }; class VertexPullingTransformTest : public VertexPullingTransformHelper, public testing::Test {}; TEST_F(VertexPullingTransformTest, Error_NoVertexState) { EXPECT_FALSE(transform()->Run()); EXPECT_EQ(transform()->error(), "SetVertexState not called"); } TEST_F(VertexPullingTransformTest, Error_NoEntryPoint) { transform()->SetVertexState(std::make_unique<VertexStateDescriptor>()); EXPECT_FALSE(transform()->Run()); EXPECT_EQ(transform()->error(), "Vertex stage entry point not found"); } TEST_F(VertexPullingTransformTest, Error_InvalidEntryPoint) { InitBasicModule(); InitTransform({}); transform()->SetEntryPoint("_"); EXPECT_FALSE(transform()->Run()); EXPECT_EQ(transform()->error(), "Vertex stage entry point not found"); } TEST_F(VertexPullingTransformTest, Error_EntryPointWrongStage) { auto func = std::make_unique<ast::Function>( "main", ast::VariableList{}, ctx()->type_mgr().Get(std::make_unique<ast::type::VoidType>())); func->add_decoration( std::make_unique<ast::StageDecoration>(ast::PipelineStage::kFragment)); mod()->AddFunction(std::move(func)); InitTransform({}); EXPECT_FALSE(transform()->Run()); EXPECT_EQ(transform()->error(), "Vertex stage entry point not found"); } TEST_F(VertexPullingTransformTest, BasicModule) { InitBasicModule(); InitTransform({}); EXPECT_TRUE(transform()->Run()); } TEST_F(VertexPullingTransformTest, OneAttribute) { InitBasicModule(); ast::type::F32Type f32; AddVertexInputVariable(0, "var_a", &f32); InitTransform({{{4, InputStepMode::kVertex, {{VertexFormat::kF32, 0, 0}}}}}); EXPECT_TRUE(transform()->Run()); EXPECT_EQ(R"(Module{ TintVertexData Struct{ [[block]] StructMember{[[ offset 0 ]] _tint_vertex_data: __array__u32_stride_4} } Variable{ var_a private __f32 } DecoratedVariable{ Decorations{ BuiltinDecoration{vertex_idx} } _tint_pulling_vertex_index in __i32 } DecoratedVariable{ Decorations{ BindingDecoration{0} SetDecoration{4} } _tint_pulling_vertex_buffer_0 storage_buffer __struct_TintVertexData } Function main -> __void StageDecoration{vertex} () { Block{ VariableDeclStatement{ Variable{ _tint_pulling_pos function __i32 } } Assignment{ Identifier{_tint_pulling_pos} Binary{ Binary{ Identifier{_tint_pulling_vertex_index} multiply ScalarConstructor{4} } add ScalarConstructor{0} } } Assignment{ Identifier{var_a} Bitcast<__f32>{ ArrayAccessor{ MemberAccessor{ Identifier{_tint_pulling_vertex_buffer_0} Identifier{_tint_vertex_data} } Binary{ Identifier{_tint_pulling_pos} divide ScalarConstructor{4} } } } } } } } )", mod()->to_str()); } TEST_F(VertexPullingTransformTest, OneInstancedAttribute) { InitBasicModule(); ast::type::F32Type f32; AddVertexInputVariable(0, "var_a", &f32); InitTransform( {{{4, InputStepMode::kInstance, {{VertexFormat::kF32, 0, 0}}}}}); EXPECT_TRUE(transform()->Run()); EXPECT_EQ(R"(Module{ TintVertexData Struct{ [[block]] StructMember{[[ offset 0 ]] _tint_vertex_data: __array__u32_stride_4} } Variable{ var_a private __f32 } DecoratedVariable{ Decorations{ BuiltinDecoration{instance_idx} } _tint_pulling_instance_index in __i32 } DecoratedVariable{ Decorations{ BindingDecoration{0} SetDecoration{4} } _tint_pulling_vertex_buffer_0 storage_buffer __struct_TintVertexData } Function main -> __void StageDecoration{vertex} () { Block{ VariableDeclStatement{ Variable{ _tint_pulling_pos function __i32 } } Assignment{ Identifier{_tint_pulling_pos} Binary{ Binary{ Identifier{_tint_pulling_instance_index} multiply ScalarConstructor{4} } add ScalarConstructor{0} } } Assignment{ Identifier{var_a} Bitcast<__f32>{ ArrayAccessor{ MemberAccessor{ Identifier{_tint_pulling_vertex_buffer_0} Identifier{_tint_vertex_data} } Binary{ Identifier{_tint_pulling_pos} divide ScalarConstructor{4} } } } } } } } )", mod()->to_str()); } TEST_F(VertexPullingTransformTest, OneAttributeDifferentOutputSet) { InitBasicModule(); ast::type::F32Type f32; AddVertexInputVariable(0, "var_a", &f32); InitTransform({{{4, InputStepMode::kVertex, {{VertexFormat::kF32, 0, 0}}}}}); transform()->SetPullingBufferBindingSet(5); EXPECT_TRUE(transform()->Run()); EXPECT_EQ(R"(Module{ TintVertexData Struct{ [[block]] StructMember{[[ offset 0 ]] _tint_vertex_data: __array__u32_stride_4} } Variable{ var_a private __f32 } DecoratedVariable{ Decorations{ BuiltinDecoration{vertex_idx} } _tint_pulling_vertex_index in __i32 } DecoratedVariable{ Decorations{ BindingDecoration{0} SetDecoration{5} } _tint_pulling_vertex_buffer_0 storage_buffer __struct_TintVertexData } Function main -> __void StageDecoration{vertex} () { Block{ VariableDeclStatement{ Variable{ _tint_pulling_pos function __i32 } } Assignment{ Identifier{_tint_pulling_pos} Binary{ Binary{ Identifier{_tint_pulling_vertex_index} multiply ScalarConstructor{4} } add ScalarConstructor{0} } } Assignment{ Identifier{var_a} Bitcast<__f32>{ ArrayAccessor{ MemberAccessor{ Identifier{_tint_pulling_vertex_buffer_0} Identifier{_tint_vertex_data} } Binary{ Identifier{_tint_pulling_pos} divide ScalarConstructor{4} } } } } } } } )", mod()->to_str()); } // We expect the transform to use an existing builtin variables if it finds them TEST_F(VertexPullingTransformTest, ExistingVertexIndexAndInstanceIndex) { InitBasicModule(); ast::type::F32Type f32; AddVertexInputVariable(0, "var_a", &f32); AddVertexInputVariable(1, "var_b", &f32); ast::type::I32Type i32; { auto vertex_index_var = std::make_unique<ast::DecoratedVariable>( std::make_unique<ast::Variable>("custom_vertex_index", ast::StorageClass::kInput, &i32)); ast::VariableDecorationList decorations; decorations.push_back( std::make_unique<ast::BuiltinDecoration>(ast::Builtin::kVertexIdx)); vertex_index_var->set_decorations(std::move(decorations)); mod()->AddGlobalVariable(std::move(vertex_index_var)); } { auto instance_index_var = std::make_unique<ast::DecoratedVariable>( std::make_unique<ast::Variable>("custom_instance_index", ast::StorageClass::kInput, &i32)); ast::VariableDecorationList decorations; decorations.push_back( std::make_unique<ast::BuiltinDecoration>(ast::Builtin::kInstanceIdx)); instance_index_var->set_decorations(std::move(decorations)); mod()->AddGlobalVariable(std::move(instance_index_var)); } InitTransform( {{{4, InputStepMode::kVertex, {{VertexFormat::kF32, 0, 0}}}, {4, InputStepMode::kInstance, {{VertexFormat::kF32, 0, 1}}}}}); EXPECT_TRUE(transform()->Run()); EXPECT_EQ(R"(Module{ TintVertexData Struct{ [[block]] StructMember{[[ offset 0 ]] _tint_vertex_data: __array__u32_stride_4} } Variable{ var_a private __f32 } Variable{ var_b private __f32 } DecoratedVariable{ Decorations{ BuiltinDecoration{vertex_idx} } custom_vertex_index in __i32 } DecoratedVariable{ Decorations{ BuiltinDecoration{instance_idx} } custom_instance_index in __i32 } DecoratedVariable{ Decorations{ BindingDecoration{0} SetDecoration{4} } _tint_pulling_vertex_buffer_0 storage_buffer __struct_TintVertexData } DecoratedVariable{ Decorations{ BindingDecoration{1} SetDecoration{4} } _tint_pulling_vertex_buffer_1 storage_buffer __struct_TintVertexData } Function main -> __void StageDecoration{vertex} () { Block{ VariableDeclStatement{ Variable{ _tint_pulling_pos function __i32 } } Assignment{ Identifier{_tint_pulling_pos} Binary{ Binary{ Identifier{custom_vertex_index} multiply ScalarConstructor{4} } add ScalarConstructor{0} } } Assignment{ Identifier{var_a} Bitcast<__f32>{ ArrayAccessor{ MemberAccessor{ Identifier{_tint_pulling_vertex_buffer_0} Identifier{_tint_vertex_data} } Binary{ Identifier{_tint_pulling_pos} divide ScalarConstructor{4} } } } } Assignment{ Identifier{_tint_pulling_pos} Binary{ Binary{ Identifier{custom_instance_index} multiply ScalarConstructor{4} } add ScalarConstructor{0} } } Assignment{ Identifier{var_b} Bitcast<__f32>{ ArrayAccessor{ MemberAccessor{ Identifier{_tint_pulling_vertex_buffer_1} Identifier{_tint_vertex_data} } Binary{ Identifier{_tint_pulling_pos} divide ScalarConstructor{4} } } } } } } } )", mod()->to_str()); } TEST_F(VertexPullingTransformTest, TwoAttributesSameBuffer) { InitBasicModule(); ast::type::F32Type f32; AddVertexInputVariable(0, "var_a", &f32); ast::type::ArrayType vec4_f32{&f32, 4u}; AddVertexInputVariable(1, "var_b", &vec4_f32); InitTransform( {{{16, InputStepMode::kVertex, {{VertexFormat::kF32, 0, 0}, {VertexFormat::kVec4F32, 0, 1}}}}}); EXPECT_TRUE(transform()->Run()); EXPECT_EQ(R"(Module{ TintVertexData Struct{ [[block]] StructMember{[[ offset 0 ]] _tint_vertex_data: __array__u32_stride_4} } Variable{ var_a private __f32 } Variable{ var_b private __array__f32_4 } DecoratedVariable{ Decorations{ BuiltinDecoration{vertex_idx} } _tint_pulling_vertex_index in __i32 } DecoratedVariable{ Decorations{ BindingDecoration{0} SetDecoration{4} } _tint_pulling_vertex_buffer_0 storage_buffer __struct_TintVertexData } Function main -> __void StageDecoration{vertex} () { Block{ VariableDeclStatement{ Variable{ _tint_pulling_pos function __i32 } } Assignment{ Identifier{_tint_pulling_pos} Binary{ Binary{ Identifier{_tint_pulling_vertex_index} multiply ScalarConstructor{16} } add ScalarConstructor{0} } } Assignment{ Identifier{var_a} Bitcast<__f32>{ ArrayAccessor{ MemberAccessor{ Identifier{_tint_pulling_vertex_buffer_0} Identifier{_tint_vertex_data} } Binary{ Identifier{_tint_pulling_pos} divide ScalarConstructor{4} } } } } Assignment{ Identifier{_tint_pulling_pos} Binary{ Binary{ Identifier{_tint_pulling_vertex_index} multiply ScalarConstructor{16} } add ScalarConstructor{0} } } Assignment{ Identifier{var_b} TypeConstructor{ __vec_4__f32 Bitcast<__f32>{ ArrayAccessor{ MemberAccessor{ Identifier{_tint_pulling_vertex_buffer_0} Identifier{_tint_vertex_data} } Binary{ Binary{ Identifier{_tint_pulling_pos} add ScalarConstructor{0} } divide ScalarConstructor{4} } } } Bitcast<__f32>{ ArrayAccessor{ MemberAccessor{ Identifier{_tint_pulling_vertex_buffer_0} Identifier{_tint_vertex_data} } Binary{ Binary{ Identifier{_tint_pulling_pos} add ScalarConstructor{4} } divide ScalarConstructor{4} } } } Bitcast<__f32>{ ArrayAccessor{ MemberAccessor{ Identifier{_tint_pulling_vertex_buffer_0} Identifier{_tint_vertex_data} } Binary{ Binary{ Identifier{_tint_pulling_pos} add ScalarConstructor{8} } divide ScalarConstructor{4} } } } Bitcast<__f32>{ ArrayAccessor{ MemberAccessor{ Identifier{_tint_pulling_vertex_buffer_0} Identifier{_tint_vertex_data} } Binary{ Binary{ Identifier{_tint_pulling_pos} add ScalarConstructor{12} } divide ScalarConstructor{4} } } } } } } } } )", mod()->to_str()); } TEST_F(VertexPullingTransformTest, FloatVectorAttributes) { InitBasicModule(); ast::type::F32Type f32; ast::type::ArrayType vec2_f32{&f32, 2u}; AddVertexInputVariable(0, "var_a", &vec2_f32); ast::type::ArrayType vec3_f32{&f32, 3u}; AddVertexInputVariable(1, "var_b", &vec3_f32); ast::type::ArrayType vec4_f32{&f32, 4u}; AddVertexInputVariable(2, "var_c", &vec4_f32); InitTransform( {{{8, InputStepMode::kVertex, {{VertexFormat::kVec2F32, 0, 0}}}, {12, InputStepMode::kVertex, {{VertexFormat::kVec3F32, 0, 1}}}, {16, InputStepMode::kVertex, {{VertexFormat::kVec4F32, 0, 2}}}}}); EXPECT_TRUE(transform()->Run()); EXPECT_EQ(R"(Module{ TintVertexData Struct{ [[block]] StructMember{[[ offset 0 ]] _tint_vertex_data: __array__u32_stride_4} } Variable{ var_a private __array__f32_2 } Variable{ var_b private __array__f32_3 } Variable{ var_c private __array__f32_4 } DecoratedVariable{ Decorations{ BuiltinDecoration{vertex_idx} } _tint_pulling_vertex_index in __i32 } DecoratedVariable{ Decorations{ BindingDecoration{0} SetDecoration{4} } _tint_pulling_vertex_buffer_0 storage_buffer __struct_TintVertexData } DecoratedVariable{ Decorations{ BindingDecoration{1} SetDecoration{4} } _tint_pulling_vertex_buffer_1 storage_buffer __struct_TintVertexData } DecoratedVariable{ Decorations{ BindingDecoration{2} SetDecoration{4} } _tint_pulling_vertex_buffer_2 storage_buffer __struct_TintVertexData } Function main -> __void StageDecoration{vertex} () { Block{ VariableDeclStatement{ Variable{ _tint_pulling_pos function __i32 } } Assignment{ Identifier{_tint_pulling_pos} Binary{ Binary{ Identifier{_tint_pulling_vertex_index} multiply ScalarConstructor{8} } add ScalarConstructor{0} } } Assignment{ Identifier{var_a} TypeConstructor{ __vec_2__f32 Bitcast<__f32>{ ArrayAccessor{ MemberAccessor{ Identifier{_tint_pulling_vertex_buffer_0} Identifier{_tint_vertex_data} } Binary{ Binary{ Identifier{_tint_pulling_pos} add ScalarConstructor{0} } divide ScalarConstructor{4} } } } Bitcast<__f32>{ ArrayAccessor{ MemberAccessor{ Identifier{_tint_pulling_vertex_buffer_0} Identifier{_tint_vertex_data} } Binary{ Binary{ Identifier{_tint_pulling_pos} add ScalarConstructor{4} } divide ScalarConstructor{4} } } } } } Assignment{ Identifier{_tint_pulling_pos} Binary{ Binary{ Identifier{_tint_pulling_vertex_index} multiply ScalarConstructor{12} } add ScalarConstructor{0} } } Assignment{ Identifier{var_b} TypeConstructor{ __vec_3__f32 Bitcast<__f32>{ ArrayAccessor{ MemberAccessor{ Identifier{_tint_pulling_vertex_buffer_1} Identifier{_tint_vertex_data} } Binary{ Binary{ Identifier{_tint_pulling_pos} add ScalarConstructor{0} } divide ScalarConstructor{4} } } } Bitcast<__f32>{ ArrayAccessor{ MemberAccessor{ Identifier{_tint_pulling_vertex_buffer_1} Identifier{_tint_vertex_data} } Binary{ Binary{ Identifier{_tint_pulling_pos} add ScalarConstructor{4} } divide ScalarConstructor{4} } } } Bitcast<__f32>{ ArrayAccessor{ MemberAccessor{ Identifier{_tint_pulling_vertex_buffer_1} Identifier{_tint_vertex_data} } Binary{ Binary{ Identifier{_tint_pulling_pos} add ScalarConstructor{8} } divide ScalarConstructor{4} } } } } } Assignment{ Identifier{_tint_pulling_pos} Binary{ Binary{ Identifier{_tint_pulling_vertex_index} multiply ScalarConstructor{16} } add ScalarConstructor{0} } } Assignment{ Identifier{var_c} TypeConstructor{ __vec_4__f32 Bitcast<__f32>{ ArrayAccessor{ MemberAccessor{ Identifier{_tint_pulling_vertex_buffer_2} Identifier{_tint_vertex_data} } Binary{ Binary{ Identifier{_tint_pulling_pos} add ScalarConstructor{0} } divide ScalarConstructor{4} } } } Bitcast<__f32>{ ArrayAccessor{ MemberAccessor{ Identifier{_tint_pulling_vertex_buffer_2} Identifier{_tint_vertex_data} } Binary{ Binary{ Identifier{_tint_pulling_pos} add ScalarConstructor{4} } divide ScalarConstructor{4} } } } Bitcast<__f32>{ ArrayAccessor{ MemberAccessor{ Identifier{_tint_pulling_vertex_buffer_2} Identifier{_tint_vertex_data} } Binary{ Binary{ Identifier{_tint_pulling_pos} add ScalarConstructor{8} } divide ScalarConstructor{4} } } } Bitcast<__f32>{ ArrayAccessor{ MemberAccessor{ Identifier{_tint_pulling_vertex_buffer_2} Identifier{_tint_vertex_data} } Binary{ Binary{ Identifier{_tint_pulling_pos} add ScalarConstructor{12} } divide ScalarConstructor{4} } } } } } } } } )", mod()->to_str()); } } // namespace } // namespace transform } // namespace tint
24.18314
80
0.555075
dorba
3b72baed5ee2814e04e45b53b455cb616676cc2f
234,149
cpp
C++
openjdk/jdk/src/windows/native/sun/windows/awt_Component.cpp
liumapp/compiling-jvm
962f37e281f4d9ec03486d9380c43b7260790eaa
[ "Apache-2.0" ]
null
null
null
openjdk/jdk/src/windows/native/sun/windows/awt_Component.cpp
liumapp/compiling-jvm
962f37e281f4d9ec03486d9380c43b7260790eaa
[ "Apache-2.0" ]
null
null
null
openjdk/jdk/src/windows/native/sun/windows/awt_Component.cpp
liumapp/compiling-jvm
962f37e281f4d9ec03486d9380c43b7260790eaa
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 1996, 2010, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ #include "awt.h" #include <windowsx.h> #include <zmouse.h> #include "jlong.h" #include "awt_AWTEvent.h" #include "awt_BitmapUtil.h" #include "awt_Component.h" #include "awt_Cursor.h" #include "awt_Dimension.h" #include "awt_Frame.h" #include "awt_InputEvent.h" #include "awt_InputTextInfor.h" #include "awt_Insets.h" #include "awt_KeyEvent.h" #include "awt_MenuItem.h" #include "awt_MouseEvent.h" #include "awt_Palette.h" #include "awt_Toolkit.h" #include "awt_Window.h" #include "awt_Win32GraphicsDevice.h" #include "Hashtable.h" #include "ComCtl32Util.h" #include <Region.h> #include <jawt.h> #include <java_awt_Toolkit.h> #include <java_awt_FontMetrics.h> #include <java_awt_Color.h> #include <java_awt_Event.h> #include <java_awt_event_KeyEvent.h> #include <java_awt_Insets.h> #include <sun_awt_windows_WPanelPeer.h> #include <java_awt_event_InputEvent.h> #include <java_awt_event_InputMethodEvent.h> #include <sun_awt_windows_WInputMethod.h> #include <java_awt_event_MouseEvent.h> #include <java_awt_event_MouseWheelEvent.h> // Begin -- Win32 SDK include files #include <imm.h> #include <ime.h> // End -- Win32 SDK include files #include <awt_DnDDT.h> LPCTSTR szAwtComponentClassName = TEXT("SunAwtComponent"); // register a message that no other window in the process (even in a plugin // scenario) will be using const UINT AwtComponent::WmAwtIsComponent = ::RegisterWindowMessage(szAwtComponentClassName); static HWND g_hwndDown = NULL; static DCList activeDCList; static DCList passiveDCList; extern void CheckFontSmoothingSettings(HWND); extern "C" { // Remember the input language has changed by some user's action // (Alt+Shift or through the language icon on the Taskbar) to control the // race condition between the toolkit thread and the AWT event thread. // This flag remains TRUE until the next WInputMethod.getNativeLocale() is // issued. BOOL g_bUserHasChangedInputLang = FALSE; } BOOL AwtComponent::sm_suppressFocusAndActivation = FALSE; BOOL AwtComponent::sm_restoreFocusAndActivation = FALSE; HWND AwtComponent::sm_focusOwner = NULL; HWND AwtComponent::sm_focusedWindow = NULL; BOOL AwtComponent::sm_bMenuLoop = FALSE; AwtComponent* AwtComponent::sm_getComponentCache = NULL; BOOL AwtComponent::sm_inSynthesizeFocus = FALSE; /************************************************************************/ // Struct for _Reshape() and ReshapeNoCheck() methods struct ReshapeStruct { jobject component; jint x, y; jint w, h; }; // Struct for _NativeHandleEvent() method struct NativeHandleEventStruct { jobject component; jobject event; }; // Struct for _SetForeground() and _SetBackground() methods struct SetColorStruct { jobject component; jint rgb; }; // Struct for _SetFont() method struct SetFontStruct { jobject component; jobject font; }; // Struct for _CreatePrintedPixels() method struct CreatePrintedPixelsStruct { jobject component; int srcx, srcy; int srcw, srch; jint alpha; }; // Struct for _SetRectangularShape() method struct SetRectangularShapeStruct { jobject component; jint x1, x2, y1, y2; jobject region; }; // Struct for _GetInsets function struct GetInsetsStruct { jobject window; RECT *insets; }; // Struct for _SetZOrder function struct SetZOrderStruct { jobject component; jlong above; }; // Struct for _SetFocus function struct SetFocusStruct { jobject component; jboolean doSetFocus; }; /************************************************************************/ ////////////////////////////////////////////////////////////////////////// /************************************************************************* * AwtComponent fields */ jfieldID AwtComponent::peerID; jfieldID AwtComponent::xID; jfieldID AwtComponent::yID; jfieldID AwtComponent::widthID; jfieldID AwtComponent::heightID; jfieldID AwtComponent::visibleID; jfieldID AwtComponent::backgroundID; jfieldID AwtComponent::foregroundID; jfieldID AwtComponent::enabledID; jfieldID AwtComponent::parentID; jfieldID AwtComponent::graphicsConfigID; jfieldID AwtComponent::peerGCID; jfieldID AwtComponent::focusableID; jfieldID AwtComponent::appContextID; jfieldID AwtComponent::cursorID; jfieldID AwtComponent::hwndID; jmethodID AwtComponent::getFontMID; jmethodID AwtComponent::getToolkitMID; jmethodID AwtComponent::isEnabledMID; jmethodID AwtComponent::getLocationOnScreenMID; jmethodID AwtComponent::replaceSurfaceDataMID; jmethodID AwtComponent::replaceSurfaceDataLaterMID; HKL AwtComponent::m_hkl = ::GetKeyboardLayout(0); LANGID AwtComponent::m_idLang = LOWORD(::GetKeyboardLayout(0)); UINT AwtComponent::m_CodePage = AwtComponent::LangToCodePage(m_idLang); jint *AwtComponent::masks; static BOOL bLeftShiftIsDown = false; static BOOL bRightShiftIsDown = false; static UINT lastShiftKeyPressed = 0; // init to safe value // Added by waleed to initialize the RTL Flags BOOL AwtComponent::sm_rtl = PRIMARYLANGID(GetInputLanguage()) == LANG_ARABIC || PRIMARYLANGID(GetInputLanguage()) == LANG_HEBREW; BOOL AwtComponent::sm_rtlReadingOrder = PRIMARYLANGID(GetInputLanguage()) == LANG_ARABIC; BOOL AwtComponent::sm_PrimaryDynamicTableBuilt = FALSE; HWND AwtComponent::sm_cursorOn; BOOL AwtComponent::m_QueryNewPaletteCalled = FALSE; CriticalSection windowMoveLock; BOOL windowMoveLockHeld = FALSE; /************************************************************************ * AwtComponent methods */ AwtComponent::AwtComponent() { m_mouseButtonClickAllowed = 0; m_callbacksEnabled = FALSE; m_hwnd = NULL; m_colorForeground = 0; m_colorBackground = 0; m_backgroundColorSet = FALSE; m_penForeground = NULL; m_brushBackground = NULL; m_DefWindowProc = NULL; m_nextControlID = 1; m_childList = NULL; m_myControlID = 0; m_hdwp = NULL; m_validationNestCount = 0; m_dropTarget = NULL; m_InputMethod = NULL; m_useNativeCompWindow = TRUE; m_PendingLeadByte = 0; m_bitsCandType = 0; windowMoveLockPosX = 0; windowMoveLockPosY = 0; windowMoveLockPosCX = 0; windowMoveLockPosCY = 0; m_hCursorCache = NULL; m_bSubclassed = FALSE; m_MessagesProcessing = 0; m_wheelRotationAmount = 0; if (!sm_PrimaryDynamicTableBuilt) { // do it once. AwtComponent::BuildPrimaryDynamicTable(); sm_PrimaryDynamicTableBuilt = TRUE; } } AwtComponent::~AwtComponent() { DASSERT(AwtToolkit::IsMainThread()); /* Disconnect all links. */ UnlinkObjects(); /* * All the messages for this component are processed, native * resources are freed, and Java object is not connected to * the native one anymore. So we can safely destroy component's * handle. */ DestroyHWnd(); if (sm_getComponentCache == this) { sm_getComponentCache = NULL; } } void AwtComponent::Dispose() { // NOTE: in case the component/toplevel was focused, Java should // have already taken care of proper transfering it or clearing. if (m_hdwp != NULL) { // end any deferred window positioning, regardless // of m_validationNestCount ::EndDeferWindowPos(m_hdwp); } // Send final message to release all DCs associated with this component SendMessage(WM_AWT_RELEASE_ALL_DCS); /* Stop message filtering. */ UnsubclassHWND(); /* Release global ref to input method */ SetInputMethod(NULL, TRUE); if (m_childList != NULL) delete m_childList; DestroyDropTarget(); if (m_myControlID != 0) { AwtComponent* parent = GetParent(); if (parent != NULL) parent->RemoveChild(m_myControlID); } ::RemoveProp(GetHWnd(), DrawingStateProp); /* Release any allocated resources. */ if (m_penForeground != NULL) { m_penForeground->Release(); m_penForeground = NULL; } if (m_brushBackground != NULL) { m_brushBackground->Release(); m_brushBackground = NULL; } // The component instance is deleted using AwtObject::Dispose() method AwtObject::Dispose(); } /* store component pointer in window extra bytes */ void AwtComponent::SetComponentInHWND() { DASSERT(::GetWindowLongPtr(GetHWnd(), GWLP_USERDATA) == NULL); ::SetWindowLongPtr(GetHWnd(), GWLP_USERDATA, (LONG_PTR)this); } /* * static function to get AwtComponent pointer from hWnd -- * you don't want to call this from inside a wndproc to avoid * infinite recursion */ AwtComponent* AwtComponent::GetComponent(HWND hWnd) { // Requests for Toolkit hwnd resolution happen pretty often. Check first. if (hWnd == AwtToolkit::GetInstance().GetHWnd()) { return NULL; } if (sm_getComponentCache && sm_getComponentCache->GetHWnd() == hWnd) { return sm_getComponentCache; } // check that it's an AWT component from the same toolkit as the caller if (::IsWindow(hWnd) && AwtToolkit::MainThread() == ::GetWindowThreadProcessId(hWnd, NULL)) { DASSERT(WmAwtIsComponent != 0); if (::SendMessage(hWnd, WmAwtIsComponent, 0, 0L)) { return sm_getComponentCache = GetComponentImpl(hWnd); } } return NULL; } /* * static function to get AwtComponent pointer from hWnd-- * different from GetComponent because caller knows the * hwnd is an AWT component hwnd */ AwtComponent* AwtComponent::GetComponentImpl(HWND hWnd) { AwtComponent *component = (AwtComponent *)::GetWindowLongPtr(hWnd, GWLP_USERDATA); DASSERT(!component || !IsBadReadPtr(component, sizeof(AwtComponent)) ); return component; } /* * Single window proc for all the components. Delegates real work to * the component's WindowProc() member function. */ LRESULT CALLBACK AwtComponent::WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { TRY; AwtComponent * self = AwtComponent::GetComponentImpl(hWnd); if (self == NULL || self->GetHWnd() != hWnd || message == WM_UNDOCUMENTED_CLIENTSHUTDOWN) // handle log-off gracefully { return ComCtl32Util::GetInstance().DefWindowProc(NULL, hWnd, message, wParam, lParam); } else { return self->WindowProc(message, wParam, lParam); } CATCH_BAD_ALLOC_RET(0); } BOOL AwtComponent::IsFocusable() { JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); jobject peer = GetPeer(env); jobject target = env->GetObjectField(peer, AwtObject::targetID); BOOL res = env->GetBooleanField(target, focusableID); AwtWindow *pCont = GetContainer(); if (pCont) { res &= pCont->IsFocusableWindow(); } env->DeleteLocalRef(target); return res; } /************************************************************************ * AwtComponent dynamic methods * * Window class registration routines */ /* * Fix for 4964237: Win XP: Changing theme changes java dialogs title icon */ void AwtComponent::FillClassInfo(WNDCLASSEX *lpwc) { lpwc->cbSize = sizeof(WNDCLASSEX); lpwc->style = 0L;//CS_OWNDC; lpwc->lpfnWndProc = (WNDPROC)::DefWindowProc; lpwc->cbClsExtra = 0; lpwc->cbWndExtra = 0; lpwc->hInstance = AwtToolkit::GetInstance().GetModuleHandle(), lpwc->hIcon = AwtToolkit::GetInstance().GetAwtIcon(); lpwc->hCursor = NULL; lpwc->hbrBackground = NULL; lpwc->lpszMenuName = NULL; lpwc->lpszClassName = GetClassName(); //Fixed 6233560: PIT: Java Cup Logo on the title bar of top-level windows look blurred, Win32 lpwc->hIconSm = AwtToolkit::GetInstance().GetAwtIconSm(); } void AwtComponent::RegisterClass() { WNDCLASSEX wc; if (!::GetClassInfoEx(AwtToolkit::GetInstance().GetModuleHandle(), GetClassName(), &wc)) { FillClassInfo(&wc); ATOM ret = ::RegisterClassEx(&wc); DASSERT(ret != 0); } } void AwtComponent::UnregisterClass() { ::UnregisterClass(GetClassName(), AwtToolkit::GetInstance().GetModuleHandle()); } /* * Copy the graphicsConfig reference from Component into WComponentPeer */ void AwtComponent::InitPeerGraphicsConfig(JNIEnv *env, jobject peer) { jobject target = env->GetObjectField(peer, AwtObject::targetID); //Get graphicsConfig object ref from Component jobject compGC = env->GetObjectField(target, AwtComponent::graphicsConfigID); //Set peer's graphicsConfig to Component's graphicsConfig if (compGC != NULL) { jclass win32GCCls = env->FindClass("sun/awt/Win32GraphicsConfig"); DASSERT(win32GCCls != NULL); DASSERT(env->IsInstanceOf(compGC, win32GCCls)); env->SetObjectField(peer, AwtComponent::peerGCID, compGC); } } void AwtComponent::CreateHWnd(JNIEnv *env, LPCWSTR title, DWORD windowStyle, DWORD windowExStyle, int x, int y, int w, int h, HWND hWndParent, HMENU hMenu, COLORREF colorForeground, COLORREF colorBackground, jobject peer) { if (env->EnsureLocalCapacity(2) < 0) { return; } /* * The window class of multifont label must be "BUTTON" because * "STATIC" class can't get WM_DRAWITEM message, and m_peerObject * member is referred in the GetClassName method of AwtLabel class. * So m_peerObject member must be set here. */ m_peerObject = env->NewGlobalRef(peer); RegisterClass(); jobject target = env->GetObjectField(peer, AwtObject::targetID); jboolean visible = env->GetBooleanField(target, AwtComponent::visibleID); m_visible = visible; if (visible) { windowStyle |= WS_VISIBLE; } else { windowStyle &= ~WS_VISIBLE; } InitPeerGraphicsConfig(env, peer); SetLastError(0); HWND hwnd = ::CreateWindowEx(windowExStyle, GetClassName(), title, windowStyle, x, y, w, h, hWndParent, hMenu, AwtToolkit::GetInstance().GetModuleHandle(), NULL); // fix for 5088782 // check if CreateWindowsEx() returns not null value and if it does - // create an InternalError or OutOfMemoryError based on GetLastError(). // This error is set to createError field of WObjectPeer and then // checked and thrown in WComponentPeer constructor. We can't throw an // error here because this code is invoked on Toolkit thread if (hwnd == NULL) { DWORD dw = ::GetLastError(); jobject createError = NULL; if (dw == ERROR_OUTOFMEMORY) { jstring errorMsg = JNU_NewStringPlatform(env, L"too many window handles"); createError = JNU_NewObjectByName(env, "java/lang/OutOfMemoryError", "(Ljava/lang/String;)V", errorMsg); env->DeleteLocalRef(errorMsg); } else { TCHAR *buf; FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, dw, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&buf, 0, NULL); jstring s = JNU_NewStringPlatform(env, buf); createError = JNU_NewObjectByName(env, "java/lang/InternalError", "(Ljava/lang/String;)V", s); LocalFree(buf); env->DeleteLocalRef(s); } env->SetObjectField(peer, AwtObject::createErrorID, createError); if (createError != NULL) { env->DeleteLocalRef(createError); } env->DeleteLocalRef(target); return; } m_hwnd = hwnd; SetDrawState((jint)JAWT_LOCK_SURFACE_CHANGED | (jint)JAWT_LOCK_BOUNDS_CHANGED | (jint)JAWT_LOCK_CLIP_CHANGED); LinkObjects(env, peer); /* Subclass the window now so that we can snoop on its messages */ SubclassHWND(); /* * Fix for 4046446. */ SetWindowPos(GetHWnd(), 0, x, y, w, h, SWP_NOZORDER | SWP_NOCOPYBITS | SWP_NOACTIVATE); /* Set default colors. */ m_colorForeground = colorForeground; m_colorBackground = colorBackground; /* * Only set background color if the color is actually set on the * target -- this avoids inheriting a parent's color unnecessarily, * and has to be done here because there isn't an API to get the * real background color from outside the AWT package. */ jobject bkgrd = env->GetObjectField(target, AwtComponent::backgroundID) ; if (bkgrd != NULL) { JNU_CallMethodByName(env, NULL, peer, "setBackground", "(Ljava/awt/Color;)V", bkgrd); DASSERT(!safe_ExceptionOccurred(env)); } env->DeleteLocalRef(target); env->DeleteLocalRef(bkgrd); } /* * Destroy this window's HWND */ void AwtComponent::DestroyHWnd() { if (m_hwnd != NULL) { AwtToolkit::DestroyComponentHWND(m_hwnd); //AwtToolkit::DestroyComponent(this); m_hwnd = NULL; } } /* * Returns hwnd for target on non Toolkit thread */ HWND AwtComponent::GetHWnd(JNIEnv* env, jobject target) { if (JNU_IsNull(env, target)) { return 0; } jobject peer = env->GetObjectField(target, AwtComponent::peerID); if (JNU_IsNull(env, peer)) { return 0; } HWND hwnd = reinterpret_cast<HWND>(static_cast<LONG_PTR> ( env->GetLongField(peer, AwtComponent::hwndID))); env->DeleteLocalRef(peer); return hwnd; } // // Propagate the background color to synchronize Java field and peer's field. // This is needed to fix 4148334 // void AwtComponent::UpdateBackground(JNIEnv *env, jobject target) { if (env->EnsureLocalCapacity(1) < 0) { return; } jobject bkgrnd = env->GetObjectField(target, AwtComponent::backgroundID); if (bkgrnd == NULL) { bkgrnd = JNU_NewObjectByName(env, "java/awt/Color", "(III)V", GetRValue(m_colorBackground), GetGValue(m_colorBackground), GetBValue(m_colorBackground)); if (bkgrnd != NULL) { env->SetObjectField(target, AwtComponent::backgroundID, bkgrnd); } } env->DeleteLocalRef(bkgrnd); } /* * Install our window proc as the proc for our HWND, and save off the * previous proc as the default */ void AwtComponent::SubclassHWND() { if (m_bSubclassed) { return; } const WNDPROC wndproc = WndProc; // let compiler type check WndProc m_DefWindowProc = ComCtl32Util::GetInstance().SubclassHWND(GetHWnd(), wndproc); m_bSubclassed = TRUE; } /* * Reinstall the original window proc as the proc for our HWND */ void AwtComponent::UnsubclassHWND() { if (!m_bSubclassed) { return; } ComCtl32Util::GetInstance().UnsubclassHWND(GetHWnd(), WndProc, m_DefWindowProc); m_bSubclassed = FALSE; } ///////////////////////////////////// // (static method) // Determines the top-level ancestor for a given window. If the given // window is a top-level window, return itself. // // 'Top-level' includes dialogs as well. // HWND AwtComponent::GetTopLevelParentForWindow(HWND hwndDescendant) { if (hwndDescendant == NULL) { return NULL; } DASSERT(IsWindow(hwndDescendant)); HWND hwnd = hwndDescendant; for(;;) { DWORD style = ::GetWindowLong(hwnd, GWL_STYLE); // a) found a non-child window so terminate // b) found real toplevel window (e.g. EmbeddedFrame // that is child though) if ( (style & WS_CHILD) == 0 || AwtComponent::IsTopLevelHWnd(hwnd) ) { break; } hwnd = ::GetParent(hwnd); } return hwnd; } //////////////////// jobject AwtComponent::FindHeavyweightUnderCursor(BOOL useCache) { JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); if (env->EnsureLocalCapacity(1) < 0) { return NULL; } HWND hit = NULL; POINT p = { 0, 0 }; AwtComponent *comp = NULL; if (useCache) { if (sm_cursorOn == NULL) { return NULL; } DASSERT(::IsWindow(sm_cursorOn)); VERIFY(::GetCursorPos(&p)); /* * Fix for BugTraq ID 4304024. * Allow a non-default cursor only for the client area. */ comp = AwtComponent::GetComponent(sm_cursorOn); if (comp != NULL && ::SendMessage(sm_cursorOn, WM_NCHITTEST, 0, MAKELPARAM(p.x, p.y)) == HTCLIENT) { goto found; } } ::GetCursorPos(&p); hit = ::WindowFromPoint(p); while (hit != NULL) { comp = AwtComponent::GetComponent(hit); if (comp != NULL) { INT nHittest = (INT)::SendMessage(hit, WM_NCHITTEST, 0, MAKELPARAM(p.x, p.y)); /* * Fix for BugTraq ID 4304024. * Allow a non-default cursor only for the client area. */ if (nHittest != HTCLIENT) { /* * When over the non-client area, send WM_SETCURSOR * to revert the cursor to an arrow. */ ::SendMessage(hit, WM_SETCURSOR, (WPARAM)hit, MAKELPARAM(nHittest, WM_MOUSEMOVE)); return NULL; } else { sm_cursorOn = hit; goto found; } } if ((::GetWindowLong(hit, GWL_STYLE) & WS_CHILD) == 0) { return NULL; } hit = ::GetParent(hit); } return NULL; found: jobject localRef = comp->GetTarget(env); jobject globalRef = env->NewGlobalRef(localRef); env->DeleteLocalRef(localRef); return globalRef; } void AwtComponent::SetColor(COLORREF c) { int screen = AwtWin32GraphicsDevice::DeviceIndexForWindow(GetHWnd()); int grayscale = AwtWin32GraphicsDevice::GetGrayness(screen); if (grayscale != GS_NOTGRAY) { int g; g = (int) (.299 * (c & 0xFF) + .587 * ((c >> 8) & 0xFF) + .114 * ((c >> 16) & 0xFF) + 0.5); // c = g | (g << 8) | (g << 16); c = PALETTERGB(g, g, g); } if (m_colorForeground == c) { return; } m_colorForeground = c; if (m_penForeground != NULL) { m_penForeground->Release(); m_penForeground = NULL; } VERIFY(::InvalidateRect(GetHWnd(), NULL, FALSE)); } void AwtComponent::SetBackgroundColor(COLORREF c) { int screen = AwtWin32GraphicsDevice::DeviceIndexForWindow(GetHWnd()); int grayscale = AwtWin32GraphicsDevice::GetGrayness(screen); if (grayscale != GS_NOTGRAY) { int g; g = (int) (.299 * (c & 0xFF) + .587 * ((c >> 8) & 0xFF) + .114 * ((c >> 16) & 0xFF) + 0.5); // c = g | (g << 8) | (g << 16); c = PALETTERGB(g, g, g); } if (m_colorBackground == c) { return; } m_colorBackground = c; m_backgroundColorSet = TRUE; if (m_brushBackground != NULL) { m_brushBackground->Release(); m_brushBackground = NULL; } VERIFY(::InvalidateRect(GetHWnd(), NULL, TRUE)); } HPEN AwtComponent::GetForegroundPen() { if (m_penForeground == NULL) { m_penForeground = AwtPen::Get(m_colorForeground); } return (HPEN)m_penForeground->GetHandle(); } COLORREF AwtComponent::GetBackgroundColor() { if (m_backgroundColorSet == FALSE) { AwtComponent* c = this; while ((c = c->GetParent()) != NULL) { if (c->IsBackgroundColorSet()) { return c->GetBackgroundColor(); } } } return m_colorBackground; } HBRUSH AwtComponent::GetBackgroundBrush() { if (m_backgroundColorSet == FALSE) { if (m_brushBackground != NULL) { m_brushBackground->Release(); m_brushBackground = NULL; } AwtComponent* c = this; while ((c = c->GetParent()) != NULL) { if (c->IsBackgroundColorSet()) { m_brushBackground = AwtBrush::Get(c->GetBackgroundColor()); break; } } } if (m_brushBackground == NULL) { m_brushBackground = AwtBrush::Get(m_colorBackground); } return (HBRUSH)m_brushBackground->GetHandle(); } void AwtComponent::SetFont(AwtFont* font) { DASSERT(font != NULL); if (font->GetAscent() < 0) { AwtFont::SetupAscent(font); } SendMessage(WM_SETFONT, (WPARAM)font->GetHFont(), MAKELPARAM(FALSE, 0)); VERIFY(::InvalidateRect(GetHWnd(), NULL, TRUE)); } AwtComponent* AwtComponent::GetParent() { HWND hwnd = ::GetParent(GetHWnd()); if (hwnd == NULL) { return NULL; } return GetComponent(hwnd); } AwtWindow* AwtComponent::GetContainer() { AwtComponent* comp = this; while (comp != NULL) { if (comp->IsContainer()) { return (AwtWindow*)comp; } comp = comp->GetParent(); } return NULL; } void AwtComponent::Show() { m_visible = true; ::ShowWindow(GetHWnd(), SW_SHOWNA); } void AwtComponent::Hide() { m_visible = false; ::ShowWindow(GetHWnd(), SW_HIDE); } BOOL AwtComponent::SetWindowPos(HWND wnd, HWND after, int x, int y, int w, int h, UINT flags) { // Conditions we shouldn't handle: // z-order changes, correct window dimensions if (after != NULL || (w < 32767 && h < 32767) || ((::GetWindowLong(wnd, GWL_STYLE) & WS_CHILD) == 0)) { return ::SetWindowPos(wnd, after, x, y, w, h, flags); } WINDOWPLACEMENT wp; ::ZeroMemory(&wp, sizeof(wp)); wp.length = sizeof(wp); ::GetWindowPlacement(wnd, &wp); wp.rcNormalPosition.left = x; wp.rcNormalPosition.top = y; wp.rcNormalPosition.right = x + w; wp.rcNormalPosition.bottom = y + h; if ( flags & SWP_NOACTIVATE ) { wp.showCmd = SW_SHOWNOACTIVATE; } ::SetWindowPlacement(wnd, &wp); return 1; } void AwtComponent::Reshape(int x, int y, int w, int h) { #if defined(DEBUG) RECT rc; ::GetWindowRect(GetHWnd(), &rc); ::MapWindowPoints(HWND_DESKTOP, ::GetParent(GetHWnd()), (LPPOINT)&rc, 2); DTRACE_PRINTLN4("AwtComponent::Reshape from %d, %d, %d, %d", rc.left, rc.top, rc.right-rc.left, rc.bottom-rc.top); #endif AwtWindow* container = GetContainer(); AwtComponent* parent = GetParent(); if (container != NULL && container == parent) { container->SubtractInsetPoint(x, y); } DTRACE_PRINTLN4("AwtComponent::Reshape to %d, %d, %d, %d", x, y, w, h); UINT flags = SWP_NOACTIVATE | SWP_NOZORDER; RECT r; ::GetWindowRect(GetHWnd(), &r); // if the component size is changing , don't copy window bits if (r.right - r.left != w || r.bottom - r.top != h) { flags |= SWP_NOCOPYBITS; } if (parent && _tcscmp(parent->GetClassName(), TEXT("SunAwtScrollPane")) == 0) { if (x > 0) { x = 0; } if (y > 0) { y = 0; } } if (m_hdwp != NULL) { m_hdwp = ::DeferWindowPos(m_hdwp, GetHWnd(), 0, x, y, w, h, flags); DASSERT(m_hdwp != NULL); } else { /* * Fox for 4046446 * If window has dimensions above the short int limit, ::SetWindowPos doesn't work. * We should use SetWindowPlacement instead. */ SetWindowPos(GetHWnd(), 0, x, y, w, h, flags); } } void AwtComponent::SetScrollValues(UINT bar, int min, int value, int max) { int minTmp, maxTmp; ::GetScrollRange(GetHWnd(), bar, &minTmp, &maxTmp); if (min == INT_MAX) { min = minTmp; } if (value == INT_MAX) { value = ::GetScrollPos(GetHWnd(), bar); } if (max == INT_MAX) { max = maxTmp; } if (min == max) { max++; } ::SetScrollRange(GetHWnd(), bar, min, max, FALSE); ::SetScrollPos(GetHWnd(), bar, value, TRUE); } /* * Save Global Reference of sun.awt.windows.WInputMethod object */ void AwtComponent::SetInputMethod(jobject im, BOOL useNativeCompWindow) { JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); if (m_InputMethod!=NULL) env->DeleteGlobalRef(m_InputMethod); if (im!=NULL){ m_InputMethod = env->NewGlobalRef(im); m_useNativeCompWindow = useNativeCompWindow; } else { m_InputMethod = NULL; m_useNativeCompWindow = TRUE; } } /* * Opportunity to process and/or eat a message before it is dispatched */ MsgRouting AwtComponent::PreProcessMsg(MSG& msg) { return mrPassAlong; } static UINT lastMessage = WM_NULL; #ifndef SPY_MESSAGES #define SpyWinMessage(hwin,msg,str) #else #define FMT_MSG(x,y) case x: _stprintf(szBuf, \ "0x%8.8x(%s):%s\n", hwnd, szComment, y); break; #define WIN_MSG(x) FMT_MSG(x,#x) void SpyWinMessage(HWND hwnd, UINT message, LPCTSTR szComment) { TCHAR szBuf[256]; switch (message) { WIN_MSG(WM_NULL) WIN_MSG(WM_CREATE) WIN_MSG(WM_DESTROY) WIN_MSG(WM_MOVE) WIN_MSG(WM_SIZE) WIN_MSG(WM_ACTIVATE) WIN_MSG(WM_SETFOCUS) WIN_MSG(WM_KILLFOCUS) WIN_MSG(WM_ENABLE) WIN_MSG(WM_SETREDRAW) WIN_MSG(WM_SETTEXT) WIN_MSG(WM_GETTEXT) WIN_MSG(WM_GETTEXTLENGTH) WIN_MSG(WM_PAINT) WIN_MSG(WM_CLOSE) WIN_MSG(WM_QUERYENDSESSION) WIN_MSG(WM_QUIT) WIN_MSG(WM_QUERYOPEN) WIN_MSG(WM_ERASEBKGND) WIN_MSG(WM_SYSCOLORCHANGE) WIN_MSG(WM_ENDSESSION) WIN_MSG(WM_SHOWWINDOW) FMT_MSG(WM_WININICHANGE,"WM_WININICHANGE/WM_SETTINGCHANGE") WIN_MSG(WM_DEVMODECHANGE) WIN_MSG(WM_ACTIVATEAPP) WIN_MSG(WM_FONTCHANGE) WIN_MSG(WM_TIMECHANGE) WIN_MSG(WM_CANCELMODE) WIN_MSG(WM_SETCURSOR) WIN_MSG(WM_MOUSEACTIVATE) WIN_MSG(WM_CHILDACTIVATE) WIN_MSG(WM_QUEUESYNC) WIN_MSG(WM_GETMINMAXINFO) WIN_MSG(WM_PAINTICON) WIN_MSG(WM_ICONERASEBKGND) WIN_MSG(WM_NEXTDLGCTL) WIN_MSG(WM_SPOOLERSTATUS) WIN_MSG(WM_DRAWITEM) WIN_MSG(WM_MEASUREITEM) WIN_MSG(WM_DELETEITEM) WIN_MSG(WM_VKEYTOITEM) WIN_MSG(WM_CHARTOITEM) WIN_MSG(WM_SETFONT) WIN_MSG(WM_GETFONT) WIN_MSG(WM_SETHOTKEY) WIN_MSG(WM_GETHOTKEY) WIN_MSG(WM_QUERYDRAGICON) WIN_MSG(WM_COMPAREITEM) FMT_MSG(0x003D, "WM_GETOBJECT") WIN_MSG(WM_COMPACTING) WIN_MSG(WM_COMMNOTIFY) WIN_MSG(WM_WINDOWPOSCHANGING) WIN_MSG(WM_WINDOWPOSCHANGED) WIN_MSG(WM_POWER) WIN_MSG(WM_COPYDATA) WIN_MSG(WM_CANCELJOURNAL) WIN_MSG(WM_NOTIFY) WIN_MSG(WM_INPUTLANGCHANGEREQUEST) WIN_MSG(WM_INPUTLANGCHANGE) WIN_MSG(WM_TCARD) WIN_MSG(WM_HELP) WIN_MSG(WM_USERCHANGED) WIN_MSG(WM_NOTIFYFORMAT) WIN_MSG(WM_CONTEXTMENU) WIN_MSG(WM_STYLECHANGING) WIN_MSG(WM_STYLECHANGED) WIN_MSG(WM_DISPLAYCHANGE) WIN_MSG(WM_GETICON) WIN_MSG(WM_SETICON) WIN_MSG(WM_NCCREATE) WIN_MSG(WM_NCDESTROY) WIN_MSG(WM_NCCALCSIZE) WIN_MSG(WM_NCHITTEST) WIN_MSG(WM_NCPAINT) WIN_MSG(WM_NCACTIVATE) WIN_MSG(WM_GETDLGCODE) WIN_MSG(WM_SYNCPAINT) WIN_MSG(WM_NCMOUSEMOVE) WIN_MSG(WM_NCLBUTTONDOWN) WIN_MSG(WM_NCLBUTTONUP) WIN_MSG(WM_NCLBUTTONDBLCLK) WIN_MSG(WM_NCRBUTTONDOWN) WIN_MSG(WM_NCRBUTTONUP) WIN_MSG(WM_NCRBUTTONDBLCLK) WIN_MSG(WM_NCMBUTTONDOWN) WIN_MSG(WM_NCMBUTTONUP) WIN_MSG(WM_NCMBUTTONDBLCLK) WIN_MSG(WM_KEYDOWN) WIN_MSG(WM_KEYUP) WIN_MSG(WM_CHAR) WIN_MSG(WM_DEADCHAR) WIN_MSG(WM_SYSKEYDOWN) WIN_MSG(WM_SYSKEYUP) WIN_MSG(WM_SYSCHAR) WIN_MSG(WM_SYSDEADCHAR) WIN_MSG(WM_IME_STARTCOMPOSITION) WIN_MSG(WM_IME_ENDCOMPOSITION) WIN_MSG(WM_IME_COMPOSITION) WIN_MSG(WM_INITDIALOG) WIN_MSG(WM_COMMAND) WIN_MSG(WM_SYSCOMMAND) WIN_MSG(WM_TIMER) WIN_MSG(WM_HSCROLL) WIN_MSG(WM_VSCROLL) WIN_MSG(WM_INITMENU) WIN_MSG(WM_INITMENUPOPUP) WIN_MSG(WM_MENUSELECT) WIN_MSG(WM_MENUCHAR) WIN_MSG(WM_ENTERIDLE) FMT_MSG(0x0122, "WM_MENURBUTTONUP") FMT_MSG(0x0123, "WM_MENUDRAG") FMT_MSG(0x0124, "WM_MENUGETOBJECT") FMT_MSG(0x0125, "WM_UNINITMENUPOPUP") FMT_MSG(0x0126, "WM_MENUCOMMAND") WIN_MSG(WM_CTLCOLORMSGBOX) WIN_MSG(WM_CTLCOLOREDIT) WIN_MSG(WM_CTLCOLORLISTBOX) WIN_MSG(WM_CTLCOLORBTN) WIN_MSG(WM_CTLCOLORDLG) WIN_MSG(WM_CTLCOLORSCROLLBAR) WIN_MSG(WM_CTLCOLORSTATIC) WIN_MSG(WM_MOUSEMOVE) WIN_MSG(WM_LBUTTONDOWN) WIN_MSG(WM_LBUTTONUP) WIN_MSG(WM_LBUTTONDBLCLK) WIN_MSG(WM_RBUTTONDOWN) WIN_MSG(WM_RBUTTONUP) WIN_MSG(WM_RBUTTONDBLCLK) WIN_MSG(WM_MBUTTONDOWN) WIN_MSG(WM_MBUTTONUP) WIN_MSG(WM_MBUTTONDBLCLK) WIN_MSG(WM_XBUTTONDBLCLK) WIN_MSG(WM_XBUTTONDOWN) WIN_MSG(WM_XBUTTONUP) WIN_MSG(WM_MOUSEWHEEL) WIN_MSG(WM_PARENTNOTIFY) WIN_MSG(WM_ENTERMENULOOP) WIN_MSG(WM_EXITMENULOOP) WIN_MSG(WM_NEXTMENU) WIN_MSG(WM_SIZING) WIN_MSG(WM_CAPTURECHANGED) WIN_MSG(WM_MOVING) WIN_MSG(WM_POWERBROADCAST) WIN_MSG(WM_DEVICECHANGE) WIN_MSG(WM_MDICREATE) WIN_MSG(WM_MDIDESTROY) WIN_MSG(WM_MDIACTIVATE) WIN_MSG(WM_MDIRESTORE) WIN_MSG(WM_MDINEXT) WIN_MSG(WM_MDIMAXIMIZE) WIN_MSG(WM_MDITILE) WIN_MSG(WM_MDICASCADE) WIN_MSG(WM_MDIICONARRANGE) WIN_MSG(WM_MDIGETACTIVE) WIN_MSG(WM_MDISETMENU) WIN_MSG(WM_ENTERSIZEMOVE) WIN_MSG(WM_EXITSIZEMOVE) WIN_MSG(WM_DROPFILES) WIN_MSG(WM_MDIREFRESHMENU) WIN_MSG(WM_IME_SETCONTEXT) WIN_MSG(WM_IME_NOTIFY) WIN_MSG(WM_IME_CONTROL) WIN_MSG(WM_IME_COMPOSITIONFULL) WIN_MSG(WM_IME_SELECT) WIN_MSG(WM_IME_CHAR) FMT_MSG(WM_IME_REQUEST) WIN_MSG(WM_IME_KEYDOWN) WIN_MSG(WM_IME_KEYUP) FMT_MSG(0x02A1, "WM_MOUSEHOVER") FMT_MSG(0x02A3, "WM_MOUSELEAVE") WIN_MSG(WM_CUT) WIN_MSG(WM_COPY) WIN_MSG(WM_PASTE) WIN_MSG(WM_CLEAR) WIN_MSG(WM_UNDO) WIN_MSG(WM_RENDERFORMAT) WIN_MSG(WM_RENDERALLFORMATS) WIN_MSG(WM_DESTROYCLIPBOARD) WIN_MSG(WM_DRAWCLIPBOARD) WIN_MSG(WM_PAINTCLIPBOARD) WIN_MSG(WM_VSCROLLCLIPBOARD) WIN_MSG(WM_SIZECLIPBOARD) WIN_MSG(WM_ASKCBFORMATNAME) WIN_MSG(WM_CHANGECBCHAIN) WIN_MSG(WM_HSCROLLCLIPBOARD) WIN_MSG(WM_QUERYNEWPALETTE) WIN_MSG(WM_PALETTEISCHANGING) WIN_MSG(WM_PALETTECHANGED) WIN_MSG(WM_HOTKEY) WIN_MSG(WM_PRINT) WIN_MSG(WM_PRINTCLIENT) WIN_MSG(WM_HANDHELDFIRST) WIN_MSG(WM_HANDHELDLAST) WIN_MSG(WM_AFXFIRST) WIN_MSG(WM_AFXLAST) WIN_MSG(WM_PENWINFIRST) WIN_MSG(WM_PENWINLAST) WIN_MSG(WM_AWT_COMPONENT_CREATE) WIN_MSG(WM_AWT_DESTROY_WINDOW) WIN_MSG(WM_AWT_MOUSEENTER) WIN_MSG(WM_AWT_MOUSEEXIT) WIN_MSG(WM_AWT_COMPONENT_SHOW) WIN_MSG(WM_AWT_COMPONENT_HIDE) WIN_MSG(WM_AWT_COMPONENT_SETFOCUS) WIN_MSG(WM_AWT_WINDOW_SETACTIVE) WIN_MSG(WM_AWT_LIST_SETMULTISELECT) WIN_MSG(WM_AWT_HANDLE_EVENT) WIN_MSG(WM_AWT_PRINT_COMPONENT) WIN_MSG(WM_AWT_RESHAPE_COMPONENT) WIN_MSG(WM_AWT_SETALWAYSONTOP) WIN_MSG(WM_AWT_BEGIN_VALIDATE) WIN_MSG(WM_AWT_END_VALIDATE) WIN_MSG(WM_AWT_FORWARD_CHAR) WIN_MSG(WM_AWT_FORWARD_BYTE) WIN_MSG(WM_AWT_SET_SCROLL_INFO) WIN_MSG(WM_AWT_CREATECONTEXT) WIN_MSG(WM_AWT_DESTROYCONTEXT) WIN_MSG(WM_AWT_ASSOCIATECONTEXT) WIN_MSG(WM_AWT_GET_DEFAULT_IME_HANDLER) WIN_MSG(WM_AWT_HANDLE_NATIVE_IME_EVENT) WIN_MSG(WM_AWT_PRE_KEYDOWN) WIN_MSG(WM_AWT_PRE_KEYUP) WIN_MSG(WM_AWT_PRE_SYSKEYDOWN) WIN_MSG(WM_AWT_PRE_SYSKEYUP) WIN_MSG(WM_AWT_ENDCOMPOSITION,) WIN_MSG(WM_AWT_DISPOSE,) WIN_MSG(WM_AWT_DELETEOBJECT,) WIN_MSG(WM_AWT_SETCONVERSIONSTATUS,) WIN_MSG(WM_AWT_GETCONVERSIONSTATUS,) WIN_MSG(WM_AWT_SETOPENSTATUS,) WIN_MSG(WM_AWT_GETOPENSTATUS) WIN_MSG(WM_AWT_ACTIVATEKEYBOARDLAYOUT) WIN_MSG(WM_AWT_OPENCANDIDATEWINDOW) WIN_MSG(WM_AWT_DLG_SHOWMODAL,) WIN_MSG(WM_AWT_DLG_ENDMODAL,) WIN_MSG(WM_AWT_SETCURSOR,) WIN_MSG(WM_AWT_WAIT_FOR_SINGLE_OBJECT,) WIN_MSG(WM_AWT_INVOKE_METHOD,) WIN_MSG(WM_AWT_INVOKE_VOID_METHOD,) WIN_MSG(WM_AWT_EXECUTE_SYNC,) WIN_MSG(WM_AWT_CURSOR_SYNC) WIN_MSG(WM_AWT_GETDC) WIN_MSG(WM_AWT_RELEASEDC) WIN_MSG(WM_AWT_RELEASE_ALL_DCS) WIN_MSG(WM_AWT_SHOWCURSOR) WIN_MSG(WM_AWT_HIDECURSOR) WIN_MSG(WM_AWT_CREATE_PRINTED_PIXELS) WIN_MSG(WM_AWT_OBJECTLISTCLEANUP) default: sprintf(szBuf, "0x%8.8x(%s):Unknown message 0x%8.8x\n", hwnd, szComment, message); break; } printf(szBuf); } #endif /* SPY_MESSAGES */ /* * Dispatch messages for this window class--general component */ LRESULT AwtComponent::WindowProc(UINT message, WPARAM wParam, LPARAM lParam) { CounterHelper ch(&m_MessagesProcessing); JNILocalFrame lframe(AwtToolkit::GetEnv(), 10); SpyWinMessage(GetHWnd(), message, (message == WM_AWT_RELEASE_ALL_DCS) ? TEXT("Disposed Component") : GetClassName()); LRESULT retValue = 0; MsgRouting mr = mrDoDefault; AwtToolkit::GetInstance().eventNumber++; static BOOL ignoreNextLBTNUP = FALSE; //Ignore next LBUTTONUP msg? lastMessage = message; if (message == WmAwtIsComponent) { // special message to identify AWT HWND's without using // resource hogging ::SetProp return (LRESULT)TRUE; } DWORD curPos = 0; UINT switchMessage = message; switch (switchMessage) { case WM_AWT_GETDC: { HDC hDC; // First, release the DCs scheduled for deletion ReleaseDCList(GetHWnd(), passiveDCList); GetDCReturnStruct *returnStruct = new GetDCReturnStruct; returnStruct->gdiLimitReached = FALSE; if (AwtGDIObject::IncrementIfAvailable()) { hDC = ::GetDCEx(GetHWnd(), NULL, DCX_CACHE | DCX_CLIPCHILDREN | DCX_CLIPSIBLINGS); if (hDC != NULL) { // Add new DC to list of DC's associated with this Component activeDCList.AddDC(hDC, GetHWnd()); } else { // Creation failed; decrement counter in AwtGDIObject AwtGDIObject::Decrement(); } } else { hDC = NULL; returnStruct->gdiLimitReached = TRUE; } returnStruct->hDC = hDC; retValue = (LRESULT)returnStruct; mr = mrConsume; break; } case WM_AWT_RELEASEDC: { HDC hDC = (HDC)wParam; MoveDCToPassiveList(hDC); ReleaseDCList(GetHWnd(), passiveDCList); mr = mrConsume; break; } case WM_AWT_RELEASE_ALL_DCS: { // Called during Component destruction. Gets current list of // DC's associated with Component and releases each DC. ReleaseDCList(GetHWnd(), activeDCList); ReleaseDCList(GetHWnd(), passiveDCList); mr = mrConsume; break; } case WM_AWT_SHOWCURSOR: ::ShowCursor(TRUE); break; case WM_AWT_HIDECURSOR: ::ShowCursor(FALSE); break; case WM_CREATE: mr = WmCreate(); break; case WM_CLOSE: mr = WmClose(); break; case WM_DESTROY: mr = WmDestroy(); break; case WM_ERASEBKGND: mr = WmEraseBkgnd((HDC)wParam, *(BOOL*)&retValue); break; case WM_PAINT: CheckFontSmoothingSettings(GetHWnd()); /* Set draw state */ SetDrawState(GetDrawState() | JAWT_LOCK_CLIP_CHANGED); mr = WmPaint((HDC)wParam); break; case WM_GETMINMAXINFO: mr = WmGetMinMaxInfo((LPMINMAXINFO)lParam); break; case WM_WINDOWPOSCHANGING: { // We process this message so that we can synchronize access to // a moving window. The Scale/Blt functions in Win32BlitLoops // take the same windowMoveLock to ensure that a window is not // moving while we are trying to copy pixels into it. WINDOWPOS *lpPosInfo = (WINDOWPOS *)lParam; if ((lpPosInfo->flags & (SWP_NOMOVE | SWP_NOSIZE)) != (SWP_NOMOVE | SWP_NOSIZE)) { // Move or Size command. // Windows tends to send erroneous events that the window // is about to move when the coordinates are exactly the // same as the last time. This can cause problems with // our windowMoveLock CriticalSection because we enter it // here and never get to WM_WINDOWPOSCHANGED to release it. // So make sure this is a real move/size event before bothering // to grab the critical section. BOOL takeLock = FALSE; if (!(lpPosInfo->flags & SWP_NOMOVE) && ((windowMoveLockPosX != lpPosInfo->x) || (windowMoveLockPosY != lpPosInfo->y))) { // Real move event takeLock = TRUE; windowMoveLockPosX = lpPosInfo->x; windowMoveLockPosY = lpPosInfo->y; } if (!(lpPosInfo->flags & SWP_NOSIZE) && ((windowMoveLockPosCX != lpPosInfo->cx) || (windowMoveLockPosCY != lpPosInfo->cy))) { // Real size event takeLock = TRUE; windowMoveLockPosCX = lpPosInfo->cx; windowMoveLockPosCY = lpPosInfo->cy; } if (takeLock) { if (!windowMoveLockHeld) { windowMoveLock.Enter(); windowMoveLockHeld = TRUE; } } } mr = WmWindowPosChanging(lParam); break; } case WM_WINDOWPOSCHANGED: { // Release lock grabbed in the POSCHANGING message if (windowMoveLockHeld) { windowMoveLockHeld = FALSE; windowMoveLock.Leave(); } mr = WmWindowPosChanged(lParam); break; } case WM_MOVE: { RECT r; ::GetWindowRect(GetHWnd(), &r); mr = WmMove(r.left, r.top); break; } case WM_SIZE: { RECT r; // fix 4128317 : use GetClientRect for full 32-bit int precision and // to avoid negative client area dimensions overflowing 16-bit params - robi ::GetClientRect( GetHWnd(), &r ); mr = WmSize(static_cast<UINT>(wParam), r.right - r.left, r.bottom - r.top); //mr = WmSize(wParam, LOWORD(lParam), HIWORD(lParam)); if (ImmGetContext() != NULL) { SetCompositionWindow(r); } break; } case WM_SIZING: mr = WmSizing(); break; case WM_SHOWWINDOW: mr = WmShowWindow(static_cast<BOOL>(wParam), static_cast<UINT>(lParam)); break; case WM_SYSCOMMAND: mr = WmSysCommand(static_cast<UINT>(wParam & 0xFFF0), GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)); break; case WM_EXITSIZEMOVE: mr = WmExitSizeMove(); break; // Bug #4039858 (Selecting menu item causes bogus mouse click event) case WM_ENTERMENULOOP: mr = WmEnterMenuLoop((BOOL)wParam); sm_bMenuLoop = TRUE; // we need to release grab if menu is shown if (AwtWindow::GetGrabbedWindow() != NULL) { AwtWindow::GetGrabbedWindow()->Ungrab(); } break; case WM_EXITMENULOOP: mr = WmExitMenuLoop((BOOL)wParam); sm_bMenuLoop = FALSE; break; // We don't expect any focus messages on non-proxy component, // except those that came from Java. case WM_SETFOCUS: if (sm_inSynthesizeFocus) { mr = WmSetFocus((HWND)wParam); } else { mr = mrConsume; } break; case WM_KILLFOCUS: if (sm_inSynthesizeFocus) { mr = WmKillFocus((HWND)wParam); } else { mr = mrConsume; } break; case WM_ACTIVATE: { UINT nState = LOWORD(wParam); BOOL fMinimized = (BOOL)HIWORD(wParam); mr = mrConsume; if (!sm_suppressFocusAndActivation && (!fMinimized || (nState == WA_INACTIVE))) { mr = WmActivate(nState, fMinimized, (HWND)lParam); // When the window is deactivated, send WM_IME_ENDCOMPOSITION // message to deactivate the composition window so that // it won't receive keyboard input focus. if (ImmGetContext() != NULL) { DefWindowProc(WM_IME_ENDCOMPOSITION, 0, 0); } } break; } case WM_MOUSEACTIVATE: { AwtWindow *window = GetContainer(); if (window && window->IsFocusableWindow()) { // AWT/Swing will later request focus to a proper component // on handling the Java mouse event. Anyway, we have to // activate the window here as it works both for AWT & Swing. // Do it in our own fassion, window->AwtSetActiveWindow(TRUE, LOWORD(lParam)/*hittest*/); } mr = mrConsume; retValue = MA_NOACTIVATE; break; } case WM_CTLCOLORMSGBOX: case WM_CTLCOLOREDIT: case WM_CTLCOLORLISTBOX: case WM_CTLCOLORBTN: case WM_CTLCOLORDLG: case WM_CTLCOLORSCROLLBAR: case WM_CTLCOLORSTATIC: mr = WmCtlColor((HDC)wParam, (HWND)lParam, message-WM_CTLCOLORMSGBOX+CTLCOLOR_MSGBOX, *(HBRUSH*)&retValue); break; case WM_HSCROLL: mr = WmHScroll(LOWORD(wParam), HIWORD(wParam), (HWND)lParam); break; case WM_VSCROLL: mr = WmVScroll(LOWORD(wParam), HIWORD(wParam), (HWND)lParam); break; // 4664415: We're seeing a WM_LBUTTONUP when the user releases the // mouse button after a WM_NCLBUTTONDBLCLK. We want to ignore this // WM_LBUTTONUP, so we set a flag in WM_NCLBUTTONDBLCLK and look for the // flag on a WM_LBUTTONUP. -bchristi case WM_NCLBUTTONDBLCLK: mr = WmNcMouseDown(wParam, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam), LEFT_BUTTON | DBL_CLICK); if (mr == mrDoDefault) { ignoreNextLBTNUP = TRUE; } break; case WM_NCLBUTTONDOWN: mr = WmNcMouseDown(wParam, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam), LEFT_BUTTON); ignoreNextLBTNUP = FALSE; break; case WM_NCLBUTTONUP: mr = WmNcMouseUp(wParam, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam), LEFT_BUTTON); break; case WM_NCRBUTTONDOWN: mr = WmNcMouseDown(wParam, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam), RIGHT_BUTTON); break; case WM_LBUTTONUP: if (ignoreNextLBTNUP) { ignoreNextLBTNUP = FALSE; return mrDoDefault; } //fall-through case WM_LBUTTONDOWN: ignoreNextLBTNUP = FALSE; //fall-through case WM_LBUTTONDBLCLK: case WM_RBUTTONDOWN: case WM_RBUTTONDBLCLK: case WM_RBUTTONUP: case WM_MBUTTONDOWN: case WM_MBUTTONDBLCLK: case WM_MBUTTONUP: case WM_XBUTTONDBLCLK: case WM_XBUTTONDOWN: case WM_XBUTTONUP: case WM_MOUSEMOVE: case WM_MOUSEWHEEL: case WM_AWT_MOUSEENTER: case WM_AWT_MOUSEEXIT: curPos = ::GetMessagePos(); POINT myPos; myPos.x = GET_X_LPARAM(curPos); myPos.y = GET_Y_LPARAM(curPos); ::ScreenToClient(GetHWnd(), &myPos); switch(switchMessage) { case WM_AWT_MOUSEENTER: mr = WmMouseEnter(static_cast<UINT>(wParam), myPos.x, myPos.y); break; case WM_LBUTTONDOWN: case WM_LBUTTONDBLCLK: mr = WmMouseDown(static_cast<UINT>(wParam), myPos.x, myPos.y, LEFT_BUTTON); break; case WM_LBUTTONUP: mr = WmMouseUp(static_cast<UINT>(wParam), myPos.x, myPos.y, LEFT_BUTTON); break; case WM_MOUSEMOVE: mr = WmMouseMove(static_cast<UINT>(wParam), myPos.x, myPos.y); break; case WM_MBUTTONDOWN: case WM_MBUTTONDBLCLK: mr = WmMouseDown(static_cast<UINT>(wParam), myPos.x, myPos.y, MIDDLE_BUTTON); break; case WM_XBUTTONDOWN: case WM_XBUTTONDBLCLK: if (AwtToolkit::GetInstance().areExtraMouseButtonsEnabled()) { if (HIWORD(wParam) == 1) { mr = WmMouseDown(static_cast<UINT>(wParam), myPos.x, myPos.y, X1_BUTTON); } if (HIWORD(wParam) == 2) { mr = WmMouseDown(static_cast<UINT>(wParam), myPos.x, myPos.y, X2_BUTTON); } } break; case WM_XBUTTONUP: if (AwtToolkit::GetInstance().areExtraMouseButtonsEnabled()) { if (HIWORD(wParam) == 1) { mr = WmMouseUp(static_cast<UINT>(wParam), myPos.x, myPos.y, X1_BUTTON); } if (HIWORD(wParam) == 2) { mr = WmMouseUp(static_cast<UINT>(wParam), myPos.x, myPos.y, X2_BUTTON); } } break; case WM_RBUTTONDOWN: case WM_RBUTTONDBLCLK: mr = WmMouseDown(static_cast<UINT>(wParam), myPos.x, myPos.y, RIGHT_BUTTON); break; case WM_RBUTTONUP: mr = WmMouseUp(static_cast<UINT>(wParam), myPos.x, myPos.y, RIGHT_BUTTON); break; case WM_MBUTTONUP: mr = WmMouseUp(static_cast<UINT>(wParam), myPos.x, myPos.y, MIDDLE_BUTTON); break; case WM_AWT_MOUSEEXIT: mr = WmMouseExit(static_cast<UINT>(wParam), myPos.x, myPos.y); break; case WM_MOUSEWHEEL: mr = WmMouseWheel(GET_KEYSTATE_WPARAM(wParam), GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam), GET_WHEEL_DELTA_WPARAM(wParam)); break; } break; case WM_SETCURSOR: mr = mrDoDefault; if (LOWORD(lParam) == HTCLIENT) { if (AwtComponent* comp = AwtComponent::GetComponent((HWND)wParam)) { AwtCursor::UpdateCursor(comp); mr = mrConsume; } } break; case WM_KEYDOWN: mr = WmKeyDown(static_cast<UINT>(wParam), LOWORD(lParam), HIWORD(lParam), FALSE); break; case WM_KEYUP: mr = WmKeyUp(static_cast<UINT>(wParam), LOWORD(lParam), HIWORD(lParam), FALSE); break; case WM_SYSKEYDOWN: mr = WmKeyDown(static_cast<UINT>(wParam), LOWORD(lParam), HIWORD(lParam), TRUE); break; case WM_SYSKEYUP: mr = WmKeyUp(static_cast<UINT>(wParam), LOWORD(lParam), HIWORD(lParam), TRUE); break; case WM_IME_SETCONTEXT: // lParam is passed as pointer and it can be modified. mr = WmImeSetContext(static_cast<BOOL>(wParam), &lParam); CallProxyDefWindowProc(message, wParam, lParam, retValue, mr); break; case WM_IME_NOTIFY: mr = WmImeNotify(wParam, lParam); CallProxyDefWindowProc(message, wParam, lParam, retValue, mr); break; case WM_IME_STARTCOMPOSITION: mr = WmImeStartComposition(); CallProxyDefWindowProc(message, wParam, lParam, retValue, mr); break; case WM_IME_ENDCOMPOSITION: mr = WmImeEndComposition(); CallProxyDefWindowProc(message, wParam, lParam, retValue, mr); break; case WM_IME_COMPOSITION: { WORD dbcschar = static_cast<WORD>(wParam); mr = WmImeComposition(dbcschar, lParam); CallProxyDefWindowProc(message, wParam, lParam, retValue, mr); break; } case WM_IME_CONTROL: case WM_IME_COMPOSITIONFULL: case WM_IME_SELECT: case WM_IME_KEYUP: case WM_IME_KEYDOWN: case WM_IME_REQUEST: CallProxyDefWindowProc(message, wParam, lParam, retValue, mr); break; case WM_CHAR: mr = WmChar(static_cast<UINT>(wParam), LOWORD(lParam), HIWORD(lParam), FALSE); break; case WM_SYSCHAR: mr = WmChar(static_cast<UINT>(wParam), LOWORD(lParam), HIWORD(lParam), TRUE); break; case WM_IME_CHAR: mr = WmIMEChar(static_cast<UINT>(wParam), LOWORD(lParam), HIWORD(lParam), FALSE); break; case WM_INPUTLANGCHANGEREQUEST: { DTRACE_PRINTLN4("WM_INPUTLANGCHANGEREQUEST: hwnd = 0x%X (%s);"// "0x%08X -> 0x%08X", GetHWnd(), GetClassName(), (UINT_PTR)GetKeyboardLayout(), (UINT_PTR)lParam); // 4267428: make sure keyboard layout is turned undead. static BYTE keyboardState[AwtToolkit::KB_STATE_SIZE]; AwtToolkit::GetKeyboardState(keyboardState); WORD ignored; ::ToAsciiEx(VK_SPACE, ::MapVirtualKey(VK_SPACE, 0), keyboardState, &ignored, 0, GetKeyboardLayout()); // Set this flag to block ActivateKeyboardLayout from // WInputMethod.activate() g_bUserHasChangedInputLang = TRUE; CallProxyDefWindowProc(message, wParam, lParam, retValue, mr); break; } case WM_INPUTLANGCHANGE: DTRACE_PRINTLN3("WM_INPUTLANGCHANGE: hwnd = 0x%X (%s);"// "new = 0x%08X", GetHWnd(), GetClassName(), (UINT)lParam); mr = WmInputLangChange(static_cast<UINT>(wParam), reinterpret_cast<HKL>(lParam)); CallProxyDefWindowProc(message, wParam, lParam, retValue, mr); // should return non-zero if we process this message retValue = 1; break; case WM_AWT_FORWARD_CHAR: mr = WmForwardChar(LOWORD(wParam), lParam, HIWORD(wParam)); break; case WM_AWT_FORWARD_BYTE: mr = HandleEvent( (MSG *) lParam, (BOOL) wParam); break; case WM_PASTE: mr = WmPaste(); break; case WM_TIMER: mr = WmTimer(wParam); break; case WM_COMMAND: mr = WmCommand(LOWORD(wParam), (HWND)lParam, HIWORD(wParam)); break; case WM_COMPAREITEM: mr = WmCompareItem(static_cast<UINT>(wParam), *(COMPAREITEMSTRUCT*)lParam, retValue); break; case WM_DELETEITEM: mr = WmDeleteItem(static_cast<UINT>(wParam), *(DELETEITEMSTRUCT*)lParam); break; case WM_DRAWITEM: mr = WmDrawItem(static_cast<UINT>(wParam), *(DRAWITEMSTRUCT*)lParam); break; case WM_MEASUREITEM: mr = WmMeasureItem(static_cast<UINT>(wParam), *(MEASUREITEMSTRUCT*)lParam); break; case WM_AWT_HANDLE_EVENT: mr = HandleEvent( (MSG *) lParam, (BOOL) wParam); break; case WM_PRINT: mr = WmPrint((HDC)wParam, lParam); break; case WM_PRINTCLIENT: mr = WmPrintClient((HDC)wParam, lParam); break; case WM_NCCALCSIZE: mr = WmNcCalcSize((BOOL)wParam, (LPNCCALCSIZE_PARAMS)lParam, retValue); break; case WM_NCPAINT: mr = WmNcPaint((HRGN)wParam); break; case WM_NCHITTEST: mr = WmNcHitTest(LOWORD(lParam), HIWORD(lParam), retValue); break; case WM_AWT_RESHAPE_COMPONENT: { RECT* r = (RECT*)lParam; WPARAM checkEmbedded = wParam; if (checkEmbedded == CHECK_EMBEDDED && IsEmbeddedFrame()) { ::OffsetRect(r, -r->left, -r->top); } Reshape(r->left, r->top, r->right - r->left, r->bottom - r->top); delete r; mr = mrConsume; break; } case WM_AWT_SETALWAYSONTOP: { AwtWindow* w = (AwtWindow*)lParam; BOOL value = (BOOL)wParam; UINT flags = SWP_NOMOVE | SWP_NOSIZE; // transient windows shouldn't change the owner window's position in the z-order if (w->IsRetainingHierarchyZOrder()) { flags |= SWP_NOOWNERZORDER; } ::SetWindowPos(w->GetHWnd(), (value != 0 ? HWND_TOPMOST : HWND_NOTOPMOST), 0,0,0,0, flags); break; } case WM_AWT_BEGIN_VALIDATE: BeginValidate(); mr = mrConsume; break; case WM_AWT_END_VALIDATE: EndValidate(); mr = mrConsume; break; case WM_PALETTEISCHANGING: mr = WmPaletteIsChanging((HWND)wParam); mr = mrDoDefault; break; case WM_QUERYNEWPALETTE: mr = WmQueryNewPalette(retValue); break; case WM_PALETTECHANGED: mr = WmPaletteChanged((HWND)wParam); break; case WM_STYLECHANGED: mr = WmStyleChanged(static_cast<int>(wParam), (LPSTYLESTRUCT)lParam); break; case WM_SETTINGCHANGE: CheckFontSmoothingSettings(NULL); mr = WmSettingChange(static_cast<UINT>(wParam), (LPCTSTR)lParam); break; case WM_CONTEXTMENU: mr = WmContextMenu((HWND)wParam, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)); break; /* * These messages are used to route Win32 calls to the * creating thread, since these calls fail unless executed * there. */ case WM_AWT_COMPONENT_SHOW: Show(); mr = mrConsume; break; case WM_AWT_COMPONENT_HIDE: Hide(); mr = mrConsume; break; case WM_AWT_COMPONENT_SETFOCUS: if ((BOOL)wParam) { retValue = SynthesizeWmSetFocus(GetHWnd(), NULL); } else { retValue = SynthesizeWmKillFocus(GetHWnd(), NULL); } mr = mrConsume; break; case WM_AWT_WINDOW_SETACTIVE: retValue = (LRESULT)((AwtWindow*)this)->AwtSetActiveWindow((BOOL)wParam); mr = mrConsume; break; case WM_AWT_SET_SCROLL_INFO: { SCROLLINFO *si = (SCROLLINFO *) lParam; ::SetScrollInfo(GetHWnd(), (int) wParam, si, TRUE); delete si; mr = mrConsume; break; } case WM_AWT_CREATE_PRINTED_PIXELS: { CreatePrintedPixelsStruct* cpps = (CreatePrintedPixelsStruct*)wParam; SIZE loc = { cpps->srcx, cpps->srcy }; SIZE size = { cpps->srcw, cpps->srch }; retValue = (LRESULT)CreatePrintedPixels(loc, size, cpps->alpha); mr = mrConsume; break; } case WM_UNDOCUMENTED_CLICKMENUBAR: { if (::IsWindow(AwtWindow::GetModalBlocker(GetHWnd()))) { mr = mrConsume; } } } /* * If not a specific Consume, it was a specific DoDefault, or a * PassAlong (since the default is the next in chain), then call the * default proc. */ if (mr != mrConsume) { retValue = DefWindowProc(message, wParam, lParam); } return retValue; } /* * Call this instance's default window proc, or if none set, call the stock * Window's one. */ LRESULT AwtComponent::DefWindowProc(UINT msg, WPARAM wParam, LPARAM lParam) { return ComCtl32Util::GetInstance().DefWindowProc(m_DefWindowProc, GetHWnd(), msg, wParam, lParam); } /* * This message should only be received when a window is destroyed by * Windows, and not Java. Window termination has been reworked so * this method should never be called during termination. */ MsgRouting AwtComponent::WmDestroy() { // fix for 6259348: we should enter the SyncCall critical section before // disposing the native object, that is value 1 of lParam is intended for if(m_peerObject != NULL) { // is not being terminating AwtToolkit::GetInstance().SendMessage(WM_AWT_DISPOSE, (WPARAM)m_peerObject, (LPARAM)1); } return mrConsume; } MsgRouting AwtComponent::WmGetMinMaxInfo(LPMINMAXINFO lpmmi) { return mrDoDefault; } MsgRouting AwtComponent::WmMove(int x, int y) { SetDrawState(GetDrawState() | static_cast<jint>(JAWT_LOCK_BOUNDS_CHANGED) | static_cast<jint>(JAWT_LOCK_CLIP_CHANGED)); return mrDoDefault; } MsgRouting AwtComponent::WmSize(UINT type, int w, int h) { SetDrawState(GetDrawState() | static_cast<jint>(JAWT_LOCK_BOUNDS_CHANGED) | static_cast<jint>(JAWT_LOCK_CLIP_CHANGED)); return mrDoDefault; } MsgRouting AwtComponent::WmSizing() { return mrDoDefault; } MsgRouting AwtComponent::WmSysCommand(UINT uCmdType, int xPos, int yPos) { return mrDoDefault; } MsgRouting AwtComponent::WmExitSizeMove() { return mrDoDefault; } MsgRouting AwtComponent::WmEnterMenuLoop(BOOL isTrackPopupMenu) { return mrDoDefault; } MsgRouting AwtComponent::WmExitMenuLoop(BOOL isTrackPopupMenu) { return mrDoDefault; } MsgRouting AwtComponent::WmShowWindow(BOOL show, UINT status) { return mrDoDefault; } MsgRouting AwtComponent::WmSetFocus(HWND hWndLostFocus) { m_wheelRotationAmount = 0; return mrDoDefault; } MsgRouting AwtComponent::WmKillFocus(HWND hWndGotFocus) { m_wheelRotationAmount = 0; return mrDoDefault; } MsgRouting AwtComponent::WmCtlColor(HDC hDC, HWND hCtrl, UINT ctlColor, HBRUSH& retBrush) { AwtComponent* child = AwtComponent::GetComponent(hCtrl); if (child) { ::SetBkColor(hDC, child->GetBackgroundColor()); ::SetTextColor(hDC, child->GetColor()); retBrush = child->GetBackgroundBrush(); return mrConsume; } return mrDoDefault; /* switch (ctlColor) { case CTLCOLOR_MSGBOX: case CTLCOLOR_EDIT: case CTLCOLOR_LISTBOX: case CTLCOLOR_BTN: case CTLCOLOR_DLG: case CTLCOLOR_SCROLLBAR: case CTLCOLOR_STATIC: } */ } MsgRouting AwtComponent::WmHScroll(UINT scrollCode, UINT pos, HWND hScrollbar) { if (hScrollbar && hScrollbar != GetHWnd()) { /* the last test should never happen */ AwtComponent* sb = GetComponent(hScrollbar); if (sb) { sb->WmHScroll(scrollCode, pos, hScrollbar); } } return mrDoDefault; } MsgRouting AwtComponent::WmVScroll(UINT scrollCode, UINT pos, HWND hScrollbar) { if (hScrollbar && hScrollbar != GetHWnd()) { /* the last test should never happen */ AwtComponent* sb = GetComponent(hScrollbar); if (sb) { sb->WmVScroll(scrollCode, pos, hScrollbar); } } return mrDoDefault; } namespace TimeHelper { // Sometimes the message belongs to another event queue and // GetMessageTime() may return wrong non-zero value (the case is // the TrayIcon peer). Using TimeHelper::windowsToUTC(::GetTickCount()) // could help there. static DWORD getMessageTimeWindows(){ DWORD time = ::GetMessageTime(); // The following 'if' seems to be a unneeded hack. // Consider removing it. if (time == 0) { time = ::GetTickCount(); } return time; } jlong getMessageTimeUTC() { return windowsToUTC(getMessageTimeWindows()); } // If calling order of GetTickCount and JVM_CurrentTimeMillis // is swapped, it would sometimes give different result. // Anyway, we would not always have determinism // and sortedness of time conversion here (due to Windows's // timers peculiarities). Having some euristic algorithm might // help here. jlong windowsToUTC(DWORD windowsTime) { jlong offset = ::GetTickCount() - windowsTime; jlong jvm_time = ::JVM_CurrentTimeMillis(NULL, 0); return jvm_time - offset; } } //TimeHelper MsgRouting AwtComponent::WmPaint(HDC) { /* Get the rectangle that covers all update regions, if any exist. */ RECT r; if (::GetUpdateRect(GetHWnd(), &r, FALSE)) { if ((r.right-r.left) > 0 && (r.bottom-r.top) > 0 && m_peerObject != NULL && m_callbacksEnabled) { /* * Always call handlePaint, because the underlying control * will have painted itself (the "background") before any * paint method is called. */ DoCallback("handlePaint", "(IIII)V", r.left, r.top, r.right-r.left, r.bottom-r.top); } } return mrDoDefault; } void AwtComponent::PaintUpdateRgn(const RECT *insets) { // Fix 4530093: Don't Validate if can't actually paint if (m_peerObject == NULL || !m_callbacksEnabled) { // Fix 4745222: If we dont ValidateRgn, windows will keep sending // WM_PAINT messages until we do. This causes java to go into // a tight loop that increases CPU to 100% and starves main // thread which needs to complete initialization, but cant. ::ValidateRgn(GetHWnd(), NULL); return; } HRGN rgn = ::CreateRectRgn(0,0,1,1); int updated = ::GetUpdateRgn(GetHWnd(), rgn, FALSE); /* * Now remove all update regions from this window -- do it * here instead of after the Java upcall, in case any new * updating is requested. */ ::ValidateRgn(GetHWnd(), NULL); if (updated == COMPLEXREGION || updated == SIMPLEREGION) { if (insets != NULL) { ::OffsetRgn(rgn, insets->left, insets->top); } int size = ::GetRegionData(rgn, 0, NULL); if (size == 0) { ::DeleteObject((HGDIOBJ)rgn); return; } char* buffer = new char[size]; memset(buffer, 0, size); LPRGNDATA rgndata = (LPRGNDATA)buffer; rgndata->rdh.dwSize = sizeof(RGNDATAHEADER); rgndata->rdh.iType = RDH_RECTANGLES; int retCode = ::GetRegionData(rgn, size, rgndata); VERIFY(retCode); if (retCode == 0) { delete [] buffer; ::DeleteObject((HGDIOBJ)rgn); return; } /* * Updating rects are divided into mostly vertical and mostly horizontal * Each group is united together and if not empty painted separately */ RECT* r = (RECT*)(buffer + rgndata->rdh.dwSize); RECT* un[2] = {0, 0}; DWORD i; for (i = 0; i < rgndata->rdh.nCount; i++, r++) { int width = r->right-r->left; int height = r->bottom-r->top; if (width > 0 && height > 0) { int toAdd = (width > height) ? 0: 1; if (un[toAdd] != 0) { ::UnionRect(un[toAdd], un[toAdd], r); } else { un[toAdd] = r; } } } for(i = 0; i < 2; i++) { if (un[i] != 0) { DoCallback("handleExpose", "(IIII)V", un[i]->left, un[i]->top, un[i]->right-un[i]->left, un[i]->bottom-un[i]->top); } } delete [] buffer; } ::DeleteObject((HGDIOBJ)rgn); } MsgRouting AwtComponent::WmMouseEnter(UINT flags, int x, int y) { SendMouseEvent(java_awt_event_MouseEvent_MOUSE_ENTERED, TimeHelper::getMessageTimeUTC(), x, y, GetJavaModifiers(), 0, JNI_FALSE); if ((flags & ALL_MK_BUTTONS) == 0) { AwtCursor::UpdateCursor(this); } sm_cursorOn = GetHWnd(); return mrConsume; /* Don't pass our synthetic event on! */ } MSG* AwtComponent::CreateMessage(UINT message, WPARAM wParam, LPARAM lParam, int x = 0, int y = 0) { MSG* pMsg = new MSG; InitMessage(pMsg, message, wParam, lParam, x, y); return pMsg; } jint AwtComponent::GetDrawState(HWND hwnd) { return (jint)(INT_PTR)(::GetProp(hwnd, DrawingStateProp)); } void AwtComponent::SetDrawState(HWND hwnd, jint state) { ::SetProp(hwnd, DrawingStateProp, (HANDLE)(INT_PTR)state); } void AwtComponent::InitMessage(MSG* msg, UINT message, WPARAM wParam, LPARAM lParam, int x = 0, int y = 0) { msg->message = message; msg->wParam = wParam; msg->lParam = lParam; msg->time = TimeHelper::getMessageTimeWindows(); msg->pt.x = x; msg->pt.y = y; } MsgRouting AwtComponent::WmNcMouseDown(WPARAM hitTest, int x, int y, int button) { return mrDoDefault; } MsgRouting AwtComponent::WmNcMouseUp(WPARAM hitTest, int x, int y, int button) { return mrDoDefault; } MsgRouting AwtComponent::WmWindowPosChanging(LPARAM windowPos) { return mrDoDefault; } MsgRouting AwtComponent::WmWindowPosChanged(LPARAM windowPos) { return mrDoDefault; } /* Double-click variables. */ static jlong multiClickTime = ::GetDoubleClickTime(); static int multiClickMaxX = ::GetSystemMetrics(SM_CXDOUBLECLK); static int multiClickMaxY = ::GetSystemMetrics(SM_CYDOUBLECLK); static AwtComponent* lastClickWnd = NULL; static jlong lastTime = 0; static int lastClickX = 0; static int lastClickY = 0; static int lastButton = 0; static int clickCount = 0; // A static method that makes the clickCount available in the derived classes // overriding WmMouseDown(). int AwtComponent::GetClickCount() { return clickCount; } MsgRouting AwtComponent::WmMouseDown(UINT flags, int x, int y, int button) { jlong now = TimeHelper::getMessageTimeUTC(); if (lastClickWnd == this && lastButton == button && (now - lastTime) <= multiClickTime && abs(x - lastClickX) <= multiClickMaxX && abs(y - lastClickY) <= multiClickMaxY) { clickCount++; } else { clickCount = 1; lastClickWnd = this; lastButton = button; lastClickX = x; lastClickY = y; } /* *Set appropriate bit of the mask on WM_MOUSE_DOWN message. */ m_mouseButtonClickAllowed |= GetButtonMK(button); lastTime = now; MSG msg; InitMessage(&msg, lastMessage, flags, MAKELPARAM(x, y), x, y); AwtWindow *toplevel = GetContainer(); if (toplevel && !toplevel->IsSimpleWindow()) { /* * The frame should be focused by click in case it is * the active window but not the focused window. See 6886678. */ if (toplevel->GetHWnd() == ::GetActiveWindow() && toplevel->GetHWnd() != AwtComponent::GetFocusedWindow()) { toplevel->AwtSetActiveWindow(); } } SendMouseEvent(java_awt_event_MouseEvent_MOUSE_PRESSED, now, x, y, GetJavaModifiers(), clickCount, JNI_FALSE, GetButton(button), &msg); /* * NOTE: this call is intentionally placed after all other code, * since AwtComponent::WmMouseDown() assumes that the cached id of the * latest retrieved message (see lastMessage in awt_Component.cpp) * matches the mouse message being processed. * SetCapture() sends WM_CAPTURECHANGED and breaks that * assumption. */ SetDragCapture(flags); AwtWindow * owner = (AwtWindow*)GetComponent(GetTopLevelParentForWindow(GetHWnd())); if (AwtWindow::GetGrabbedWindow() != NULL && owner != NULL) { if (!AwtWindow::GetGrabbedWindow()->IsOneOfOwnersOf(owner)) { AwtWindow::GetGrabbedWindow()->Ungrab(); } } return mrConsume; } MsgRouting AwtComponent::WmMouseUp(UINT flags, int x, int y, int button) { MSG msg; InitMessage(&msg, lastMessage, flags, MAKELPARAM(x, y), x, y); SendMouseEvent(java_awt_event_MouseEvent_MOUSE_RELEASED, TimeHelper::getMessageTimeUTC(), x, y, GetJavaModifiers(), clickCount, (GetButton(button) == java_awt_event_MouseEvent_BUTTON3 ? TRUE : FALSE), GetButton(button), &msg); /* * If no movement, then report a click following the button release. * When WM_MOUSEUP comes to a window without previous WM_MOUSEDOWN, * spurous MOUSE_CLICK is about to happen. See 6430553. */ if ((m_mouseButtonClickAllowed & GetButtonMK(button)) != 0) { //CLICK allowed SendMouseEvent(java_awt_event_MouseEvent_MOUSE_CLICKED, TimeHelper::getMessageTimeUTC(), x, y, GetJavaModifiers(), clickCount, JNI_FALSE, GetButton(button)); } // Exclude button from allowed to generate CLICK messages m_mouseButtonClickAllowed &= ~GetButtonMK(button); if ((flags & ALL_MK_BUTTONS) == 0) { // only update if all buttons have been released AwtCursor::UpdateCursor(this); } /* * NOTE: this call is intentionally placed after all other code, * since AwtComponent::WmMouseUp() assumes that the cached id of the * latest retrieved message (see lastMessage in awt_Component.cpp) * matches the mouse message being processed. * ReleaseCapture() sends WM_CAPTURECHANGED and breaks that * assumption. */ ReleaseDragCapture(flags); return mrConsume; } MsgRouting AwtComponent::WmMouseMove(UINT flags, int x, int y) { static AwtComponent* lastComp = NULL; static int lastX = 0; static int lastY = 0; /* * Only report mouse move and drag events if a move or drag * actually happened -- Windows sends a WM_MOUSEMOVE in case the * app wants to modify the cursor. */ if (lastComp != this || x != lastX || y != lastY) { lastComp = this; lastX = x; lastY = y; BOOL extraButtonsEnabled = AwtToolkit::GetInstance().areExtraMouseButtonsEnabled(); if (((flags & (ALL_MK_BUTTONS)) != 0) || (extraButtonsEnabled && (flags & (X_BUTTONS)) != 0)) // if (( extraButtonsEnabled && ( (flags & (ALL_MK_BUTTONS | X_BUTTONS)) != 0 )) || // ( !extraButtonsEnabled && (((flags & (ALL_MK_BUTTONS)) != 0 )) && ((flags & (X_BUTTONS)) == 0) )) { // 6404008 : if Dragged event fired we shouldn't fire // Clicked event: m_firstDragSent set to TRUE. // This is a partial backout of 5039416 fix. MSG msg; InitMessage(&msg, lastMessage, flags, MAKELPARAM(x, y), x, y); SendMouseEvent(java_awt_event_MouseEvent_MOUSE_DRAGGED, TimeHelper::getMessageTimeUTC(), x, y, GetJavaModifiers(), 0, JNI_FALSE, java_awt_event_MouseEvent_NOBUTTON, &msg); //dragging means no more CLICKs until next WM_MOUSE_DOWN/WM_MOUSE_UP message sequence m_mouseButtonClickAllowed = 0; } else { MSG msg; InitMessage(&msg, lastMessage, flags, MAKELPARAM(x, y), x, y); SendMouseEvent(java_awt_event_MouseEvent_MOUSE_MOVED, TimeHelper::getMessageTimeUTC(), x, y, GetJavaModifiers(), 0, JNI_FALSE, java_awt_event_MouseEvent_NOBUTTON, &msg); } } return mrConsume; } MsgRouting AwtComponent::WmMouseExit(UINT flags, int x, int y) { SendMouseEvent(java_awt_event_MouseEvent_MOUSE_EXITED, TimeHelper::getMessageTimeUTC(), x, y, GetJavaModifiers(), 0, JNI_FALSE); sm_cursorOn = NULL; return mrConsume; /* Don't pass our synthetic event on! */ } MsgRouting AwtComponent::WmMouseWheel(UINT flags, int x, int y, int wheelRotation) { // convert coordinates to be Component-relative, not screen relative // for wheeling when outside the window, this works similar to // coordinates during a drag POINT eventPt; eventPt.x = x; eventPt.y = y; DTRACE_PRINT2(" original coords: %i,%i\n", x, y); ::ScreenToClient(GetHWnd(), &eventPt); DTRACE_PRINT2(" new coords: %i,%i\n\n", eventPt.x, eventPt.y); // set some defaults jint scrollType = java_awt_event_MouseWheelEvent_WHEEL_UNIT_SCROLL; jint scrollLines = 3; BOOL result; UINT platformLines; m_wheelRotationAmount += wheelRotation; // AWT interprets wheel rotation differently than win32, so we need to // decode wheel amount. jint roundedWheelRotation = m_wheelRotationAmount / (-1 * WHEEL_DELTA); jdouble preciseWheelRotation = (jdouble) wheelRotation / (-1 * WHEEL_DELTA); MSG msg; result = ::SystemParametersInfo(SPI_GETWHEELSCROLLLINES, 0, &platformLines, 0); InitMessage(&msg, lastMessage, MAKEWPARAM(flags, wheelRotation), MAKELPARAM(x, y)); if (result) { if (platformLines == WHEEL_PAGESCROLL) { scrollType = java_awt_event_MouseWheelEvent_WHEEL_BLOCK_SCROLL; scrollLines = 1; } else { scrollType = java_awt_event_MouseWheelEvent_WHEEL_UNIT_SCROLL; scrollLines = platformLines; } } DTRACE_PRINTLN("calling SendMouseWheelEvent"); SendMouseWheelEvent(java_awt_event_MouseEvent_MOUSE_WHEEL, TimeHelper::getMessageTimeUTC(), eventPt.x, eventPt.y, GetJavaModifiers(), 0, 0, scrollType, scrollLines, roundedWheelRotation, preciseWheelRotation, &msg); m_wheelRotationAmount %= WHEEL_DELTA; // this message could be propagated up to the parent chain // by the mouse message post processors return mrConsume; } jint AwtComponent::GetKeyLocation(UINT wkey, UINT flags) { // Rector+Newcomer page 413 // The extended keys are the Alt and Control on the right of // the space bar, the non-Numpad arrow keys, the non-Numpad // Insert, PageUp, etc. keys, and the Numpad Divide and Enter keys. // Note that neither Shift key is extended. // Although not listed in Rector+Newcomer, both Windows keys // (91 and 92) are extended keys, the Context Menu key // (property key or application key - 93) is extended, // and so is the NumLock key. // wkey is the wParam, flags is the HIWORD of the lParam // "Extended" bit is 24th in lParam, so it's 8th in flags = HIWORD(lParam) BOOL extended = ((1<<8) & flags); if (IsNumPadKey(wkey, extended)) { return java_awt_event_KeyEvent_KEY_LOCATION_NUMPAD; } switch (wkey) { case VK_SHIFT: return AwtComponent::GetShiftKeyLocation(wkey, flags); case VK_CONTROL: // fall through case VK_MENU: if (extended) { return java_awt_event_KeyEvent_KEY_LOCATION_RIGHT; } else { return java_awt_event_KeyEvent_KEY_LOCATION_LEFT; } case VK_LWIN: return java_awt_event_KeyEvent_KEY_LOCATION_LEFT; case VK_RWIN: return java_awt_event_KeyEvent_KEY_LOCATION_RIGHT; default: break; } // REMIND: if we add keycodes for the windows keys, we'll have to // include left/right discrimination code for them. return java_awt_event_KeyEvent_KEY_LOCATION_STANDARD; } jint AwtComponent::GetShiftKeyLocation(UINT vkey, UINT flags) { // init scancodes to safe values UINT leftShiftScancode = 0; UINT rightShiftScancode = 0; // First 8 bits of flags is the scancode UINT keyScanCode = flags & 0xFF; DTRACE_PRINTLN3( "AwtComponent::GetShiftKeyLocation vkey = %d = 0x%x scan = %d", vkey, vkey, keyScanCode); leftShiftScancode = ::MapVirtualKey(VK_LSHIFT, 0); rightShiftScancode = ::MapVirtualKey(VK_RSHIFT, 0); if (keyScanCode == leftShiftScancode) { return java_awt_event_KeyEvent_KEY_LOCATION_LEFT; } if (keyScanCode == rightShiftScancode) { return java_awt_event_KeyEvent_KEY_LOCATION_RIGHT; } DASSERT(false); // Note: the above should not fail on NT (or 2000) // default value return java_awt_event_KeyEvent_KEY_LOCATION_LEFT; } /* Returns Java extended InputEvent modifieres. * Since ::GetKeyState returns current state and Java modifiers represent * state before event, modifier on changed key are inverted. */ jint AwtComponent::GetJavaModifiers() { jint modifiers = 0; if (HIBYTE(::GetKeyState(VK_CONTROL)) != 0) { modifiers |= java_awt_event_InputEvent_CTRL_DOWN_MASK; } if (HIBYTE(::GetKeyState(VK_SHIFT)) != 0) { modifiers |= java_awt_event_InputEvent_SHIFT_DOWN_MASK; } if (HIBYTE(::GetKeyState(VK_MENU)) != 0) { modifiers |= java_awt_event_InputEvent_ALT_DOWN_MASK; } if (HIBYTE(::GetKeyState(VK_MBUTTON)) != 0) { modifiers |= java_awt_event_InputEvent_BUTTON2_DOWN_MASK; } if (HIBYTE(::GetKeyState(VK_RBUTTON)) != 0) { modifiers |= java_awt_event_InputEvent_BUTTON3_DOWN_MASK; } if (HIBYTE(::GetKeyState(VK_LBUTTON)) != 0) { modifiers |= java_awt_event_InputEvent_BUTTON1_DOWN_MASK; } if (HIBYTE(::GetKeyState(VK_XBUTTON1)) != 0) { modifiers |= masks[3]; } if (HIBYTE(::GetKeyState(VK_XBUTTON2)) != 0) { modifiers |= masks[4]; } return modifiers; } jint AwtComponent::GetButton(int mouseButton) { /* Mouse buttons are already set correctly for left/right handedness */ switch(mouseButton) { case LEFT_BUTTON: return java_awt_event_MouseEvent_BUTTON1; case MIDDLE_BUTTON: return java_awt_event_MouseEvent_BUTTON2; case RIGHT_BUTTON: return java_awt_event_MouseEvent_BUTTON3; case X1_BUTTON: //16 : //just assign 4 and 5 numbers because MouseEvent class doesn't contain const identifier for them now return 4; case X2_BUTTON: //32 return 5; } return java_awt_event_MouseEvent_NOBUTTON; } UINT AwtComponent::GetButtonMK(int mouseButton) { switch(mouseButton) { case LEFT_BUTTON: return MK_LBUTTON; case MIDDLE_BUTTON: return MK_MBUTTON; case RIGHT_BUTTON: return MK_RBUTTON; case X1_BUTTON: return MK_XBUTTON1; case X2_BUTTON: return MK_XBUTTON2; } return 0; } // FIXME: Keyboard related stuff has grown so big and hairy that we // really need to move it into a class of its own. And, since // keyboard is a shared resource, AwtComponent is a bad place for it. // These constants are defined in the Japanese version of VC++5.0, // but not the US version #ifndef VK_CONVERT #define VK_KANA 0x15 #define VK_KANJI 0x19 #define VK_CONVERT 0x1C #define VK_NONCONVERT 0x1D #endif #ifndef VK_XBUTTON1 #define VK_XBUTTON1 0x05 #endif #ifndef VK_XBUTTON2 #define VK_XBUTTON2 0x06 #endif typedef struct { UINT javaKey; UINT windowsKey; } KeyMapEntry; // Static table, arranged more or less spatially. KeyMapEntry keyMapTable[] = { // Modifier keys {java_awt_event_KeyEvent_VK_CAPS_LOCK, VK_CAPITAL}, {java_awt_event_KeyEvent_VK_SHIFT, VK_SHIFT}, {java_awt_event_KeyEvent_VK_CONTROL, VK_CONTROL}, {java_awt_event_KeyEvent_VK_ALT, VK_MENU}, {java_awt_event_KeyEvent_VK_NUM_LOCK, VK_NUMLOCK}, // Miscellaneous Windows keys {java_awt_event_KeyEvent_VK_WINDOWS, VK_LWIN}, {java_awt_event_KeyEvent_VK_WINDOWS, VK_RWIN}, {java_awt_event_KeyEvent_VK_CONTEXT_MENU, VK_APPS}, // Alphabet {java_awt_event_KeyEvent_VK_A, 'A'}, {java_awt_event_KeyEvent_VK_B, 'B'}, {java_awt_event_KeyEvent_VK_C, 'C'}, {java_awt_event_KeyEvent_VK_D, 'D'}, {java_awt_event_KeyEvent_VK_E, 'E'}, {java_awt_event_KeyEvent_VK_F, 'F'}, {java_awt_event_KeyEvent_VK_G, 'G'}, {java_awt_event_KeyEvent_VK_H, 'H'}, {java_awt_event_KeyEvent_VK_I, 'I'}, {java_awt_event_KeyEvent_VK_J, 'J'}, {java_awt_event_KeyEvent_VK_K, 'K'}, {java_awt_event_KeyEvent_VK_L, 'L'}, {java_awt_event_KeyEvent_VK_M, 'M'}, {java_awt_event_KeyEvent_VK_N, 'N'}, {java_awt_event_KeyEvent_VK_O, 'O'}, {java_awt_event_KeyEvent_VK_P, 'P'}, {java_awt_event_KeyEvent_VK_Q, 'Q'}, {java_awt_event_KeyEvent_VK_R, 'R'}, {java_awt_event_KeyEvent_VK_S, 'S'}, {java_awt_event_KeyEvent_VK_T, 'T'}, {java_awt_event_KeyEvent_VK_U, 'U'}, {java_awt_event_KeyEvent_VK_V, 'V'}, {java_awt_event_KeyEvent_VK_W, 'W'}, {java_awt_event_KeyEvent_VK_X, 'X'}, {java_awt_event_KeyEvent_VK_Y, 'Y'}, {java_awt_event_KeyEvent_VK_Z, 'Z'}, // Standard numeric row {java_awt_event_KeyEvent_VK_0, '0'}, {java_awt_event_KeyEvent_VK_1, '1'}, {java_awt_event_KeyEvent_VK_2, '2'}, {java_awt_event_KeyEvent_VK_3, '3'}, {java_awt_event_KeyEvent_VK_4, '4'}, {java_awt_event_KeyEvent_VK_5, '5'}, {java_awt_event_KeyEvent_VK_6, '6'}, {java_awt_event_KeyEvent_VK_7, '7'}, {java_awt_event_KeyEvent_VK_8, '8'}, {java_awt_event_KeyEvent_VK_9, '9'}, // Misc key from main block {java_awt_event_KeyEvent_VK_ENTER, VK_RETURN}, {java_awt_event_KeyEvent_VK_SPACE, VK_SPACE}, {java_awt_event_KeyEvent_VK_BACK_SPACE, VK_BACK}, {java_awt_event_KeyEvent_VK_TAB, VK_TAB}, {java_awt_event_KeyEvent_VK_ESCAPE, VK_ESCAPE}, // NumPad with NumLock off & extended block (rectangular) {java_awt_event_KeyEvent_VK_INSERT, VK_INSERT}, {java_awt_event_KeyEvent_VK_DELETE, VK_DELETE}, {java_awt_event_KeyEvent_VK_HOME, VK_HOME}, {java_awt_event_KeyEvent_VK_END, VK_END}, {java_awt_event_KeyEvent_VK_PAGE_UP, VK_PRIOR}, {java_awt_event_KeyEvent_VK_PAGE_DOWN, VK_NEXT}, {java_awt_event_KeyEvent_VK_CLEAR, VK_CLEAR}, // NumPad 5 // NumPad with NumLock off & extended arrows block (triangular) {java_awt_event_KeyEvent_VK_LEFT, VK_LEFT}, {java_awt_event_KeyEvent_VK_RIGHT, VK_RIGHT}, {java_awt_event_KeyEvent_VK_UP, VK_UP}, {java_awt_event_KeyEvent_VK_DOWN, VK_DOWN}, // NumPad with NumLock on: numbers {java_awt_event_KeyEvent_VK_NUMPAD0, VK_NUMPAD0}, {java_awt_event_KeyEvent_VK_NUMPAD1, VK_NUMPAD1}, {java_awt_event_KeyEvent_VK_NUMPAD2, VK_NUMPAD2}, {java_awt_event_KeyEvent_VK_NUMPAD3, VK_NUMPAD3}, {java_awt_event_KeyEvent_VK_NUMPAD4, VK_NUMPAD4}, {java_awt_event_KeyEvent_VK_NUMPAD5, VK_NUMPAD5}, {java_awt_event_KeyEvent_VK_NUMPAD6, VK_NUMPAD6}, {java_awt_event_KeyEvent_VK_NUMPAD7, VK_NUMPAD7}, {java_awt_event_KeyEvent_VK_NUMPAD8, VK_NUMPAD8}, {java_awt_event_KeyEvent_VK_NUMPAD9, VK_NUMPAD9}, // NumPad with NumLock on {java_awt_event_KeyEvent_VK_MULTIPLY, VK_MULTIPLY}, {java_awt_event_KeyEvent_VK_ADD, VK_ADD}, {java_awt_event_KeyEvent_VK_SEPARATOR, VK_SEPARATOR}, {java_awt_event_KeyEvent_VK_SUBTRACT, VK_SUBTRACT}, {java_awt_event_KeyEvent_VK_DECIMAL, VK_DECIMAL}, {java_awt_event_KeyEvent_VK_DIVIDE, VK_DIVIDE}, // Functional keys {java_awt_event_KeyEvent_VK_F1, VK_F1}, {java_awt_event_KeyEvent_VK_F2, VK_F2}, {java_awt_event_KeyEvent_VK_F3, VK_F3}, {java_awt_event_KeyEvent_VK_F4, VK_F4}, {java_awt_event_KeyEvent_VK_F5, VK_F5}, {java_awt_event_KeyEvent_VK_F6, VK_F6}, {java_awt_event_KeyEvent_VK_F7, VK_F7}, {java_awt_event_KeyEvent_VK_F8, VK_F8}, {java_awt_event_KeyEvent_VK_F9, VK_F9}, {java_awt_event_KeyEvent_VK_F10, VK_F10}, {java_awt_event_KeyEvent_VK_F11, VK_F11}, {java_awt_event_KeyEvent_VK_F12, VK_F12}, {java_awt_event_KeyEvent_VK_F13, VK_F13}, {java_awt_event_KeyEvent_VK_F14, VK_F14}, {java_awt_event_KeyEvent_VK_F15, VK_F15}, {java_awt_event_KeyEvent_VK_F16, VK_F16}, {java_awt_event_KeyEvent_VK_F17, VK_F17}, {java_awt_event_KeyEvent_VK_F18, VK_F18}, {java_awt_event_KeyEvent_VK_F19, VK_F19}, {java_awt_event_KeyEvent_VK_F20, VK_F20}, {java_awt_event_KeyEvent_VK_F21, VK_F21}, {java_awt_event_KeyEvent_VK_F22, VK_F22}, {java_awt_event_KeyEvent_VK_F23, VK_F23}, {java_awt_event_KeyEvent_VK_F24, VK_F24}, {java_awt_event_KeyEvent_VK_PRINTSCREEN, VK_SNAPSHOT}, {java_awt_event_KeyEvent_VK_SCROLL_LOCK, VK_SCROLL}, {java_awt_event_KeyEvent_VK_PAUSE, VK_PAUSE}, {java_awt_event_KeyEvent_VK_CANCEL, VK_CANCEL}, {java_awt_event_KeyEvent_VK_HELP, VK_HELP}, // Japanese {java_awt_event_KeyEvent_VK_CONVERT, VK_CONVERT}, {java_awt_event_KeyEvent_VK_NONCONVERT, VK_NONCONVERT}, {java_awt_event_KeyEvent_VK_INPUT_METHOD_ON_OFF, VK_KANJI}, {java_awt_event_KeyEvent_VK_ALPHANUMERIC, VK_DBE_ALPHANUMERIC}, {java_awt_event_KeyEvent_VK_KATAKANA, VK_DBE_KATAKANA}, {java_awt_event_KeyEvent_VK_HIRAGANA, VK_DBE_HIRAGANA}, {java_awt_event_KeyEvent_VK_FULL_WIDTH, VK_DBE_DBCSCHAR}, {java_awt_event_KeyEvent_VK_HALF_WIDTH, VK_DBE_SBCSCHAR}, {java_awt_event_KeyEvent_VK_ROMAN_CHARACTERS, VK_DBE_ROMAN}, {java_awt_event_KeyEvent_VK_UNDEFINED, 0} }; // Dynamic mapping table for OEM VK codes. This table is refilled // by BuildDynamicKeyMapTable when keyboard layout is switched. // (see NT4 DDK src/input/inc/vkoem.h for OEM VK_ values). struct DynamicKeyMapEntry { UINT windowsKey; // OEM VK codes known in advance UINT javaKey; // depends on input langauge (kbd layout) }; static DynamicKeyMapEntry dynamicKeyMapTable[] = { {0x00BA, java_awt_event_KeyEvent_VK_UNDEFINED}, // VK_OEM_1 {0x00BB, java_awt_event_KeyEvent_VK_UNDEFINED}, // VK_OEM_PLUS {0x00BC, java_awt_event_KeyEvent_VK_UNDEFINED}, // VK_OEM_COMMA {0x00BD, java_awt_event_KeyEvent_VK_UNDEFINED}, // VK_OEM_MINUS {0x00BE, java_awt_event_KeyEvent_VK_UNDEFINED}, // VK_OEM_PERIOD {0x00BF, java_awt_event_KeyEvent_VK_UNDEFINED}, // VK_OEM_2 {0x00C0, java_awt_event_KeyEvent_VK_UNDEFINED}, // VK_OEM_3 {0x00DB, java_awt_event_KeyEvent_VK_UNDEFINED}, // VK_OEM_4 {0x00DC, java_awt_event_KeyEvent_VK_UNDEFINED}, // VK_OEM_5 {0x00DD, java_awt_event_KeyEvent_VK_UNDEFINED}, // VK_OEM_6 {0x00DE, java_awt_event_KeyEvent_VK_UNDEFINED}, // VK_OEM_7 {0x00DF, java_awt_event_KeyEvent_VK_UNDEFINED}, // VK_OEM_8 {0x00E2, java_awt_event_KeyEvent_VK_UNDEFINED}, // VK_OEM_102 {0, 0} }; // Auxiliary tables used to fill the above dynamic table. We first // find the character for the OEM VK code using ::MapVirtualKey and // then go through these auxiliary tables to map it to Java VK code. struct CharToVKEntry { WCHAR c; UINT javaKey; }; static const CharToVKEntry charToVKTable[] = { {L'!', java_awt_event_KeyEvent_VK_EXCLAMATION_MARK}, {L'"', java_awt_event_KeyEvent_VK_QUOTEDBL}, {L'#', java_awt_event_KeyEvent_VK_NUMBER_SIGN}, {L'$', java_awt_event_KeyEvent_VK_DOLLAR}, {L'&', java_awt_event_KeyEvent_VK_AMPERSAND}, {L'\'', java_awt_event_KeyEvent_VK_QUOTE}, {L'(', java_awt_event_KeyEvent_VK_LEFT_PARENTHESIS}, {L')', java_awt_event_KeyEvent_VK_RIGHT_PARENTHESIS}, {L'*', java_awt_event_KeyEvent_VK_ASTERISK}, {L'+', java_awt_event_KeyEvent_VK_PLUS}, {L',', java_awt_event_KeyEvent_VK_COMMA}, {L'-', java_awt_event_KeyEvent_VK_MINUS}, {L'.', java_awt_event_KeyEvent_VK_PERIOD}, {L'/', java_awt_event_KeyEvent_VK_SLASH}, {L':', java_awt_event_KeyEvent_VK_COLON}, {L';', java_awt_event_KeyEvent_VK_SEMICOLON}, {L'<', java_awt_event_KeyEvent_VK_LESS}, {L'=', java_awt_event_KeyEvent_VK_EQUALS}, {L'>', java_awt_event_KeyEvent_VK_GREATER}, {L'@', java_awt_event_KeyEvent_VK_AT}, {L'[', java_awt_event_KeyEvent_VK_OPEN_BRACKET}, {L'\\', java_awt_event_KeyEvent_VK_BACK_SLASH}, {L']', java_awt_event_KeyEvent_VK_CLOSE_BRACKET}, {L'^', java_awt_event_KeyEvent_VK_CIRCUMFLEX}, {L'_', java_awt_event_KeyEvent_VK_UNDERSCORE}, {L'`', java_awt_event_KeyEvent_VK_BACK_QUOTE}, {L'{', java_awt_event_KeyEvent_VK_BRACELEFT}, {L'}', java_awt_event_KeyEvent_VK_BRACERIGHT}, {0x00A1, java_awt_event_KeyEvent_VK_INVERTED_EXCLAMATION_MARK}, {0x20A0, java_awt_event_KeyEvent_VK_EURO_SIGN}, // ???? {0,0} }; // For dead accents some layouts return ASCII punctuation, while some // return spacing accent chars, so both should be listed. NB: MS docs // say that conversion routings return spacing accent character, not // combining. static const CharToVKEntry charToDeadVKTable[] = { {L'`', java_awt_event_KeyEvent_VK_DEAD_GRAVE}, {L'\'', java_awt_event_KeyEvent_VK_DEAD_ACUTE}, {0x00B4, java_awt_event_KeyEvent_VK_DEAD_ACUTE}, {L'^', java_awt_event_KeyEvent_VK_DEAD_CIRCUMFLEX}, {L'~', java_awt_event_KeyEvent_VK_DEAD_TILDE}, {0x02DC, java_awt_event_KeyEvent_VK_DEAD_TILDE}, {0x00AF, java_awt_event_KeyEvent_VK_DEAD_MACRON}, {0x02D8, java_awt_event_KeyEvent_VK_DEAD_BREVE}, {0x02D9, java_awt_event_KeyEvent_VK_DEAD_ABOVEDOT}, {L'"', java_awt_event_KeyEvent_VK_DEAD_DIAERESIS}, {0x00A8, java_awt_event_KeyEvent_VK_DEAD_DIAERESIS}, {0x02DA, java_awt_event_KeyEvent_VK_DEAD_ABOVERING}, {0x02DD, java_awt_event_KeyEvent_VK_DEAD_DOUBLEACUTE}, {0x02C7, java_awt_event_KeyEvent_VK_DEAD_CARON}, // aka hacek {L',', java_awt_event_KeyEvent_VK_DEAD_CEDILLA}, {0x00B8, java_awt_event_KeyEvent_VK_DEAD_CEDILLA}, {0x02DB, java_awt_event_KeyEvent_VK_DEAD_OGONEK}, {0x037A, java_awt_event_KeyEvent_VK_DEAD_IOTA}, // ASCII ??? {0x309B, java_awt_event_KeyEvent_VK_DEAD_VOICED_SOUND}, {0x309C, java_awt_event_KeyEvent_VK_DEAD_SEMIVOICED_SOUND}, {0,0} }; // The full map of the current keyboard state including // windows virtual key, scancode, java virtual key, and unicode // for this key sans modifiers. // All but first element may be 0. // XXX in the update releases this is an addition to the unchanged existing code struct DynPrimaryKeymapEntry { UINT wkey; UINT scancode; UINT jkey; WCHAR unicode; }; static DynPrimaryKeymapEntry dynPrimaryKeymap[256]; void AwtComponent::InitDynamicKeyMapTable() { static BOOL kbdinited = FALSE; if (!kbdinited) { AwtComponent::BuildDynamicKeyMapTable(); // We cannot build it here since JNI is not available yet: //AwtComponent::BuildPrimaryDynamicTable(); kbdinited = TRUE; } } void AwtComponent::BuildDynamicKeyMapTable() { HKL hkl = GetKeyboardLayout(); DTRACE_PRINTLN2("Building dynamic VK mapping tables: HKL = %08X (CP%d)", hkl, AwtComponent::GetCodePage()); // Will need this to reset layout after dead keys. UINT spaceScanCode = ::MapVirtualKeyEx(VK_SPACE, 0, hkl); // Entries in dynamic table that maps between Java VK and Windows // VK are built in three steps: // 1. Map windows VK to ANSI character (cannot map to unicode // directly, since ::ToUnicode is not implemented on win9x) // 2. Convert ANSI char to Unicode char // 3. Map Unicode char to Java VK via two auxilary tables. for (DynamicKeyMapEntry *dynamic = dynamicKeyMapTable; dynamic->windowsKey != 0; ++dynamic) { // Defaults to VK_UNDEFINED dynamic->javaKey = java_awt_event_KeyEvent_VK_UNDEFINED; BYTE kbdState[AwtToolkit::KB_STATE_SIZE]; AwtToolkit::GetKeyboardState(kbdState); kbdState[dynamic->windowsKey] |= 0x80; // Press the key. // Unpress modifiers, since they are most likely pressed as // part of the keyboard switching shortcut. kbdState[VK_CONTROL] &= ~0x80; kbdState[VK_SHIFT] &= ~0x80; kbdState[VK_MENU] &= ~0x80; char cbuf[2] = { '\0', '\0'}; UINT scancode = ::MapVirtualKeyEx(dynamic->windowsKey, 0, hkl); int nchars = ::ToAsciiEx(dynamic->windowsKey, scancode, kbdState, (WORD*)cbuf, 0, hkl); // Auxiliary table used to map Unicode character to Java VK. // Will assign a different table for dead keys (below). const CharToVKEntry *charMap = charToVKTable; if (nchars < 0) { // Dead key // Use a different table for dead chars since different layouts // return different characters for the same dead key. charMap = charToDeadVKTable; // We also need to reset layout so that next translation // is unaffected by the dead status. We do this by // translating <SPACE> key. kbdState[dynamic->windowsKey] &= ~0x80; kbdState[VK_SPACE] |= 0x80; char junkbuf[2] = { '\0', '\0'}; ::ToAsciiEx(VK_SPACE, spaceScanCode, kbdState, (WORD*)junkbuf, 0, hkl); } #ifdef DEBUG if (nchars == 0) { DTRACE_PRINTLN1("VK 0x%02X -> cannot convert to ANSI char", dynamic->windowsKey); continue; } else if (nchars > 1) { // can't happen, see reset code below DTRACE_PRINTLN3("VK 0x%02X -> converted to <0x%02X,0x%02X>", dynamic->windowsKey, (UCHAR)cbuf[0], (UCHAR)cbuf[1]); continue; } #endif WCHAR ucbuf[2] = { L'\0', L'\0' }; int nconverted = ::MultiByteToWideChar(AwtComponent::GetCodePage(), 0, cbuf, 1, ucbuf, 2); #ifdef DEBUG if (nconverted < 0) { DTRACE_PRINTLN3("VK 0x%02X -> ANSI 0x%02X -> MultiByteToWideChar failed (0x%X)", dynamic->windowsKey, (UCHAR)cbuf[0], ::GetLastError()); continue; } #endif WCHAR uc = ucbuf[0]; for (const CharToVKEntry *map = charMap; map->c != 0; ++map) { if (uc == map->c) { dynamic->javaKey = map->javaKey; break; } } DTRACE_PRINTLN4("VK 0x%02X -> ANSI 0x%02X -> U+%04X -> Java VK 0x%X", dynamic->windowsKey, (UCHAR)cbuf[0], (UINT)ucbuf[0], dynamic->javaKey); } // for each VK_OEM_* } static BOOL isKanaLockAvailable() { // This method is to determine whether the Kana Lock feature is // available on the attached keyboard. Kana Lock feature does not // necessarily require that the real KANA keytop is available on // keyboard, so using MapVirtualKey(VK_KANA) is not sufficient for testing. // Instead of that we regard it as Japanese keyboard (w/ Kana Lock) if :- // // - the keyboard layout is Japanese (VK_KANA has the same value as VK_HANGUL) // - the keyboard is Japanese keyboard (keyboard type == 7). return (LOWORD(GetKeyboardLayout(0)) == MAKELANGID(LANG_JAPANESE, SUBLANG_DEFAULT)) && (GetKeyboardType(0) == 7); } void AwtComponent::JavaKeyToWindowsKey(UINT javaKey, UINT *windowsKey, UINT *modifiers, UINT originalWindowsKey) { // Handle the few cases where a Java VK code corresponds to a Windows // key/modifier combination or applies only to specific keyboard layouts switch (javaKey) { case java_awt_event_KeyEvent_VK_ALL_CANDIDATES: *windowsKey = VK_CONVERT; *modifiers = java_awt_event_InputEvent_ALT_DOWN_MASK; return; case java_awt_event_KeyEvent_VK_PREVIOUS_CANDIDATE: *windowsKey = VK_CONVERT; *modifiers = java_awt_event_InputEvent_SHIFT_DOWN_MASK; return; case java_awt_event_KeyEvent_VK_CODE_INPUT: *windowsKey = VK_DBE_ALPHANUMERIC; *modifiers = java_awt_event_InputEvent_ALT_DOWN_MASK; return; case java_awt_event_KeyEvent_VK_KANA_LOCK: if (isKanaLockAvailable()) { *windowsKey = VK_KANA; *modifiers = java_awt_event_InputEvent_CTRL_DOWN_MASK; return; } } // for the general case, use a bi-directional table for (int i = 0; keyMapTable[i].windowsKey != 0; i++) { if (keyMapTable[i].javaKey == javaKey) { *windowsKey = keyMapTable[i].windowsKey; *modifiers = 0; return; } } // Bug 4766655 // Two Windows keys could map to the same Java key, so // give preference to the originalWindowsKey if it is // specified (not IGNORE_KEY). if (originalWindowsKey == IGNORE_KEY) { for (int j = 0; dynamicKeyMapTable[j].windowsKey != 0; j++) { if (dynamicKeyMapTable[j].javaKey == javaKey) { *windowsKey = dynamicKeyMapTable[j].windowsKey; *modifiers = 0; return; } } } else { BOOL found = false; for (int j = 0; dynamicKeyMapTable[j].windowsKey != 0; j++) { if (dynamicKeyMapTable[j].javaKey == javaKey) { *windowsKey = dynamicKeyMapTable[j].windowsKey; *modifiers = 0; found = true; if (*windowsKey == originalWindowsKey) { return; /* if ideal case found return, else keep looking */ } } } if (found) { return; } } *windowsKey = 0; *modifiers = 0; return; } UINT AwtComponent::WindowsKeyToJavaKey(UINT windowsKey, UINT modifiers) { // Handle the few cases where we need to take the modifier into // consideration for the Java VK code or where we have to take the keyboard // layout into consideration so that function keys can get // recognized in a platform-independent way. switch (windowsKey) { case VK_CONVERT: if ((modifiers & java_awt_event_InputEvent_ALT_DOWN_MASK) != 0) { return java_awt_event_KeyEvent_VK_ALL_CANDIDATES; } if ((modifiers & java_awt_event_InputEvent_SHIFT_DOWN_MASK) != 0) { return java_awt_event_KeyEvent_VK_PREVIOUS_CANDIDATE; } break; case VK_DBE_ALPHANUMERIC: if ((modifiers & java_awt_event_InputEvent_ALT_DOWN_MASK) != 0) { return java_awt_event_KeyEvent_VK_CODE_INPUT; } break; case VK_KANA: if (isKanaLockAvailable()) { return java_awt_event_KeyEvent_VK_KANA_LOCK; } break; }; // for the general case, use a bi-directional table for (int i = 0; keyMapTable[i].windowsKey != 0; i++) { if (keyMapTable[i].windowsKey == windowsKey) { return keyMapTable[i].javaKey; } } for (int j = 0; dynamicKeyMapTable[j].windowsKey != 0; j++) { if (dynamicKeyMapTable[j].windowsKey == windowsKey) { if (dynamicKeyMapTable[j].javaKey != java_awt_event_KeyEvent_VK_UNDEFINED) { return dynamicKeyMapTable[j].javaKey; }else{ break; } } } return java_awt_event_KeyEvent_VK_UNDEFINED; } BOOL AwtComponent::IsNavigationKey(UINT wkey) { switch (wkey) { case VK_END: case VK_PRIOR: // PageUp case VK_NEXT: // PageDown case VK_HOME: case VK_LEFT: case VK_UP: case VK_RIGHT: case VK_DOWN: return TRUE; } return FALSE; } // determine if a key is a numpad key (distinguishes the numpad // arrow keys from the non-numpad arrow keys, for example). BOOL AwtComponent::IsNumPadKey(UINT vkey, BOOL extended) { // Note: scancodes are the same for the numpad arrow keys and // the non-numpad arrow keys (also for PageUp, etc.). // The scancodes for the numpad divide and the non-numpad slash // are the same, but the wparams are different DTRACE_PRINTLN3("AwtComponent::IsNumPadKey vkey = %d = 0x%x extended = %d", vkey, vkey, extended); switch (vkey) { case VK_CLEAR: // numpad 5 with numlock off case VK_NUMPAD0: case VK_NUMPAD1: case VK_NUMPAD2: case VK_NUMPAD3: case VK_NUMPAD4: case VK_NUMPAD5: case VK_NUMPAD6: case VK_NUMPAD7: case VK_NUMPAD8: case VK_NUMPAD9: case VK_MULTIPLY: case VK_ADD: case VK_SEPARATOR: // numpad , not on US kbds case VK_SUBTRACT: case VK_DECIMAL: case VK_DIVIDE: case VK_NUMLOCK: return TRUE; break; case VK_END: case VK_PRIOR: // PageUp case VK_NEXT: // PageDown case VK_HOME: case VK_LEFT: case VK_UP: case VK_RIGHT: case VK_DOWN: case VK_INSERT: case VK_DELETE: // extended if non-numpad return (!extended); break; case VK_RETURN: // extended if on numpad return (extended); break; default: break; } return FALSE; } static void resetKbdState( BYTE kstate[256]) { BYTE tmpState[256]; WCHAR wc[2]; memmove(tmpState, kstate, sizeof(kstate)); tmpState[VK_SHIFT] = 0; tmpState[VK_CONTROL] = 0; tmpState[VK_MENU] = 0; ::ToUnicodeEx(VK_SPACE,::MapVirtualKey(VK_SPACE, 0), tmpState, wc, 2, 0, GetKeyboardLayout(0)); } // XXX in the update releases this is an addition to the unchanged existing code // After the call, a table will have a unicode associated with a windows virtual keycode // sans modifiers. With some further simplification, one can // derive java keycode from it, and anyway we will pass this unicode value // all the way up in a comment to a KeyEvent. void AwtComponent::BuildPrimaryDynamicTable() { JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); // XXX: how about that? //CriticalSection::Lock l(GetLock()); //if (GetPeer(env) == NULL) { // /* event received during termination. */ // return; //} HKL hkl = GetKeyboardLayout(); UINT sc = 0; BYTE kbdState[AwtToolkit::KB_STATE_SIZE]; memset(kbdState, 0, sizeof (kbdState)); // Use JNI call to obtain java key code. We should keep a list // of currently available keycodes in a single place. static jclass extKeyCodesCls; if( extKeyCodesCls == NULL) { jclass extKeyCodesClsLocal = env->FindClass("sun/awt/ExtendedKeyCodes"); DASSERT(extKeyCodesClsLocal); if (extKeyCodesClsLocal == NULL) { /* exception already thrown */ return; } extKeyCodesCls = (jclass)env->NewGlobalRef(extKeyCodesClsLocal); env->DeleteLocalRef(extKeyCodesClsLocal); } static jmethodID getExtendedKeyCodeForChar; if (getExtendedKeyCodeForChar == NULL) { getExtendedKeyCodeForChar = env->GetStaticMethodID(extKeyCodesCls, "getExtendedKeyCodeForChar", "(I)I"); DASSERT(getExtendedKeyCodeForChar); } jint extJKC; //extended Java key code for (UINT i = 0; i < 256; i++) { dynPrimaryKeymap[i].wkey = i; dynPrimaryKeymap[i].jkey = java_awt_event_KeyEvent_VK_UNDEFINED; dynPrimaryKeymap[i].unicode = 0; if ((sc = MapVirtualKey (i, 0)) == 0) { dynPrimaryKeymap[i].scancode = 0; continue; } dynPrimaryKeymap[i].scancode = sc; // XXX process cases like VK_SHIFT etc. kbdState[i] = 0x80; // "key pressed". WCHAR wc[16]; int k = ::ToUnicodeEx(i, sc, kbdState, wc, 16, 0, hkl); if (k == 1) { // unicode dynPrimaryKeymap[i].unicode = wc[0]; if (dynPrimaryKeymap[i].jkey == java_awt_event_KeyEvent_VK_UNDEFINED) { // Convert unicode to java keycode. //dynPrimaryKeymap[i].jkey = ((UINT)(wc[0]) + 0x01000000); // //XXX If this key in on the keypad, we should force a special value equal to //XXX an old java keycode: but how to say if it is a keypad key? //XXX We'll do it in WmKeyUp/Down. extJKC = env->CallStaticIntMethod(extKeyCodesCls, getExtendedKeyCodeForChar, (jint)(wc[0])); dynPrimaryKeymap[i].jkey = extJKC; } }else if (k == -1) { // dead key: use charToDeadVKTable dynPrimaryKeymap[i].unicode = wc[0]; resetKbdState( kbdState ); for (const CharToVKEntry *map = charToDeadVKTable; map->c != 0; ++map) { if (wc[0] == map->c) { dynPrimaryKeymap[i].jkey = map->javaKey; break; } } } else if (k == 0) { // reset resetKbdState( kbdState ); }else { // k > 1: this key does generate multiple characters. Ignore it. // An example: Arabic Lam and Alef ligature. // There will be no extended keycode and thus shortcuts for this key. // XXX shouldn't we reset the kbd state? #ifdef DEBUG DTRACE_PRINTLN2("wkey 0x%02X (%d)", i,i); #endif } kbdState[i] = 0; // "key unpressed" } } void AwtComponent::UpdateDynPrimaryKeymap(UINT wkey, UINT jkeyLegacy, jint keyLocation, UINT modifiers) { if( wkey && wkey < 256 ) { if(keyLocation == java_awt_event_KeyEvent_KEY_LOCATION_NUMPAD) { // At the creation time, // dynPrimaryKeymap cannot distinguish between e.g. "/" and "NumPad /" dynPrimaryKeymap[wkey].jkey = jkeyLegacy; } if(dynPrimaryKeymap[wkey].jkey == java_awt_event_KeyEvent_VK_UNDEFINED) { // E.g. it is non-unicode key dynPrimaryKeymap[wkey].jkey = jkeyLegacy; } } } UINT AwtComponent::WindowsKeyToJavaChar(UINT wkey, UINT modifiers, TransOps ops) { static Hashtable transTable("VKEY translations"); // Try to translate using last saved translation if (ops == LOAD) { void* value = transTable.remove(reinterpret_cast<void*>(static_cast<INT_PTR>(wkey))); if (value != NULL) { return static_cast<UINT>(reinterpret_cast<INT_PTR>(value)); } } // If the windows key is a return, wkey will equal 13 ('\r') // In this case, we want to return 10 ('\n') // Since ToAscii would convert VK_RETURN to '\r', we need // to have a special case here. if (wkey == VK_RETURN) return '\n'; // high order bit in keyboardState indicates whether the key is down static const BYTE KEY_STATE_DOWN = 0x80; BYTE keyboardState[AwtToolkit::KB_STATE_SIZE]; AwtToolkit::GetKeyboardState(keyboardState); // apply modifiers to keyboard state if necessary if (modifiers) { BOOL shiftIsDown = modifiers & java_awt_event_InputEvent_SHIFT_DOWN_MASK; BOOL altIsDown = modifiers & java_awt_event_InputEvent_ALT_DOWN_MASK; BOOL ctrlIsDown = modifiers & java_awt_event_InputEvent_CTRL_DOWN_MASK; // Windows treats AltGr as Ctrl+Alt if (modifiers & java_awt_event_InputEvent_ALT_GRAPH_DOWN_MASK) { altIsDown = TRUE; ctrlIsDown = TRUE; } if (shiftIsDown) { keyboardState[VK_SHIFT] |= KEY_STATE_DOWN; } // fix for 4623376,4737679,4501485,4740906,4708221 (4173679/4122715) // Here we try to resolve a conflict with ::ToAsciiEx's translating // ALT+number key combinations. kdm@sarc.spb.su // yan: Do it for navigation keys only, otherwise some AltGr deadkeys fail. if( IsNavigationKey(wkey) ) { keyboardState[VK_MENU] &= ~KEY_STATE_DOWN; } if (ctrlIsDown) { if (altIsDown) { // bugid 4215009: don't mess with AltGr == Ctrl + Alt keyboardState[VK_CONTROL] |= KEY_STATE_DOWN; } else { // bugid 4098210: old event model doesn't have KEY_TYPED // events, so try to provide a meaningful character for // Ctrl+<key>. Take Ctrl into account only when we know // that Ctrl+<key> will be an ASCII control. Ignore by // default. keyboardState[VK_CONTROL] &= ~KEY_STATE_DOWN; // Letters have Ctrl+<letter> counterparts. According to // <winuser.h> VK_A through VK_Z are the same as ASCII // 'A' through 'Z'. if (wkey >= 'A' && wkey <= 'Z') { keyboardState[VK_CONTROL] |= KEY_STATE_DOWN; } else { // Non-letter controls 033 to 037 are: // ^[ (ESC), ^\ (FS), ^] (GS), ^^ (RS), and ^_ (US) // Shift state bits returned by ::VkKeyScan in HIBYTE static const UINT _VKS_SHIFT_MASK = 0x01; static const UINT _VKS_CTRL_MASK = 0x02; static const UINT _VKS_ALT_MASK = 0x04; // Check to see whether there is a meaningful translation TCHAR ch; short vk; for (ch = _T('\033'); ch < _T('\040'); ch++) { vk = ::VkKeyScan(ch); if (wkey == LOBYTE(vk)) { UINT shiftState = HIBYTE(vk); if ((shiftState & _VKS_CTRL_MASK) || (!(shiftState & _VKS_SHIFT_MASK) == !shiftIsDown)) { keyboardState[VK_CONTROL] |= KEY_STATE_DOWN; } break; } } } } // ctrlIsDown && altIsDown } // ctrlIsDown } // modifiers // instead of creating our own conversion tables, I'll let Win32 // convert the character for me. WORD mbChar; UINT scancode = ::MapVirtualKey(wkey, 0); int converted = ::ToAsciiEx(wkey, scancode, keyboardState, &mbChar, 0, GetKeyboardLayout()); UINT translation; // Dead Key if (converted < 0) { translation = java_awt_event_KeyEvent_CHAR_UNDEFINED; } else // No translation available -- try known conversions or else punt. if (converted == 0) { if (wkey == VK_DELETE) { translation = '\177'; } else if (wkey >= VK_NUMPAD0 && wkey <= VK_NUMPAD9) { translation = '0' + wkey - VK_NUMPAD0; } else { translation = java_awt_event_KeyEvent_CHAR_UNDEFINED; } } else // the caller expects a Unicode character. if (converted > 0) { WCHAR unicodeChar[2]; VERIFY(::MultiByteToWideChar(GetCodePage(), MB_PRECOMPOSED, (LPCSTR)&mbChar, 1, unicodeChar, 1)); translation = unicodeChar[0]; } if (ops == SAVE) { transTable.put(reinterpret_cast<void*>(static_cast<INT_PTR>(wkey)), reinterpret_cast<void*>(static_cast<INT_PTR>(translation))); } return translation; } MsgRouting AwtComponent::WmKeyDown(UINT wkey, UINT repCnt, UINT flags, BOOL system) { // VK_PROCESSKEY is a special value which means // "Current IME wants to consume this KeyEvent" // Real key code is saved by IMM32.DLL and can be retrieved by // calling ImmGetVirtualKey(); if (wkey == VK_PROCESSKEY) { return mrDoDefault; } MSG msg; InitMessage(&msg, (system ? WM_SYSKEYDOWN : WM_KEYDOWN), wkey, MAKELPARAM(repCnt, flags)); UINT modifiers = GetJavaModifiers(); jint keyLocation = GetKeyLocation(wkey, flags); UINT jkey = WindowsKeyToJavaKey(wkey, modifiers); UINT character = WindowsKeyToJavaChar(wkey, modifiers, SAVE); UpdateDynPrimaryKeymap(wkey, jkey, keyLocation, modifiers); SendKeyEventToFocusOwner(java_awt_event_KeyEvent_KEY_PRESSED, TimeHelper::windowsToUTC(msg.time), jkey, character, modifiers, keyLocation, (jlong)wkey, &msg); // bugid 4724007: Windows does not create a WM_CHAR for the Del key // for some reason, so we need to create the KEY_TYPED event on the // WM_KEYDOWN. Use null msg so the character doesn't get sent back // to the native window for processing (this event is synthesized // for Java - we don't want Windows trying to process it). if (jkey == java_awt_event_KeyEvent_VK_DELETE) { SendKeyEventToFocusOwner(java_awt_event_KeyEvent_KEY_TYPED, TimeHelper::windowsToUTC(msg.time), java_awt_event_KeyEvent_VK_UNDEFINED, character, modifiers, java_awt_event_KeyEvent_KEY_LOCATION_UNKNOWN, (jlong)0); } return mrConsume; } MsgRouting AwtComponent::WmKeyUp(UINT wkey, UINT repCnt, UINT flags, BOOL system) { // VK_PROCESSKEY is a special value which means // "Current IME wants to consume this KeyEvent" // Real key code is saved by IMM32.DLL and can be retrieved by // calling ImmGetVirtualKey(); if (wkey == VK_PROCESSKEY) { return mrDoDefault; } MSG msg; InitMessage(&msg, (system ? WM_SYSKEYUP : WM_KEYUP), wkey, MAKELPARAM(repCnt, flags)); UINT modifiers = GetJavaModifiers(); jint keyLocation = GetKeyLocation(wkey, flags); UINT jkey = WindowsKeyToJavaKey(wkey, modifiers); UINT character = WindowsKeyToJavaChar(wkey, modifiers, LOAD); UpdateDynPrimaryKeymap(wkey, jkey, keyLocation, modifiers); SendKeyEventToFocusOwner(java_awt_event_KeyEvent_KEY_RELEASED, TimeHelper::windowsToUTC(msg.time), jkey, character, modifiers, keyLocation, (jlong)wkey, &msg); return mrConsume; } MsgRouting AwtComponent::WmInputLangChange(UINT charset, HKL hKeyboardLayout) { // Normally we would be able to use charset and TranslateCharSetInfo // to get a code page that should be associated with this keyboard // layout change. However, there seems to be an NT 4.0 bug associated // with the WM_INPUTLANGCHANGE message, which makes the charset parameter // unreliable, especially on Asian systems. Our workaround uses the // keyboard layout handle instead. m_hkl = hKeyboardLayout; m_idLang = LOWORD(hKeyboardLayout); // lower word of HKL is LANGID m_CodePage = LangToCodePage(m_idLang); BuildDynamicKeyMapTable(); // compute new mappings for VK_OEM BuildPrimaryDynamicTable(); return mrConsume; // do not propagate to children } // Convert Language ID to CodePage UINT AwtComponent::LangToCodePage(LANGID idLang) { TCHAR strCodePage[MAX_ACP_STR_LEN]; // use the LANGID to create a LCID LCID idLocale = MAKELCID(idLang, SORT_DEFAULT); // get the ANSI code page associated with this locale if (GetLocaleInfo(idLocale, LOCALE_IDEFAULTANSICODEPAGE, strCodePage, sizeof(strCodePage)/sizeof(TCHAR)) > 0 ) return _ttoi(strCodePage); else return GetACP(); } MsgRouting AwtComponent::WmIMEChar(UINT character, UINT repCnt, UINT flags, BOOL system) { // We will simply create Java events here. WCHAR unicodeChar = character; MSG msg; InitMessage(&msg, WM_IME_CHAR, character, MAKELPARAM(repCnt, flags)); jint modifiers = GetJavaModifiers(); SendKeyEventToFocusOwner(java_awt_event_KeyEvent_KEY_TYPED, TimeHelper::windowsToUTC(msg.time), java_awt_event_KeyEvent_VK_UNDEFINED, unicodeChar, modifiers, java_awt_event_KeyEvent_KEY_LOCATION_UNKNOWN, (jlong)0, &msg); return mrConsume; } MsgRouting AwtComponent::WmChar(UINT character, UINT repCnt, UINT flags, BOOL system) { // Will only get WmChar messages with DBCS if we create them for // an Edit class in the WmForwardChar method. These synthesized // DBCS chars are ok to pass on directly to the default window // procedure. They've already been filtered through the Java key // event queue. We will never get the trail byte since the edit // class will PeekMessage(&msg, hwnd, WM_CHAR, WM_CHAR, // PM_REMOVE). I would like to be able to pass this character off // via WM_AWT_FORWARD_BYTE, but the Edit classes don't seem to // like that. // We will simply create Java events here. UINT message = system ? WM_SYSCHAR : WM_CHAR; // The Alt modifier is reported in the 29th bit of the lParam, // i.e., it is the 13th bit of `flags' (which is HIWORD(lParam)). bool alt_is_down = (flags & (1<<13)) != 0; // Fix for bug 4141621, corrected by fix for bug 6223726: Alt+space doesn't invoke system menu // We should not pass this particular combination to Java. if (system && alt_is_down) { if (character == VK_SPACE) { return mrDoDefault; } } // If this is a WM_CHAR (non-system) message, then the Alt flag // indicates that the character was typed using an AltGr key // (which Windows treats as Ctrl+Alt), so in this case we do NOT // pass the Ctrl and Alt modifiers to Java, but instead we // replace them with Java's AltGraph modifier. Note: the AltGraph // modifier does not exist in 1.1.x releases. jint modifiers = GetJavaModifiers(); if (!system && alt_is_down) { // character typed with AltGraph modifiers &= ~(java_awt_event_InputEvent_ALT_DOWN_MASK | java_awt_event_InputEvent_CTRL_DOWN_MASK); modifiers |= java_awt_event_InputEvent_ALT_GRAPH_DOWN_MASK; } WCHAR unicodeChar = character; // Kludge: Combine pending single byte with this char for some Chinese IMEs if (m_PendingLeadByte != 0) { character = (m_PendingLeadByte & 0x00ff) | (character << 8); m_PendingLeadByte = 0; ::MultiByteToWideChar(GetCodePage(), 0, (CHAR*)&character, 2, &unicodeChar, 1); } if (unicodeChar == VK_RETURN) { // Enter key generates \r in windows, but \n is required in java unicodeChar = java_awt_event_KeyEvent_VK_ENTER; } MSG msg; InitMessage(&msg, message, character, MAKELPARAM(repCnt, flags)); SendKeyEventToFocusOwner(java_awt_event_KeyEvent_KEY_TYPED, TimeHelper::windowsToUTC(msg.time), java_awt_event_KeyEvent_VK_UNDEFINED, unicodeChar, modifiers, java_awt_event_KeyEvent_KEY_LOCATION_UNKNOWN, (jlong)0, &msg); return mrConsume; } MsgRouting AwtComponent::WmForwardChar(WCHAR character, LPARAM lParam, BOOL synthetic) { // just post WM_CHAR with unicode key value DefWindowProc(WM_CHAR, (WPARAM)character, lParam); return mrConsume; } MsgRouting AwtComponent::WmPaste() { return mrDoDefault; } // support IME Composition messages void AwtComponent::SetCompositionWindow(RECT& r) { HIMC hIMC = ImmGetContext(); if (hIMC == NULL) { return; } COMPOSITIONFORM cf = {CFS_DEFAULT, {0, 0}, {0, 0, 0, 0}}; ImmSetCompositionWindow(hIMC, &cf); } void AwtComponent::OpenCandidateWindow(int x, int y) { UINT bits = 1; RECT rc; GetWindowRect(GetHWnd(), &rc); for (int iCandType=0; iCandType<32; iCandType++, bits<<=1) { if ( m_bitsCandType & bits ) SetCandidateWindow(iCandType, x-rc.left, y-rc.top); } if (m_bitsCandType != 0) { HWND proxy = GetProxyFocusOwner(); // REMIND: is there any chance GetProxyFocusOwner() returns NULL here? ::DefWindowProc((proxy != NULL) ? proxy : GetHWnd(), WM_IME_NOTIFY, IMN_OPENCANDIDATE, m_bitsCandType); } } void AwtComponent::SetCandidateWindow(int iCandType, int x, int y) { HIMC hIMC = ImmGetContext(); CANDIDATEFORM cf; cf.dwIndex = iCandType; cf.dwStyle = CFS_CANDIDATEPOS; cf.ptCurrentPos.x = x; cf.ptCurrentPos.y = y; ImmSetCandidateWindow(hIMC, &cf); } MsgRouting AwtComponent::WmImeSetContext(BOOL fSet, LPARAM *lplParam) { // If the Windows input context is disabled, do not let Windows // display any UIs. HIMC hIMC = ImmGetContext(); if (hIMC == NULL) { *lplParam = 0; return mrDoDefault; } if (fSet) { LPARAM lParam = *lplParam; if (!m_useNativeCompWindow) { // stop to draw native composing window. *lplParam &= ~ISC_SHOWUICOMPOSITIONWINDOW; } } return mrDoDefault; } MsgRouting AwtComponent::WmImeNotify(WPARAM subMsg, LPARAM bitsCandType) { if (!m_useNativeCompWindow && subMsg == IMN_OPENCANDIDATE) { m_bitsCandType = bitsCandType; InquireCandidatePosition(); return mrConsume; } return mrDoDefault; } MsgRouting AwtComponent::WmImeStartComposition() { if (m_useNativeCompWindow) { RECT rc; ::GetClientRect(GetHWnd(), &rc); SetCompositionWindow(rc); return mrDoDefault; } else return mrConsume; } MsgRouting AwtComponent::WmImeEndComposition() { if (m_useNativeCompWindow) return mrDoDefault; SendInputMethodEvent( java_awt_event_InputMethodEvent_INPUT_METHOD_TEXT_CHANGED, NULL, 0, NULL, NULL, 0, NULL, NULL, 0, 0, 0 ); return mrConsume; } MsgRouting AwtComponent::WmImeComposition(WORD wChar, LPARAM flags) { if (m_useNativeCompWindow) return mrDoDefault; int* bndClauseW = NULL; jstring* readingClauseW = NULL; int* bndAttrW = NULL; BYTE* valAttrW = NULL; int cClauseW = 0; AwtInputTextInfor* textInfor = NULL; try { HIMC hIMC = ImmGetContext(); DASSERT(hIMC!=0); textInfor = new AwtInputTextInfor; textInfor->GetContextData(hIMC, flags); jstring jtextString = textInfor->GetText(); /* The conditions to send the input method event to AWT EDT are: 1. Whenever there is a composition message sent regarding whether the composition text is NULL or not. See details at bug 6222692. 2. When there is a committed message sent, in which case, we have to check whether the committed string is NULL or not. If the committed string is NULL, there is no need to send any input method event. (Minor note: 'jtextString' returned is the merged string in the case of partial commit.) */ if ((flags & GCS_RESULTSTR && jtextString != NULL) || (flags & GCS_COMPSTR)) { int cursorPosW = textInfor->GetCursorPosition(); // In order not to delete the readingClauseW in the catch clause, // calling GetAttributeInfor before GetClauseInfor. int cAttrW = textInfor->GetAttributeInfor(bndAttrW, valAttrW); cClauseW = textInfor->GetClauseInfor(bndClauseW, readingClauseW); /* Send INPUT_METHOD_TEXT_CHANGED event to the WInputMethod which in turn sends the event to AWT EDT. The last two paremeters are set to equal since we don't have recommendations for the visible position within the current composed text. See details at java.awt.event.InputMethodEvent. */ SendInputMethodEvent(java_awt_event_InputMethodEvent_INPUT_METHOD_TEXT_CHANGED, jtextString, cClauseW, bndClauseW, readingClauseW, cAttrW, bndAttrW, valAttrW, textInfor->GetCommittedTextLength(), cursorPosW, cursorPosW); } } catch (...) { // since GetClauseInfor and GetAttributeInfor could throw exception, we have to release // the pointer here. delete [] bndClauseW; delete [] readingClauseW; delete [] bndAttrW; delete [] valAttrW; throw; } /* Free the storage allocated. Since jtextString won't be passed from threads * to threads, we just use the local ref and it will be deleted within the destructor * of AwtInputTextInfor object. */ JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); if (cClauseW && readingClauseW) { for (int i = 0; i < cClauseW; i ++) { if (readingClauseW[i]) { env->DeleteLocalRef(readingClauseW[i]); } } } delete [] bndClauseW; delete [] readingClauseW; delete [] bndAttrW; delete [] valAttrW; delete textInfor; return mrConsume; } // // generate and post InputMethodEvent // void AwtComponent::SendInputMethodEvent(jint id, jstring text, int cClause, int* rgClauseBoundary, jstring* rgClauseReading, int cAttrBlock, int* rgAttrBoundary, BYTE *rgAttrValue, int commitedTextLength, int caretPos, int visiblePos) { JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); // assumption for array type casting DASSERT(sizeof(int)==sizeof(jint)); DASSERT(sizeof(BYTE)==sizeof(jbyte)); // caluse information jintArray clauseBoundary = NULL; jobjectArray clauseReading = NULL; if (cClause && rgClauseBoundary && rgClauseReading) { // convert clause boundary offset array to java array clauseBoundary = env->NewIntArray(cClause+1); env->SetIntArrayRegion(clauseBoundary, 0, cClause+1, (jint *)rgClauseBoundary); DASSERT(!safe_ExceptionOccurred(env)); // convert clause reading string array to java array clauseReading = env->NewObjectArray(cClause, JNU_ClassString(env), NULL); for (int i=0; i<cClause; i++) env->SetObjectArrayElement(clauseReading, i, rgClauseReading[i]); DASSERT(!safe_ExceptionOccurred(env)); } // attrubute value definition in WInputMethod.java must be equal to that in IMM.H DASSERT(ATTR_INPUT==sun_awt_windows_WInputMethod_ATTR_INPUT); DASSERT(ATTR_TARGET_CONVERTED==sun_awt_windows_WInputMethod_ATTR_TARGET_CONVERTED); DASSERT(ATTR_CONVERTED==sun_awt_windows_WInputMethod_ATTR_CONVERTED); DASSERT(ATTR_TARGET_NOTCONVERTED==sun_awt_windows_WInputMethod_ATTR_TARGET_NOTCONVERTED); DASSERT(ATTR_INPUT_ERROR==sun_awt_windows_WInputMethod_ATTR_INPUT_ERROR); // attribute information jintArray attrBoundary = NULL; jbyteArray attrValue = NULL; if (cAttrBlock && rgAttrBoundary && rgAttrValue) { // convert attribute boundary offset array to java array attrBoundary = env->NewIntArray(cAttrBlock+1); env->SetIntArrayRegion(attrBoundary, 0, cAttrBlock+1, (jint *)rgAttrBoundary); DASSERT(!safe_ExceptionOccurred(env)); // convert attribute value byte array to java array attrValue = env->NewByteArray(cAttrBlock); env->SetByteArrayRegion(attrValue, 0, cAttrBlock, (jbyte *)rgAttrValue); DASSERT(!safe_ExceptionOccurred(env)); } // get global reference of WInputMethod class (run only once) static jclass wInputMethodCls = NULL; if (wInputMethodCls == NULL) { jclass wInputMethodClsLocal = env->FindClass("sun/awt/windows/WInputMethod"); DASSERT(wInputMethodClsLocal); if (wInputMethodClsLocal == NULL) { /* exception already thrown */ return; } wInputMethodCls = (jclass)env->NewGlobalRef(wInputMethodClsLocal); env->DeleteLocalRef(wInputMethodClsLocal); } // get method ID of sendInputMethodEvent() (run only once) static jmethodID sendIMEventMid = 0; if (sendIMEventMid == 0) { sendIMEventMid = env->GetMethodID(wInputMethodCls, "sendInputMethodEvent", "(IJLjava/lang/String;[I[Ljava/lang/String;[I[BIII)V"); DASSERT(sendIMEventMid); } // call m_InputMethod.sendInputMethod() env->CallVoidMethod(m_InputMethod, sendIMEventMid, id, TimeHelper::getMessageTimeUTC(), text, clauseBoundary, clauseReading, attrBoundary, attrValue, commitedTextLength, caretPos, visiblePos); if (safe_ExceptionOccurred(env)) env->ExceptionDescribe(); DASSERT(!safe_ExceptionOccurred(env)); } // // Inquires candidate position according to the composed text // void AwtComponent::InquireCandidatePosition() { JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); // get global reference of WInputMethod class (run only once) static jclass wInputMethodCls = NULL; if (wInputMethodCls == NULL) { jclass wInputMethodClsLocal = env->FindClass("sun/awt/windows/WInputMethod"); DASSERT(wInputMethodClsLocal); if (wInputMethodClsLocal == NULL) { /* exception already thrown */ return; } wInputMethodCls = (jclass)env->NewGlobalRef(wInputMethodClsLocal); env->DeleteLocalRef(wInputMethodClsLocal); } // get method ID of sendInputMethodEvent() (run only once) static jmethodID inqCandPosMid = 0; if (inqCandPosMid == 0) { inqCandPosMid = env->GetMethodID(wInputMethodCls, "inquireCandidatePosition", "()V"); DASSERT(!safe_ExceptionOccurred(env)); DASSERT(inqCandPosMid); } // call m_InputMethod.sendInputMethod() jobject candPos = env->CallObjectMethod(m_InputMethod, inqCandPosMid); DASSERT(!safe_ExceptionOccurred(env)); } HIMC AwtComponent::ImmGetContext() { HWND proxy = GetProxyFocusOwner(); return ::ImmGetContext((proxy != NULL) ? proxy : GetHWnd()); } HIMC AwtComponent::ImmAssociateContext(HIMC himc) { HWND proxy = GetProxyFocusOwner(); return ::ImmAssociateContext((proxy != NULL) ? proxy : GetHWnd(), himc); } HWND AwtComponent::GetProxyFocusOwner() { AwtWindow *window = GetContainer(); if (window != 0) { AwtFrame *owner = window->GetOwningFrameOrDialog(); if (owner != 0) { return owner->GetProxyFocusOwner(); } else if (!window->IsSimpleWindow()) { // isn't an owned simple window return ((AwtFrame*)window)->GetProxyFocusOwner(); } } return (HWND)NULL; } /* Call DefWindowProc for the focus proxy, if any */ void AwtComponent::CallProxyDefWindowProc(UINT message, WPARAM wParam, LPARAM lParam, LRESULT &retVal, MsgRouting &mr) { if (mr != mrConsume) { HWND proxy = GetProxyFocusOwner(); if (proxy != NULL) { retVal = ComCtl32Util::GetInstance().DefWindowProc(NULL, proxy, message, wParam, lParam); mr = mrConsume; } } } MsgRouting AwtComponent::WmCommand(UINT id, HWND hWndChild, UINT notifyCode) { /* Menu/Accelerator */ if (hWndChild == 0) { AwtObject* obj = AwtToolkit::GetInstance().LookupCmdID(id); if (obj == NULL) { return mrConsume; } DASSERT(((AwtMenuItem*)obj)->GetID() == id); obj->DoCommand(); return mrConsume; } /* Child id notification */ else { AwtComponent* child = AwtComponent::GetComponent(hWndChild); if (child) { child->WmNotify(notifyCode); } } return mrDoDefault; } MsgRouting AwtComponent::WmNotify(UINT notifyCode) { return mrDoDefault; } MsgRouting AwtComponent::WmCompareItem(UINT ctrlId, COMPAREITEMSTRUCT &compareInfo, LRESULT &result) { AwtComponent* child = AwtComponent::GetComponent(compareInfo.hwndItem); if (child == this) { /* DoCallback("handleItemDelete", */ } else if (child) { return child->WmCompareItem(ctrlId, compareInfo, result); } return mrConsume; } MsgRouting AwtComponent::WmDeleteItem(UINT ctrlId, DELETEITEMSTRUCT &deleteInfo) { /* * Workaround for NT 4.0 bug -- if SetWindowPos is called on a AwtList * window, a WM_DELETEITEM message is sent to its parent with a window * handle of one of the list's child windows. The property lookup * succeeds, but the HWNDs don't match. */ if (deleteInfo.hwndItem == NULL) { return mrConsume; } AwtComponent* child = (AwtComponent *)AwtComponent::GetComponent(deleteInfo.hwndItem); if (child && child->GetHWnd() != deleteInfo.hwndItem) { return mrConsume; } if (child == this) { /*DoCallback("handleItemDelete", */ } else if (child) { return child->WmDeleteItem(ctrlId, deleteInfo); } return mrConsume; } MsgRouting AwtComponent::WmDrawItem(UINT ctrlId, DRAWITEMSTRUCT &drawInfo) { JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); if (drawInfo.CtlType == ODT_MENU) { if (drawInfo.itemData != 0) { AwtMenu* menu = (AwtMenu*)(drawInfo.itemData); menu->DrawItem(drawInfo); } } else { return OwnerDrawItem(ctrlId, drawInfo); } return mrConsume; } MsgRouting AwtComponent::WmMeasureItem(UINT ctrlId, MEASUREITEMSTRUCT &measureInfo) { JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); if (measureInfo.CtlType == ODT_MENU) { if (measureInfo.itemData != 0) { AwtMenu* menu = (AwtMenu*)(measureInfo.itemData); HDC hDC = ::GetDC(GetHWnd()); /* menu->MeasureItem(env, hDC, measureInfo); */ menu->MeasureItem(hDC, measureInfo); ::ReleaseDC(GetHWnd(), hDC); } } else { return OwnerMeasureItem(ctrlId, measureInfo); } return mrConsume; } MsgRouting AwtComponent::OwnerDrawItem(UINT ctrlId, DRAWITEMSTRUCT &drawInfo) { AwtComponent* child = AwtComponent::GetComponent(drawInfo.hwndItem); if (child == this) { /* DoCallback("handleItemDelete", */ } else if (child != NULL) { return child->WmDrawItem(ctrlId, drawInfo); } return mrConsume; } MsgRouting AwtComponent::OwnerMeasureItem(UINT ctrlId, MEASUREITEMSTRUCT &measureInfo) { HWND hChild = ::GetDlgItem(GetHWnd(), measureInfo.CtlID); AwtComponent* child = AwtComponent::GetComponent(hChild); /* * If the parent cannot find the child's instance from its handle, * maybe the child is in its creation. So the child must be searched * from the list linked before the child's creation. */ if (child == NULL) { child = SearchChild((UINT)ctrlId); } if (child == this) { /* DoCallback("handleItemDelete", */ } else if (child) { return child->WmMeasureItem(ctrlId, measureInfo); } return mrConsume; } /* for WmDrawItem method of Label, Button and Checkbox */ void AwtComponent::DrawWindowText(HDC hDC, jobject font, jstring text, int x, int y) { int nOldBkMode = ::SetBkMode(hDC,TRANSPARENT); DASSERT(nOldBkMode != 0); AwtFont::drawMFString(hDC, font, text, x, y, GetCodePage()); VERIFY(::SetBkMode(hDC,nOldBkMode)); } /* * Draw text in gray (the color being set to COLOR_GRAYTEXT) when the * component is disabled. Used only for label, checkbox and button in * OWNER_DRAW. It draws the text in emboss. */ void AwtComponent::DrawGrayText(HDC hDC, jobject font, jstring text, int x, int y) { ::SetTextColor(hDC, ::GetSysColor(COLOR_BTNHILIGHT)); AwtComponent::DrawWindowText(hDC, font, text, x+1, y+1); ::SetTextColor(hDC, ::GetSysColor(COLOR_BTNSHADOW)); AwtComponent::DrawWindowText(hDC, font, text, x, y); } /* for WmMeasureItem method of List and Choice */ jstring AwtComponent::GetItemString(JNIEnv *env, jobject target, jint index) { jstring str = (jstring)JNU_CallMethodByName(env, NULL, target, "getItemImpl", "(I)Ljava/lang/String;", index).l; DASSERT(!safe_ExceptionOccurred(env)); return str; } /* for WmMeasureItem method of List and Choice */ void AwtComponent::MeasureListItem(JNIEnv *env, MEASUREITEMSTRUCT &measureInfo) { if (env->EnsureLocalCapacity(1) < 0) { return; } jobject dimension = PreferredItemSize(env); DASSERT(dimension); measureInfo.itemWidth = env->GetIntField(dimension, AwtDimension::widthID); measureInfo.itemHeight = env->GetIntField(dimension, AwtDimension::heightID); env->DeleteLocalRef(dimension); } /* for WmDrawItem method of List and Choice */ void AwtComponent::DrawListItem(JNIEnv *env, DRAWITEMSTRUCT &drawInfo) { if (env->EnsureLocalCapacity(3) < 0) { return; } jobject peer = GetPeer(env); jobject target = env->GetObjectField(peer, AwtObject::targetID); HDC hDC = drawInfo.hDC; RECT rect = drawInfo.rcItem; BOOL bEnabled = isEnabled(); BOOL unfocusableChoice = (drawInfo.itemState & ODS_COMBOBOXEDIT) && !IsFocusable(); DWORD crBack, crText; if (drawInfo.itemState & ODS_SELECTED){ /* Set background and text colors for selected item */ crBack = ::GetSysColor (COLOR_HIGHLIGHT); crText = ::GetSysColor (COLOR_HIGHLIGHTTEXT); } else { /* Set background and text colors for unselected item */ crBack = GetBackgroundColor(); crText = bEnabled ? GetColor() : ::GetSysColor(COLOR_GRAYTEXT); } if (unfocusableChoice) { //6190728. Shouldn't draw selection field (edit control) of an owner-drawn combo box. crBack = GetBackgroundColor(); crText = bEnabled ? GetColor() : ::GetSysColor(COLOR_GRAYTEXT); } /* Fill item rectangle with background color */ HBRUSH hbrBack = ::CreateSolidBrush (crBack); DASSERT(hbrBack); /* 6190728. Shouldn't draw any kind of rectangle around selection field * (edit control) of an owner-drawn combo box while unfocusable */ if (!unfocusableChoice){ VERIFY(::FillRect (hDC, &rect, hbrBack)); } VERIFY(::DeleteObject (hbrBack)); /* Set current background and text colors */ ::SetBkColor (hDC, crBack); ::SetTextColor (hDC, crText); /*draw string (with left margin of 1 point) */ if ((int) (drawInfo.itemID) >= 0) { jobject font = GET_FONT(target, peer); jstring text = GetItemString(env, target, drawInfo.itemID); SIZE size = AwtFont::getMFStringSize(hDC, font, text); AwtFont::drawMFString(hDC, font, text, (GetRTL()) ? rect.right - size.cx - 1 : rect.left + 1, (rect.top + rect.bottom - size.cy) / 2, GetCodePage()); env->DeleteLocalRef(font); env->DeleteLocalRef(text); } if ((drawInfo.itemState & ODS_FOCUS) && (drawInfo.itemAction & (ODA_FOCUS | ODA_DRAWENTIRE))) { if (!unfocusableChoice){ VERIFY(::DrawFocusRect(hDC, &rect)); } } env->DeleteLocalRef(target); } /* for MeasureListItem method and WmDrawItem method of Checkbox */ jint AwtComponent::GetFontHeight(JNIEnv *env) { if (env->EnsureLocalCapacity(4) < 0) { return NULL; } jobject self = GetPeer(env); jobject target = env->GetObjectField(self, AwtObject::targetID); jobject font = GET_FONT(target, self); jobject toolkit = env->CallObjectMethod(target, AwtComponent::getToolkitMID); DASSERT(!safe_ExceptionOccurred(env)); jobject fontMetrics = env->CallObjectMethod(toolkit, AwtToolkit::getFontMetricsMID, font); DASSERT(!safe_ExceptionOccurred(env)); jint height = env->CallIntMethod(fontMetrics, AwtFont::getHeightMID); DASSERT(!safe_ExceptionOccurred(env)); env->DeleteLocalRef(target); env->DeleteLocalRef(font); env->DeleteLocalRef(toolkit); env->DeleteLocalRef(fontMetrics); return height; } // If you override WmPrint, make sure to save a copy of the DC on the GDI // stack to be restored in WmPrintClient. Windows mangles the DC in // ::DefWindowProc. MsgRouting AwtComponent::WmPrint(HDC hDC, LPARAM flags) { /* * DefWindowProc for WM_PRINT changes DC parameters, so we have * to restore it ourselves. Otherwise it will cause problems * when several components are printed to the same DC. */ int nOriginalDC = ::SaveDC(hDC); DASSERT(nOriginalDC != 0); if (flags & PRF_NONCLIENT) { VERIFY(::SaveDC(hDC)); DefWindowProc(WM_PRINT, (WPARAM)hDC, (flags & (PRF_NONCLIENT | PRF_CHECKVISIBLE | PRF_ERASEBKGND))); VERIFY(::RestoreDC(hDC, -1)); // Special case for components with a sunken border. Windows does not // print the border correctly on PCL printers, so we have to do it ourselves. if (GetStyleEx() & WS_EX_CLIENTEDGE) { RECT r; VERIFY(::GetWindowRect(GetHWnd(), &r)); VERIFY(::OffsetRect(&r, -r.left, -r.top)); VERIFY(::DrawEdge(hDC, &r, EDGE_SUNKEN, BF_RECT)); } } if (flags & PRF_CLIENT) { /* * Special case for components with a sunken border. * Windows prints a client area without offset to a border width. * We will first print the non-client area with the original offset, * then the client area with a corrected offset. */ if (GetStyleEx() & WS_EX_CLIENTEDGE) { int nEdgeWidth = ::GetSystemMetrics(SM_CXEDGE); int nEdgeHeight = ::GetSystemMetrics(SM_CYEDGE); VERIFY(::OffsetWindowOrgEx(hDC, -nEdgeWidth, -nEdgeHeight, NULL)); // Save a copy of the DC for WmPrintClient VERIFY(::SaveDC(hDC)); DefWindowProc(WM_PRINT, (WPARAM) hDC, (flags & (PRF_CLIENT | PRF_CHECKVISIBLE | PRF_ERASEBKGND))); VERIFY(::OffsetWindowOrgEx(hDC, nEdgeWidth, nEdgeHeight, NULL)); } else { // Save a copy of the DC for WmPrintClient VERIFY(::SaveDC(hDC)); DefWindowProc(WM_PRINT, (WPARAM) hDC, (flags & (PRF_CLIENT | PRF_CHECKVISIBLE | PRF_ERASEBKGND))); } } if (flags & (PRF_CHILDREN | PRF_OWNED)) { DefWindowProc(WM_PRINT, (WPARAM) hDC, (flags & ~PRF_CLIENT & ~PRF_NONCLIENT)); } VERIFY(::RestoreDC(hDC, nOriginalDC)); return mrConsume; } // If you override WmPrintClient, make sure to obtain a valid copy of // the DC from the GDI stack. The copy of the DC should have been placed // there by WmPrint. Windows mangles the DC in ::DefWindowProc. MsgRouting AwtComponent::WmPrintClient(HDC hDC, LPARAM) { // obtain valid DC from GDI stack ::RestoreDC(hDC, -1); return mrDoDefault; } MsgRouting AwtComponent::WmNcCalcSize(BOOL fCalcValidRects, LPNCCALCSIZE_PARAMS lpncsp, LRESULT &retVal) { return mrDoDefault; } MsgRouting AwtComponent::WmNcPaint(HRGN hrgn) { return mrDoDefault; } MsgRouting AwtComponent::WmNcHitTest(UINT x, UINT y, LRESULT &retVal) { return mrDoDefault; } /** * WmQueryNewPalette is called whenever our component is coming to * the foreground; this gives us an opportunity to install our * custom palette. If this install actually changes entries in * the system palette, then we get a further call to WmPaletteChanged * (but note that we only need to realize our palette once). */ MsgRouting AwtComponent::WmQueryNewPalette(LRESULT &retVal) { int screen = AwtWin32GraphicsDevice::DeviceIndexForWindow(GetHWnd()); m_QueryNewPaletteCalled = TRUE; HDC hDC = ::GetDC(GetHWnd()); DASSERT(hDC); AwtWin32GraphicsDevice::SelectPalette(hDC, screen); AwtWin32GraphicsDevice::RealizePalette(hDC, screen); ::ReleaseDC(GetHWnd(), hDC); // We must realize the palettes of all of our DC's // There is sometimes a problem where the realization of // our temporary hDC here does not actually do what // we want. Not clear why, but presumably fallout from // our use of several simultaneous hDC's. activeDCList.RealizePalettes(screen); // Do not invalidate here; if the palette // has not changed we will get an extra repaint retVal = TRUE; return mrDoDefault; } /** * We should not need to track this event since we handle our * palette management effectively in the WmQueryNewPalette and * WmPaletteChanged methods. However, there seems to be a bug * on some win32 systems (e.g., NT4) whereby the palette * immediately after a displayChange is not yet updated to its * final post-display-change values (hence we adjust our palette * using the wrong system palette entries), then the palette is * updated, but a WM_PALETTECHANGED message is never sent. * By tracking the ISCHANGING message as well (and by tracking * displayChange events in the AwtToolkit object), we can account * for this error by forcing our WmPaletteChanged method to be * called and thereby realizing our logical palette and updating * our dynamic colorModel object. */ MsgRouting AwtComponent::WmPaletteIsChanging(HWND hwndPalChg) { if (AwtToolkit::GetInstance().HasDisplayChanged()) { WmPaletteChanged(hwndPalChg); AwtToolkit::GetInstance().ResetDisplayChanged(); } return mrDoDefault; } MsgRouting AwtComponent::WmPaletteChanged(HWND hwndPalChg) { // We need to re-realize our palette here (unless we're the one // that was realizing it in the first place). That will let us match the // remaining colors in the system palette as best we can. We always // invalidate because the palette will have changed when we receive this // message. int screen = AwtWin32GraphicsDevice::DeviceIndexForWindow(GetHWnd()); if (hwndPalChg != GetHWnd()) { HDC hDC = ::GetDC(GetHWnd()); DASSERT(hDC); AwtWin32GraphicsDevice::SelectPalette(hDC, screen); AwtWin32GraphicsDevice::RealizePalette(hDC, screen); ::ReleaseDC(GetHWnd(), hDC); // We must realize the palettes of all of our DC's activeDCList.RealizePalettes(screen); } if (AwtWin32GraphicsDevice::UpdateSystemPalette(screen)) { AwtWin32GraphicsDevice::UpdateDynamicColorModel(screen); } Invalidate(NULL); return mrDoDefault; } MsgRouting AwtComponent::WmStyleChanged(int wStyleType, LPSTYLESTRUCT lpss) { DASSERT(!IsBadReadPtr(lpss, sizeof(STYLESTRUCT))); return mrDoDefault; } MsgRouting AwtComponent::WmSettingChange(UINT wFlag, LPCTSTR pszSection) { DASSERT(!IsBadStringPtr(pszSection, 20)); DTRACE_PRINTLN2("WM_SETTINGCHANGE: wFlag=%d pszSection=%s", (int)wFlag, pszSection); return mrDoDefault; } HDC AwtComponent::GetDCFromComponent() { GetDCReturnStruct *hdcStruct = (GetDCReturnStruct*)SendMessage(WM_AWT_GETDC); HDC hdc; if (hdcStruct) { if (hdcStruct->gdiLimitReached) { if (jvm != NULL) { JNIEnv* env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); if (env != NULL && !safe_ExceptionOccurred(env)) { JNU_ThrowByName(env, "java/awt/AWTError", "HDC creation failure - " \ "exceeded maximum GDI resources"); } } } hdc = hdcStruct->hDC; delete hdcStruct; } else { hdc = NULL; } return hdc; } void AwtComponent::FillBackground(HDC hMemoryDC, SIZE &size) { RECT eraseR = { 0, 0, size.cx, size.cy }; VERIFY(::FillRect(hMemoryDC, &eraseR, GetBackgroundBrush())); } void AwtComponent::FillAlpha(void *bitmapBits, SIZE &size, BYTE alpha) { if (!bitmapBits) { return; } DWORD* dest = (DWORD*)bitmapBits; //XXX: might be optimized to use one loop (cy*cx -> 0) for (int i = 0; i < size.cy; i++ ) { for (int j = 0; j < size.cx; j++ ) { ((BYTE*)(dest++))[3] = alpha; } } } jintArray AwtComponent::CreatePrintedPixels(SIZE &loc, SIZE &size, int alpha) { JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); if (!::IsWindowVisible(GetHWnd())) { return NULL; } HDC hdc = GetDCFromComponent(); if (!hdc) { return NULL; } HDC hMemoryDC = ::CreateCompatibleDC(hdc); void *bitmapBits = NULL; HBITMAP hBitmap = BitmapUtil::CreateARGBBitmap(size.cx, size.cy, &bitmapBits); HBITMAP hOldBitmap = (HBITMAP)::SelectObject(hMemoryDC, hBitmap); SendMessage(WM_AWT_RELEASEDC, (WPARAM)hdc); FillBackground(hMemoryDC, size); VERIFY(::SetWindowOrgEx(hMemoryDC, loc.cx, loc.cy, NULL)); // Don't bother with PRF_CHECKVISIBLE because we called IsWindowVisible // above. SendMessage(WM_PRINT, (WPARAM)hMemoryDC, PRF_CLIENT | PRF_NONCLIENT); // First make sure the system completed any drawing to the bitmap. ::GdiFlush(); // WM_PRINT does not fill the alpha-channel of the ARGB bitmap // leaving it equal to zero. Hence we need to fill it manually. Otherwise // the pixels will be considered transparent when interpreting the data. FillAlpha(bitmapBits, size, alpha); ::SelectObject(hMemoryDC, hOldBitmap); BITMAPINFO bmi; memset(&bmi, 0, sizeof(BITMAPINFO)); bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); bmi.bmiHeader.biWidth = size.cx; bmi.bmiHeader.biHeight = -size.cy; bmi.bmiHeader.biPlanes = 1; bmi.bmiHeader.biBitCount = 32; bmi.bmiHeader.biCompression = BI_RGB; jobject localPixelArray = env->NewIntArray(size.cx * size.cy); jintArray pixelArray = NULL; if (localPixelArray != NULL) { pixelArray = (jintArray)env->NewGlobalRef(localPixelArray); env->DeleteLocalRef(localPixelArray); localPixelArray = NULL; jboolean isCopy; jint *pixels = env->GetIntArrayElements(pixelArray, &isCopy); ::GetDIBits(hMemoryDC, hBitmap, 0, size.cy, (LPVOID)pixels, &bmi, DIB_RGB_COLORS); env->ReleaseIntArrayElements(pixelArray, pixels, 0); } VERIFY(::DeleteObject(hBitmap)); VERIFY(::DeleteDC(hMemoryDC)); return pixelArray; } void* AwtComponent::SetNativeFocusOwner(void *self) { if (self == NULL) { // It means that the KFM wants to set focus to null sm_focusOwner = NULL; return NULL; } JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); AwtComponent *c = NULL; jobject peer = (jobject)self; PDATA pData; JNI_CHECK_NULL_GOTO(peer, "peer", ret); pData = JNI_GET_PDATA(peer); if (pData == NULL) { goto ret; } c = (AwtComponent *)pData; ret: if (c && ::IsWindow(c->GetHWnd())) { sm_focusOwner = c->GetHWnd(); } else { sm_focusOwner = NULL; } env->DeleteGlobalRef(peer); return NULL; } void* AwtComponent::GetNativeFocusedWindow() { JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); AwtComponent *comp = AwtComponent::GetComponent(AwtComponent::GetFocusedWindow()); return (comp != NULL) ? comp->GetTargetAsGlobalRef(env) : NULL; } void* AwtComponent::GetNativeFocusOwner() { JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); AwtComponent *comp = AwtComponent::GetComponent(AwtComponent::sm_focusOwner); return (comp != NULL) ? comp->GetTargetAsGlobalRef(env) : NULL; } AwtComponent* AwtComponent::SearchChild(UINT id) { ChildListItem* child; for (child = m_childList; child != NULL;child = child->m_next) { if (child->m_ID == id) return child->m_Component; } /* * DASSERT(FALSE); * This should not be happend if all children are recorded */ return NULL; /* make compiler happy */ } void AwtComponent::RemoveChild(UINT id) { ChildListItem* child = m_childList; ChildListItem* lastChild = NULL; while (child != NULL) { if (child->m_ID == id) { if (lastChild == NULL) { m_childList = child->m_next; } else { lastChild->m_next = child->m_next; } child->m_next = NULL; DASSERT(child != NULL); delete child; return; } lastChild = child; child = child->m_next; } } void AwtComponent::SendKeyEvent(jint id, jlong when, jint raw, jint cooked, jint modifiers, jint keyLocation, jlong nativeCode, MSG *pMsg) { JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); CriticalSection::Lock l(GetLock()); if (GetPeer(env) == NULL) { /* event received during termination. */ return; } static jclass keyEventCls; if (keyEventCls == NULL) { jclass keyEventClsLocal = env->FindClass("java/awt/event/KeyEvent"); DASSERT(keyEventClsLocal); if (keyEventClsLocal == NULL) { /* exception already thrown */ return; } keyEventCls = (jclass)env->NewGlobalRef(keyEventClsLocal); env->DeleteLocalRef(keyEventClsLocal); } static jmethodID keyEventConst; if (keyEventConst == NULL) { keyEventConst = env->GetMethodID(keyEventCls, "<init>", "(Ljava/awt/Component;IJIICI)V"); DASSERT(keyEventConst); } if (env->EnsureLocalCapacity(2) < 0) { return; } jobject target = GetTarget(env); jobject keyEvent = env->NewObject(keyEventCls, keyEventConst, target, id, when, modifiers, raw, cooked, keyLocation); if (safe_ExceptionOccurred(env)) env->ExceptionDescribe(); DASSERT(!safe_ExceptionOccurred(env)); DASSERT(keyEvent != NULL); env->SetLongField(keyEvent, AwtKeyEvent::rawCodeID, nativeCode); if( nativeCode && nativeCode < 256 ) { env->SetLongField(keyEvent, AwtKeyEvent::primaryLevelUnicodeID, (jlong)(dynPrimaryKeymap[nativeCode].unicode)); env->SetLongField(keyEvent, AwtKeyEvent::extendedKeyCodeID, (jlong)(dynPrimaryKeymap[nativeCode].jkey)); if( nativeCode < 255 ) { env->SetLongField(keyEvent, AwtKeyEvent::scancodeID, (jlong)(dynPrimaryKeymap[nativeCode].scancode)); }else if( pMsg != NULL ) { // unknown key with virtual keycode 0xFF. // Its scancode is not in the table, pickup it from the message. env->SetLongField(keyEvent, AwtKeyEvent::scancodeID, (jlong)(HIWORD(pMsg->lParam) & 0xFF)); } } if (pMsg != NULL) { AwtAWTEvent::saveMSG(env, pMsg, keyEvent); } SendEvent(keyEvent); env->DeleteLocalRef(keyEvent); env->DeleteLocalRef(target); } void AwtComponent::SendKeyEventToFocusOwner(jint id, jlong when, jint raw, jint cooked, jint modifiers, jint keyLocation, jlong nativeCode, MSG *msg) { /* * if focus owner is null, but focused window isn't * we will send key event to focused window */ HWND hwndTarget = ((sm_focusOwner != NULL) ? sm_focusOwner : AwtComponent::GetFocusedWindow()); if (hwndTarget == GetHWnd()) { SendKeyEvent(id, when, raw, cooked, modifiers, keyLocation, nativeCode, msg); } else { AwtComponent *target = NULL; if (hwndTarget != NULL) { target = AwtComponent::GetComponent(hwndTarget); if (target == NULL) { target = this; } } if (target != NULL) { target->SendKeyEvent(id, when, raw, cooked, modifiers, keyLocation, nativeCode, msg); } } } void AwtComponent::SetDragCapture(UINT flags) { // don't want to interfere with other controls if (::GetCapture() == NULL) { ::SetCapture(GetHWnd()); } } void AwtComponent::ReleaseDragCapture(UINT flags) { if ((::GetCapture() == GetHWnd()) && ((flags & ALL_MK_BUTTONS) == 0)) { // user has released all buttons, so release the capture ::ReleaseCapture(); } } void AwtComponent::SendMouseEvent(jint id, jlong when, jint x, jint y, jint modifiers, jint clickCount, jboolean popupTrigger, jint button, MSG *pMsg) { JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); CriticalSection::Lock l(GetLock()); if (GetPeer(env) == NULL) { /* event received during termination. */ return; } static jclass mouseEventCls; if (mouseEventCls == NULL) { jclass mouseEventClsLocal = env->FindClass("java/awt/event/MouseEvent"); if (!mouseEventClsLocal) { /* exception already thrown */ return; } mouseEventCls = (jclass)env->NewGlobalRef(mouseEventClsLocal); env->DeleteLocalRef(mouseEventClsLocal); } RECT insets; GetInsets(&insets); static jmethodID mouseEventConst; if (mouseEventConst == NULL) { mouseEventConst = env->GetMethodID(mouseEventCls, "<init>", "(Ljava/awt/Component;IJIIIIIIZI)V"); DASSERT(mouseEventConst); } if (env->EnsureLocalCapacity(2) < 0) { return; } jobject target = GetTarget(env); DWORD curMousePos = ::GetMessagePos(); int xAbs = GET_X_LPARAM(curMousePos); int yAbs = GET_Y_LPARAM(curMousePos); jobject mouseEvent = env->NewObject(mouseEventCls, mouseEventConst, target, id, when, modifiers, x+insets.left, y+insets.top, xAbs, yAbs, clickCount, popupTrigger, button); if (safe_ExceptionOccurred(env)) { env->ExceptionDescribe(); env->ExceptionClear(); } DASSERT(mouseEvent != NULL); if (pMsg != 0) { AwtAWTEvent::saveMSG(env, pMsg, mouseEvent); } SendEvent(mouseEvent); env->DeleteLocalRef(mouseEvent); env->DeleteLocalRef(target); } void AwtComponent::SendMouseWheelEvent(jint id, jlong when, jint x, jint y, jint modifiers, jint clickCount, jboolean popupTrigger, jint scrollType, jint scrollAmount, jint roundedWheelRotation, jdouble preciseWheelRotation, MSG *pMsg) { /* Code based not so loosely on AwtComponent::SendMouseEvent */ JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); CriticalSection::Lock l(GetLock()); if (GetPeer(env) == NULL) { /* event received during termination. */ return; } static jclass mouseWheelEventCls; if (mouseWheelEventCls == NULL) { jclass mouseWheelEventClsLocal = env->FindClass("java/awt/event/MouseWheelEvent"); if (!mouseWheelEventClsLocal) { /* exception already thrown */ return; } mouseWheelEventCls = (jclass)env->NewGlobalRef(mouseWheelEventClsLocal); env->DeleteLocalRef(mouseWheelEventClsLocal); } RECT insets; GetInsets(&insets); static jmethodID mouseWheelEventConst; if (mouseWheelEventConst == NULL) { mouseWheelEventConst = env->GetMethodID(mouseWheelEventCls, "<init>", "(Ljava/awt/Component;IJIIIIIIZIIID)V"); DASSERT(mouseWheelEventConst); } if (env->EnsureLocalCapacity(2) < 0) { return; } jobject target = GetTarget(env); DTRACE_PRINTLN("creating MWE in JNI"); jobject mouseWheelEvent = env->NewObject(mouseWheelEventCls, mouseWheelEventConst, target, id, when, modifiers, x+insets.left, y+insets.top, 0, 0, clickCount, popupTrigger, scrollType, scrollAmount, roundedWheelRotation, preciseWheelRotation); if (safe_ExceptionOccurred(env)) { env->ExceptionDescribe(); env->ExceptionClear(); } DASSERT(mouseWheelEvent != NULL); if (pMsg != NULL) { AwtAWTEvent::saveMSG(env, pMsg, mouseWheelEvent); } SendEvent(mouseWheelEvent); env->DeleteLocalRef(mouseWheelEvent); env->DeleteLocalRef(target); } void AwtComponent::SendFocusEvent(jint id, HWND opposite) { JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); CriticalSection::Lock l(GetLock()); if (GetPeer(env) == NULL) { /* event received during termination. */ return; } static jclass focusEventCls; if (focusEventCls == NULL) { jclass focusEventClsLocal = env->FindClass("java/awt/event/FocusEvent"); DASSERT(focusEventClsLocal); if (focusEventClsLocal == NULL) { /* exception already thrown */ return; } focusEventCls = (jclass)env->NewGlobalRef(focusEventClsLocal); env->DeleteLocalRef(focusEventClsLocal); } static jmethodID focusEventConst; if (focusEventConst == NULL) { focusEventConst = env->GetMethodID(focusEventCls, "<init>", "(Ljava/awt/Component;IZLjava/awt/Component;)V"); DASSERT(focusEventConst); } static jclass sequencedEventCls; if (sequencedEventCls == NULL) { jclass sequencedEventClsLocal = env->FindClass("java/awt/SequencedEvent"); DASSERT(sequencedEventClsLocal); if (sequencedEventClsLocal == NULL) { /* exception already thrown */ return; } sequencedEventCls = (jclass)env->NewGlobalRef(sequencedEventClsLocal); env->DeleteLocalRef(sequencedEventClsLocal); } static jmethodID sequencedEventConst; if (sequencedEventConst == NULL) { sequencedEventConst = env->GetMethodID(sequencedEventCls, "<init>", "(Ljava/awt/AWTEvent;)V"); } if (env->EnsureLocalCapacity(3) < 0) { return; } jobject target = GetTarget(env); jobject jOpposite = NULL; if (opposite != NULL) { AwtComponent *awtOpposite = AwtComponent::GetComponent(opposite); if (awtOpposite != NULL) { jOpposite = awtOpposite->GetTarget(env); } } jobject focusEvent = env->NewObject(focusEventCls, focusEventConst, target, id, JNI_FALSE, jOpposite); DASSERT(!safe_ExceptionOccurred(env)); DASSERT(focusEvent != NULL); if (jOpposite != NULL) { env->DeleteLocalRef(jOpposite); jOpposite = NULL; } env->DeleteLocalRef(target); target = NULL; jobject sequencedEvent = env->NewObject(sequencedEventCls, sequencedEventConst, focusEvent); DASSERT(!safe_ExceptionOccurred(env)); DASSERT(sequencedEvent != NULL); env->DeleteLocalRef(focusEvent); focusEvent = NULL; SendEvent(sequencedEvent); env->DeleteLocalRef(sequencedEvent); } /* * Forward a filtered event directly to the subclassed window. * This method is needed so that DefWindowProc is invoked on the * component's owning thread. */ MsgRouting AwtComponent::HandleEvent(MSG *msg, BOOL) { DefWindowProc(msg->message, msg->wParam, msg->lParam); delete msg; return mrConsume; } /* Post a WM_AWT_HANDLE_EVENT message which invokes HandleEvent on the toolkit thread. This method may pre-filter the messages. */ BOOL AwtComponent::PostHandleEventMessage(MSG *msg, BOOL synthetic) { JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); // We should cut off keyboard events to disabled components // to avoid the components responding visually to keystrokes when disabled. // we shouldn't cut off WM_SYS* messages as they aren't used for normal activity // but to activate menus, close windows, etc switch(msg->message) { case WM_KEYDOWN: case WM_KEYUP: case WM_CHAR: case WM_DEADCHAR: { if (!isRecursivelyEnabled()) { goto quit; } break; } } if (PostMessage(GetHWnd(), WM_AWT_HANDLE_EVENT, (WPARAM) synthetic, (LPARAM) msg)) { return TRUE; } else { JNU_ThrowInternalError(env, "Message not posted, native event queue may be full."); } quit: delete msg; return FALSE; } void AwtComponent::SynthesizeKeyMessage(JNIEnv *env, jobject keyEvent) { jint id = (env)->GetIntField(keyEvent, AwtAWTEvent::idID); UINT message; switch (id) { case java_awt_event_KeyEvent_KEY_PRESSED: message = WM_KEYDOWN; break; case java_awt_event_KeyEvent_KEY_RELEASED: message = WM_KEYUP; break; case java_awt_event_KeyEvent_KEY_TYPED: message = WM_CHAR; break; default: return; } /* * KeyEvent.modifiers aren't supported -- the Java apppwd must send separate * KEY_PRESSED and KEY_RELEASED events for the modifier virtual keys. */ if (id == java_awt_event_KeyEvent_KEY_TYPED) { // WM_CHAR message must be posted using WM_AWT_FORWARD_CHAR // (for Edit control) jchar keyChar = (jchar) (env)->GetCharField(keyEvent, AwtKeyEvent::keyCharID); // Bugid 4724007. If it is a Delete character, don't send the fake // KEY_TYPED we created back to the native window: Windows doesn't // expect a WM_CHAR for Delete in TextFields, so it tries to enter a // character after deleting. if (keyChar == '\177') { // the Delete character return; } // Disable forwarding WM_CHAR messages to disabled components if (isRecursivelyEnabled()) { if (!::PostMessage(GetHWnd(), WM_AWT_FORWARD_CHAR, MAKEWPARAM(keyChar, TRUE), 0)) { JNU_ThrowInternalError(env, "Message not posted, native event queue may be full."); } } } else { jint keyCode = (env)->GetIntField(keyEvent, AwtKeyEvent::keyCodeID); UINT key, modifiers; AwtComponent::JavaKeyToWindowsKey(keyCode, &key, &modifiers); MSG* msg = CreateMessage(message, key, 0); PostHandleEventMessage(msg, TRUE); } } void AwtComponent::SynthesizeMouseMessage(JNIEnv *env, jobject mouseEvent) { /* DebugBreak(); */ jint button = (env)->GetIntField(mouseEvent, AwtMouseEvent::buttonID); jint modifiers = (env)->GetIntField(mouseEvent, AwtInputEvent::modifiersID); WPARAM wParam = 0; WORD wLow = 0; jint wheelAmt = 0; jint id = (env)->GetIntField(mouseEvent, AwtAWTEvent::idID); UINT message; switch (id) { case java_awt_event_MouseEvent_MOUSE_PRESSED: { switch (button) { case java_awt_event_MouseEvent_BUTTON1: message = WM_LBUTTONDOWN; break; case java_awt_event_MouseEvent_BUTTON3: message = WM_MBUTTONDOWN; break; case java_awt_event_MouseEvent_BUTTON2: message = WM_RBUTTONDOWN; break; } break; } case java_awt_event_MouseEvent_MOUSE_RELEASED: { switch (button) { case java_awt_event_MouseEvent_BUTTON1: message = WM_LBUTTONUP; break; case java_awt_event_MouseEvent_BUTTON3: message = WM_MBUTTONUP; break; case java_awt_event_MouseEvent_BUTTON2: message = WM_RBUTTONUP; break; } break; } case java_awt_event_MouseEvent_MOUSE_MOVED: /* MOUSE_DRAGGED events must first have sent a MOUSE_PRESSED event. */ case java_awt_event_MouseEvent_MOUSE_DRAGGED: message = WM_MOUSEMOVE; break; case java_awt_event_MouseEvent_MOUSE_WHEEL: if (modifiers & java_awt_event_InputEvent_CTRL_DOWN_MASK) { wLow |= MK_CONTROL; } if (modifiers & java_awt_event_InputEvent_SHIFT_DOWN_MASK) { wLow |= MK_SHIFT; } if (modifiers & java_awt_event_InputEvent_BUTTON1_DOWN_MASK) { wLow |= MK_LBUTTON; } if (modifiers & java_awt_event_InputEvent_BUTTON2_DOWN_MASK) { wLow |= MK_RBUTTON; } if (modifiers & java_awt_event_InputEvent_BUTTON3_DOWN_MASK) { wLow |= MK_MBUTTON; } if (modifiers & X1_BUTTON) { wLow |= GetButtonMK(X1_BUTTON); } if (modifiers & X2_BUTTON) { wLow |= GetButtonMK(X2_BUTTON); } wheelAmt = (jint)JNU_CallMethodByName(env, NULL, mouseEvent, "getWheelRotation", "()I").i; DASSERT(!safe_ExceptionOccurred(env)); //DASSERT(wheelAmt); DTRACE_PRINTLN1("wheelAmt = %i\n", wheelAmt); // convert Java wheel amount value to Win32 wheelAmt *= -1 * WHEEL_DELTA; message = WM_MOUSEWHEEL; wParam = MAKEWPARAM(wLow, wheelAmt); break; default: return; } jint x = (env)->GetIntField(mouseEvent, AwtMouseEvent::xID); jint y = (env)->GetIntField(mouseEvent, AwtMouseEvent::yID); MSG* msg = CreateMessage(message, wParam, MAKELPARAM(x, y), x, y); PostHandleEventMessage(msg, TRUE); } BOOL AwtComponent::InheritsNativeMouseWheelBehavior() {return false;} void AwtComponent::Invalidate(RECT* r) { ::InvalidateRect(GetHWnd(), r, FALSE); } void AwtComponent::BeginValidate() { DASSERT(m_validationNestCount >= 0 && m_validationNestCount < 1000); // sanity check if (m_validationNestCount == 0) { // begin deferred window positioning if we're not inside // another Begin/EndValidate pair DASSERT(m_hdwp == NULL); m_hdwp = ::BeginDeferWindowPos(32); } m_validationNestCount++; } void AwtComponent::EndValidate() { DASSERT(m_validationNestCount > 0 && m_validationNestCount < 1000); // sanity check DASSERT(m_hdwp != NULL); m_validationNestCount--; if (m_validationNestCount == 0) { // if this call to EndValidate is not nested inside another // Begin/EndValidate pair, end deferred window positioning ::EndDeferWindowPos(m_hdwp); m_hdwp = NULL; } } /** * HWND, AwtComponent and Java Peer interaction */ /* *Link the C++, Java peer, and HWNDs together. */ void AwtComponent::LinkObjects(JNIEnv *env, jobject peer) { /* * Bind all three objects together thru this C++ object, two-way to each: * JavaPeer <-> C++ <-> HWND * * C++ -> JavaPeer */ if (m_peerObject == NULL) { // This may have already been set up by CreateHWnd // And we don't want to create two references so we // will leave the prior one alone m_peerObject = env->NewGlobalRef(peer); } /* JavaPeer -> HWND */ env->SetLongField(peer, AwtComponent::hwndID, reinterpret_cast<jlong>(m_hwnd)); /* JavaPeer -> C++ */ JNI_SET_PDATA(peer, this); /* HWND -> C++ */ SetComponentInHWND(); } /* Cleanup above linking */ void AwtComponent::UnlinkObjects() { JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); if (m_peerObject) { env->SetLongField(m_peerObject, AwtComponent::hwndID, 0); JNI_SET_PDATA(m_peerObject, static_cast<PDATA>(NULL)); JNI_SET_DESTROYED(m_peerObject); env->DeleteGlobalRef(m_peerObject); m_peerObject = NULL; } } void AwtComponent::Enable(BOOL bEnable) { if (bEnable && IsTopLevel()) { // we should not enable blocked toplevels bEnable = !::IsWindow(AwtWindow::GetModalBlocker(GetHWnd())); } // Shouldn't trigger native focus change // (only the proxy may be the native focus owner). ::EnableWindow(GetHWnd(), bEnable); CriticalSection::Lock l(GetLock()); VerifyState(); } /* * associate an AwtDropTarget with this AwtComponent */ AwtDropTarget* AwtComponent::CreateDropTarget(JNIEnv* env) { m_dropTarget = new AwtDropTarget(env, this); m_dropTarget->RegisterTarget(TRUE); return m_dropTarget; } /* * disassociate an AwtDropTarget with this AwtComponent */ void AwtComponent::DestroyDropTarget() { if (m_dropTarget != NULL) { m_dropTarget->RegisterTarget(FALSE); m_dropTarget->Release(); m_dropTarget = NULL; } } BOOL AwtComponent::IsFocusingMouseMessage(MSG *pMsg) { return pMsg->message == WM_LBUTTONDOWN || pMsg->message == WM_LBUTTONDBLCLK; } BOOL AwtComponent::IsFocusingKeyMessage(MSG *pMsg) { return pMsg->message == WM_KEYDOWN && pMsg->wParam == VK_SPACE; } void AwtComponent::_Show(void *param) { JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); jobject self = (jobject)param; AwtComponent *p; PDATA pData; JNI_CHECK_PEER_GOTO(self, ret); p = (AwtComponent *)pData; if (::IsWindow(p->GetHWnd())) { p->SendMessage(WM_AWT_COMPONENT_SHOW); } ret: env->DeleteGlobalRef(self); } void AwtComponent::_Hide(void *param) { JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); jobject self = (jobject)param; AwtComponent *p; PDATA pData; JNI_CHECK_PEER_GOTO(self, ret); p = (AwtComponent *)pData; if (::IsWindow(p->GetHWnd())) { p->SendMessage(WM_AWT_COMPONENT_HIDE); } ret: env->DeleteGlobalRef(self); } void AwtComponent::_Enable(void *param) { JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); jobject self = (jobject)param; AwtComponent *p; PDATA pData; JNI_CHECK_PEER_GOTO(self, ret); p = (AwtComponent *)pData; if (::IsWindow(p->GetHWnd())) { p->Enable(TRUE); } ret: env->DeleteGlobalRef(self); } void AwtComponent::_Disable(void *param) { JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); jobject self = (jobject)param; AwtComponent *p; PDATA pData; JNI_CHECK_PEER_GOTO(self, ret); p = (AwtComponent *)pData; if (::IsWindow(p->GetHWnd())) { p->Enable(FALSE); } ret: env->DeleteGlobalRef(self); } jobject AwtComponent::_GetLocationOnScreen(void *param) { JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); jobject self = (jobject)param; jobject result = NULL; AwtComponent *p; PDATA pData; JNI_CHECK_PEER_GOTO(self, ret); p = (AwtComponent *)pData; if (::IsWindow(p->GetHWnd())) { RECT rect; VERIFY(::GetWindowRect(p->GetHWnd(),&rect)); result = JNU_NewObjectByName(env, "java/awt/Point", "(II)V", rect.left, rect.top); } ret: env->DeleteGlobalRef(self); if (result != NULL) { jobject resultGlobalRef = env->NewGlobalRef(result); env->DeleteLocalRef(result); return resultGlobalRef; } else { return NULL; } } void AwtComponent::_Reshape(void *param) { JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); ReshapeStruct *rs = (ReshapeStruct*)param; jobject self = rs->component; jint x = rs->x; jint y = rs->y; jint w = rs->w; jint h = rs->h; AwtComponent *p; PDATA pData; JNI_CHECK_PEER_GOTO(self, ret); p = (AwtComponent *)pData; if (::IsWindow(p->GetHWnd())) { RECT* r = new RECT; ::SetRect(r, x, y, x + w, y + h); p->SendMessage(WM_AWT_RESHAPE_COMPONENT, CHECK_EMBEDDED, (LPARAM)r); } ret: env->DeleteGlobalRef(self); delete rs; } void AwtComponent::_ReshapeNoCheck(void *param) { JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); ReshapeStruct *rs = (ReshapeStruct*)param; jobject self = rs->component; jint x = rs->x; jint y = rs->y; jint w = rs->w; jint h = rs->h; AwtComponent *p; PDATA pData; JNI_CHECK_PEER_GOTO(self, ret); p = (AwtComponent *)pData; if (::IsWindow(p->GetHWnd())) { RECT* r = new RECT; ::SetRect(r, x, y, x + w, y + h); p->SendMessage(WM_AWT_RESHAPE_COMPONENT, DONT_CHECK_EMBEDDED, (LPARAM)r); } ret: env->DeleteGlobalRef(self); delete rs; } void AwtComponent::_NativeHandleEvent(void *param) { JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); NativeHandleEventStruct *nhes = (NativeHandleEventStruct *)param; jobject self = nhes->component; jobject event = nhes->event; AwtComponent *p; PDATA pData; JNI_CHECK_NULL_GOTO(self, "peer", ret); pData = JNI_GET_PDATA(self); if (pData == NULL) { env->DeleteGlobalRef(self); if (event != NULL) { env->DeleteGlobalRef(event); } delete nhes; return; } JNI_CHECK_NULL_GOTO(event, "null AWTEvent", ret); p = (AwtComponent *)pData; if (::IsWindow(p->GetHWnd())) { if (env->EnsureLocalCapacity(1) < 0) { env->DeleteGlobalRef(self); env->DeleteGlobalRef(event); delete nhes; return; } jbyteArray bdata = (jbyteArray)(env)->GetObjectField(event, AwtAWTEvent::bdataID); int id = (env)->GetIntField(event, AwtAWTEvent::idID); DASSERT(!safe_ExceptionOccurred(env)); if (bdata != 0) { MSG msg; (env)->GetByteArrayRegion(bdata, 0, sizeof(MSG), (jbyte *)&msg); (env)->DeleteLocalRef(bdata); static BOOL keyDownConsumed = FALSE; static BOOL bCharChanged = FALSE; static WCHAR modifiedChar; WCHAR unicodeChar; /* Remember if a KEY_PRESSED event is consumed, as an old model * program won't consume a subsequent KEY_TYPED event. */ jboolean consumed = (env)->GetBooleanField(event, AwtAWTEvent::consumedID); DASSERT(!safe_ExceptionOccurred(env)); if (consumed) { keyDownConsumed = (id == java_awt_event_KeyEvent_KEY_PRESSED); env->DeleteGlobalRef(self); env->DeleteGlobalRef(event); delete nhes; return; } else if (id == java_awt_event_KeyEvent_KEY_PRESSED) { // Fix for 6637607: reset consuming keyDownConsumed = FALSE; } /* Consume a KEY_TYPED event if a KEY_PRESSED had been, to support * the old model. */ if ((id == java_awt_event_KeyEvent_KEY_TYPED) && keyDownConsumed) { keyDownConsumed = FALSE; env->DeleteGlobalRef(self); env->DeleteGlobalRef(event); delete nhes; return; } /* Modify any event parameters, if necessary. */ if (self && pData && id >= java_awt_event_KeyEvent_KEY_FIRST && id <= java_awt_event_KeyEvent_KEY_LAST) { AwtComponent* p = (AwtComponent*)pData; jint keyCode = (env)->GetIntField(event, AwtKeyEvent::keyCodeID); jchar keyChar = (env)->GetCharField(event, AwtKeyEvent::keyCharID); jint modifiers = (env)->GetIntField(event, AwtInputEvent::modifiersID); DASSERT(!safe_ExceptionOccurred(env)); /* Check to see whether the keyCode or modifiers were changed on the keyPressed event, and tweak the following keyTyped event (if any) accodingly. */ switch (id) { case java_awt_event_KeyEvent_KEY_PRESSED: { UINT winKey = (UINT)msg.wParam; bCharChanged = FALSE; if (winKey == VK_PROCESSKEY) { // Leave it up to IME break; } if (keyCode != java_awt_event_KeyEvent_VK_UNDEFINED) { UINT newWinKey, ignored; p->JavaKeyToWindowsKey(keyCode, &newWinKey, &ignored, winKey); if (newWinKey != 0) { winKey = newWinKey; } } modifiedChar = p->WindowsKeyToJavaChar(winKey, modifiers, AwtComponent::NONE); bCharChanged = (keyChar != modifiedChar); } break; case java_awt_event_KeyEvent_KEY_RELEASED: { keyDownConsumed = FALSE; bCharChanged = FALSE; } break; case java_awt_event_KeyEvent_KEY_TYPED: { if (bCharChanged) { unicodeChar = modifiedChar; } else { unicodeChar = keyChar; } bCharChanged = FALSE; // Disable forwarding KEY_TYPED messages to peers of // disabled components if (p->isRecursivelyEnabled()) { // send the character back to the native window for // processing. The WM_AWT_FORWARD_CHAR handler will send // this character to DefWindowProc if (!::PostMessage(p->GetHWnd(), WM_AWT_FORWARD_CHAR, MAKEWPARAM(unicodeChar, FALSE), msg.lParam)) { JNU_ThrowInternalError(env, "Message not posted, native event queue may be full."); } } env->DeleteGlobalRef(self); env->DeleteGlobalRef(event); delete nhes; return; } break; default: break; } } // ignore all InputMethodEvents if (self && (pData = JNI_GET_PDATA(self)) && id >= java_awt_event_InputMethodEvent_INPUT_METHOD_FIRST && id <= java_awt_event_InputMethodEvent_INPUT_METHOD_LAST) { env->DeleteGlobalRef(self); env->DeleteGlobalRef(event); delete nhes; return; } // Create copy for local msg MSG* pCopiedMsg = new MSG; memmove(pCopiedMsg, &msg, sizeof(MSG)); // Event handler deletes msg p->PostHandleEventMessage(pCopiedMsg, FALSE); env->DeleteGlobalRef(self); env->DeleteGlobalRef(event); delete nhes; return; } /* Forward any valid synthesized events. Currently only mouse and * key events are supported. */ if (self == NULL || (pData = JNI_GET_PDATA(self)) == NULL) { env->DeleteGlobalRef(self); env->DeleteGlobalRef(event); delete nhes; return; } AwtComponent* p = (AwtComponent*)pData; if (id >= java_awt_event_KeyEvent_KEY_FIRST && id <= java_awt_event_KeyEvent_KEY_LAST) { p->SynthesizeKeyMessage(env, event); } else if (id >= java_awt_event_MouseEvent_MOUSE_FIRST && id <= java_awt_event_MouseEvent_MOUSE_LAST) { p->SynthesizeMouseMessage(env, event); } } ret: if (self != NULL) { env->DeleteGlobalRef(self); } if (event != NULL) { env->DeleteGlobalRef(event); } delete nhes; } void AwtComponent::_SetForeground(void *param) { JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); SetColorStruct *scs = (SetColorStruct *)param; jobject self = scs->component; jint rgb = scs->rgb; AwtComponent *c = NULL; PDATA pData; JNI_CHECK_PEER_GOTO(self, ret); c = (AwtComponent *)pData; if (::IsWindow(c->GetHWnd())) { c->SetColor(PALETTERGB((rgb>>16)&0xff, (rgb>>8)&0xff, (rgb)&0xff)); c->VerifyState(); } ret: env->DeleteGlobalRef(self); delete scs; } void AwtComponent::_SetBackground(void *param) { JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); SetColorStruct *scs = (SetColorStruct *)param; jobject self = scs->component; jint rgb = scs->rgb; AwtComponent *c = NULL; PDATA pData; JNI_CHECK_PEER_GOTO(self, ret); c = (AwtComponent *)pData; if (::IsWindow(c->GetHWnd())) { c->SetBackgroundColor(PALETTERGB((rgb>>16)&0xff, (rgb>>8)&0xff, (rgb)&0xff)); c->VerifyState(); } ret: env->DeleteGlobalRef(self); delete scs; } void AwtComponent::_SetFont(void *param) { JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); SetFontStruct *sfs = (SetFontStruct *)param; jobject self = sfs->component; jobject font = sfs->font; AwtComponent *c = NULL; PDATA pData; JNI_CHECK_PEER_GOTO(self, ret); JNI_CHECK_NULL_GOTO(font, "null font", ret); c = (AwtComponent *)pData; if (::IsWindow(c->GetHWnd())) { AwtFont *awtFont = (AwtFont *)env->GetLongField(font, AwtFont::pDataID); if (awtFont == NULL) { /*arguments of AwtFont::Create are changed for multifont component */ awtFont = AwtFont::Create(env, font); } env->SetLongField(font, AwtFont::pDataID, (jlong)awtFont); c->SetFont(awtFont); } ret: env->DeleteGlobalRef(self); env->DeleteGlobalRef(font); delete sfs; } // Sets or kills focus for a component. void AwtComponent::_SetFocus(void *param) { JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); SetFocusStruct *sfs = (SetFocusStruct *)param; jobject self = sfs->component; jboolean doSetFocus = sfs->doSetFocus; AwtComponent *c = NULL; PDATA pData; JNI_CHECK_NULL_GOTO(self, "peer", ret); pData = JNI_GET_PDATA(self); if (pData == NULL) { // do nothing just return false goto ret; } c = (AwtComponent *)pData; if (::IsWindow(c->GetHWnd())) { c->SendMessage(WM_AWT_COMPONENT_SETFOCUS, (WPARAM)doSetFocus, 0); } ret: env->DeleteGlobalRef(self); delete sfs; } void AwtComponent::_Start(void *param) { JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); jobject self = (jobject)param; AwtComponent *c = NULL; PDATA pData; JNI_CHECK_PEER_GOTO(self, ret); c = (AwtComponent *)pData; if (::IsWindow(c->GetHWnd())) { jobject target = c->GetTarget(env); /* Disable window if specified -- windows are enabled by default. */ jboolean enabled = (jboolean)env->GetBooleanField(target, AwtComponent::enabledID); if (!enabled) { ::EnableWindow(c->GetHWnd(), FALSE); } /* The peer is now ready for callbacks, since this is the last * initialization call */ c->EnableCallbacks(TRUE); // Fix 4745222: we need to invalidate region since we validated it before initialization. ::InvalidateRgn(c->GetHWnd(), NULL, FALSE); // Fix 4530093: WM_PAINT after EnableCallbacks ::UpdateWindow(c->GetHWnd()); env->DeleteLocalRef(target); } ret: env->DeleteGlobalRef(self); } void AwtComponent::_BeginValidate(void *param) { JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); if (AwtToolkit::IsMainThread()) { jobject self = (jobject)param; if (self != NULL) { PDATA pData = JNI_GET_PDATA(self); if (pData) { AwtComponent *c = (AwtComponent *)pData; if (::IsWindow(c->GetHWnd())) { c->SendMessage(WM_AWT_BEGIN_VALIDATE); } } env->DeleteGlobalRef(self); } } else { AwtToolkit::GetInstance().InvokeFunction(AwtComponent::_BeginValidate, param); } } void AwtComponent::_EndValidate(void *param) { if (AwtToolkit::IsMainThread()) { JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); jobject self = (jobject)param; if (self != NULL) { PDATA pData = JNI_GET_PDATA(self); if (pData) { AwtComponent *c = (AwtComponent *)pData; if (::IsWindow(c->GetHWnd())) { c->SendMessage(WM_AWT_END_VALIDATE); } } env->DeleteGlobalRef(self); } } else { AwtToolkit::GetInstance().InvokeFunction(AwtComponent::_EndValidate, param); } } void AwtComponent::_UpdateWindow(void *param) { JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); if (AwtToolkit::IsMainThread()) { jobject self = (jobject)param; AwtComponent *c = NULL; PDATA pData; JNI_CHECK_PEER_GOTO(self, ret); c = (AwtComponent *)pData; if (::IsWindow(c->GetHWnd())) { ::UpdateWindow(c->GetHWnd()); } ret: env->DeleteGlobalRef(self); } else { AwtToolkit::GetInstance().InvokeFunction(AwtComponent::_UpdateWindow, param); } } jlong AwtComponent::_AddNativeDropTarget(void *param) { JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); jobject self = (jobject)param; jlong result = 0; AwtComponent *c = NULL; PDATA pData; JNI_CHECK_PEER_GOTO(self, ret); c = (AwtComponent *)pData; if (::IsWindow(c->GetHWnd())) { result = (jlong)(c->CreateDropTarget(env)); } ret: env->DeleteGlobalRef(self); return result; } void AwtComponent::_RemoveNativeDropTarget(void *param) { JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); jobject self = (jobject)param; AwtComponent *c = NULL; PDATA pData; JNI_CHECK_PEER_GOTO(self, ret); c = (AwtComponent *)pData; if (::IsWindow(c->GetHWnd())) { c->DestroyDropTarget(); } ret: env->DeleteGlobalRef(self); } jintArray AwtComponent::_CreatePrintedPixels(void *param) { JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); CreatePrintedPixelsStruct *cpps = (CreatePrintedPixelsStruct *)param; jobject self = cpps->component; jintArray result = NULL; AwtComponent *c = NULL; PDATA pData; JNI_CHECK_PEER_GOTO(self, ret); c = (AwtComponent *)pData; if (::IsWindow(c->GetHWnd())) { result = (jintArray)c->SendMessage(WM_AWT_CREATE_PRINTED_PIXELS, (WPARAM)cpps, 0); } ret: env->DeleteGlobalRef(self); delete cpps; return result; // this reference is global } jboolean AwtComponent::_IsObscured(void *param) { JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); jobject self = (jobject)param; jboolean result = JNI_FALSE; AwtComponent *c = NULL; PDATA pData; JNI_CHECK_PEER_GOTO(self, ret); c = (AwtComponent *)pData; if (::IsWindow(c->GetHWnd())) { HWND hWnd = c->GetHWnd(); HDC hDC = ::GetDC(hWnd); RECT clipbox; int callresult = ::GetClipBox(hDC, &clipbox); switch(callresult) { case NULLREGION : result = JNI_FALSE; break; case SIMPLEREGION : { RECT windowRect; if (!::GetClientRect(hWnd, &windowRect)) { result = JNI_TRUE; } else { result = (jboolean)((clipbox.bottom != windowRect.bottom) || (clipbox.left != windowRect.left) || (clipbox.right != windowRect.right) || (clipbox.top != windowRect.top)); } break; } case COMPLEXREGION : default : result = JNI_TRUE; break; } ::ReleaseDC(hWnd, hDC); } ret: env->DeleteGlobalRef(self); return result; } jboolean AwtComponent::_NativeHandlesWheelScrolling(void *param) { JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); jobject self = (jobject)param; jboolean result = JNI_FALSE; AwtComponent *c = NULL; PDATA pData; JNI_CHECK_PEER_GOTO(self, ret); c = (AwtComponent *)pData; if (::IsWindow(c->GetHWnd())) { result = (jboolean)c->InheritsNativeMouseWheelBehavior(); } ret: env->DeleteGlobalRef(self); return result; } void AwtComponent::SetParent(void * param) { if (AwtToolkit::IsMainThread()) { AwtComponent** comps = (AwtComponent**)param; if ((comps[0] != NULL) && (comps[1] != NULL)) { HWND selfWnd = comps[0]->GetHWnd(); HWND parentWnd = comps[1]->GetHWnd(); if (::IsWindow(selfWnd) && ::IsWindow(parentWnd)) { // Shouldn't trigger native focus change // (only the proxy may be the native focus owner). ::SetParent(selfWnd, parentWnd); } } delete[] comps; } else { AwtToolkit::GetInstance().InvokeFunction(AwtComponent::SetParent, param); } } void AwtComponent::_SetRectangularShape(void *param) { if (!AwtToolkit::IsMainThread()) { AwtToolkit::GetInstance().InvokeFunction(AwtComponent::_SetRectangularShape, param); } else { JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); SetRectangularShapeStruct *data = (SetRectangularShapeStruct *)param; jobject self = data->component; jint x1 = data->x1; jint x2 = data->x2; jint y1 = data->y1; jint y2 = data->y2; jobject region = data->region; AwtComponent *c = NULL; PDATA pData; JNI_CHECK_PEER_GOTO(self, ret); c = (AwtComponent *)pData; if (::IsWindow(c->GetHWnd())) { HRGN hRgn = NULL; if (region || x1 || x2 || y1 || y2) { // If all the params are zeros, the shape must be simply reset. // Otherwise, convert it into a region. RGNDATA *pRgnData = NULL; RGNDATAHEADER *pRgnHdr; /* reserving memory for the worst case */ size_t worstBufferSize = size_t(((x2 - x1) / 2 + 1) * (y2 - y1)); pRgnData = (RGNDATA *) safe_Malloc(sizeof(RGNDATAHEADER) + sizeof(RECT_T) * worstBufferSize); pRgnHdr = (RGNDATAHEADER *) pRgnData; pRgnHdr->dwSize = sizeof(RGNDATAHEADER); pRgnHdr->iType = RDH_RECTANGLES; pRgnHdr->nRgnSize = 0; pRgnHdr->rcBound.top = 0; pRgnHdr->rcBound.left = 0; pRgnHdr->rcBound.bottom = LONG(y2 - y1); pRgnHdr->rcBound.right = LONG(x2 - x1); RECT_T * pRect = (RECT_T *) (((BYTE *) pRgnData) + sizeof(RGNDATAHEADER)); pRgnHdr->nCount = RegionToYXBandedRectangles(env, x1, y1, x2, y2, region, &pRect, worstBufferSize); hRgn = ::ExtCreateRegion(NULL, sizeof(RGNDATAHEADER) + sizeof(RECT_T) * pRgnHdr->nCount, pRgnData); free(pRgnData); } ::SetWindowRgn(c->GetHWnd(), hRgn, TRUE); } ret: env->DeleteGlobalRef(self); if (region) { env->DeleteGlobalRef(region); } delete data; } } void AwtComponent::_SetZOrder(void *param) { JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); SetZOrderStruct *data = (SetZOrderStruct *)param; jobject self = data->component; HWND above = HWND_TOP; if (data->above != 0) { above = reinterpret_cast<HWND>(data->above); } AwtComponent *c = NULL; PDATA pData; JNI_CHECK_PEER_GOTO(self, ret); c = (AwtComponent *)pData; if (::IsWindow(c->GetHWnd())) { ::SetWindowPos(c->GetHWnd(), above, 0, 0, 0, 0, SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_DEFERERASE | SWP_ASYNCWINDOWPOS); } ret: env->DeleteGlobalRef(self); delete data; } void AwtComponent::PostUngrabEvent() { JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); jobject target = GetTarget(env); jobject event = JNU_NewObjectByName(env, "sun/awt/UngrabEvent", "(Ljava/awt/Component;)V", target); if (safe_ExceptionOccurred(env)) { env->ExceptionDescribe(); env->ExceptionClear(); } env->DeleteLocalRef(target); if (event != NULL) { SendEvent(event); env->DeleteLocalRef(event); } } void AwtComponent::SetFocusedWindow(HWND window) { HWND old = sm_focusedWindow; sm_focusedWindow = window; AwtWindow::FocusedWindowChanged(old, window); } /************************************************************************ * Component native methods */ extern "C" { /** * This method is called from the WGL pipeline when it needs to retrieve * the HWND associated with a ComponentPeer's C++ level object. */ HWND AwtComponent_GetHWnd(JNIEnv *env, jlong pData) { AwtComponent *p = (AwtComponent *)jlong_to_ptr(pData); if (p == NULL) { return (HWND)0; } return p->GetHWnd(); } static void _GetInsets(void* param) { JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); GetInsetsStruct *gis = (GetInsetsStruct *)param; jobject self = gis->window; gis->insets->left = gis->insets->top = gis->insets->right = gis->insets->bottom = 0; PDATA pData; JNI_CHECK_PEER_GOTO(self, ret); AwtComponent *component = (AwtComponent *)pData; component->GetInsets(gis->insets); ret: env->DeleteGlobalRef(self); delete gis; } /** * This method is called from the WGL pipeline when it needs to retrieve * the insets associated with a ComponentPeer's C++ level object. */ void AwtComponent_GetInsets(JNIEnv *env, jobject peer, RECT *insets) { TRY; GetInsetsStruct *gis = new GetInsetsStruct; gis->window = env->NewGlobalRef(peer); gis->insets = insets; AwtToolkit::GetInstance().InvokeFunction(_GetInsets, gis); // global refs and mds are deleted in _UpdateWindow CATCH_BAD_ALLOC; } JNIEXPORT void JNICALL Java_java_awt_Component_initIDs(JNIEnv *env, jclass cls) { TRY; jclass inputEventClazz = env->FindClass("java/awt/event/InputEvent"); jmethodID getButtonDownMasksID = env->GetStaticMethodID(inputEventClazz, "getButtonDownMasks", "()[I"); jintArray obj = (jintArray)env->CallStaticObjectMethod(inputEventClazz, getButtonDownMasksID); jint * tmp = env->GetIntArrayElements(obj, JNI_FALSE); jsize len = env->GetArrayLength(obj); AwtComponent::masks = new jint[len]; for (int i = 0; i < len; i++) { AwtComponent::masks[i] = tmp[i]; } env->ReleaseIntArrayElements(obj, tmp, 0); env->DeleteLocalRef(obj); /* class ids */ jclass peerCls = env->FindClass("sun/awt/windows/WComponentPeer"); DASSERT(peerCls); /* field ids */ AwtComponent::peerID = env->GetFieldID(cls, "peer", "Ljava/awt/peer/ComponentPeer;"); AwtComponent::xID = env->GetFieldID(cls, "x", "I"); AwtComponent::yID = env->GetFieldID(cls, "y", "I"); AwtComponent::heightID = env->GetFieldID(cls, "height", "I"); AwtComponent::widthID = env->GetFieldID(cls, "width", "I"); AwtComponent::visibleID = env->GetFieldID(cls, "visible", "Z"); AwtComponent::backgroundID = env->GetFieldID(cls, "background", "Ljava/awt/Color;"); AwtComponent::foregroundID = env->GetFieldID(cls, "foreground", "Ljava/awt/Color;"); AwtComponent::enabledID = env->GetFieldID(cls, "enabled", "Z"); AwtComponent::parentID = env->GetFieldID(cls, "parent", "Ljava/awt/Container;"); AwtComponent::graphicsConfigID = env->GetFieldID(cls, "graphicsConfig", "Ljava/awt/GraphicsConfiguration;"); AwtComponent::focusableID = env->GetFieldID(cls, "focusable", "Z"); AwtComponent::appContextID = env->GetFieldID(cls, "appContext", "Lsun/awt/AppContext;"); AwtComponent::peerGCID = env->GetFieldID(peerCls, "winGraphicsConfig", "Lsun/awt/Win32GraphicsConfig;"); AwtComponent::hwndID = env->GetFieldID(peerCls, "hwnd", "J"); AwtComponent::cursorID = env->GetFieldID(cls, "cursor", "Ljava/awt/Cursor;"); /* method ids */ AwtComponent::getFontMID = env->GetMethodID(cls, "getFont_NoClientCode", "()Ljava/awt/Font;"); AwtComponent::getToolkitMID = env->GetMethodID(cls, "getToolkitImpl", "()Ljava/awt/Toolkit;"); AwtComponent::isEnabledMID = env->GetMethodID(cls, "isEnabledImpl", "()Z"); AwtComponent::getLocationOnScreenMID = env->GetMethodID(cls, "getLocationOnScreen_NoTreeLock", "()Ljava/awt/Point;"); AwtComponent::replaceSurfaceDataMID = env->GetMethodID(peerCls, "replaceSurfaceData", "()V"); AwtComponent::replaceSurfaceDataLaterMID = env->GetMethodID(peerCls, "replaceSurfaceDataLater", "()V"); DASSERT(AwtComponent::xID); DASSERT(AwtComponent::yID); DASSERT(AwtComponent::heightID); DASSERT(AwtComponent::widthID); DASSERT(AwtComponent::visibleID); DASSERT(AwtComponent::backgroundID); DASSERT(AwtComponent::foregroundID); DASSERT(AwtComponent::enabledID); DASSERT(AwtComponent::parentID); DASSERT(AwtComponent::hwndID); DASSERT(AwtComponent::getFontMID); DASSERT(AwtComponent::getToolkitMID); DASSERT(AwtComponent::isEnabledMID); DASSERT(AwtComponent::getLocationOnScreenMID); DASSERT(AwtComponent::replaceSurfaceDataMID); DASSERT(AwtComponent::replaceSurfaceDataLaterMID); CATCH_BAD_ALLOC; } } /* extern "C" */ /************************************************************************ * ComponentPeer native methods */ extern "C" { /* * Class: sun_awt_windows_WComponentPeer * Method: pShow * Signature: ()V */ JNIEXPORT void JNICALL Java_sun_awt_windows_WComponentPeer_pShow(JNIEnv *env, jobject self) { TRY; jobject selfGlobalRef = env->NewGlobalRef(self); AwtToolkit::GetInstance().SyncCall(AwtComponent::_Show, (void *)selfGlobalRef); // selfGlobalRef is deleted in _Show CATCH_BAD_ALLOC; } /* * Class: sun_awt_windows_WComponentPeer * Method: hide * Signature: ()V */ JNIEXPORT void JNICALL Java_sun_awt_windows_WComponentPeer_hide(JNIEnv *env, jobject self) { TRY; jobject selfGlobalRef = env->NewGlobalRef(self); AwtToolkit::GetInstance().SyncCall(AwtComponent::_Hide, (void *)selfGlobalRef); // selfGlobalRef is deleted in _Hide CATCH_BAD_ALLOC; } /* * Class: sun_awt_windows_WComponentPeer * Method: enable * Signature: ()V */ JNIEXPORT void JNICALL Java_sun_awt_windows_WComponentPeer_enable(JNIEnv *env, jobject self) { TRY; jobject selfGlobalRef = env->NewGlobalRef(self); AwtToolkit::GetInstance().SyncCall(AwtComponent::_Enable, (void *)selfGlobalRef); // selfGlobalRef is deleted in _Enable CATCH_BAD_ALLOC; } /* * Class: sun_awt_windows_WComponentPeer * Method: disable * Signature: ()V */ JNIEXPORT void JNICALL Java_sun_awt_windows_WComponentPeer_disable(JNIEnv *env, jobject self) { TRY; jobject selfGlobalRef = env->NewGlobalRef(self); AwtToolkit::GetInstance().SyncCall(AwtComponent::_Disable, (void *)selfGlobalRef); // selfGlobalRef is deleted in _Disable CATCH_BAD_ALLOC; } /* * Class: sun_awt_windows_WComponentPeer * Method: getLocationOnScreen * Signature: ()Ljava/awt/Point; */ JNIEXPORT jobject JNICALL Java_sun_awt_windows_WComponentPeer_getLocationOnScreen(JNIEnv *env, jobject self) { TRY; jobject selfGlobalRef = env->NewGlobalRef(self); jobject resultGlobalRef = (jobject)AwtToolkit::GetInstance().SyncCall( (void*(*)(void*))AwtComponent::_GetLocationOnScreen, (void *)selfGlobalRef); // selfGlobalRef is deleted in _GetLocationOnScreen if (resultGlobalRef != NULL) { jobject resultLocalRef = env->NewLocalRef(resultGlobalRef); env->DeleteGlobalRef(resultGlobalRef); return resultLocalRef; } return NULL; CATCH_BAD_ALLOC_RET(NULL); } /* * Class: sun_awt_windows_WComponentPeer * Method: reshape * Signature: (IIII)V */ JNIEXPORT void JNICALL Java_sun_awt_windows_WComponentPeer_reshape(JNIEnv *env, jobject self, jint x, jint y, jint w, jint h) { TRY; ReshapeStruct *rs = new ReshapeStruct; rs->component = env->NewGlobalRef(self); rs->x = x; rs->y = y; rs->w = w; rs->h = h; AwtToolkit::GetInstance().SyncCall(AwtComponent::_Reshape, rs); // global ref and rs are deleted in _Reshape CATCH_BAD_ALLOC; } /* * Class: sun_awt_windows_WComponentPeer * Method: reshape * Signature: (IIII)V */ JNIEXPORT void JNICALL Java_sun_awt_windows_WComponentPeer_reshapeNoCheck(JNIEnv *env, jobject self, jint x, jint y, jint w, jint h) { TRY; ReshapeStruct *rs = new ReshapeStruct; rs->component = env->NewGlobalRef(self); rs->x = x; rs->y = y; rs->w = w; rs->h = h; AwtToolkit::GetInstance().SyncCall(AwtComponent::_ReshapeNoCheck, rs); // global ref and rs are deleted in _ReshapeNoCheck CATCH_BAD_ALLOC; } /* * Class: sun_awt_windows_WComponentPeer * Method: nativeHandleEvent * Signature: (Ljava/awt/AWTEvent;)V */ JNIEXPORT void JNICALL Java_sun_awt_windows_WComponentPeer_nativeHandleEvent(JNIEnv *env, jobject self, jobject event) { TRY; jobject selfGlobalRef = env->NewGlobalRef(self); jobject eventGlobalRef = env->NewGlobalRef(event); NativeHandleEventStruct *nhes = new NativeHandleEventStruct; nhes->component = selfGlobalRef; nhes->event = eventGlobalRef; AwtToolkit::GetInstance().SyncCall(AwtComponent::_NativeHandleEvent, nhes); // global refs and nhes are deleted in _NativeHandleEvent CATCH_BAD_ALLOC; } /* * Class: sun_awt_windows_WComponentPeer * Method: _dispose * Signature: ()V */ JNIEXPORT void JNICALL Java_sun_awt_windows_WComponentPeer__1dispose(JNIEnv *env, jobject self) { TRY_NO_HANG; AwtObject::_Dispose(self); CATCH_BAD_ALLOC; } /* * Class: sun_awt_windows_WComponentPeer * Method: _setForeground * Signature: (I)V */ JNIEXPORT void JNICALL Java_sun_awt_windows_WComponentPeer__1setForeground(JNIEnv *env, jobject self, jint rgb) { TRY; jobject selfGlobalRef = env->NewGlobalRef(self); SetColorStruct *scs = new SetColorStruct; scs->component = selfGlobalRef; scs->rgb = rgb; AwtToolkit::GetInstance().SyncCall(AwtComponent::_SetForeground, scs); // selfGlobalRef and scs are deleted in _SetForeground() CATCH_BAD_ALLOC; } /* * Class: sun_awt_windows_WComponentPeer * Method: _setBackground * Signature: (I)V */ JNIEXPORT void JNICALL Java_sun_awt_windows_WComponentPeer__1setBackground(JNIEnv *env, jobject self, jint rgb) { TRY; jobject selfGlobalRef = env->NewGlobalRef(self); SetColorStruct *scs = new SetColorStruct; scs->component = selfGlobalRef; scs->rgb = rgb; AwtToolkit::GetInstance().SyncCall(AwtComponent::_SetBackground, scs); // selfGlobalRef and scs are deleted in _SetBackground() CATCH_BAD_ALLOC; } /* * Class: sun_awt_windows_WComponentPeer * Method: _setFont * Signature: (Ljava/awt/Font;)V */ JNIEXPORT void JNICALL Java_sun_awt_windows_WComponentPeer__1setFont(JNIEnv *env, jobject self, jobject font) { TRY; jobject selfGlobalRef = env->NewGlobalRef(self); jobject fontGlobalRef = env->NewGlobalRef(font); SetFontStruct *sfs = new SetFontStruct; sfs->component = selfGlobalRef; sfs->font = fontGlobalRef; AwtToolkit::GetInstance().SyncCall(AwtComponent::_SetFont, sfs); // global refs and sfs are deleted in _SetFont() CATCH_BAD_ALLOC; } /* * Class: sun_awt_windows_WComponentPeer * Method: focusGained * Signature: (Z) */ JNIEXPORT void JNICALL Java_sun_awt_windows_WComponentPeer_setFocus (JNIEnv *env, jobject self, jboolean doSetFocus) { TRY; jobject selfGlobalRef = env->NewGlobalRef(self); SetFocusStruct *sfs = new SetFocusStruct; sfs->component = selfGlobalRef; sfs->doSetFocus = doSetFocus; AwtToolkit::GetInstance().SyncCall( (void*(*)(void*))AwtComponent::_SetFocus, sfs); // global refs and self are deleted in _SetFocus CATCH_BAD_ALLOC; } /* * Class: sun_awt_windows_WComponentPeer * Method: start * Signature: ()V */ JNIEXPORT void JNICALL Java_sun_awt_windows_WComponentPeer_start(JNIEnv *env, jobject self) { TRY; jobject selfGlobalRef = env->NewGlobalRef(self); AwtToolkit::GetInstance().SyncCall(AwtComponent::_Start, (void *)selfGlobalRef); // selfGlobalRef is deleted in _Start CATCH_BAD_ALLOC; } /* * Class: sun_awt_windows_WComponentPeer * Method: beginValidate * Signature: ()V */ JNIEXPORT void JNICALL Java_sun_awt_windows_WComponentPeer_beginValidate(JNIEnv *env, jobject self) { TRY; jobject selfGlobalRef = env->NewGlobalRef(self); AwtToolkit::GetInstance().SyncCall(AwtComponent::_BeginValidate, (void *)selfGlobalRef); // selfGlobalRef is deleted in _BeginValidate CATCH_BAD_ALLOC; } /* * Class: sun_awt_windows_WComponentPeer * Method: endValidate * Signature: ()V */ JNIEXPORT void JNICALL Java_sun_awt_windows_WComponentPeer_endValidate(JNIEnv *env, jobject self) { TRY; jobject selfGlobalRef = env->NewGlobalRef(self); AwtToolkit::GetInstance().SyncCall(AwtComponent::_EndValidate, (void *)selfGlobalRef); // selfGlobalRef is deleted in _EndValidate CATCH_BAD_ALLOC; } JNIEXPORT void JNICALL Java_sun_awt_windows_WComponentPeer_updateWindow(JNIEnv *env, jobject self) { TRY; jobject selfGlobalRef = env->NewGlobalRef(self); AwtToolkit::GetInstance().SyncCall(AwtComponent::_UpdateWindow, (void *)selfGlobalRef); // selfGlobalRef is deleted in _UpdateWindow CATCH_BAD_ALLOC; } /* * Class: sun_awt_windows_WComponentPeer * Method: addNativeDropTarget * Signature: ()L */ JNIEXPORT jlong JNICALL Java_sun_awt_windows_WComponentPeer_addNativeDropTarget(JNIEnv *env, jobject self) { TRY; jobject selfGlobalRef = env->NewGlobalRef(self); return ptr_to_jlong(AwtToolkit::GetInstance().SyncCall( (void*(*)(void*))AwtComponent::_AddNativeDropTarget, (void *)selfGlobalRef)); // selfGlobalRef is deleted in _AddNativeDropTarget CATCH_BAD_ALLOC_RET(0); } /* * Class: sun_awt_windows_WComponentPeer * Method: removeNativeDropTarget * Signature: ()V */ JNIEXPORT void JNICALL Java_sun_awt_windows_WComponentPeer_removeNativeDropTarget(JNIEnv *env, jobject self) { TRY; jobject selfGlobalRef = env->NewGlobalRef(self); AwtToolkit::GetInstance().SyncCall( AwtComponent::_RemoveNativeDropTarget, (void *)selfGlobalRef); // selfGlobalRef is deleted in _RemoveNativeDropTarget CATCH_BAD_ALLOC; } /* * Class: sun_awt_windows_WComponentPeer * Method: getTargetGC * Signature: ()Ljava/awt/GraphicsConfiguration; */ JNIEXPORT jobject JNICALL Java_sun_awt_windows_WComponentPeer_getTargetGC(JNIEnv* env, jobject theThis) { TRY; jobject targetObj; jobject gc = 0; targetObj = env->GetObjectField(theThis, AwtObject::targetID); DASSERT(targetObj); gc = env->GetObjectField(targetObj, AwtComponent::graphicsConfigID); return gc; CATCH_BAD_ALLOC_RET(NULL); } /* * Class: sun_awt_windows_WComponentPeer * Method: createPrintedPixels * Signature: (IIIIII)I[ */ JNIEXPORT jintArray JNICALL Java_sun_awt_windows_WComponentPeer_createPrintedPixels(JNIEnv* env, jobject self, jint srcX, jint srcY, jint srcW, jint srcH, jint alpha) { TRY; jobject selfGlobalRef = env->NewGlobalRef(self); CreatePrintedPixelsStruct *cpps = new CreatePrintedPixelsStruct; cpps->component = selfGlobalRef; cpps->srcx = srcX; cpps->srcy = srcY; cpps->srcw = srcW; cpps->srch = srcH; cpps->alpha = alpha; jintArray globalRef = (jintArray)AwtToolkit::GetInstance().SyncCall( (void*(*)(void*))AwtComponent::_CreatePrintedPixels, cpps); // selfGlobalRef and cpps are deleted in _CreatePrintedPixels if (globalRef != NULL) { jintArray localRef = (jintArray)env->NewLocalRef(globalRef); env->DeleteGlobalRef(globalRef); return localRef; } else { return NULL; } CATCH_BAD_ALLOC_RET(NULL); } /* * Class: sun_awt_windows_WComponentPeer * Method: nativeHandlesWheelScrolling * Signature: ()Z */ JNIEXPORT jboolean JNICALL Java_sun_awt_windows_WComponentPeer_nativeHandlesWheelScrolling (JNIEnv* env, jobject self) { TRY; return (jboolean)AwtToolkit::GetInstance().SyncCall( (void *(*)(void *))AwtComponent::_NativeHandlesWheelScrolling, env->NewGlobalRef(self)); // global ref is deleted in _NativeHandlesWheelScrolling CATCH_BAD_ALLOC_RET(NULL); } /* * Class: sun_awt_windows_WComponentPeer * Method: isObscured * Signature: ()Z */ JNIEXPORT jboolean JNICALL Java_sun_awt_windows_WComponentPeer_isObscured(JNIEnv* env, jobject self) { TRY; jobject selfGlobalRef = env->NewGlobalRef(self); return (jboolean)AwtToolkit::GetInstance().SyncCall( (void*(*)(void*))AwtComponent::_IsObscured, (void *)selfGlobalRef); // selfGlobalRef is deleted in _IsObscured CATCH_BAD_ALLOC_RET(NULL); } JNIEXPORT void JNICALL Java_sun_awt_windows_WComponentPeer_pSetParent(JNIEnv* env, jobject self, jobject parent) { TRY; typedef AwtComponent* PComponent; AwtComponent** comps = new PComponent[2]; AwtComponent* comp = (AwtComponent*)JNI_GET_PDATA(self); AwtComponent* parentComp = (AwtComponent*)JNI_GET_PDATA(parent); comps[0] = comp; comps[1] = parentComp; AwtToolkit::GetInstance().SyncCall(AwtComponent::SetParent, comps); // comps is deleted in SetParent CATCH_BAD_ALLOC; } JNIEXPORT void JNICALL Java_sun_awt_windows_WComponentPeer_setRectangularShape(JNIEnv* env, jobject self, jint x1, jint y1, jint x2, jint y2, jobject region) { TRY; SetRectangularShapeStruct * data = new SetRectangularShapeStruct; data->component = env->NewGlobalRef(self); data->x1 = x1; data->x2 = x2; data->y1 = y1; data->y2 = y2; if (region) { data->region = env->NewGlobalRef(region); } else { data->region = NULL; } AwtToolkit::GetInstance().SyncCall(AwtComponent::_SetRectangularShape, data); // global refs and data are deleted in _SetRectangularShape CATCH_BAD_ALLOC; } JNIEXPORT void JNICALL Java_sun_awt_windows_WComponentPeer_setZOrder(JNIEnv* env, jobject self, jlong above) { TRY; SetZOrderStruct * data = new SetZOrderStruct; data->component = env->NewGlobalRef(self); data->above = above; AwtToolkit::GetInstance().SyncCall(AwtComponent::_SetZOrder, data); // global refs and data are deleted in _SetLower CATCH_BAD_ALLOC; } } /* extern "C" */ /************************************************************************ * Diagnostic routines */ #ifdef DEBUG void AwtComponent::VerifyState() { if (AwtToolkit::GetInstance().VerifyComponents() == FALSE) { return; } if (m_callbacksEnabled == FALSE) { /* Component is not fully setup yet. */ return; } /* Get target bounds. */ JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); if (env->PushLocalFrame(10) < 0) return; jobject target = GetTarget(env); jint x = env->GetIntField(target, AwtComponent::xID); jint y = env->GetIntField(target, AwtComponent::yID); jint width = env->GetIntField(target, AwtComponent::widthID); jint height = env->GetIntField(target, AwtComponent::heightID); /* Convert target origin to absolute coordinates */ while (TRUE) { jobject parent = env->GetObjectField(target, AwtComponent::parentID); if (parent == NULL) { break; } x += env->GetIntField(parent, AwtComponent::xID); y += env->GetIntField(parent, AwtComponent::yID); /* If this component has insets, factor them in, but ignore * top-level windows. */ jobject parent2 = env->GetObjectField(parent, AwtComponent::parentID); if (parent2 != NULL) { jobject peer = GetPeerForTarget(env, parent); if (peer != NULL && JNU_IsInstanceOfByName(env, peer, "sun/awt/windows/WPanelPeer") > 0) { jobject insets = JNU_CallMethodByName(env, NULL, peer,"insets", "()Ljava/awt/Insets;").l; x += (env)->GetIntField(insets, AwtInsets::leftID); y += (env)->GetIntField(insets, AwtInsets::topID); } } env->DeleteLocalRef(target); target = parent; } // Test whether component's bounds match the native window's RECT rect; VERIFY(::GetWindowRect(GetHWnd(), &rect)); #if 0 DASSERT( (x == rect.left) && (y == rect.top) && (width == (rect.right-rect.left)) && (height == (rect.bottom-rect.top)) ); #else BOOL fSizeValid = ( (x == rect.left) && (y == rect.top) && (width == (rect.right-rect.left)) && (height == (rect.bottom-rect.top)) ); #endif // See if visible state matches BOOL wndVisible = ::IsWindowVisible(GetHWnd()); jboolean targetVisible; // To avoid possibly running client code on the toolkit thread, don't // do the following check if we're running on the toolkit thread. if (AwtToolkit::MainThread() != ::GetCurrentThreadId()) { targetVisible = JNU_CallMethodByName(env, NULL, GetTarget(env), "isShowing", "()Z").z; DASSERT(!safe_ExceptionOccurred(env)); } else { targetVisible = wndVisible ? 1 : 0; } #if 0 DASSERT( (targetVisible && wndVisible) || (!targetVisible && !wndVisible) ); #else BOOL fVisibleValid = ( (targetVisible && wndVisible) || (!targetVisible && !wndVisible) ); #endif // Check enabled state BOOL wndEnabled = ::IsWindowEnabled(GetHWnd()); jboolean enabled = (jboolean)env->GetBooleanField(target, AwtComponent::enabledID); #if 0 DASSERT( (enabled && wndEnabled) || (!enabled && !wndEnabled) ); #else BOOL fEnabledValid = ((enabled && wndEnabled) || (!(enabled && !wndEnabled) )); if (!fSizeValid || !fVisibleValid || !fEnabledValid) { printf("AwtComponent::ValidateState() failed:\n"); // To avoid possibly running client code on the toolkit thread, don't // do the following call if we're running on the toolkit thread. if (AwtToolkit::MainThread() != ::GetCurrentThreadId()) { jstring targetStr = (jstring)JNU_CallMethodByName(env, NULL, GetTarget(env), "getName", "()Ljava/lang/String;").l; DASSERT(!safe_ExceptionOccurred(env)); LPCWSTR targetStrW = JNU_GetStringPlatformChars(env, targetStr, NULL); printf("\t%S\n", targetStrW); JNU_ReleaseStringPlatformChars(env, targetStr, targetStrW); } printf("\twas: [%d,%d,%dx%d]\n", x, y, width, height); if (!fSizeValid) { printf("\tshould be: [%d,%d,%dx%d]\n", rect.left, rect.top, rect.right-rect.left, rect.bottom-rect.top); } if (!fVisibleValid) { printf("\tshould be: %s\n", (targetVisible) ? "visible" : "hidden"); } if (!fEnabledValid) { printf("\tshould be: %s\n", enabled ? "enabled" : "disabled"); } } #endif env->PopLocalFrame(0); } #endif //DEBUG // Methods for globally managed DC list /** * Add a new DC to the DC list for this component. */ void DCList::AddDC(HDC hDC, HWND hWnd) { DCItem *newItem = new DCItem; newItem->hDC = hDC; newItem->hWnd = hWnd; AddDCItem(newItem); } void DCList::AddDCItem(DCItem *newItem) { listLock.Enter(); newItem->next = head; head = newItem; listLock.Leave(); } /** * Given a DC, remove it from the DC list and return * TRUE if it exists on the current list. Otherwise * return FALSE. * A DC may not exist on the list because it has already * been released elsewhere (for example, the window * destruction process may release a DC while a rendering * thread may also want to release a DC when it notices that * its DC is obsolete for the current window). */ DCItem *DCList::RemoveDC(HDC hDC) { listLock.Enter(); DCItem **prevPtrPtr = &head; DCItem *listPtr = head; while (listPtr) { DCItem *nextPtr = listPtr->next; if (listPtr->hDC == hDC) { *prevPtrPtr = nextPtr; break; } prevPtrPtr = &listPtr->next; listPtr = nextPtr; } listLock.Leave(); return listPtr; } /** * Remove all DCs from the DC list which are associated with * the same window as hWnd. Return the list of those * DC's to the caller (which will then probably want to * call ReleaseDC() for the returned DCs). */ DCItem *DCList::RemoveAllDCs(HWND hWnd) { listLock.Enter(); DCItem **prevPtrPtr = &head; DCItem *listPtr = head; DCItem *newListPtr = NULL; BOOL ret = FALSE; while (listPtr) { DCItem *nextPtr = listPtr->next; if (listPtr->hWnd == hWnd) { *prevPtrPtr = nextPtr; listPtr->next = newListPtr; newListPtr = listPtr; } else { prevPtrPtr = &listPtr->next; } listPtr = nextPtr; } listLock.Leave(); return newListPtr; } /** * Realize palettes of all existing HDC objects */ void DCList::RealizePalettes(int screen) { listLock.Enter(); DCItem *listPtr = head; while (listPtr) { AwtWin32GraphicsDevice::RealizePalette(listPtr->hDC, screen); listPtr = listPtr->next; } listLock.Leave(); } void MoveDCToPassiveList(HDC hDC) { DCItem *removedDC; if ((removedDC = activeDCList.RemoveDC(hDC)) != NULL) { passiveDCList.AddDCItem(removedDC); } } void ReleaseDCList(HWND hwnd, DCList &list) { DCItem *removedDCs = list.RemoveAllDCs(hwnd); while (removedDCs) { DCItem *tmpDCList = removedDCs; DASSERT(::GetObjectType(tmpDCList->hDC) == OBJ_DC); int retValue = ::ReleaseDC(tmpDCList->hWnd, tmpDCList->hDC); VERIFY(retValue != 0); if (retValue != 0) { // Valid ReleaseDC call; need to decrement GDI object counter AwtGDIObject::Decrement(); } removedDCs = removedDCs->next; delete tmpDCList; } }
32.816959
119
0.611213
liumapp
3b72dffedf31ab9716ad1fbeccc9a2fc976f1b7a
9,363
cpp
C++
src/xml.cpp
Lieutenant-Debaser/rom-checksum
45104adc2280dac448b9f37e7b637909e69f760c
[ "MIT" ]
null
null
null
src/xml.cpp
Lieutenant-Debaser/rom-checksum
45104adc2280dac448b9f37e7b637909e69f760c
[ "MIT" ]
null
null
null
src/xml.cpp
Lieutenant-Debaser/rom-checksum
45104adc2280dac448b9f37e7b637909e69f760c
[ "MIT" ]
null
null
null
/* File: xml.cpp * Author: Lieutenant Debaser * Last Update (yyyy-mm-dd_hhMM): 2022-01-27_1441 * * File contains definitions for the Xml class functions, along with constructor definitions. Functions for handling * searching within strings and XML data are also defined here. * * See xml.h for Xml class definition and other function prototypes. */ #include "xml.h" // Class constructors Xml::Xml() { name = ""; description = ""; author = ""; homepage = ""; list_size = 0; } Xml::Xml (std::string n, std::string d, std::string a, std::string h) { name = n; description = d; author = a; homepage = h; list_size = 0; } // Accessors std::string Xml::get_name() { return name; } std::string Xml::get_description() { return description; } std::string Xml::get_author() { return author; } std::string Xml::get_homepage() { return homepage; } Rom_File Xml::get_game (unsigned int index) { return list [index]; } Rom_File* Xml::get_list() { return &list[0]; } unsigned int Xml::get_list_size() { return list_size; } // Mutators void Xml::set_name (std::string s) { name = s; } void Xml::set_description (std::string s) { description = s; } void Xml::set_author (std::string s) { author = s; } void Xml::set_homepage (std::string s) { homepage = s; } bool Xml::set_rom (Rom_File r, unsigned int index) { if (index < MAX_LIST_SIZE) { list[index] = r; return true; } return false; } bool Xml::append_rom (Rom_File r) { if (list_size < MAX_LIST_SIZE) { list[list_size] = r; list_size++; return true; } return false; } void Xml::set_list_size (unsigned int i) { list_size = i; } // Rom searching functions Rom_File* Xml::search_rom_md5 (std::string key) { for (unsigned int i = 0; i < list_size; i++) { if (key == list[i].get_md5()) return &list[i]; } return NULL; } Rom_File* Xml::search_rom_sha1 (std::string key) { for (unsigned int i = 0; i < list_size; i++) { if (key == list[i].get_sha1()) return &list[i]; } return NULL; } Rom_File* Xml::search_rom_size (unsigned long long key) { for (unsigned int i = 0; i < list_size; i++) { if (key == list[i].get_size()) return &list[i]; } return NULL; } // Non-class functions // Load the contents of a file into a structure and return that structure bool load_file (std::string f_name, std::vector <std::string> &xml_data) { std::ifstream xml_read; xml_read.open (f_name.c_str()); if (xml_read.is_open()) { std::string buffer; while (true) { getline (xml_read, buffer); // Check for EOF and stop if it has been reached if (xml_read.eof()) { break; } // Check for certain characters and delete them if necessary buffer.erase (remove (buffer.begin(), buffer.end(), '\r'), buffer.end()); // Carridge Return buffer.erase (remove (buffer.begin(), buffer.end(), '\t'), buffer.end()); // Tab xml_data.push_back (buffer); } xml_read.close(); return true; } return false; } // Ensure that an input file has the XML_HEADER on its first line bool verify_xml (std::vector <std::string> &xml_data) { if (xml_data[0] == XML_HEADER) { return true; } return false; } // Search for specific text within the XML's <header> section std::string find_in_xml_header (std::string keyword, std::vector <std::string> &xml_data) { const std::string keyword_start_tag {'<' + keyword + '>'}, keyword_end_tag {"</" + keyword + '>'}, header_start_tag {"<header>"}, header_end_tag {"</header>"}; unsigned int header_start_pos {0}, header_end_pos {0}; std::string data_string {""}; // Variable to be returned at the end of the function // Find the <header> and </header> locations for (unsigned int line_i = 0; line_i < xml_data.size(); line_i++) { // Check for the header_start_tag if (xml_data[line_i] == header_start_tag) { header_start_pos = line_i; } // Check for the header_end_tag else if (xml_data[line_i] == header_end_tag) { header_end_pos = line_i; } // Stop loop if both the header start and end tags have been found if ((header_start_pos != 0) && (header_start_pos < header_end_pos)) break; } // If the headers were successfully found, find the keyword within the headers if ((header_start_pos != 0) && (header_end_pos != 0)) { size_t keyword_start_pos {}, keyword_end_pos {}; // Search lines in header for desired information for (unsigned int header_i = header_start_pos; header_i < header_end_pos; header_i++) { keyword_start_pos = xml_data[header_i].find (keyword_start_tag); keyword_end_pos = xml_data[header_i].find (keyword_end_tag); if ((keyword_start_pos != std::string::npos) && (keyword_end_pos != std::string::npos)) { for (unsigned int line_i = keyword_start_pos + keyword_start_tag.size(); line_i < keyword_end_pos; line_i++) { data_string += xml_data[header_i][line_i]; } break; } } } return data_string; // Empty string = No match found // String with data = Match found } // Search for specific text within the XML's body unsigned int find_in_xml_body (std::string keyword, Rom_File rom_list[], std::vector <std::string> &xml_data) { const std::string keyword_start_tag {'<' + keyword}, keyword_end_tag {"/>"}; unsigned int list_size {0}; std::string data_string {""}; size_t keyword_start_pos {}, keyword_end_pos {}; // Search through XML data for all instances of desired information for (unsigned int line_i = 0; line_i < xml_data.size(); line_i++) { keyword_start_pos = xml_data[line_i].find (keyword_start_tag); keyword_end_pos = xml_data[line_i].find (keyword_end_tag); // A match has been found for the data if ((keyword_start_pos != std::string::npos) && (keyword_end_pos != std::string::npos)) { // Variables used to convert string to long std::string size_str {""}; unsigned long long size_long {0}; data_string = ""; for (unsigned int data_i = keyword_start_pos + keyword_start_tag.size(); data_i < keyword_end_pos; data_i++) { data_string += xml_data[line_i][data_i]; } if (list_size + 1 < MAX_LIST_SIZE) { // Load data from line into rom structure rom_list[list_size].set_name (find_in_string ("name", data_string)); rom_list[list_size].set_md5 (find_in_string ("md5" , data_string)); rom_list[list_size].set_sha1 (find_in_string ("sha1", data_string)); // Attempt to convert data related to size from a string to a long size_str = find_in_string ("size", data_string); try { size_long = stoull (size_str, nullptr, 10); rom_list[list_size].set_size (size_long); } catch (const std::invalid_argument &bad_arg) { // Argument was not an integer std::cerr << "\n! String to Long Conversion Error: " << bad_arg.what() << ", Bad Arg." << "\n\tEntry: " << rom_list[list_size].get_name() << "\n\t Size: " << size_str; } catch (const std::out_of_range &bad_range) { // Argument is out of range std::cerr << "\n! String to Long Conversion Error: " << bad_range.what() << ", Out of Range" << "\n\tEntry: " << rom_list[list_size].get_name() << "\n\t Size: " << size_str; } list_size++; } else { break; } } } return list_size; } // Find a string of text within a string std::string find_in_string (std::string keyword, std::string input) { const std::string keyword_start_tag {keyword + "=\""}, keyword_end_tag {"\""}; size_t keyword_start_pos {}, keyword_end_pos {}; std::string data_string {""}; // Find the location of the start tag keyword_start_pos = input.find (keyword_start_tag); if (keyword_start_pos != std::string::npos) { // Find the end tag in a location that comes after the start tag keyword_end_pos = input.find (keyword_end_tag, keyword_start_pos + keyword_start_tag.size() + 1); // Data has been found if the start tag and end tag are not npos if ((keyword_end_pos != std::string::npos) && (keyword_end_pos > keyword_start_pos)) { for (unsigned int j = keyword_start_pos + keyword_start_tag.size(); j < keyword_end_pos; j++) { data_string += input[j]; } } } return data_string; }
27.866071
126
0.579729
Lieutenant-Debaser
3b74323558aaa8402247e8e5391afc1c73f7dc80
3,969
hpp
C++
3rdParty/boost/1.71.0/libs/thread/test/shared_mutex_locking_thread.hpp
rajeev02101987/arangodb
817e6c04cb82777d266f3b444494140676da98e2
[ "Apache-2.0" ]
12,278
2015-01-29T17:11:33.000Z
2022-03-31T21:12:00.000Z
3rdParty/boost/1.71.0/libs/thread/test/shared_mutex_locking_thread.hpp
rajeev02101987/arangodb
817e6c04cb82777d266f3b444494140676da98e2
[ "Apache-2.0" ]
9,469
2015-01-30T05:33:07.000Z
2022-03-31T16:17:21.000Z
3rdParty/boost/1.71.0/libs/thread/test/shared_mutex_locking_thread.hpp
rajeev02101987/arangodb
817e6c04cb82777d266f3b444494140676da98e2
[ "Apache-2.0" ]
1,343
2017-12-08T19:47:19.000Z
2022-03-26T11:31:36.000Z
#ifndef SHARED_MUTEX_LOCKING_THREAD_HPP #define SHARED_MUTEX_LOCKING_THREAD_HPP // (C) Copyright 2008 Anthony Williams // // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include <boost/thread/mutex.hpp> #include <boost/thread/condition_variable.hpp> #include <boost/thread/shared_mutex.hpp> template<typename lock_type> class locking_thread { boost::shared_mutex& rw_mutex; unsigned& unblocked_count; boost::condition_variable& unblocked_condition; unsigned& simultaneous_running_count; unsigned& max_simultaneous_running; boost::mutex& unblocked_count_mutex; boost::mutex& finish_mutex; public: locking_thread(boost::shared_mutex& rw_mutex_, unsigned& unblocked_count_, boost::mutex& unblocked_count_mutex_, boost::condition_variable& unblocked_condition_, boost::mutex& finish_mutex_, unsigned& simultaneous_running_count_, unsigned& max_simultaneous_running_): rw_mutex(rw_mutex_), unblocked_count(unblocked_count_), unblocked_condition(unblocked_condition_), simultaneous_running_count(simultaneous_running_count_), max_simultaneous_running(max_simultaneous_running_), unblocked_count_mutex(unblocked_count_mutex_), finish_mutex(finish_mutex_) {} void operator()() { // acquire lock lock_type lock(rw_mutex); // increment count to show we're unblocked { boost::unique_lock<boost::mutex> ublock(unblocked_count_mutex); ++unblocked_count; unblocked_condition.notify_one(); ++simultaneous_running_count; if(simultaneous_running_count>max_simultaneous_running) { max_simultaneous_running=simultaneous_running_count; } } // wait to finish boost::unique_lock<boost::mutex> finish_lock(finish_mutex); { boost::unique_lock<boost::mutex> ublock(unblocked_count_mutex); --simultaneous_running_count; } } private: void operator=(locking_thread&); }; class simple_writing_thread { boost::shared_mutex& rwm; boost::mutex& finish_mutex; boost::mutex& unblocked_mutex; unsigned& unblocked_count; void operator=(simple_writing_thread&); public: simple_writing_thread(boost::shared_mutex& rwm_, boost::mutex& finish_mutex_, boost::mutex& unblocked_mutex_, unsigned& unblocked_count_): rwm(rwm_),finish_mutex(finish_mutex_), unblocked_mutex(unblocked_mutex_),unblocked_count(unblocked_count_) {} void operator()() { boost::unique_lock<boost::shared_mutex> lk(rwm); { boost::unique_lock<boost::mutex> ulk(unblocked_mutex); ++unblocked_count; } boost::unique_lock<boost::mutex> flk(finish_mutex); } }; class simple_reading_thread { boost::shared_mutex& rwm; boost::mutex& finish_mutex; boost::mutex& unblocked_mutex; unsigned& unblocked_count; void operator=(simple_reading_thread&); public: simple_reading_thread(boost::shared_mutex& rwm_, boost::mutex& finish_mutex_, boost::mutex& unblocked_mutex_, unsigned& unblocked_count_): rwm(rwm_),finish_mutex(finish_mutex_), unblocked_mutex(unblocked_mutex_),unblocked_count(unblocked_count_) {} void operator()() { boost::shared_lock<boost::shared_mutex> lk(rwm); { boost::unique_lock<boost::mutex> ulk(unblocked_mutex); ++unblocked_count; } boost::unique_lock<boost::mutex> flk(finish_mutex); } }; #endif
29.842105
75
0.648274
rajeev02101987
3b76373f85b176cc4fed368925a435e3857faf74
1,938
cpp
C++
Libraries/RobsJuceModules/rosic/analysis/rosic_PitchDetector.cpp
RobinSchmidt/RS-MET-Preliminary
6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe
[ "FTL" ]
34
2017-04-19T18:26:02.000Z
2022-02-15T17:47:26.000Z
Libraries/RobsJuceModules/rosic/analysis/rosic_PitchDetector.cpp
RobinSchmidt/RS-MET-Preliminary
6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe
[ "FTL" ]
307
2017-05-04T21:45:01.000Z
2022-02-03T00:59:01.000Z
Libraries/RobsJuceModules/rosic/analysis/rosic_PitchDetector.cpp
RobinSchmidt/RS-MET-Preliminary
6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe
[ "FTL" ]
4
2017-09-05T17:04:31.000Z
2021-12-15T21:24:28.000Z
//#include "rosic_PitchDetector.h" //using namespace rosic; // Construction/Destruction: PitchDetector::PitchDetector() : formantRemover(30) { // initialize parameters: sampleRate = 44100.0; sampleRateRec = 1.0/sampleRate; minFundamental = 20.0; maxFundamental = 10000.0; minPeriod = 1.0 / maxFundamental; maxPeriod = 1.0 / minFundamental; y0 = y1 = y2 = y3 = 0.0; fracOld = 0.0; periodEstimate = 0.001; frequencyEstimate = 1.0 / periodEstimate; cycleCorrelation = 0.0; sampleCounter = 0; formantRemover.setOrder(30); dcBlocker.setMode(rsOnePoleFilterDD::HIGHPASS_MZT); dcBlocker.setCutoff(20.0); dcBlocker.setSampleRate(sampleRate); lowpass.setMode(FourPoleFilterParameters::LOWPASS_6); lowpass.useTwoStages(true); lowpass.setFrequency(50.0); lowpass.setSampleRate(sampleRate); envFollower.setMode(EnvelopeFollower::MEAN_ABS); envFollower.setAttackTime(0.0); envFollower.setReleaseTime(20.0); envFollower.setSampleRate(sampleRate); } // Setup: void PitchDetector::setSampleRate(double newSampleRate) { if( newSampleRate > 0.0 ) { sampleRate = newSampleRate; sampleRateRec = 1.0/sampleRate; dcBlocker.setSampleRate(sampleRate); lowpass.setSampleRate(sampleRate); envFollower.setSampleRate(sampleRate); } else DEBUG_BREAK; // invalid sample-rate } void PitchDetector::setMinFundamental(double newMinFundamental) { if( newMinFundamental >= 10.0 && newMinFundamental <= 5000.0 && newMinFundamental < maxFundamental) { minFundamental = newMinFundamental; maxPeriod = 1.0 / minFundamental; } } void PitchDetector::setMaxFundamental(double newMaxFundamental) { if( newMaxFundamental >= 100.0 && newMaxFundamental <= 20000.0 && newMaxFundamental > minFundamental) { maxFundamental = newMaxFundamental; minPeriod = 1.0 / maxFundamental; } }
25.168831
63
0.701754
RobinSchmidt
3b78e97df9a17ef8b3dbc3a2fbd3277645971109
769
cpp
C++
examples/indent_align_string/false_01.unc.cpp
beardog-ukr/uncrustify-config-examples
23308192b377107cf287bdb073ae7eccbbf06383
[ "Unlicense" ]
1
2021-06-23T00:12:23.000Z
2021-06-23T00:12:23.000Z
examples/indent_align_string/false_01.unc.cpp
beardog-ukr/uncrustify-config-examples
23308192b377107cf287bdb073ae7eccbbf06383
[ "Unlicense" ]
null
null
null
examples/indent_align_string/false_01.unc.cpp
beardog-ukr/uncrustify-config-examples
23308192b377107cf287bdb073ae7eccbbf06383
[ "Unlicense" ]
null
null
null
#include <iostream> #include <string> std::string zz = "Lorem ipsum dolor sit amet, \ consectetur adipiscing elit. \ Cras fermentum id diam sit amet consequat."; std::string z2 = "Lorem ipsum dolor sit amet," "consectetur adipiscing elit." "Cras fermentum id diam sit amet consequat."; int main() { int x = 10; std::string s = std::string("booo (short)"); if (x<50) { s = std::string("Lorem ipsum dolor sit amet," "consectetur adipiscing elit." "Cras fermentum id diam sit amet consequat."); s = ssff(20, "Lorem ipsum dolor sit amet," "consectetur adipiscing elit." "Cras fermentum id diam sit amet consequat."); } std::cout << "s is " << s << '\n'; return 0; }
26.517241
64
0.598179
beardog-ukr
3b7a9132f2eb951e62f7961b8d82e92d7baa00fa
2,127
cc
C++
desktop_drag_drop_client_egl.cc
zenoalbisser/ozone-egl
764fa502f28eab052c2f6e9eb992042190c544c4
[ "BSD-3-Clause" ]
null
null
null
desktop_drag_drop_client_egl.cc
zenoalbisser/ozone-egl
764fa502f28eab052c2f6e9eb992042190c544c4
[ "BSD-3-Clause" ]
null
null
null
desktop_drag_drop_client_egl.cc
zenoalbisser/ozone-egl
764fa502f28eab052c2f6e9eb992042190c544c4
[ "BSD-3-Clause" ]
null
null
null
/* * --------------------------------------------------------------------------------- * Copyright (C) 2015 STMicroelectronics - All Rights Reserved * * May be copied or modified under the terms of the LGPL v2.1. * * ST makes no warranty express or implied including but not limited to, * any warranty of * * (i) merchantability or fitness for a particular purpose and/or * (ii) requirements, for a particular purpose in relation to the LICENSED * MATERIALS, which is provided AS IS, WITH ALL FAULTS. ST does not * represent or warrant that the LICENSED MATERIALS provided here * under is free of infringement of any third party patents, * copyrights, trade secrets or other intellectual property rights. * ALL WARRANTIES, CONDITIONS OR OTHER TERMS IMPLIED BY LAW ARE * EXCLUDED TO THE FULLEST EXTENT PERMITTED BY LAW * * --------------------------------------------------------------------------------- */ #include "ozone/ui/desktop_aura/desktop_drag_drop_client_egl.h" #include "ui/base/dragdrop/drag_drop_types.h" #include "ui/base/dragdrop/drop_target_event.h" namespace views { DesktopDragDropClientEgl::DesktopDragDropClientEgl( aura::Window* root_window) { NOTIMPLEMENTED(); } DesktopDragDropClientEgl::~DesktopDragDropClientEgl() { NOTIMPLEMENTED(); } int DesktopDragDropClientEgl::StartDragAndDrop( const ui::OSExchangeData& data, aura::Window* root_window, aura::Window* source_window, const gfx::Point& root_location, int operation, ui::DragDropTypes::DragEventSource source) { NOTIMPLEMENTED(); return false; } void DesktopDragDropClientEgl::DragUpdate(aura::Window* target, const ui::LocatedEvent& event) { NOTIMPLEMENTED(); } void DesktopDragDropClientEgl::Drop(aura::Window* target, const ui::LocatedEvent& event) { NOTIMPLEMENTED(); } void DesktopDragDropClientEgl::DragCancel() { NOTIMPLEMENTED(); } bool DesktopDragDropClientEgl::IsDragDropInProgress() { return false; } } // namespace views
31.279412
84
0.64598
zenoalbisser
3b7bd09b13852fcf3685def0a40a79b41223cefa
350
cpp
C++
src/decoderms3bits.cpp
leroythelegend/rough_idea_pcars
07ead73fa04402c860b21039d5aa8c22a33a7d93
[ "MIT" ]
4
2018-08-09T00:44:01.000Z
2021-07-03T08:26:39.000Z
src/decoderms3bits.cpp
ejmhub/rough_idea_project_cars
d7cd062cbff2a1df82b5a623205d9c1920c41b1c
[ "MIT" ]
1
2018-02-02T10:44:43.000Z
2018-02-02T10:44:43.000Z
src/decoderms3bits.cpp
ejmhub/rough_idea_project_cars
d7cd062cbff2a1df82b5a623205d9c1920c41b1c
[ "MIT" ]
1
2018-11-24T09:12:51.000Z
2018-11-24T09:12:51.000Z
#include "decoderms3bits.h" #include "exception.h" namespace pcars { Decoder_MS3bits::Decoder_MS3bits() : num_(0) { } Decoder_MS3bits::~Decoder_MS3bits() { } void Decoder_MS3bits::decode(const PCars_Data & data, Position & position) { num_ = (data.at(position) >> 4) & 7; } unsigned int Decoder_MS3bits::ms3bits() const { return num_; } }
14.583333
76
0.702857
leroythelegend
3b7c4cc83c8dfa32e9e58d8596ccd7e8ca91ca99
1,212
cpp
C++
lib/IDEDiagnostics.cpp
clagah/mull
9b5a7824b4f3ecdeff64e3b77ee63db2b40b3f99
[ "Apache-2.0" ]
null
null
null
lib/IDEDiagnostics.cpp
clagah/mull
9b5a7824b4f3ecdeff64e3b77ee63db2b40b3f99
[ "Apache-2.0" ]
null
null
null
lib/IDEDiagnostics.cpp
clagah/mull
9b5a7824b4f3ecdeff64e3b77ee63db2b40b3f99
[ "Apache-2.0" ]
1
2019-06-10T02:43:04.000Z
2019-06-10T02:43:04.000Z
#include "mull/IDEDiagnostics.h" #include "mull/MutationPoint.h" #include <llvm/IR/DebugInfoMetadata.h> #include <llvm/IR/Instruction.h> #include <llvm/Support/raw_ostream.h> using namespace mull; using namespace llvm; void NormalIDEDiagnostics::report(mull::MutationPoint *mutationPoint, bool killed) { if (diagnostics == Diagnostics::None) { return; } if (diagnostics == Diagnostics::Survived && killed) { return; } if (diagnostics == Diagnostics::Killed && !killed) { return; } const std::string &diagnostics = mutationPoint->getDiagnostics(); if (diagnostics.empty()) { return; } Instruction *instruction = dyn_cast<Instruction>(mutationPoint->getOriginalValue()); if (instruction->getMetadata(0) == nullptr) { return; } const DebugLoc &debugLoc = instruction->getDebugLoc(); std::string fileNameOrNil = debugLoc->getFilename().str(); std::string lineOrNil = std::to_string(debugLoc->getLine()); std::string columnOrNil = std::to_string(debugLoc->getColumn()); errs() << "\n"; errs() << fileNameOrNil << ":" << lineOrNil << ":" << columnOrNil << ": " << "warning: " << diagnostics << "\n"; }
25.787234
75
0.65099
clagah
3b7ca17731a5b04fe48163b077b1b540d96b64e7
1,108
cpp
C++
structure/develop/vertex-set-path-sum.cpp
neal2018/library
a19f3b29f3355e32f7e5f6768a7943db48fcdff7
[ "Unlicense" ]
127
2019-07-22T03:52:01.000Z
2022-03-11T07:20:21.000Z
structure/develop/vertex-set-path-sum.cpp
neal2018/library
a19f3b29f3355e32f7e5f6768a7943db48fcdff7
[ "Unlicense" ]
39
2019-09-16T12:04:53.000Z
2022-03-29T15:43:35.000Z
structure/develop/vertex-set-path-sum.cpp
neal2018/library
a19f3b29f3355e32f7e5f6768a7943db48fcdff7
[ "Unlicense" ]
29
2019-08-10T11:27:06.000Z
2022-03-11T07:02:43.000Z
#include "super-link-cut-tree.cpp" /** * @brief Vertex Set Path Sum */ using T = int64_t; // 遅延伝搬をするための作用素 struct Lazy { // 単位元 Lazy() {} // 初期化 Lazy(T v) {} // 遅延伝搬 void propagate(const Lazy &p) {} }; // Light-edge の情報 template< typename Lazy > struct LInfo { // 単位元(キーの値はアクセスしないので未初期化でもよい LInfo() {} // 初期化 LInfo(T v) {} // l, r は Splay-tree の子 (原理上、各ノード区別はない) void update(const LInfo &l, const LInfo &r) {} // 部分木への遅延伝搬 void propagate(const Lazy &p) {} }; // Heavy-edge の情報 template< typename LInfo, typename Lazy > struct Info { T v; T sum; // 単位元(キーの値はアクセスしないので未初期化でもよい Info() : sum{0} {} // 初期化 Info(T v) : v{v} {} // 反転 void toggle() {} // pが親, cがheavy-edgeで結ばれた子, lがそれ以外の子 void update(const Info &p, const Info &c, const LInfo &l) { sum = p.sum + v + c.sum; } // 親と light-edge で繋げる LInfo link() const { return LInfo(); } // 遅延伝搬 void propagate(const Lazy &p) {} // light-edgeに対する遅延伝搬 // pathとsubtreeの遅延伝搬が両方ある場合に実装する void propagate_light(const Lazy &p) {} }; using LCT = SuperLinkCutTree< Info, LInfo, Lazy >;
15.605634
61
0.610108
neal2018
3b7d630543b9cb400341ab7d41ee743df1f52d45
14,750
cc
C++
content/browser/renderer_host/image_transport_factory.cc
gavinp/chromium
681563ea0f892a051f4ef3d5e53438e0bb7d2261
[ "BSD-3-Clause" ]
1
2016-03-10T09:13:57.000Z
2016-03-10T09:13:57.000Z
content/browser/renderer_host/image_transport_factory.cc
gavinp/chromium
681563ea0f892a051f4ef3d5e53438e0bb7d2261
[ "BSD-3-Clause" ]
1
2022-03-13T08:39:05.000Z
2022-03-13T08:39:05.000Z
content/browser/renderer_host/image_transport_factory.cc
gavinp/chromium
681563ea0f892a051f4ef3d5e53438e0bb7d2261
[ "BSD-3-Clause" ]
null
null
null
// 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/renderer_host/image_transport_factory.h" #include <algorithm> #include <map> #include "base/bind.h" #include "base/command_line.h" #include "base/memory/ref_counted.h" #include "base/observer_list.h" #include "content/browser/gpu/gpu_surface_tracker.h" #include "content/browser/gpu/browser_gpu_channel_host_factory.h" #include "content/browser/renderer_host/image_transport_client.h" #include "content/common/gpu/client/command_buffer_proxy.h" #include "content/common/gpu/client/gpu_channel_host.h" #include "content/common/gpu/client/webgraphicscontext3d_command_buffer_impl.h" #include "content/public/common/content_switches.h" #include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebGraphicsContext3D.h" #include "ui/gfx/compositor/compositor.h" #include "ui/gfx/compositor/compositor_setup.h" #include "ui/gfx/gl/gl_context.h" #include "ui/gfx/gl/gl_surface.h" #include "ui/gfx/gl/scoped_make_current.h" #include "ui/gfx/native_widget_types.h" #include "ui/gfx/size.h" #include "webkit/gpu/webgraphicscontext3d_in_process_impl.h" using content::BrowserGpuChannelHostFactory; namespace { ImageTransportFactory* g_factory; class DefaultTransportFactory : public ui::DefaultContextFactory, public ImageTransportFactory { public: DefaultTransportFactory() { ui::DefaultContextFactory::Initialize(); } virtual ui::ContextFactory* AsContextFactory() OVERRIDE { return this; } virtual gfx::GLSurfaceHandle CreateSharedSurfaceHandle( ui::Compositor* compositor) OVERRIDE { return gfx::GLSurfaceHandle(); } virtual void DestroySharedSurfaceHandle( gfx::GLSurfaceHandle surface) OVERRIDE { } virtual WebKit::WebGraphicsContext3D* GetSharedContext( ui::Compositor* compositor) OVERRIDE { return NULL; } virtual scoped_refptr<ImageTransportClient> CreateTransportClient( const gfx::Size& size, uint64* transport_handle) OVERRIDE { return NULL; } virtual gfx::ScopedMakeCurrent* GetScopedMakeCurrent() OVERRIDE { return NULL; } // We don't generate lost context events, so we don't need to keep track of // observers virtual void AddObserver(ImageTransportFactoryObserver* observer) OVERRIDE { } virtual void RemoveObserver( ImageTransportFactoryObserver* observer) OVERRIDE { } private: DISALLOW_COPY_AND_ASSIGN(DefaultTransportFactory); }; class TestTransportFactory : public DefaultTransportFactory { public: TestTransportFactory() {} virtual gfx::GLSurfaceHandle CreateSharedSurfaceHandle( ui::Compositor* compositor) OVERRIDE { return gfx::GLSurfaceHandle(gfx::kNullPluginWindow, true); } virtual scoped_refptr<ImageTransportClient> CreateTransportClient( const gfx::Size& size, uint64* transport_handle) OVERRIDE { #if defined(UI_COMPOSITOR_IMAGE_TRANSPORT) scoped_refptr<ImageTransportClient> surface( ImageTransportClient::Create(this, size)); if (!surface || !surface->Initialize(transport_handle)) { LOG(ERROR) << "Failed to create ImageTransportClient"; return NULL; } return surface; #else return NULL; #endif } private: DISALLOW_COPY_AND_ASSIGN(TestTransportFactory); }; #if defined(UI_COMPOSITOR_IMAGE_TRANSPORT) class InProcessTransportFactory : public DefaultTransportFactory { public: InProcessTransportFactory() { surface_ = gfx::GLSurface::CreateOffscreenGLSurface(false, gfx::Size(1, 1)); CHECK(surface_.get()) << "Unable to create compositor GL surface."; context_ = gfx::GLContext::CreateGLContext( NULL, surface_.get(), gfx::PreferIntegratedGpu); CHECK(context_.get()) <<"Unable to create compositor GL context."; set_share_group(context_->share_group()); } virtual ~InProcessTransportFactory() {} virtual gfx::ScopedMakeCurrent* GetScopedMakeCurrent() OVERRIDE { return new gfx::ScopedMakeCurrent(context_.get(), surface_.get()); } virtual gfx::GLSurfaceHandle CreateSharedSurfaceHandle( ui::Compositor* compositor) OVERRIDE { return gfx::GLSurfaceHandle(gfx::kNullPluginWindow, true); } virtual WebKit::WebGraphicsContext3D* GetSharedContext( ui::Compositor* compositor) OVERRIDE { // TODO(mazda): Implement this (http://crbug.com/118546). return NULL; } virtual scoped_refptr<ImageTransportClient> CreateTransportClient( const gfx::Size& size, uint64* transport_handle) OVERRIDE { scoped_refptr<ImageTransportClient> surface( ImageTransportClient::Create(this, size)); if (!surface || !surface->Initialize(transport_handle)) { LOG(ERROR) << "Failed to create ImageTransportClient"; return NULL; } return surface; } // We don't generate lost context events, so we don't need to keep track of // observers virtual void AddObserver(ImageTransportFactoryObserver* observer) OVERRIDE { } virtual void RemoveObserver( ImageTransportFactoryObserver* observer) OVERRIDE { } private: scoped_refptr<gfx::GLContext> context_; scoped_refptr<gfx::GLSurface> surface_; DISALLOW_COPY_AND_ASSIGN(InProcessTransportFactory); }; #endif class ImageTransportClientTexture : public ImageTransportClient { public: explicit ImageTransportClientTexture(const gfx::Size& size) : ImageTransportClient(true, size) { } virtual bool Initialize(uint64* surface_id) OVERRIDE { set_texture_id(*surface_id); return true; } virtual ~ImageTransportClientTexture() {} virtual void Update() OVERRIDE {} virtual TransportDIB::Handle Handle() const OVERRIDE { return TransportDIB::DefaultHandleValue(); } private: DISALLOW_COPY_AND_ASSIGN(ImageTransportClientTexture); }; class GpuProcessTransportFactory; class CompositorSwapClient : public base::SupportsWeakPtr<CompositorSwapClient>, public WebGraphicsContext3DSwapBuffersClient { public: CompositorSwapClient(ui::Compositor* compositor, GpuProcessTransportFactory* factory) : compositor_(compositor), factory_(factory) { } ~CompositorSwapClient() { } virtual void OnViewContextSwapBuffersPosted() OVERRIDE { compositor_->OnSwapBuffersPosted(); } virtual void OnViewContextSwapBuffersComplete() OVERRIDE { compositor_->OnSwapBuffersComplete(); } virtual void OnViewContextSwapBuffersAborted() OVERRIDE { // Recreating contexts directly from here causes issues, so post a task // instead. // TODO(piman): Fix the underlying issues. MessageLoop::current()->PostTask(FROM_HERE, base::Bind(&CompositorSwapClient::OnLostContext, this->AsWeakPtr())); } private: void OnLostContext(); ui::Compositor* compositor_; GpuProcessTransportFactory* factory_; DISALLOW_COPY_AND_ASSIGN(CompositorSwapClient); }; class GpuProcessTransportFactory : public ui::ContextFactory, public ImageTransportFactory { public: GpuProcessTransportFactory() {} virtual ~GpuProcessTransportFactory() { DCHECK(per_compositor_data_.empty()); } virtual WebKit::WebGraphicsContext3D* CreateContext( ui::Compositor* compositor) OVERRIDE { PerCompositorData* data = per_compositor_data_[compositor]; if (!data) data = CreatePerCompositorData(compositor); WebKit::WebGraphicsContext3D::Attributes attrs; attrs.shareResources = true; GpuChannelHostFactory* factory = BrowserGpuChannelHostFactory::instance(); scoped_ptr<WebGraphicsContext3DCommandBufferImpl> context( new WebGraphicsContext3DCommandBufferImpl( data->surface_id, GURL(), factory, data->swap_client->AsWeakPtr())); if (!context->Initialize(attrs)) return NULL; return context.release(); } virtual void RemoveCompositor(ui::Compositor* compositor) OVERRIDE { PerCompositorDataMap::iterator it = per_compositor_data_.find(compositor); if (it == per_compositor_data_.end()) return; PerCompositorData* data = it->second; DCHECK(data); GpuSurfaceTracker::Get()->RemoveSurface(data->surface_id); delete data; per_compositor_data_.erase(it); } virtual ui::ContextFactory* AsContextFactory() OVERRIDE { return this; } virtual gfx::GLSurfaceHandle CreateSharedSurfaceHandle( ui::Compositor* compositor) OVERRIDE { PerCompositorData* data = per_compositor_data_[compositor]; if (!data) data = CreatePerCompositorData(compositor); gfx::GLSurfaceHandle handle = gfx::GLSurfaceHandle( gfx::kNullPluginWindow, true); ContentGLContext* context = data->shared_context->content_gl_context(); handle.parent_gpu_process_id = context->GetGPUProcessID(); handle.parent_client_id = context->GetChannelID(); handle.parent_context_id = context->GetContextID(); handle.parent_texture_id[0] = data->shared_context->createTexture(); handle.parent_texture_id[1] = data->shared_context->createTexture(); // Finish is overkill, but flush semantics don't apply cross-channel. // TODO(piman): Use a cross-channel synchronization mechanism instead. data->shared_context->finish(); return handle; } virtual void DestroySharedSurfaceHandle( gfx::GLSurfaceHandle surface) OVERRIDE { for (PerCompositorDataMap::iterator it = per_compositor_data_.begin(); it != per_compositor_data_.end(); ++it) { PerCompositorData* data = it->second; DCHECK(data); ContentGLContext* context = data->shared_context->content_gl_context(); int gpu_process_id = context->GetGPUProcessID(); uint32 client_id = context->GetChannelID(); uint32 context_id = context->GetContextID(); if (surface.parent_gpu_process_id == gpu_process_id && surface.parent_client_id == client_id && surface.parent_context_id == context_id) { data->shared_context->deleteTexture(surface.parent_texture_id[0]); data->shared_context->deleteTexture(surface.parent_texture_id[1]); break; } } } virtual WebKit::WebGraphicsContext3D* GetSharedContext( ui::Compositor* compositor) OVERRIDE { PerCompositorDataMap::const_iterator itr = per_compositor_data_.find(compositor); if (itr == per_compositor_data_.end()) return NULL; return itr->second->shared_context.get(); } virtual scoped_refptr<ImageTransportClient> CreateTransportClient( const gfx::Size& size, uint64* transport_handle) { scoped_refptr<ImageTransportClientTexture> image( new ImageTransportClientTexture(size)); image->Initialize(transport_handle); return image; } virtual gfx::ScopedMakeCurrent* GetScopedMakeCurrent() { return NULL; } virtual void AddObserver(ImageTransportFactoryObserver* observer) { observer_list_.AddObserver(observer); } virtual void RemoveObserver(ImageTransportFactoryObserver* observer) { observer_list_.RemoveObserver(observer); } void OnLostContext(ui::Compositor* compositor) { LOG(ERROR) << "Lost UI compositor context."; PerCompositorData* data = per_compositor_data_[compositor]; DCHECK(data); // Note: this has the effect of recreating the swap_client, which means we // won't get more reports of lost context from the same gpu process. It's a // good thing. CreateSharedContext(compositor); FOR_EACH_OBSERVER(ImageTransportFactoryObserver, observer_list_, OnLostResources(compositor)); compositor->OnSwapBuffersAborted(); } private: struct PerCompositorData { int surface_id; scoped_ptr<CompositorSwapClient> swap_client; scoped_ptr<WebGraphicsContext3DCommandBufferImpl> shared_context; }; PerCompositorData* CreatePerCompositorData(ui::Compositor* compositor) { DCHECK(!per_compositor_data_[compositor]); gfx::AcceleratedWidget widget = compositor->widget(); GpuSurfaceTracker* tracker = GpuSurfaceTracker::Get(); PerCompositorData* data = new PerCompositorData; data->surface_id = tracker->AddSurfaceForNativeWidget(widget); tracker->SetSurfaceHandle( data->surface_id, gfx::GLSurfaceHandle(widget, false)); per_compositor_data_[compositor] = data; CreateSharedContext(compositor); return data; } void CreateSharedContext(ui::Compositor* compositor) { PerCompositorData* data = per_compositor_data_[compositor]; DCHECK(data); data->swap_client.reset(new CompositorSwapClient(compositor, this)); GpuChannelHostFactory* factory = BrowserGpuChannelHostFactory::instance(); WebKit::WebGraphicsContext3D::Attributes attrs; attrs.shareResources = true; data->shared_context.reset(new WebGraphicsContext3DCommandBufferImpl( data->surface_id, GURL(), factory, data->swap_client->AsWeakPtr())); if (!data->shared_context->Initialize(attrs)) { // If we can't recreate contexts, we won't be able to show the UI. Better // crash at this point. LOG(FATAL) << "Failed to initialize compositor shared context."; } if (!data->shared_context->makeContextCurrent()) { // If we can't recreate contexts, we won't be able to show the UI. Better // crash at this point. LOG(FATAL) << "Failed to make compositor shared context current."; } } typedef std::map<ui::Compositor*, PerCompositorData*> PerCompositorDataMap; PerCompositorDataMap per_compositor_data_; ObserverList<ImageTransportFactoryObserver> observer_list_; DISALLOW_COPY_AND_ASSIGN(GpuProcessTransportFactory); }; void CompositorSwapClient::OnLostContext() { factory_->OnLostContext(compositor_); // Note: previous line destroyed this. Don't access members from now on. } } // anonymous namespace // static void ImageTransportFactory::Initialize() { CommandLine* command_line = CommandLine::ForCurrentProcess(); if (command_line->HasSwitch(switches::kTestCompositor)) { ui::SetupTestCompositor(); } if (ui::IsTestCompositorEnabled()) { g_factory = new TestTransportFactory(); } else if (command_line->HasSwitch(switches::kUIUseGPUProcess)) { g_factory = new GpuProcessTransportFactory(); } else { #if defined(UI_COMPOSITOR_IMAGE_TRANSPORT) g_factory = new InProcessTransportFactory(); #else g_factory = new DefaultTransportFactory(); #endif } ui::ContextFactory::SetInstance(g_factory->AsContextFactory()); } // static void ImageTransportFactory::Terminate() { ui::ContextFactory::SetInstance(NULL); delete g_factory; g_factory = NULL; } // static ImageTransportFactory* ImageTransportFactory::GetInstance() { return g_factory; }
32.632743
91
0.736339
gavinp
3b85c60b7bb76ea7e59aa9a287054ad60c3046e2
15,328
cpp
C++
modules/diagnostics/diagnostics.cpp
Clyde-Beep/sporks-test
c760d68c23a12dcc5c1a48ee0fc5e26c344f5c07
[ "Apache-2.0" ]
null
null
null
modules/diagnostics/diagnostics.cpp
Clyde-Beep/sporks-test
c760d68c23a12dcc5c1a48ee0fc5e26c344f5c07
[ "Apache-2.0" ]
null
null
null
modules/diagnostics/diagnostics.cpp
Clyde-Beep/sporks-test
c760d68c23a12dcc5c1a48ee0fc5e26c344f5c07
[ "Apache-2.0" ]
null
null
null
/************************************************************************************ * * Sporks, the learning, scriptable Discord bot! * * Copyright 2019 Craig Edwards <support@sporks.gg> * * 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 <sporks/bot.h> #include <sporks/regex.h> #include <sporks/modules.h> #include <sporks/stringops.h> #include <sporks/database.h> #include <sstream> #include <chrono> #include <cstdio> #include <iostream> #include <memory> #include <stdexcept> #include <string> #include <array> struct guild_count_data { size_t guilds; size_t members; }; struct shard_data { std::chrono::time_point<std::chrono::steady_clock> last_message; }; std::string exec(const char* cmd) { std::array<char, 128> buffer; std::string result; std::unique_ptr<FILE, decltype(&pclose)> pipe(popen(cmd, "r"), pclose); if (!pipe) { return ""; } while (fgets(buffer.data(), buffer.size(), pipe.get()) != nullptr) { result += buffer.data(); } return result; } /** * Provides diagnostic commands for monitoring the bot and debugging it interactively while it's running. */ class DiagnosticsModule : public Module { PCRE* diagnosticmessage; std::vector<shard_data> shards; double microseconds_ping; public: DiagnosticsModule(Bot* instigator, ModuleLoader* ml) : Module(instigator, ml) { ml->Attach({ I_OnMessage, I_OnRestEnd }, this); diagnosticmessage = new PCRE("^sudo(\\s+(.+?))$", true); for (uint32_t i = 0; i < bot->core.get_shard_mgr().shard_max_count; ++i) { shards.push_back({}); } } virtual ~DiagnosticsModule() { delete diagnosticmessage; } virtual std::string GetVersion() { /* NOTE: This version string below is modified by a pre-commit hook on the git repository */ std::string version = "$ModVer 24$"; return "1.0." + version.substr(8,version.length() - 9); } virtual std::string GetDescription() { return "Diagnostic Commands (sudo), '@Sporks sudo'"; } virtual bool OnRestEnd(std::chrono::steady_clock::time_point start_time, uint16_t code) { microseconds_ping = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::steady_clock::now() - start_time).count(); return true; } virtual bool OnMessage(const modevent::message_create &message, const std::string& clean_message, bool mentioned, const std::vector<std::string> &stringmentions) { std::vector<std::string> param; std::string botusername = bot->user.username; aegis::gateway::objects::message msg = message.msg; shards[message.shard.get_id()].last_message = std::chrono::steady_clock::now(); if (mentioned && diagnosticmessage->Match(clean_message, param) && param.size() >= 3) { aegis::gateway::objects::message msg = message.msg; std::stringstream tokens(trim(param[2])); std::string subcommand; tokens >> subcommand; bot->core.log->info("SUDO: <{}> {}", msg.get_user().get_username(), clean_message); /* Get owner snowflake id from config file */ int64_t owner_id = from_string<int64_t>(Bot::GetConfig("owner"), std::dec); /* Only allow these commands to the bot owner */ if (msg.author.id.get() == owner_id) { if (param.size() < 3) { /* Invalid number of parameters */ EmbedSimple("Sudo make me a sandwich.", msg.get_channel_id().get()); } else { /* Module list command */ if (lowercase(subcommand) == "modules") { std::stringstream s; // NOTE: GetModuleList's reference is safe from within a module event const ModMap& modlist = bot->Loader->GetModuleList(); s << "```diff" << std::endl; s << fmt::format("- ╭─────────────────────────┬───────────┬────────────────────────────────────────────────╮") << std::endl; s << fmt::format("- │ Filename | Version | Description |") << std::endl; s << fmt::format("- ├─────────────────────────┼───────────┼────────────────────────────────────────────────┤") << std::endl; for (auto mod = modlist.begin(); mod != modlist.end(); ++mod) { s << fmt::format("+ │ {:23} | {:9} | {:46} |", mod->first, mod->second->GetVersion(), mod->second->GetDescription()) << std::endl; } s << fmt::format("+ ╰─────────────────────────┴───────────┴────────────────────────────────────────────────╯") << std::endl; s << "```"; aegis::channel* c = bot->core.find_channel(msg.get_channel_id().get()); if (c) { if (!bot->IsTestMode() || from_string<uint64_t>(Bot::GetConfig("test_server"), std::dec) == c->get_guild().get_id()) { c->create_message(s.str()); bot->sent_messages++; } } } else if (lowercase(subcommand) == "load") { /* Load a module */ std::string modfile; tokens >> modfile; if (bot->Loader->Load(modfile)) { EmbedSimple("Loaded module: " + modfile, msg.get_channel_id().get()); } else { EmbedSimple(std::string("Can't do that: ``") + bot->Loader->GetLastError() + "``", msg.get_channel_id().get()); } } else if (lowercase(subcommand) == "unload") { /* Unload a module */ std::string modfile; tokens >> modfile; if (modfile == "module_diagnostics.so") { EmbedSimple("I suppose you think that's funny, dont you? *I'm sorry. can't do that, dave.*", msg.get_channel_id().get()); } else { if (bot->Loader->Unload(modfile)) { EmbedSimple("Unloaded module: " + modfile, msg.get_channel_id().get()); } else { EmbedSimple(std::string("Can't do that: ``") + bot->Loader->GetLastError() + "``", msg.get_channel_id().get()); } } } else if (lowercase(subcommand) == "reload") { /* Reload a currently loaded module */ std::string modfile; tokens >> modfile; if (modfile == "module_diagnostics.so") { EmbedSimple("I suppose you think that's funny, dont you? *I'm sorry. can't do that, dave.*", msg.get_channel_id().get()); } else { if (bot->Loader->Reload(modfile)) { EmbedSimple("Reloaded module: " + modfile, msg.get_channel_id().get()); } else { EmbedSimple(std::string("Can't do that: ``") + bot->Loader->GetLastError() + "``", msg.get_channel_id().get()); } } } else if (lowercase(subcommand) == "threadstats") { std::string result = exec("top -b -n1 -d0 | head -n7 && top -b -n1 -d0 -H | grep \"./bot\\|run.sh\" | grep -v grep | grep -v perl"); aegis::channel* c = bot->core.find_channel(msg.get_channel_id().get()); if (c) { if (!bot->IsTestMode() || from_string<uint64_t>(Bot::GetConfig("test_server"), std::dec) == c->get_guild().get_id()) { c->create_message("```" + result + "```"); bot->sent_messages++; } } } else if (lowercase(subcommand) == "lock") { std::string keyword; std::getline(tokens, keyword); keyword = trim(keyword); db::query("UPDATE infobot SET locked = 1 WHERE key_word = '?'", {keyword}); EmbedSimple("**Locked** key word: " + keyword, msg.get_channel_id().get()); } else if (lowercase(subcommand) == "unlock") { std::string keyword; std::getline(tokens, keyword); keyword = trim(keyword); db::query("UPDATE infobot SET locked = 0 WHERE key_word = '?'", {keyword}); EmbedSimple("**Unlocked** key word: " + keyword, msg.get_channel_id().get()); } else if (lowercase(subcommand) == "sql") { std::string sql; std::getline(tokens, sql); sql = trim(sql); db::resultset rs = db::query(sql, {}); std::stringstream w; if (rs.size() == 0) { if (db::error() != "") { EmbedSimple("SQL Error: " + db::error(), msg.get_channel_id().get()); } else { EmbedSimple("Successfully executed, no rows returned.", msg.get_channel_id().get()); } } else { w << "- " << sql << std::endl; auto check = rs[0].begin(); w << "+ Rows Returned: " << rs.size() << std::endl; for (auto name = rs[0].begin(); name != rs[0].end(); ++name) { if (name == rs[0].begin()) { w << " ╭"; } w << "────────────────────"; check = name; w << (++check != rs[0].end() ? "┬" : "╮\n"); } w << " "; for (auto name = rs[0].begin(); name != rs[0].end(); ++name) { w << fmt::format("│{:20}", name->first.substr(0, 20)); } w << "│" << std::endl; for (auto name = rs[0].begin(); name != rs[0].end(); ++name) { if (name == rs[0].begin()) { w << " ├"; } w << "────────────────────"; check = name; w << (++check != rs[0].end() ? "┼" : "┤\n"); } for (auto row : rs) { if (w.str().length() < 1900) { w << " "; for (auto field : row) { w << fmt::format("│{:20}", field.second.substr(0, 20)); } w << "│" << std::endl; } } for (auto name = rs[0].begin(); name != rs[0].end(); ++name) { if (name == rs[0].begin()) { w << " ╰"; } w << "────────────────────"; check = name; w << (++check != rs[0].end() ? "┴" : "╯\n"); } aegis::channel* c = bot->core.find_channel(msg.get_channel_id().get()); if (c) { if (!bot->IsTestMode() || from_string<uint64_t>(Bot::GetConfig("test_server"), std::dec) == c->get_guild().get_id()) { c->create_message("```diff\n" + w.str() + "```"); bot->sent_messages++; } } } } else if (lowercase(subcommand) == "reconnect") { uint32_t snum = 0; tokens >> snum; auto & s = bot->core.get_shard_by_id(snum); if (s.is_connected()) { EmbedSimple("Shard is already connected.", msg.get_channel_id().get()); } else { bot->core.get_shard_mgr().queue_reconnect(s); } } else if (lowercase(subcommand) == "forcereconnect") { uint32_t snum = 0; tokens >> snum; auto & s = bot->core.get_shard_by_id(snum); if (s.is_connected()) { EmbedSimple("Shard is already connected.", msg.get_channel_id().get()); } else { s.connect(); } } else if (lowercase(subcommand) == "disconnect") { uint32_t snum = 0; tokens >> snum; auto & s = bot->core.get_shard_by_id(snum); bot->core.get_shard_mgr().close(s); EmbedSimple("Shard disconnected.", msg.get_channel_id().get()); } else if (lowercase(subcommand) == "restart") { EmbedSimple("Restarting...", msg.get_channel_id().get()); ::sleep(5); /* Note: exit here will restart, because we run the bot via run.sh which restarts the bot on quit. */ exit(0); } else if (lowercase(subcommand) == "ping") { aegis::channel* c = bot->core.find_channel(msg.get_channel_id().get()); if (c) { std::chrono::steady_clock::time_point start_time = std::chrono::steady_clock::now(); aegis::gateway::objects::message m = c->create_message("Pinging...", msg.get_channel_id().get()).get(); double microseconds_ping = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::steady_clock::now() - start_time).count(); m.delete_message(); EmbedSimple(fmt::format("**Pong!** REST Response time: {:.3f} ms", microseconds_ping / 1000, 4), msg.get_channel_id().get()); } } else if (lowercase(subcommand) == "lookup") { int64_t gnum = 0; tokens >> gnum; aegis::guild* guild = bot->core.find_guild(gnum); if (guild) { EmbedSimple(fmt::format("**Guild** {} is on **shard** #{}", gnum, guild->shard_id), msg.get_channel_id().get()); } else { EmbedSimple(fmt::format("**Guild** {} is not in my list!", gnum), msg.get_channel_id().get()); } } else if (lowercase(subcommand) == "shardstats") { std::stringstream w; w << "```diff\n"; uint64_t count = 0, u_count = 0; count = bot->core.get_shard_transfer(); u_count = bot->core.get_shard_u_transfer(); std::vector<guild_count_data> shard_guild_c(bot->core.shard_max_count); for (auto & v : bot->core.guilds) { ++shard_guild_c[v.second->shard_id].guilds; shard_guild_c[v.second->shard_id].members += v.second->get_members().size(); } w << fmt::format(" Total transfer: {} (U: {} | {:.2f}%) Memory usage: {}\n", aegis::utility::format_bytes(count), aegis::utility::format_bytes(u_count), (count / (double)u_count)*100, aegis::utility::format_bytes(aegis::utility::getCurrentRSS())); w << fmt::format("- ╭──────┬──────────┬───────┬───────┬────────────────┬────────────┬───────────┬──────────╮\n"); w << fmt::format("- │shard#│ sequence│servers│members│uptime │last message│transferred│reconnects│\n"); w << fmt::format("- ├──────┼──────────┼───────┼───────┼────────────────┼────────────┼───────────┼──────────┤\n"); for (uint32_t i = 0; i < bot->core.shard_max_count; ++i) { auto & s = bot->core.get_shard_by_id(i); auto time_count = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - shards[s.get_id()].last_message).count(); std::string divisor = "ms"; if (time_count > 1000) { time_count /= 1000; divisor = "s "; } if (s.is_connected()) w << "+ "; else w << " "; w << fmt::format("|{:6}|{:10}|{:7}|{:7}|{:>16}|{:10}{:2}|{:>11}|{:10}|", s.get_id(), s.get_sequence(), shard_guild_c[s.get_id()].guilds, shard_guild_c[s.get_id()].members, s.uptime_str(), time_count, divisor, s.get_transfer_str(), s.counters.reconnects); if (message.shard.get_id() == s.get_id()) { w << " *\n"; } else { w << "\n"; } } w << fmt::format("+ ╰──────┴──────────┴───────┴───────┴────────────────┴────────────┴───────────┴──────────╯\n"); w << "```"; aegis::channel *channel = bot->core.find_channel(msg.get_channel_id()); if (channel) { if (!bot->IsTestMode() || from_string<uint64_t>(Bot::GetConfig("test_server"), std::dec) == channel->get_guild().get_id()) { channel->create_message(w.str()); bot->sent_messages++; } } } else { /* Invalid command */ EmbedSimple("Sudo **what**? I don't know what that command means.", msg.get_channel_id().get()); } } } else { /* Access denied */ EmbedSimple("Make your own sandwich, mortal.", msg.get_channel_id().get()); } /* Eat the event */ return false; } return true; } }; ENTRYPOINT(DiagnosticsModule);
38.41604
254
0.545472
Clyde-Beep
3b864bd71f412be269bb407f331dfad51a2a33b2
754
cpp
C++
Programs/ColladaConverter/Collada15/FCollada/FMath/FMAngleAxis.cpp
stinvi/dava.engine
2b396ca49cdf10cdc98ad8a9ffcf7768a05e285e
[ "BSD-3-Clause" ]
26
2018-09-03T08:48:22.000Z
2022-02-14T05:14:50.000Z
Programs/ColladaConverter/Collada15/FCollada/FMath/FMAngleAxis.cpp
ANHELL-blitz/dava.engine
ed83624326f000866e29166c7f4cccfed1bb41d4
[ "BSD-3-Clause" ]
null
null
null
Programs/ColladaConverter/Collada15/FCollada/FMath/FMAngleAxis.cpp
ANHELL-blitz/dava.engine
ed83624326f000866e29166c7f4cccfed1bb41d4
[ "BSD-3-Clause" ]
45
2018-05-11T06:47:17.000Z
2022-02-03T11:30:55.000Z
/* Copyright (C) 2005-2007 Feeling Software Inc. Portions of the code are: Copyright (C) 2005-2007 Sony Computer Entertainment America MIT License: http://www.opensource.org/licenses/mit-license.php */ #include "StdAfx.h" #include "FMAngleAxis.h" // // FMAngleAxis // FMAngleAxis::FMAngleAxis() { } FMAngleAxis::FMAngleAxis(const FMVector3& _axis, float _angle) : axis(_axis) , angle(_angle) { } bool operator==(const FMAngleAxis& first, const FMAngleAxis& other) { if (IsEquivalent(first.angle, other.angle)) { return IsEquivalent(first.axis, other.axis); } else { return IsEquivalent(first.angle, -other.angle) && IsEquivalent(first.axis, -other.axis); } }
20.378378
97
0.651194
stinvi
3b872581b6730fc593c5e0c4436e78be88e664f4
5,604
hpp
C++
src/Utilities/FakeVirtual.hpp
marissawalker/spectre
afc8205e2f697de5e8e4f05e881499e05c9fd8a0
[ "MIT" ]
null
null
null
src/Utilities/FakeVirtual.hpp
marissawalker/spectre
afc8205e2f697de5e8e4f05e881499e05c9fd8a0
[ "MIT" ]
null
null
null
src/Utilities/FakeVirtual.hpp
marissawalker/spectre
afc8205e2f697de5e8e4f05e881499e05c9fd8a0
[ "MIT" ]
null
null
null
// Distributed under the MIT License. // See LICENSE.txt for details. #pragma once #include <type_traits> #include <typeinfo> #include "ErrorHandling/Error.hpp" #include "Utilities/PrettyType.hpp" #include "Utilities/Requires.hpp" #include "Utilities/TMPL.hpp" #include "Utilities/TypeTraits.hpp" /// \ingroup UtilitiesGroup /// \brief Define a function that acts similarly to a virtual /// function, but can take template parameters. /// /// \details `DEFINE_FAKE_VIRTUAL(func)` defines the function /// `fake_virtual_func` and the struct `FakeVirtualInherit_func`. It /// should usually be called in a detail namespace. /// /// A base class `Base` using this functionality should define a type /// \code /// using Inherit = FakeVirtualInherit_func<Base>; /// \endcode /// and a member function `func` wrapping `fake_virtual_func`, with /// the wrapper passing the derived classes as a typelist as the first /// template argument and the `this` pointer as the first normal /// argument. /// /// Derived classes should then inherit from `Base::Inherit` instead /// of directly from `Base`. (`Base::Inherit` inherits from `Base`.) /// /// If the base class has no pure virtual functions remaining it will /// generally be desirable to mark the constructors and assignment /// operators protected so that a bare base class cannot be instantiated. /// /// If it is necessary to use multiple fake virtual functions with the /// same base class, the `Inherit` definition can nest the fake /// virtual classes: /// \code /// using Inherit = FakeVirtualInherit_func1<FakeVirtualInherit_func2<Base>>; /// \endcode /// /// \example /// \snippet Test_FakeVirtual.cpp fake_virtual_example /// /// \see call_with_dynamic_type #define DEFINE_FAKE_VIRTUAL(function) \ /* This struct is only needed for producing an error if the function */ \ /* is not overridden in the derived class. */ \ template <typename Base> \ struct FakeVirtualInherit_##function : public Base { \ using Base::Base; \ /* clang-tidy: I think "= delete" was overlooked in the guideline */ \ void function(...) const = delete; /* NOLINT */ \ }; \ \ template <typename Classes, typename... TArgs, typename Base, \ typename... Args> \ decltype(auto) fake_virtual_##function(Base* obj, Args&&... args) noexcept { \ /* clang-tidy: macro arg in parentheses */ \ return call_with_dynamic_type< \ decltype(obj->template function<TArgs...>(args...)), /* NOLINT */ \ Classes>( \ obj, [&args...](auto* const dynamic_obj) noexcept -> decltype(auto) { \ static_assert( \ cpp17::is_base_of_v<typename Base::Inherit, \ std::decay_t<decltype(*dynamic_obj)>>, \ "Derived class does not inherit from Base::Inherit"); \ /* clang-tidy: macro arg in parentheses */ \ return dynamic_obj->template function<TArgs...>(/* NOLINT */ \ std::forward<Args>( \ args)...); \ }); \ } /// \cond template <typename Result, typename Classes, typename Base, typename Callable, Requires<(tmpl::size<Classes>::value == 0)> = nullptr> [[noreturn]] Result call_with_dynamic_type(Base* const obj, Callable&& /*f*/) noexcept { ERROR("Class " << pretty_type::get_runtime_type_name(*obj) << " is not registered with " << pretty_type::get_name<std::remove_const_t<Base>>()); } /// \endcond /// \ingroup Utilities /// \brief Call a functor with the derived type of a base class pointer. /// /// \details Calls functor with obj cast to type `T*` where T is the /// dynamic type of `*obj`. The decay type of `T` must be in the /// provided list of classes. /// /// \see DEFINE_FAKE_VIRTUAL /// /// \tparam Result the return type /// \tparam Classes the typelist of derived classes template <typename Result, typename Classes, typename Base, typename Callable, Requires<(tmpl::size<Classes>::value != 0)> = nullptr> Result call_with_dynamic_type(Base* const obj, Callable&& f) noexcept { using Derived = tmpl::front<Classes>; using DerivedPointer = std::conditional_t<std::is_const<Base>::value, Derived const*, Derived*>; // If we want to allow creatable classses to return objects of // types derived from themselves then this will have to be changed // to a dynamic_cast, but we probably won't want that and this // form is significantly faster. return typeid(*obj) == typeid(Derived) ? std::forward<Callable>(f)(static_cast<DerivedPointer>(obj)) : call_with_dynamic_type<Result, tmpl::pop_front<Classes>>( obj, std::forward<Callable>(f)); }
48.310345
80
0.563169
marissawalker
3b87ec6a310a6a48f6766cd44c12d4082e622cd7
238
cpp
C++
2017_05_29_GameStateManager/IGameState_old.cpp
DarthDementous/2017_05_29_GameStateManagement
207d3bbd2d5184a32a1437d4417343b696f60e60
[ "MIT" ]
null
null
null
2017_05_29_GameStateManager/IGameState_old.cpp
DarthDementous/2017_05_29_GameStateManagement
207d3bbd2d5184a32a1437d4417343b696f60e60
[ "MIT" ]
null
null
null
2017_05_29_GameStateManager/IGameState_old.cpp
DarthDementous/2017_05_29_GameStateManagement
207d3bbd2d5184a32a1437d4417343b696f60e60
[ "MIT" ]
null
null
null
#include "IGameState.h" #include "_2017_05_29_GameStateManagerApp.h" #include <Application.h> #pragma region Constructors IGameState::IGameState(aie::Application* a_app) : m_app(a_app) {} IGameState::~IGameState() { } #pragma endregion
19.833333
65
0.773109
DarthDementous
3b88994e9f2bba31d5310cd887f4d29babc32da0
2,239
cpp
C++
libraries/MySensors/core/MyTransportRFM95.cpp
kaniick/Growtek-Controller
9826776fa1c6f835c84f62dac84e1848509d9e76
[ "MIT" ]
null
null
null
libraries/MySensors/core/MyTransportRFM95.cpp
kaniick/Growtek-Controller
9826776fa1c6f835c84f62dac84e1848509d9e76
[ "MIT" ]
null
null
null
libraries/MySensors/core/MyTransportRFM95.cpp
kaniick/Growtek-Controller
9826776fa1c6f835c84f62dac84e1848509d9e76
[ "MIT" ]
null
null
null
/* * The MySensors Arduino library handles the wireless radio link and protocol * between your home built sensors/actuators and HA controller of choice. * The sensors forms a self healing radio network with optional repeaters. Each * repeater and gateway builds a routing tables in EEPROM which keeps track of the * network topology allowing messages to be routed to nodes. * * Created by Henrik Ekblad <henrik.ekblad@mysensors.org> * Copyright (C) 2013-2016 Sensnology AB * Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors * * Documentation: http://www.mysensors.org * Support Forum: http://forum.mysensors.org * * 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. * */ #include "MyConfig.h" #include "MyTransport.h" #include "drivers/RFM95/RFM95.h" bool transportInit(void) { const bool result = RFM95_initialise(MY_RFM95_FREQUENCY); #if !defined(MY_GATEWAY_FEATURE) && !defined(MY_RFM95_ATC_MODE_DISABLED) // only enable ATC mode nodes RFM95_ATCmode(true, MY_RFM95_ATC_TARGET_RSSI); #endif return result; } void transportSetAddress(const uint8_t address) { RFM95_setAddress(address); } uint8_t transportGetAddress(void) { return RFM95_getAddress(); } bool transportSend(const uint8_t to, const void* data, const uint8_t len) { return RFM95_sendWithRetry(to, data, len); } bool transportAvailable(void) { return RFM95_available(); } bool transportSanityCheck(void) { return RFM95_sanityCheck(); } uint8_t transportReceive(void* data) { return RFM95_recv((uint8_t*)data); } void transportPowerDown(void) { (void)RFM95_sleep(); } // experimental // ********************************************** int16_t transportGetReceivingSignalStrength(void) { return RFM95_getReceivingRSSI(); } int16_t transportGetSendingSignalStrength(void) { return RFM95_getSendingRSSI(); } int8_t transportGetReceivingSNR(void) { return RFM95_getReceivingSNR(); } int8_t transportGetSendingSNR(void) { return RFM95_getSendingSNR(); } uint8_t transportGetTxPower(void) { return RFM95_getTxPowerPercent(); } // **********************************************
24.075269
82
0.742742
kaniick
3b8b4dd936642a50874ddf4d96dcf5027ed46148
443
cpp
C++
src/helped/stdafx.cpp
ptitSeb/freespace2
500ee249f7033aac9b389436b1737a404277259c
[ "Linux-OpenIB" ]
1
2020-07-14T07:29:18.000Z
2020-07-14T07:29:18.000Z
src/helped/stdafx.cpp
ptitSeb/freespace2
500ee249f7033aac9b389436b1737a404277259c
[ "Linux-OpenIB" ]
2
2019-01-01T22:35:56.000Z
2022-03-14T07:34:00.000Z
src/helped/stdafx.cpp
ptitSeb/freespace2
500ee249f7033aac9b389436b1737a404277259c
[ "Linux-OpenIB" ]
2
2021-03-07T11:40:42.000Z
2021-12-26T21:40:39.000Z
/* * Copyright (C) Volition, Inc. 1999. All rights reserved. * * All source code herein is the property of Volition, Inc. You may not sell * or otherwise commercially exploit the source or things you created based on * the source. */ // stdafx.cpp : source file that includes just the standard includes // HelpEd.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h"
26.058824
78
0.733634
ptitSeb
3b8d67b84d6079ac4fc905fac94d103c906f2d3e
3,397
cpp
C++
storage/storage_integration_tests/storage_downloading_tests.cpp
Barysman/omim
469632c879027ec38278ebda699415c28dbd79e0
[ "Apache-2.0" ]
1
2021-07-02T08:45:02.000Z
2021-07-02T08:45:02.000Z
storage/storage_integration_tests/storage_downloading_tests.cpp
Barysman/omim
469632c879027ec38278ebda699415c28dbd79e0
[ "Apache-2.0" ]
1
2020-06-15T15:16:23.000Z
2020-06-15T15:59:19.000Z
storage/storage_integration_tests/storage_downloading_tests.cpp
maksimandrianov/omim
cbc5a80d09d585afbda01e471887f63b9d3ab0c2
[ "Apache-2.0" ]
1
2018-10-01T10:27:21.000Z
2018-10-01T10:27:21.000Z
#include "testing/testing.hpp" #include "storage/storage_integration_tests/test_defines.hpp" #include "storage/storage.hpp" #include "platform/local_country_file_utils.hpp" #include "platform/mwm_version.hpp" #include "platform/platform.hpp" #include "platform/platform_tests_support/scoped_dir.hpp" #include "platform/platform_tests_support/writable_dir_changer.hpp" #include "coding/file_name_utils.hpp" #include "base/scope_guard.hpp" #include "base/string_utils.hpp" #include "base/thread.hpp" #include "std/bind.hpp" #include "std/exception.hpp" #include "std/string.hpp" using namespace platform; using namespace storage; namespace { using Runner = Platform::ThreadRunner; string const kCountryId = "Angola"; class InterruptException : public exception {}; void Update(TCountryId const &, storage::TLocalFilePtr const localCountryFile) { TEST_EQUAL(localCountryFile->GetCountryName(), kCountryId, ()); } void ChangeCountry(Storage & storage, TCountryId const & countryId) { TEST_EQUAL(countryId, kCountryId, ()); if (!storage.IsDownloadInProgress()) testing::StopEventLoop(); } void InitStorage(Storage & storage, Storage::TProgressFunction const & onProgressFn) { storage.Init(Update, [](TCountryId const &, storage::TLocalFilePtr const){return false;}); storage.RegisterAllLocalMaps(false /* enableDiffs */); storage.Subscribe(bind(&ChangeCountry, ref(storage), _1), onProgressFn); storage.SetDownloadingUrlsForTesting({kTestWebServer}); } } // namespace UNIT_TEST(SmallMwms_ReDownloadExistedMWMIgnored_Test) { WritableDirChanger writableDirChanger(kMapTestDir); Storage storage(COUNTRIES_FILE); TEST(version::IsSingleMwm(storage.GetCurrentDataVersion()), ()); InitStorage(storage, [](TCountryId const & countryId, TLocalAndRemoteSize const & mapSize){}); TEST(!storage.IsDownloadInProgress(), ()); storage.DownloadNode(kCountryId); TEST(storage.IsDownloadInProgress(), ()); testing::RunEventLoop(); TEST(!storage.IsDownloadInProgress(), ()); storage.DownloadNode(kCountryId); TEST(!storage.IsDownloadInProgress(), ()); } UNIT_CLASS_TEST(Runner, SmallMwms_InterruptDownloadResumeDownload_Test) { WritableDirChanger writableDirChanger(kMapTestDir); // Start download but interrupt it { Storage storage(COUNTRIES_FILE); TEST(version::IsSingleMwm(storage.GetCurrentDataVersion()), ()); auto onProgressFn = [](TCountryId const & countryId, TLocalAndRemoteSize const & mapSize) { TEST_EQUAL(countryId, kCountryId, ()); // Interrupt download testing::StopEventLoop(); }; InitStorage(storage, onProgressFn); TEST(!storage.IsDownloadInProgress(), ()); storage.DownloadNode(kCountryId); testing::RunEventLoop(); TEST(storage.IsDownloadInProgress(), ()); } // Continue download { Storage storage(COUNTRIES_FILE); auto onProgressFn = [](TCountryId const & countryId, TLocalAndRemoteSize const & mapSize) { TEST_EQUAL(countryId, kCountryId, ()); }; InitStorage(storage, onProgressFn); TEST(storage.IsDownloadInProgress(), ()); NodeAttrs attrs; storage.GetNodeAttrs(kCountryId, attrs); TEST_EQUAL(NodeStatus::Downloading, attrs.m_status, ()); storage.DownloadNode(kCountryId); testing::RunEventLoop(); storage.GetNodeAttrs(kCountryId, attrs); TEST_EQUAL(NodeStatus::OnDisk, attrs.m_status, ()); } }
27.176
96
0.743597
Barysman
3b8f3e6c815e4d483f03628723a32b0e543bfb76
1,434
hpp
C++
Code/Foundation/SpatialPartition/SpatialPartitionStandard.hpp
WelderUpdates/WelderEngineRevamp
1c665239566e9c7156926852f7952948d9286d7d
[ "MIT" ]
3
2022-02-11T10:34:33.000Z
2022-02-24T17:44:17.000Z
Code/Foundation/SpatialPartition/SpatialPartitionStandard.hpp
WelderUpdates/WelderEngineRevamp
1c665239566e9c7156926852f7952948d9286d7d
[ "MIT" ]
null
null
null
Code/Foundation/SpatialPartition/SpatialPartitionStandard.hpp
WelderUpdates/WelderEngineRevamp
1c665239566e9c7156926852f7952948d9286d7d
[ "MIT" ]
null
null
null
// MIT Licensed (see LICENSE.md). #pragma once // Standard includes #include "Foundation/Geometry/GeometryStandard.hpp" #include "Foundation/Serialization/SerializationStandard.hpp" namespace Zero { // SpatialPartition library class ZeroNoImportExport SpatialPartitionLibrary : public Zilch::StaticLibrary { public: ZilchDeclareStaticLibraryInternals(SpatialPartitionLibrary, "ZeroEngine"); static void Initialize(); static void Shutdown(); }; } // namespace Zero // Project includes #include "BroadPhaseProxy.hpp" #include "ProxyCast.hpp" #include "BroadPhase.hpp" #include "SimpleCastCallbacks.hpp" #include "BroadPhaseRanges.hpp" #include "BaseDynamicAabbTreeBroadPhase.hpp" #include "DynamicTreeHelpers.hpp" #include "BaseDynamicAabbTree.hpp" #include "AvlDynamicAabbTree.hpp" #include "DynamicAabbTree.hpp" #include "DynamicAabbTreeBroadPhase.hpp" #include "AvlDynamicAabbTreeBroadPhase.hpp" #include "BaseNSquared.hpp" #include "NSquared.hpp" #include "NSquaredBroadPhase.hpp" #include "BoundingBox.hpp" #include "BoundingBoxBroadPhase.hpp" #include "BoundingSphere.hpp" #include "BoundingSphereBroadPhase.hpp" #include "SapContainers.hpp" #include "Sap.hpp" #include "SapBroadPhase.hpp" #include "AabbTreeNode.hpp" #include "AabbTreeMethods.hpp" #include "StaticAabbTree.hpp" #include "StaticAabbTreeBroadPhase.hpp" #include "BroadPhasePackage.hpp" #include "BroadPhaseCreator.hpp" #include "BroadPhaseTracker.hpp"
27.056604
78
0.806137
WelderUpdates
3b8ff879cc0962061baa0750af07664605e96750
1,299
cpp
C++
src/Sova/Graphics/Color.cpp
connorcarpenter/sova
3b640bea83c7fe1013196977c39a27e7cd4947ec
[ "MIT" ]
null
null
null
src/Sova/Graphics/Color.cpp
connorcarpenter/sova
3b640bea83c7fe1013196977c39a27e7cd4947ec
[ "MIT" ]
null
null
null
src/Sova/Graphics/Color.cpp
connorcarpenter/sova
3b640bea83c7fe1013196977c39a27e7cd4947ec
[ "MIT" ]
null
null
null
// // Created by connor on 7/29/18. // #include "Color.h" namespace Sova { Color::Color(int red, int green, int blue) { this->red = red; this->green = green; this->blue = blue; } Color Color::Red = Color(255, 0, 0); Color Color::Green = Color(0, 255, 0); Color Color::Blue = Color(0, 0, 255); Color Color::Yellow = Color(255, 255, 0); Color Color::White = Color(255, 255, 255); Color Color::Black = Color(0, 0, 0); Color Color::LightGray = Color(192, 192, 192); Color Color::Gray = Color(128, 128, 128); Color Color::DarkGray = Color(64, 64, 64); Color Color::Brown = Color(128, 64, 0); bool Color::operator==(const Color &other) const { return (this->red == other.red && this->blue == other.blue && this->green == other.green); } bool Color::operator!=(const Color &other) const { return (this->red != other.red || this->blue != other.blue || this->green != other.green); } Color Color::MixColors(Color color1, Color color2) { int red = (color1.red*color2.red) / 255; int blue = (color1.blue*color2.blue) / 255; int green = (color1.green*color2.green) / 255; return Color(red, blue, green); } }
28.866667
98
0.558122
connorcarpenter
3b9114112533cdb7840fca15584b7e577a4cdc07
4,115
cpp
C++
src/zaurus/zinfones.cpp
jay-kumogata/InfoNES
045dd572123753cd53bbbcd387b70a66d0a8562c
[ "Apache-2.0" ]
6
2019-05-10T02:09:55.000Z
2021-09-16T09:10:14.000Z
src/zaurus/zinfones.cpp
b004004/InfoNES-1
045dd572123753cd53bbbcd387b70a66d0a8562c
[ "Apache-2.0" ]
null
null
null
src/zaurus/zinfones.cpp
b004004/InfoNES-1
045dd572123753cd53bbbcd387b70a66d0a8562c
[ "Apache-2.0" ]
1
2019-05-10T16:02:51.000Z
2019-05-10T16:02:51.000Z
/*===================================================================*/ /* */ /* zinfones.cpp : A Qt-specific class implementation */ /* */ /* 2004/06/26 InfoNES Project */ /* */ /*===================================================================*/ /*-------------------------------------------------------------------*/ /* Include files */ /*-------------------------------------------------------------------*/ #include "zinfones.h" /*-------------------------------------------------------------------*/ /* Constructor */ /*-------------------------------------------------------------------*/ zinfones::zinfones( WORD *wf ) { /* FrameBuffer */ QDirectPainter dq( this ); pFb = (WORD *)dq.frameBuffer(); pWf = wf; dx = dy = 0; /* To center */ #if 0 /* 1.5 magnification */ setGeometry(320 - ( NES_DISP_WIDTH * 3 / 4 ), \ 240 - ( NES_DISP_HEIGHT * 3 / 4 ), \ NES_DISP_WIDTH * 3 / 2, NES_DISP_HEIGHT * 3 / 2); #else setGeometry(320 - ( NES_DISP_WIDTH / 2 ), \ 240 - ( NES_DISP_HEIGHT / 2 ), \ NES_DISP_WIDTH, NES_DISP_HEIGHT); #endif } /* Repaint */ void zinfones::paintEvent( QPaintEvent * e ) { /* To center */ #if 0 /* 1.5 magnification */ setGeometry(320 - ( NES_DISP_WIDTH * 3 / 4 ), \ 240 - ( NES_DISP_HEIGHT * 3 / 4 ), \ NES_DISP_WIDTH * 3 / 2, NES_DISP_HEIGHT * 3 / 2); #else setGeometry(320 - ( NES_DISP_WIDTH / 2 ), \ 240 - ( NES_DISP_HEIGHT / 2 ), \ NES_DISP_WIDTH, NES_DISP_HEIGHT); #endif } /* Load Frame */ void zinfones::loadFrame() { /* If not active, doesn't draw */ if ( !isActiveWindow() ) return; /* Draw a screen */ for ( register unsigned int x = 0; x < NES_DISP_WIDTH; x++ ) { for ( register unsigned int y = 0; y < NES_DISP_HEIGHT; y++ ) { /* Exchange 15-bit to 16-bit */ register WORD wColor = pWf[ ( y << 8 ) + x ]; wColor = ((wColor& 0x7fe0)<<1)|(wColor&0x001f); #if 0 /* 1.5 magnification */ register int p = (((x+x+x)>>1)+dx) * 480 - (((y+y+y)>>1)+dy); pFb[ p ] = wColor; if (y&1) pFb[ p- 1 ] = wColor; if (x&1) pFb[ p+480 ] = wColor; if ((x&1)&&(y&1)) pFb[ p+479 ] = wColor; #else /* 1 magnification */ pFb[ (x + dx) * 480 - (y + dy) ] = wColor; #endif } } } /* Key press */ void zinfones::keyPressEvent( QKeyEvent *e ) { switch ( e->key() ) { case Key_Right: dwKeyPad1 |= (1<<7); break; case Key_Left: dwKeyPad1 |= (1<<6); break; case Key_Down: dwKeyPad1 |= (1<<5); break; case Key_Up: dwKeyPad1 |= (1<<4); break; case Key_S: dwKeyPad1 |= (1<<3); break; case Key_A: dwKeyPad1 |= (1<<2); break; case Key_Z: dwKeyPad1 |= (1<<1); break; case Key_X: dwKeyPad1 |= (1<<0); break; /* extra */ case Key_C: PPU_UpDown_Clip = ( PPU_UpDown_Clip ? 0 : 1); break; case Key_M: APU_Mute = ( APU_Mute ? 0 : 1 ); break; case Key_D: FrameSkip = (FrameSkip == 0 ? 0 : FrameSkip - 1); break; case Key_U: FrameSkip++; break; } } /* Key release */ void zinfones::keyReleaseEvent( QKeyEvent *e ) { switch ( e->key() ) { case Key_Right: dwKeyPad1 &= ~(1<<7); break; case Key_Left: dwKeyPad1 &= ~(1<<6); break; case Key_Down: dwKeyPad1 &= ~(1<<5); break; case Key_Up: dwKeyPad1 &= ~(1<<4); break; case Key_S: dwKeyPad1 &= ~(1<<3); break; case Key_A: dwKeyPad1 &= ~(1<<2); break; case Key_Z: dwKeyPad1 &= ~(1<<1); break; case Key_X: dwKeyPad1 &= ~(1<<0); break; } } /* Move */ void zinfones::moveEvent( QMoveEvent *e ) { dx = e->pos().x(); dy = e->pos().y(); } /* End of zinfones.cpp */
23.786127
71
0.425516
jay-kumogata
3b91694bd335b3e5d4b0626ab2ee37b7ea90ea3c
2,026
cpp
C++
Homework_Seminar_2/Homework_Seminar_2/main.cpp
AlexStoyanova/UP-FMI
fe0d3a0410645cc0e132d6728d8ee26067c025dc
[ "MIT" ]
4
2018-09-27T20:33:19.000Z
2020-03-31T19:19:58.000Z
Homework_Seminar_2/Homework_Seminar_2/main.cpp
AlexStoyanova/UP-FMI
fe0d3a0410645cc0e132d6728d8ee26067c025dc
[ "MIT" ]
null
null
null
Homework_Seminar_2/Homework_Seminar_2/main.cpp
AlexStoyanova/UP-FMI
fe0d3a0410645cc0e132d6728d8ee26067c025dc
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; const int MAX_SIZE = 100; //2. int positionLetter(const char *str, char letter, size_t n, size_t start = 0) { if (start == (strlen(str) + 1)) { return -1; } if (str[start] == letter) { n--; } if (n == 0) { return start; } return positionLetter(str, letter, n, start + 1); } //1. size_t m_strlen(const char *str) { unsigned int len = 0; while (str[len] != '\0') { len++; } return len; } bool isPalindrom(const char *str, size_t size) { if (str == nullptr) { return false; } unsigned int temp = size / 2; for (int i = 0; i < temp; i++) { if (str[i] != str[size - i - 1]) { return false; } } return true; } char mostCommonLetter(const char *str) { unsigned int count = 0; unsigned int big_count = 0; char letter; for (int i = 0; str[i] != '\0'; i++) { for (int j = i; str[j] != '\0'; j++) { if (str[i] == str[j]) { count++; } } if (count > big_count) { big_count = count; letter = str[i]; } else if (count == big_count) { if (str[i] < letter) { letter = str[i]; } } count = 0; } return letter; } typedef char(*mostComLetter)(const char *str); typedef bool(*isPalind)(const char *str, size_t size); typedef size_t(*myStrlen)(const char *str); void mostCommonLetterInEvenPalindrom(char str[][MAX_SIZE], size_t n, mostComLetter mstCmL, isPalind palindrom, myStrlen len) { size_t size; for (int i = 0; i < n; i++) { size = len(str[i]); if ((size % 2 == 0) && palindrom(str[i], size)) { cout << mstCmL(str[i]) << ' '; } } } int main() { //2. /*char str[MAX_SIZE]; char letter; unsigned int n; cin >> str; cin >> letter; do { cin >> n; } while (n < 1 || n > 100); cout << positionLetter(str, letter, n);*/ //1. char str[MAX_SIZE][MAX_SIZE]; unsigned int n; do { cin >> n; } while (n < 1 || n > 100); for (int i = 0; i < n; i++) { cin >> str[i]; } mostCommonLetterInEvenPalindrom(str, n, mostCommonLetter, isPalindrom, m_strlen); return 0; }
15.705426
124
0.572063
AlexStoyanova
3b9348c67b2dbb10e9cb75758561c81519fc0cb8
1,830
hh
C++
unittests/libtests/bc/TestTimeDependent.hh
joegeisz/pylith
f74060b7b19d7e90abf8597bbe9250c96593c0ad
[ "MIT" ]
1
2021-09-09T06:24:11.000Z
2021-09-09T06:24:11.000Z
unittests/libtests/bc/TestTimeDependent.hh
joegeisz/pylith
f74060b7b19d7e90abf8597bbe9250c96593c0ad
[ "MIT" ]
null
null
null
unittests/libtests/bc/TestTimeDependent.hh
joegeisz/pylith
f74060b7b19d7e90abf8597bbe9250c96593c0ad
[ "MIT" ]
null
null
null
// -*- C++ -*- // // ---------------------------------------------------------------------- // // Brad T. Aagaard, U.S. Geological Survey // Charles A. Williams, GNS Science // Matthew G. Knepley, University of Chicago // // This code was developed as part of the Computational Infrastructure // for Geodynamics (http://geodynamics.org). // // Copyright (c) 2010-2017 University of California, Davis // // See COPYING for license information. // // ---------------------------------------------------------------------- // /** * @file unittests/libtests/bc/TestTimeDependent.hh * * @brief C++ TestTimeDependent object. * * C++ unit testing for TimeDependent. */ #if !defined(pylith_bc_testtimedependent_hh) #define pylith_bc_testtimedependent_hh #include <cppunit/extensions/HelperMacros.h> /// Namespace for pylith package namespace pylith { namespace bc { class TestTimeDependent; } // bc } // pylith /// C++ unit testing for PointForce. class pylith::bc::TestTimeDependent : public CppUnit::TestFixture { // class TestTimeDependent // CPPUNIT TEST SUITE ///////////////////////////////////////////////// CPPUNIT_TEST_SUITE( TestTimeDependent ); CPPUNIT_TEST( testDBInitial ); CPPUNIT_TEST( testDBRate ); CPPUNIT_TEST( testDBChange ); CPPUNIT_TEST( testDBTimeHistory ); CPPUNIT_TEST( testVerifyConfiguration ); CPPUNIT_TEST_SUITE_END(); // PUBLIC METHODS ///////////////////////////////////////////////////// public : /// Test dbInitial(). void testDBInitial(void); /// Test dbRate(). void testDBRate(void); /// Test dbChange(). void testDBChange(void); /// Test dbTimeHistory(). void testDBTimeHistory(void); /// Test verifyConfiguration(). void testVerifyConfiguration(void); }; // class TestTimeDependent #endif // pylith_bc_pointforce_hh // End of file
23.461538
73
0.615301
joegeisz
3b935e6251bb8a396afc11a71d6fdb4b5b0e56c0
112
cpp
C++
Dataset/Leetcode/train/75/164.cpp
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
Dataset/Leetcode/train/75/164.cpp
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
Dataset/Leetcode/train/75/164.cpp
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
class Solution { public: void XXX(vector<int>& nums) { return sort(nums.begin(),nums.end()); } };
14
42
0.580357
kkcookies99
3b94feda02b7dff6720c3999e539581fdf424e62
33,509
cpp
C++
Blizzlike/Trinity/Scripts/Dungeons/CoilfangReservoir/SerpentShrine/boss_lady_vashj.cpp
499453466/Lua-Other
43fd2b72405faf3f2074fd2a2706ef115d16faa6
[ "Unlicense" ]
2
2015-06-23T16:26:32.000Z
2019-06-27T07:45:59.000Z
Blizzlike/Trinity/Scripts/Dungeons/CoilfangReservoir/SerpentShrine/boss_lady_vashj.cpp
Eduardo-Silla/Lua-Other
db610f946dbcaf81b3de9801f758e11a7bf2753f
[ "Unlicense" ]
null
null
null
Blizzlike/Trinity/Scripts/Dungeons/CoilfangReservoir/SerpentShrine/boss_lady_vashj.cpp
Eduardo-Silla/Lua-Other
db610f946dbcaf81b3de9801f758e11a7bf2753f
[ "Unlicense" ]
3
2015-01-10T18:22:59.000Z
2021-04-27T21:28:28.000Z
/* * Copyright (C) 2008-2012 TrinityCore <http://www.trinitycore.org/> * Copyright (C) 2006-2009 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ /* ScriptData SDName: Boss_Lady_Vashj SD%Complete: 99 SDComment: Missing blizzlike Shield Generators coords SDCategory: Coilfang Resevoir, Serpent Shrine Cavern EndScriptData */ #include "ScriptMgr.h" #include "ScriptedCreature.h" #include "serpent_shrine.h" #include "Spell.h" #define SAY_INTRO -1548042 #define SAY_AGGRO1 -1548043 #define SAY_AGGRO2 -1548044 #define SAY_AGGRO3 -1548045 #define SAY_AGGRO4 -1548046 #define SAY_PHASE1 -1548047 #define SAY_PHASE2 -1548048 #define SAY_PHASE3 -1548049 #define SAY_BOWSHOT1 -1548050 #define SAY_BOWSHOT2 -1548051 #define SAY_SLAY1 -1548052 #define SAY_SLAY2 -1548053 #define SAY_SLAY3 -1548054 #define SAY_DEATH -1548055 #define SPELL_SURGE 38044 #define SPELL_MULTI_SHOT 38310 #define SPELL_SHOCK_BLAST 38509 #define SPELL_ENTANGLE 38316 #define SPELL_STATIC_CHARGE_TRIGGER 38280 #define SPELL_FORKED_LIGHTNING 40088 #define SPELL_SHOOT 40873 #define SPELL_POISON_BOLT 40095 #define SPELL_TOXIC_SPORES 38575 #define SPELL_MAGIC_BARRIER 38112 #define MIDDLE_X 30.134f #define MIDDLE_Y -923.65f #define MIDDLE_Z 42.9f #define SPOREBAT_X 30.977156f #define SPOREBAT_Y -925.297761f #define SPOREBAT_Z 77.176567f #define SPOREBAT_O 5.223932f #define SHIED_GENERATOR_CHANNEL 19870 #define ENCHANTED_ELEMENTAL 21958 #define TAINTED_ELEMENTAL 22009 #define COILFANG_STRIDER 22056 #define COILFANG_ELITE 22055 #define TOXIC_SPOREBAT 22140 #define TOXIC_SPORES_TRIGGER 22207 #define TEXT_NOT_INITIALIZED "Instance script not initialized" #define TEXT_ALREADY_DEACTIVATED "Already deactivated" float ElementPos[8][4] = { {8.3f, -835.3f, 21.9f, 5.0f}, {53.4f, -835.3f, 21.9f, 4.5f}, {96.0f, -861.9f, 21.8f, 4.0f}, {96.0f, -986.4f, 21.4f, 2.5f}, {54.4f, -1010.6f, 22, 1.8f}, {9.8f, -1012, 21.7f, 1.4f}, {-35.0f, -987.6f, 21.5f, 0.8f}, {-58.9f, -901.6f, 21.5f, 6.0f} }; float ElementWPPos[8][3] = { {71.700752f, -883.905884f, 41.097168f}, {45.039848f, -868.022827f, 41.097015f}, {14.585141f, -867.894470f, 41.097061f}, {-25.415508f, -906.737732f, 41.097061f}, {-11.801594f, -963.405884f, 41.097067f}, {14.556657f, -979.051514f, 41.097137f}, {43.466549f, -979.406677f, 41.097027f}, {69.945908f, -964.663940f, 41.097054f} }; float SporebatWPPos[8][3] = { {31.6f, -896.3f, 59.1f}, {9.1f, -913.9f, 56.0f}, {5.2f, -934.4f, 52.4f}, {20.7f, -946.9f, 49.7f}, {41.0f, -941.9f, 51.0f}, {47.7f, -927.3f, 55.0f}, {42.2f, -912.4f, 51.7f}, {27.0f, -905.9f, 50.0f} }; float CoilfangElitePos[3][4] = { {28.84f, -923.28f, 42.9f, 6.0f}, {31.183281f, -953.502625f, 41.523602f, 1.640957f}, {58.895180f, -923.124268f, 41.545307f, 3.152848f} }; float CoilfangStriderPos[3][4] = { {66.427010f, -948.778503f, 41.262245f, 2.584220f}, {7.513962f, -959.538208f, 41.300422f, 1.034629f}, {-12.843201f, -907.798401f, 41.239620f, 6.087094f} }; float ShieldGeneratorChannelPos[4][4] = { {49.6262f, -902.181f, 43.0975f, 3.95683f}, {10.988f, -901.616f, 42.5371f, 5.4373f}, {10.3859f, -944.036f, 42.5446f, 0.779888f}, {49.3126f, -943.398f, 42.5501f, 2.40174f} }; class boss_lady_vashj : public CreatureScript { public: boss_lady_vashj() : CreatureScript("boss_lady_vashj") { } CreatureAI* GetAI(Creature* creature) const { return new boss_lady_vashjAI (creature); } struct boss_lady_vashjAI : public ScriptedAI { boss_lady_vashjAI (Creature* creature) : ScriptedAI(creature) { instance = creature->GetInstanceScript(); Intro = false; JustCreated = true; creature->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE); // set it only once on Creature create (no need do intro if wiped) } InstanceScript* instance; uint64 ShieldGeneratorChannel[4]; uint32 AggroTimer; uint32 ShockBlastTimer; uint32 EntangleTimer; uint32 StaticChargeTimer; uint32 ForkedLightningTimer; uint32 CheckTimer; uint32 EnchantedElementalTimer; uint32 TaintedElementalTimer; uint32 CoilfangEliteTimer; uint32 CoilfangStriderTimer; uint32 SummonSporebatTimer; uint32 SummonSporebatStaticTimer; uint8 EnchantedElementalPos; uint8 Phase; bool Entangle; bool Intro; bool CanAttack; bool JustCreated; void Reset() { AggroTimer = 19000; ShockBlastTimer = 1+rand()%60000; EntangleTimer = 30000; StaticChargeTimer = 10000+rand()%15000; ForkedLightningTimer = 2000; CheckTimer = 15000; EnchantedElementalTimer = 5000; TaintedElementalTimer = 50000; CoilfangEliteTimer = 45000+rand()%5000; CoilfangStriderTimer = 60000+rand()%10000; SummonSporebatTimer = 10000; SummonSporebatStaticTimer = 30000; EnchantedElementalPos = 0; Phase = 0; Entangle = false; if (JustCreated) { CanAttack = false; JustCreated = false; } else CanAttack = true; for (uint8 i = 0; i < 4; ++i) if (Unit* remo = Unit::GetUnit(*me, ShieldGeneratorChannel[i])) remo->setDeathState(JUST_DIED); if (instance) instance->SetData(DATA_LADYVASHJEVENT, NOT_STARTED); ShieldGeneratorChannel[0] = 0; ShieldGeneratorChannel[1] = 0; ShieldGeneratorChannel[2] = 0; ShieldGeneratorChannel[3] = 0; me->SetCorpseDelay(1000*60*60); } // Called when a tainted elemental dies void EventTaintedElementalDeath() { // the next will spawn 50 seconds after the previous one's death if (TaintedElementalTimer > 50000) TaintedElementalTimer = 50000; } void KilledUnit(Unit* /*victim*/) { DoScriptText(RAND(SAY_SLAY1, SAY_SLAY2, SAY_SLAY3), me); } void JustDied(Unit* /*killer*/) { DoScriptText(SAY_DEATH, me); if (instance) instance->SetData(DATA_LADYVASHJEVENT, DONE); } void StartEvent() { DoScriptText(RAND(SAY_AGGRO1, SAY_AGGRO2, SAY_AGGRO3, SAY_AGGRO4), me); Phase = 1; if (instance) instance->SetData(DATA_LADYVASHJEVENT, IN_PROGRESS); } void EnterCombat(Unit* who) { if (instance) { // remove old tainted cores to prevent cheating in phase 2 Map* map = me->GetMap(); Map::PlayerList const &PlayerList = map->GetPlayers(); for (Map::PlayerList::const_iterator itr = PlayerList.begin(); itr != PlayerList.end(); ++itr) if (Player* player = itr->getSource()) player->DestroyItemCount(31088, 1, true); } StartEvent(); // this is EnterCombat(), so were are 100% in combat, start the event if (Phase != 2) AttackStart(who); } void MoveInLineOfSight(Unit* who) { if (!Intro) { Intro = true; DoScriptText(SAY_INTRO, me); } if (!CanAttack) return; if (!who || me->getVictim()) return; if (me->canCreatureAttack(who)) { float attackRadius = me->GetAttackDistance(who); if (me->IsWithinDistInMap(who, attackRadius) && me->GetDistanceZ(who) <= CREATURE_Z_ATTACK_RANGE && me->IsWithinLOSInMap(who)) { if (!me->isInCombat()) // AttackStart() sets UNIT_FLAG_IN_COMBAT, so this msut be before attacking StartEvent(); if (Phase != 2) AttackStart(who); } } } void CastShootOrMultishot() { switch (urand(0, 1)) { case 0: // Shoot // Used in Phases 1 and 3 after Entangle or while having nobody in melee range. A shot that hits her target for 4097-5543 Physical damage. DoCast(me->getVictim(), SPELL_SHOOT); break; case 1: // Multishot // Used in Phases 1 and 3 after Entangle or while having nobody in melee range. A shot that hits 1 person and 4 people around him for 6475-7525 physical damage. DoCast(me->getVictim(), SPELL_MULTI_SHOT); break; } if (rand()%3) { DoScriptText(RAND(SAY_BOWSHOT1, SAY_BOWSHOT2), me); } } void UpdateAI(const uint32 diff) { if (!CanAttack && Intro) { if (AggroTimer <= diff) { CanAttack = true; me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE); AggroTimer=19000; } else { AggroTimer-=diff; return; } } // to prevent abuses during phase 2 if (Phase == 2 && !me->getVictim() && me->isInCombat()) { EnterEvadeMode(); return; } // Return since we have no target if (!UpdateVictim()) return; if (Phase == 1 || Phase == 3) { // ShockBlastTimer if (ShockBlastTimer <= diff) { // Shock Burst // Randomly used in Phases 1 and 3 on Vashj's target, it's a Shock spell doing 8325-9675 nature damage and stunning the target for 5 seconds, during which she will not attack her target but switch to the next person on the aggro list. DoCast(me->getVictim(), SPELL_SHOCK_BLAST); me->TauntApply(me->getVictim()); ShockBlastTimer = 1000+rand()%14000; // random cooldown } else ShockBlastTimer -= diff; // StaticChargeTimer if (StaticChargeTimer <= diff) { // Static Charge // Used on random people (only 1 person at any given time) in Phases 1 and 3, it's a debuff doing 2775 to 3225 Nature damage to the target and everybody in about 5 yards around it, every 1 seconds for 30 seconds. It can be removed by Cloak of Shadows, Iceblock, Divine Shield, etc, but not by Cleanse or Dispel Magic. Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 200, true); if (target && !target->HasAura(SPELL_STATIC_CHARGE_TRIGGER)) DoCast(target, SPELL_STATIC_CHARGE_TRIGGER); // cast Static Charge every 2 seconds for 20 seconds StaticChargeTimer = 10000+rand()%20000; } else StaticChargeTimer -= diff; // EntangleTimer if (EntangleTimer <= diff) { if (!Entangle) { // Entangle // Used in Phases 1 and 3, it casts Entangling Roots on everybody in a 15 yard radius of Vashj, immobilzing them for 10 seconds and dealing 500 damage every 2 seconds. It's not a magic effect so it cannot be dispelled, but is removed by various buffs such as Cloak of Shadows or Blessing of Freedom. DoCast(me->getVictim(), SPELL_ENTANGLE); Entangle = true; EntangleTimer = 10000; } else { CastShootOrMultishot(); Entangle = false; EntangleTimer = 20000+rand()%5000; } } else EntangleTimer -= diff; // Phase 1 if (Phase == 1) { // Start phase 2 if (HealthBelowPct(70)) { // Phase 2 begins when Vashj hits 70%. She will run to the middle of her platform and surround herself in a shield making her invulerable. Phase = 2; me->GetMotionMaster()->Clear(); DoTeleportTo(MIDDLE_X, MIDDLE_Y, MIDDLE_Z); for (uint8 i = 0; i < 4; ++i) if (Creature* creature = me->SummonCreature(SHIED_GENERATOR_CHANNEL, ShieldGeneratorChannelPos[i][0], ShieldGeneratorChannelPos[i][1], ShieldGeneratorChannelPos[i][2], ShieldGeneratorChannelPos[i][3], TEMPSUMMON_CORPSE_DESPAWN, 0)) ShieldGeneratorChannel[i] = creature->GetGUID(); DoScriptText(SAY_PHASE2, me); } } // Phase 3 else { // SummonSporebatTimer if (SummonSporebatTimer <= diff) { if (Creature* sporebat = me->SummonCreature(TOXIC_SPOREBAT, SPOREBAT_X, SPOREBAT_Y, SPOREBAT_Z, SPOREBAT_O, TEMPSUMMON_CORPSE_DESPAWN, 0)) if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0)) sporebat->AI()->AttackStart(target); // summon sporebats faster and faster if (SummonSporebatStaticTimer > 1000) SummonSporebatStaticTimer -= 1000; SummonSporebatTimer = SummonSporebatStaticTimer; if (SummonSporebatTimer < 5000) SummonSporebatTimer = 5000; } else SummonSporebatTimer -= diff; } // Melee attack DoMeleeAttackIfReady(); // CheckTimer - used to check if somebody is in melee range if (CheckTimer <= diff) { bool inMeleeRange = false; std::list<HostileReference*> t_list = me->getThreatManager().getThreatList(); for (std::list<HostileReference*>::const_iterator itr = t_list.begin(); itr!= t_list.end(); ++itr) { Unit* target = Unit::GetUnit(*me, (*itr)->getUnitGuid()); if (target && target->IsWithinDistInMap(me, 5)) // if in melee range { inMeleeRange = true; break; } } // if nobody is in melee range if (!inMeleeRange) CastShootOrMultishot(); CheckTimer = 5000; } else CheckTimer -= diff; } // Phase 2 else { // ForkedLightningTimer if (ForkedLightningTimer <= diff) { // Forked Lightning // Used constantly in Phase 2, it shoots out completely randomly targeted bolts of lightning which hit everybody in a roughtly 60 degree cone in front of Vashj for 2313-2687 nature damage. Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0); if (!target) target = me->getVictim(); DoCast(target, SPELL_FORKED_LIGHTNING); ForkedLightningTimer = 2000+rand()%6000; } else ForkedLightningTimer -= diff; // EnchantedElementalTimer if (EnchantedElementalTimer <= diff) { me->SummonCreature(ENCHANTED_ELEMENTAL, ElementPos[EnchantedElementalPos][0], ElementPos[EnchantedElementalPos][1], ElementPos[EnchantedElementalPos][2], ElementPos[EnchantedElementalPos][3], TEMPSUMMON_CORPSE_DESPAWN, 0); if (EnchantedElementalPos == 7) EnchantedElementalPos = 0; else ++EnchantedElementalPos; EnchantedElementalTimer = 10000+rand()%5000; } else EnchantedElementalTimer -= diff; // TaintedElementalTimer if (TaintedElementalTimer <= diff) { uint32 pos = rand()%8; me->SummonCreature(TAINTED_ELEMENTAL, ElementPos[pos][0], ElementPos[pos][1], ElementPos[pos][2], ElementPos[pos][3], TEMPSUMMON_DEAD_DESPAWN, 0); TaintedElementalTimer = 120000; } else TaintedElementalTimer -= diff; // CoilfangEliteTimer if (CoilfangEliteTimer <= diff) { uint32 pos = rand()%3; Creature* coilfangElite = me->SummonCreature(COILFANG_ELITE, CoilfangElitePos[pos][0], CoilfangElitePos[pos][1], CoilfangElitePos[pos][2], CoilfangElitePos[pos][3], TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 5000); if (coilfangElite) { if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0)) coilfangElite->AI()->AttackStart(target); else if (me->getVictim()) coilfangElite->AI()->AttackStart(me->getVictim()); } CoilfangEliteTimer = 45000+rand()%5000; } else CoilfangEliteTimer -= diff; // CoilfangStriderTimer if (CoilfangStriderTimer <= diff) { uint32 pos = rand()%3; if (Creature* CoilfangStrider = me->SummonCreature(COILFANG_STRIDER, CoilfangStriderPos[pos][0], CoilfangStriderPos[pos][1], CoilfangStriderPos[pos][2], CoilfangStriderPos[pos][3], TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 5000)) { if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0)) CoilfangStrider->AI()->AttackStart(target); else if (me->getVictim()) CoilfangStrider->AI()->AttackStart(me->getVictim()); } CoilfangStriderTimer = 60000+rand()%10000; } else CoilfangStriderTimer -= diff; // CheckTimer if (CheckTimer <= diff) { // Start Phase 3 if (instance && instance->GetData(DATA_CANSTARTPHASE3)) { // set life 50% me->SetHealth(me->CountPctFromMaxHealth(50)); me->RemoveAurasDueToSpell(SPELL_MAGIC_BARRIER); DoScriptText(SAY_PHASE3, me); Phase = 3; // return to the tank me->GetMotionMaster()->MoveChase(me->getVictim()); } CheckTimer = 1000; } else CheckTimer -= diff; } } }; }; // Enchanted Elemental // If one of them reaches Vashj he will increase her damage done by 5%. class mob_enchanted_elemental : public CreatureScript { public: mob_enchanted_elemental() : CreatureScript("mob_enchanted_elemental") { } CreatureAI* GetAI(Creature* creature) const { return new mob_enchanted_elementalAI (creature); } struct mob_enchanted_elementalAI : public ScriptedAI { mob_enchanted_elementalAI(Creature* creature) : ScriptedAI(creature) { instance = creature->GetInstanceScript(); } InstanceScript* instance; uint32 Move; uint32 Phase; float X, Y, Z; uint64 VashjGUID; void Reset() { me->SetSpeed(MOVE_WALK, 0.6f); // walk me->SetSpeed(MOVE_RUN, 0.6f); // run Move = 0; Phase = 1; VashjGUID = 0; X = ElementWPPos[0][0]; Y = ElementWPPos[0][1]; Z = ElementWPPos[0][2]; //search for nearest waypoint (up on stairs) for (uint32 i = 1; i < 8; ++i) { if (me->GetDistance(ElementWPPos[i][0], ElementWPPos[i][1], ElementWPPos[i][2]) < me->GetDistance(X, Y, Z)) { X = ElementWPPos[i][0]; Y = ElementWPPos[i][1]; Z = ElementWPPos[i][2]; } } if (instance) VashjGUID = instance->GetData64(DATA_LADYVASHJ); } void EnterCombat(Unit* /*who*/) {} void MoveInLineOfSight(Unit* /*who*/) {} void UpdateAI(const uint32 diff) { if (!instance) return; if (!VashjGUID) return; if (Move <= diff) { me->SetWalk(true); if (Phase == 1) me->GetMotionMaster()->MovePoint(0, X, Y, Z); if (Phase == 1 && me->IsWithinDist3d(X, Y, Z, 0.1f)) Phase = 2; if (Phase == 2) { me->GetMotionMaster()->MovePoint(0, MIDDLE_X, MIDDLE_Y, MIDDLE_Z); Phase = 3; } if (Phase == 3) { me->GetMotionMaster()->MovePoint(0, MIDDLE_X, MIDDLE_Y, MIDDLE_Z); if (me->IsWithinDist3d(MIDDLE_X, MIDDLE_Y, MIDDLE_Z, 3)) DoCast(me, SPELL_SURGE); } if (Creature* vashj = Unit::GetCreature(*me, VashjGUID)) if (!vashj->isInCombat() || CAST_AI(boss_lady_vashj::boss_lady_vashjAI, vashj->AI())->Phase != 2 || vashj->isDead()) me->Kill(me); Move = 1000; } else Move -= diff; } }; }; // Tainted Elemental // This mob has 7, 900 life, doesn't move, and shoots Poison Bolts at one person anywhere in the area, doing 3, 000 nature damage and placing a posion doing 2, 000 damage every 2 seconds. He will switch targets often, or sometimes just hang on a single player, but there is nothing you can do about it except heal the damage and kill the Tainted Elemental class mob_tainted_elemental : public CreatureScript { public: mob_tainted_elemental() : CreatureScript("mob_tainted_elemental") { } CreatureAI* GetAI(Creature* creature) const { return new mob_tainted_elementalAI (creature); } struct mob_tainted_elementalAI : public ScriptedAI { mob_tainted_elementalAI(Creature* creature) : ScriptedAI(creature) { instance = creature->GetInstanceScript(); } InstanceScript* instance; uint32 PoisonBoltTimer; uint32 DespawnTimer; void Reset() { PoisonBoltTimer = 5000+rand()%5000; DespawnTimer = 30000; } void JustDied(Unit* /*killer*/) { if (instance) if (Creature* vashj = Unit::GetCreature((*me), instance->GetData64(DATA_LADYVASHJ))) CAST_AI(boss_lady_vashj::boss_lady_vashjAI, vashj->AI())->EventTaintedElementalDeath(); } void EnterCombat(Unit* who) { me->AddThreat(who, 0.1f); } void UpdateAI(const uint32 diff) { // PoisonBoltTimer if (PoisonBoltTimer <= diff) { Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0); if (target && target->IsWithinDistInMap(me, 30)) DoCast(target, SPELL_POISON_BOLT); PoisonBoltTimer = 5000+rand()%5000; } else PoisonBoltTimer -= diff; // DespawnTimer if (DespawnTimer <= diff) { // call Unsummon() me->setDeathState(DEAD); // to prevent crashes DespawnTimer = 1000; } else DespawnTimer -= diff; } }; }; //Toxic Sporebat //Toxic Spores: Used in Phase 3 by the Spore Bats, it creates a contaminated green patch of ground, dealing about 2775-3225 nature damage every second to anyone who stands in it. class mob_toxic_sporebat : public CreatureScript { public: mob_toxic_sporebat() : CreatureScript("mob_toxic_sporebat") { } CreatureAI* GetAI(Creature* creature) const { return new mob_toxic_sporebatAI (creature); } struct mob_toxic_sporebatAI : public ScriptedAI { mob_toxic_sporebatAI(Creature* creature) : ScriptedAI(creature) { instance = creature->GetInstanceScript(); EnterEvadeMode(); } InstanceScript* instance; uint32 MovementTimer; uint32 ToxicSporeTimer; uint32 BoltTimer; uint32 CheckTimer; void Reset() { me->SetDisableGravity(true); me->setFaction(14); MovementTimer = 0; ToxicSporeTimer = 5000; BoltTimer = 5500; CheckTimer = 1000; } void MoveInLineOfSight(Unit* /*who*/) { } void MovementInform(uint32 type, uint32 id) { if (type != POINT_MOTION_TYPE) return; if (id == 1) MovementTimer = 0; } void UpdateAI (const uint32 diff) { // Random movement if (MovementTimer <= diff) { uint32 rndpos = rand()%8; me->GetMotionMaster()->MovePoint(1, SporebatWPPos[rndpos][0], SporebatWPPos[rndpos][1], SporebatWPPos[rndpos][2]); MovementTimer = 6000; } else MovementTimer -= diff; // toxic spores if (BoltTimer <= diff) { if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0)) { if (Creature* trig = me->SummonCreature(TOXIC_SPORES_TRIGGER, target->GetPositionX(), target->GetPositionY(), target->GetPositionZ(), 0, TEMPSUMMON_TIMED_DESPAWN, 30000)) { trig->setFaction(14); trig->CastSpell(trig, SPELL_TOXIC_SPORES, true); } } BoltTimer = 10000+rand()%5000; } else BoltTimer -= diff; // CheckTimer if (CheckTimer <= diff) { if (instance) { // check if vashj is death Unit* Vashj = Unit::GetUnit(*me, instance->GetData64(DATA_LADYVASHJ)); if (!Vashj || (Vashj && !Vashj->isAlive()) || (Vashj && CAST_AI(boss_lady_vashj::boss_lady_vashjAI, CAST_CRE(Vashj)->AI())->Phase != 3)) { // remove me->setDeathState(DEAD); me->RemoveCorpse(); me->setFaction(35); } } CheckTimer = 1000; } else CheckTimer -= diff; } }; }; class mob_shield_generator_channel : public CreatureScript { public: mob_shield_generator_channel() : CreatureScript("mob_shield_generator_channel") { } CreatureAI* GetAI(Creature* creature) const { return new mob_shield_generator_channelAI (creature); } struct mob_shield_generator_channelAI : public ScriptedAI { mob_shield_generator_channelAI(Creature* creature) : ScriptedAI(creature) { instance = creature->GetInstanceScript(); } InstanceScript* instance; uint32 CheckTimer; bool Casted; void Reset() { CheckTimer = 0; Casted = false; me->SetDisplayId(11686); // invisible me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); } void MoveInLineOfSight(Unit* /*who*/) {} void UpdateAI (const uint32 diff) { if (!instance) return; if (CheckTimer <= diff) { Unit* vashj = Unit::GetUnit(*me, instance->GetData64(DATA_LADYVASHJ)); if (vashj && vashj->isAlive()) { // start visual channel if (!Casted || !vashj->HasAura(SPELL_MAGIC_BARRIER)) { DoCast(vashj, SPELL_MAGIC_BARRIER, true); Casted = true; } } CheckTimer = 1000; } else CheckTimer -= diff; } }; }; class item_tainted_core : public ItemScript { public: item_tainted_core() : ItemScript("item_tainted_core") { } bool OnUse(Player* player, Item* /*item*/, SpellCastTargets const& targets) { InstanceScript* instance = player->GetInstanceScript(); if (!instance) { player->GetSession()->SendNotification(TEXT_NOT_INITIALIZED); return true; } Creature* vashj = Unit::GetCreature((*player), instance->GetData64(DATA_LADYVASHJ)); if (vashj && (CAST_AI(boss_lady_vashj::boss_lady_vashjAI, vashj->AI())->Phase == 2)) { if (GameObject* gObj = targets.GetGOTarget()) { uint32 identifier; uint8 channelIdentifier; switch (gObj->GetEntry()) { case 185052: identifier = DATA_SHIELDGENERATOR1; channelIdentifier = 0; break; case 185053: identifier = DATA_SHIELDGENERATOR2; channelIdentifier = 1; break; case 185051: identifier = DATA_SHIELDGENERATOR3; channelIdentifier = 2; break; case 185054: identifier = DATA_SHIELDGENERATOR4; channelIdentifier = 3; break; default: return true; } if (instance->GetData(identifier)) { player->GetSession()->SendNotification(TEXT_ALREADY_DEACTIVATED); return true; } // get and remove channel if (Unit* channel = Unit::GetCreature(*vashj, CAST_AI(boss_lady_vashj::boss_lady_vashjAI, vashj->AI())->ShieldGeneratorChannel[channelIdentifier])) channel->setDeathState(JUST_DIED); // call Unsummon() instance->SetData(identifier, 1); // remove this item player->DestroyItemCount(31088, 1, true); return true; } else if (targets.GetUnitTarget()->GetTypeId() == TYPEID_UNIT) return false; else if (targets.GetUnitTarget()->GetTypeId() == TYPEID_PLAYER) { player->DestroyItemCount(31088, 1, true); player->CastSpell(targets.GetUnitTarget(), 38134, true); return true; } } return true; } }; void AddSC_boss_lady_vashj() { new boss_lady_vashj(); new mob_enchanted_elemental(); new mob_tainted_elemental(); new mob_toxic_sporebat(); new mob_shield_generator_channel(); new item_tainted_core(); }
35.534464
355
0.520756
499453466
3b962e4338ccd3f5d92c68775b21a40475ae4513
292
cpp
C++
server/src/coverage/Coverage.cpp
PolyProgrammist/UTBotCpp
4886622f21c92e3b73daa553008e541be9d82f21
[ "Apache-2.0" ]
null
null
null
server/src/coverage/Coverage.cpp
PolyProgrammist/UTBotCpp
4886622f21c92e3b73daa553008e541be9d82f21
[ "Apache-2.0" ]
null
null
null
server/src/coverage/Coverage.cpp
PolyProgrammist/UTBotCpp
4886622f21c92e3b73daa553008e541be9d82f21
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2021. All rights reserved. */ #include "Coverage.h" int Coverage::TestStatusMap::getNumberOfTests() { int cnt = 0; for (auto const &[fileName, testsStatus] : *this) { cnt += testsStatus.size(); } return cnt; }
20.857143
78
0.626712
PolyProgrammist
3b973b9b15b5571661f88bb58dd8bcfb355ad1e9
709
cpp
C++
jp.atcoder/abc021/abc021_c/11693515.cpp
kagemeka/atcoder-submissions
91d8ad37411ea2ec582b10ba41b1e3cae01d4d6e
[ "MIT" ]
1
2022-02-09T03:06:25.000Z
2022-02-09T03:06:25.000Z
jp.atcoder/abc021/abc021_c/11693515.cpp
kagemeka/atcoder-submissions
91d8ad37411ea2ec582b10ba41b1e3cae01d4d6e
[ "MIT" ]
1
2022-02-05T22:53:18.000Z
2022-02-09T01:29:30.000Z
jp.atcoder/abc021/abc021_c/11693515.cpp
kagemeka/atcoder-submissions
91d8ad37411ea2ec582b10ba41b1e3cae01d4d6e
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int MOD = 1e9 + 7; int main() { ios::sync_with_stdio(false); cin.tie(0); int n, a, b, m; cin >> n >> a >> b >> m; a--; b--; vector<vector<int>> graph(n, vector<int>(n, 0)); for (int i = 0; i < m; i++) { int x, y; cin >> x >> y; x--; y--; graph[x][y] = 1; graph[y][x] = 1; } vector<long long> paths(n, 0); paths[a] = 1; while (!paths[b]) { vector<long long> nxt(n, 0); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { nxt[i] += graph[i][j] * paths[j]; nxt[i] %= MOD; } } paths = nxt; } cout << paths[b] << '\n'; return 0; }
19.694444
51
0.4189
kagemeka
3b9762bea0ab3c3b8887b4092b09f9ae47991d52
26,165
cc
C++
plugin/plugin.cc
abique/vst-bridge
2fd29f806c4a54e3f97367974a3d48b9eabb10f7
[ "MIT" ]
235
2015-02-14T03:02:13.000Z
2022-03-30T04:46:40.000Z
plugin/plugin.cc
abique/vst-bridge
2fd29f806c4a54e3f97367974a3d48b9eabb10f7
[ "MIT" ]
9
2015-11-04T18:17:49.000Z
2020-12-01T14:40:04.000Z
plugin/plugin.cc
abique/vst-bridge
2fd29f806c4a54e3f97367974a3d48b9eabb10f7
[ "MIT" ]
16
2015-06-12T20:10:00.000Z
2020-12-01T14:37:29.000Z
#include <sys/types.h> #include <sys/socket.h> #include <sys/wait.h> #include <limits.h> #include <fcntl.h> #include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <assert.h> #include <pthread.h> #include <signal.h> #include <list> #include <X11/Xlib.h> #define __cdecl #include "../config.h" #include "../common/common.h" const char g_plugin_path[PATH_MAX] = VST_BRIDGE_TPL_DLL; const char g_host_path[PATH_MAX] = VST_BRIDGE_TPL_HOST; const char g_plugin_wineprefix[PATH_MAX] = VST_BRIDGE_TPL_WINEPREFIX; #ifdef DEBUG # define LOG(Args...) \ do { \ fprintf(g_log ? : stderr, "P: " Args); \ fflush(g_log ? : stderr); \ } while (0) #else # define LOG(Args...) do { ; } while (0) #endif #define CRIT(Args...) \ do { \ fprintf(g_log ? : stderr, "[CRIT] P: " Args); \ fflush(g_log ? : stderr); \ } while (0) #include "../vstsdk2.4/pluginterfaces/vst2.x/aeffectx.h" static FILE *g_log = NULL; struct vst_bridge_effect { vst_bridge_effect() : socket(-1), child(-1), next_tag(0), chunk(NULL) { pthread_mutexattr_t attr; pthread_mutexattr_init(&attr); pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); pthread_mutex_init(&lock, &attr); pthread_mutexattr_destroy(&attr); memset(&e, 0, sizeof (e)); } ~vst_bridge_effect() { if (socket >= 0) close(socket); free(chunk); pthread_mutex_destroy(&lock); int st; waitpid(child, &st, 0); if (display) XCloseDisplay(display); } struct AEffect e; int socket; pid_t child; uint32_t next_tag; audioMasterCallback audio_master; void *chunk; pthread_mutex_t lock; ERect rect; bool close_flag; std::list<vst_bridge_request> pending; Display *display; bool show_window; }; void copy_plugin_data(struct vst_bridge_effect *vbe, struct vst_bridge_request *rq) { vbe->e.numPrograms = rq->plugin_data.numPrograms; vbe->e.numParams = rq->plugin_data.numParams; vbe->e.numInputs = rq->plugin_data.numInputs; vbe->e.numOutputs = rq->plugin_data.numOutputs; vbe->e.flags = rq->plugin_data.flags; vbe->e.initialDelay = rq->plugin_data.initialDelay; vbe->e.uniqueID = rq->plugin_data.uniqueID; vbe->e.version = rq->plugin_data.version; if (!rq->plugin_data.hasSetParameter) vbe->e.setParameter = NULL; if (!rq->plugin_data.hasGetParameter) vbe->e.getParameter = NULL; if (!rq->plugin_data.hasProcessReplacing) vbe->e.processReplacing = NULL; if (!rq->plugin_data.hasProcessDoubleReplacing) vbe->e.processDoubleReplacing = NULL; } void vst_bridge_handle_audio_master(struct vst_bridge_effect *vbe, struct vst_bridge_request *rq) { LOG("audio_master(%s, %d, %d, %f) <= tag %d\n", vst_bridge_audio_master_opcode_name[rq->amrq.opcode], rq->amrq.index, rq->amrq.value, rq->amrq.opt, rq->tag); switch (rq->amrq.opcode) { // no additional data case audioMasterAutomate: case audioMasterVersion: case audioMasterCurrentId: case audioMasterIdle: case __audioMasterPinConnectedDeprecated: case audioMasterIOChanged: case audioMasterSizeWindow: case audioMasterGetSampleRate: case audioMasterGetBlockSize: case audioMasterGetInputLatency: case audioMasterGetOutputLatency: case audioMasterGetCurrentProcessLevel: case audioMasterGetAutomationState: case __audioMasterWantMidiDeprecated: case __audioMasterNeedIdleDeprecated: case audioMasterCanDo: case audioMasterGetVendorVersion: case audioMasterBeginEdit: case audioMasterEndEdit: case audioMasterUpdateDisplay: case __audioMasterTempoAtDeprecated: rq->amrq.value = vbe->audio_master(&vbe->e, rq->amrq.opcode, rq->amrq.index, rq->amrq.value, rq->amrq.data, rq->amrq.opt); write(vbe->socket, rq, VST_BRIDGE_AMRQ_LEN(0)); break; case audioMasterGetProductString: case audioMasterGetVendorString: rq->amrq.value = vbe->audio_master(&vbe->e, rq->amrq.opcode, rq->amrq.index, rq->amrq.value, rq->amrq.data, rq->amrq.opt); write(vbe->socket, rq, VST_BRIDGE_AMRQ_LEN(strlen((const char *)rq->amrq.data) + 1)); break; case audioMasterProcessEvents: { struct vst_bridge_midi_events *mes = (struct vst_bridge_midi_events *)rq->amrq.data; struct VstEvents *ves = (struct VstEvents *)malloc(sizeof (*ves) + mes->nb * sizeof (void*)); ves->numEvents = mes->nb; ves->reserved = 0; struct vst_bridge_midi_event *me = mes->events; for (size_t i = 0; i < mes->nb; ++i) { ves->events[i] = (VstEvent*)me; me = (struct vst_bridge_midi_event *)(me->data + me->byteSize); } rq->amrq.value = vbe->audio_master(&vbe->e, rq->amrq.opcode, rq->amrq.index, rq->amrq.value, ves, rq->amrq.opt); free(ves); write(vbe->socket, rq, ((uint8_t*)me) - ((uint8_t*)rq)); break; } case audioMasterGetTime: { VstTimeInfo *time_info = (VstTimeInfo *)vbe->audio_master( &vbe->e, rq->amrq.opcode, rq->amrq.index, rq->amrq.value, rq->amrq.data, rq->amrq.opt); if (!time_info) rq->amrq.value = 0; else { rq->amrq.value = 1; memcpy(rq->amrq.data, time_info, sizeof (*time_info)); } write(vbe->socket, rq, VST_BRIDGE_AMRQ_LEN(sizeof (*time_info))); break; } default: CRIT(" !!!!!!! audio master callback (unhandled): op: %d," " index: %d, value: %ld, opt: %f\n", rq->amrq.opcode, rq->amrq.index, rq->amrq.value, rq->amrq.opt); break; } } bool vst_bridge_wait_response(struct vst_bridge_effect *vbe, struct vst_bridge_request *rq, uint32_t tag) { ssize_t len; while (true) { std::list<vst_bridge_request>::iterator it; for (it = vbe->pending.begin(); it != vbe->pending.end(); ++it) { if (it->tag != tag) continue; *rq = *it; // XXX could be optimized? vbe->pending.erase(it); return true; } LOG(" <=== Waiting for tag %d\n", tag); len = ::read(vbe->socket, rq, sizeof (*rq)); if (len <= 0) return false; assert(len >= VST_BRIDGE_RQ_LEN); LOG(" ===> Got tag %d\n", rq->tag); if (rq->tag == tag) return true; // handle request if (rq->cmd == VST_BRIDGE_CMD_AUDIO_MASTER_CALLBACK) { vst_bridge_handle_audio_master(vbe, rq); continue; } else if (rq->cmd == VST_BRIDGE_CMD_PLUGIN_DATA) { copy_plugin_data(vbe, rq); continue; } vbe->pending.push_back(*rq); } } void vst_bridge_show_window(struct vst_bridge_effect *vbe) { struct vst_bridge_request rq; if (vbe->show_window) { rq.tag = vbe->next_tag; rq.cmd = VST_BRIDGE_CMD_SHOW_WINDOW; vbe->next_tag += 2; vbe->show_window = false; write(vbe->socket, &rq, VST_BRIDGE_RQ_LEN); vst_bridge_wait_response(vbe, &rq, rq.tag); } } void vst_bridge_call_process(AEffect* effect, float** inputs, float** outputs, VstInt32 sampleFrames) { struct vst_bridge_effect *vbe = container_of(effect, struct vst_bridge_effect, e); struct vst_bridge_request rq; pthread_mutex_lock(&vbe->lock); rq.tag = vbe->next_tag; rq.cmd = VST_BRIDGE_CMD_PROCESS; rq.frames.nframes = sampleFrames; vbe->next_tag += 2; for (int i = 0; i < vbe->e.numInputs; ++i) memcpy(rq.frames.frames + i * sampleFrames, inputs[i], sizeof (float) * sampleFrames); write(vbe->socket, &rq, VST_BRIDGE_FRAMES_LEN(vbe->e.numInputs * sampleFrames)); vst_bridge_wait_response(vbe, &rq, rq.tag); for (int i = 0; i < vbe->e.numOutputs; ++i) memcpy(outputs[i], rq.frames.frames + i * sampleFrames, sizeof (float) * sampleFrames); pthread_mutex_unlock(&vbe->lock); } void vst_bridge_call_process_double(AEffect* effect, double** inputs, double** outputs, VstInt32 sampleFrames) { struct vst_bridge_effect *vbe = container_of(effect, struct vst_bridge_effect, e); struct vst_bridge_request rq; pthread_mutex_lock(&vbe->lock); rq.tag = vbe->next_tag; rq.cmd = VST_BRIDGE_CMD_PROCESS_DOUBLE; rq.framesd.nframes = sampleFrames; vbe->next_tag += 2; for (int i = 0; i < vbe->e.numInputs; ++i) memcpy(rq.framesd.frames + i * sampleFrames, inputs[i], sizeof (double) * sampleFrames); write(vbe->socket, &rq, VST_BRIDGE_FRAMES_DOUBLE_LEN(vbe->e.numInputs * sampleFrames)); vst_bridge_wait_response(vbe, &rq, rq.tag); for (int i = 0; i < vbe->e.numOutputs; ++i) memcpy(outputs[i], rq.framesd.frames + i * sampleFrames, sizeof (double) * sampleFrames); pthread_mutex_unlock(&vbe->lock); } float vst_bridge_call_get_parameter(AEffect* effect, VstInt32 index) { struct vst_bridge_effect *vbe = container_of(effect, struct vst_bridge_effect, e); struct vst_bridge_request rq; pthread_mutex_lock(&vbe->lock); rq.tag = vbe->next_tag; rq.cmd = VST_BRIDGE_CMD_GET_PARAMETER; rq.param.index = index; vbe->next_tag += 2; write(vbe->socket, &rq, VST_BRIDGE_PARAM_LEN); vst_bridge_wait_response(vbe, &rq, rq.tag); pthread_mutex_unlock(&vbe->lock); return rq.param.value; } void vst_bridge_call_set_parameter(AEffect* effect, VstInt32 index, float parameter) { struct vst_bridge_effect *vbe = container_of(effect, struct vst_bridge_effect, e); struct vst_bridge_request rq; pthread_mutex_lock(&vbe->lock); rq.tag = vbe->next_tag; rq.cmd = VST_BRIDGE_CMD_SET_PARAMETER; rq.param.index = index; rq.param.value = parameter; vbe->next_tag += 2; write(vbe->socket, &rq, VST_BRIDGE_PARAM_LEN); pthread_mutex_unlock(&vbe->lock); } VstIntPtr vst_bridge_call_effect_dispatcher2(AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt) { struct vst_bridge_effect *vbe = container_of(effect, struct vst_bridge_effect, e); struct vst_bridge_request rq; ssize_t len; LOG("[%p] effect_dispatcher(%s, %d, %d, %p, %f) => next_tag: %d\n", pthread_self(), vst_bridge_effect_opcode_name[opcode], index, value, ptr, opt, vbe->next_tag); switch (opcode) { case effSetBlockSize: case effSetProgram: case effSetSampleRate: case effEditIdle: case effGetProgram: case __effIdleDeprecated: case effSetTotalSampleToProcess: case effStartProcess: case effStopProcess: case effSetPanLaw: case effSetProcessPrecision: case effGetNumMidiInputChannels: case effGetNumMidiOutputChannels: case effEditClose: case effCanBeAutomated: case effGetTailSize: rq.tag = vbe->next_tag; rq.cmd = VST_BRIDGE_CMD_EFFECT_DISPATCHER; rq.erq.opcode = opcode; rq.erq.index = index; rq.erq.value = value; rq.erq.opt = opt; vbe->next_tag += 2; write(vbe->socket, &rq, VST_BRIDGE_ERQ_LEN(0)); vst_bridge_wait_response(vbe, &rq, rq.tag); return rq.amrq.value; case effGetOutputProperties: case effGetInputProperties: rq.tag = vbe->next_tag; rq.cmd = VST_BRIDGE_CMD_EFFECT_DISPATCHER; rq.erq.opcode = opcode; rq.erq.index = index; rq.erq.value = value; rq.erq.opt = opt; vbe->next_tag += 2; write(vbe->socket, &rq, VST_BRIDGE_ERQ_LEN(0)); vst_bridge_wait_response(vbe, &rq, rq.tag); memcpy(ptr, rq.erq.data, sizeof (VstPinProperties)); return rq.erq.value; case effBeginLoadBank: rq.tag = vbe->next_tag; rq.cmd = VST_BRIDGE_CMD_EFFECT_DISPATCHER; rq.erq.opcode = opcode; rq.erq.index = index; rq.erq.value = value; rq.erq.opt = opt; vbe->next_tag += 2; write(vbe->socket, &rq, VST_BRIDGE_ERQ_LEN(sizeof (VstPatchChunkInfo))); vst_bridge_wait_response(vbe, &rq, rq.tag); return rq.erq.value; case effOpen: case effGetPlugCategory: case effGetVstVersion: case effGetVendorVersion: case effMainsChanged: case effBeginSetProgram: case effEndSetProgram: case __effConnectOutputDeprecated: case __effConnectInputDeprecated: case effSetEditKnobMode: case effEditKeyUp: case effEditKeyDown: rq.tag = vbe->next_tag; rq.cmd = VST_BRIDGE_CMD_EFFECT_DISPATCHER; rq.erq.opcode = opcode; rq.erq.index = index; rq.erq.value = value; rq.erq.opt = opt; vbe->next_tag += 2; write(vbe->socket, &rq, sizeof (rq)); vst_bridge_wait_response(vbe, &rq, rq.tag); return rq.amrq.value; case effClose: // quit rq.tag = vbe->next_tag; rq.cmd = VST_BRIDGE_CMD_EFFECT_DISPATCHER; rq.erq.opcode = opcode; rq.erq.index = index; rq.erq.value = value; rq.erq.opt = opt; vbe->next_tag += 2; write(vbe->socket, &rq, VST_BRIDGE_ERQ_LEN(0)); vbe->close_flag = true; return 0; case effEditOpen: { rq.tag = vbe->next_tag; rq.cmd = VST_BRIDGE_CMD_EFFECT_DISPATCHER; rq.erq.opcode = opcode; rq.erq.index = index; rq.erq.value = value; rq.erq.opt = opt; vbe->next_tag += 2; write(vbe->socket, &rq, VST_BRIDGE_ERQ_LEN(0)); vst_bridge_wait_response(vbe, &rq, rq.tag); Window parent = (Window)ptr; Window child = (Window)rq.erq.index; if (!vbe->display) vbe->display = XOpenDisplay(NULL); XReparentWindow(vbe->display, child, parent, 0, 0); #if 0 XEvent ev; memset(&ev, 0, sizeof (ev)); ev.xclient.type = ClientMessage; ev.xclient.window = child; ev.xclient.message_type = XInternAtom(vbe->display, "_XEMBED", false); ev.xclient.format = 32; ev.xclient.data.l[0] = CurrentTime; ev.xclient.data.l[1] = XEMBED_EMBEDDED_NOTIFY; ev.xclient.data.l[3] = parent; XSendEvent(vbe->display, child, false, NoEventMask, &ev); #endif XSync(vbe->display, false); XFlush(vbe->display); vbe->show_window = true; vst_bridge_show_window(vbe); return rq.erq.value; } case effEditGetRect: { rq.tag = vbe->next_tag; rq.cmd = VST_BRIDGE_CMD_EFFECT_DISPATCHER; rq.erq.opcode = opcode; rq.erq.index = index; rq.erq.value = value; rq.erq.opt = opt; vbe->next_tag += 2; write(vbe->socket, &rq, VST_BRIDGE_ERQ_LEN(0)); vst_bridge_wait_response(vbe, &rq, rq.tag); memcpy(&vbe->rect, rq.erq.data, sizeof (vbe->rect)); ERect **r = (ERect **)ptr; *r = &vbe->rect; return rq.erq.value; } case effSetProgramName: rq.tag = vbe->next_tag; rq.cmd = VST_BRIDGE_CMD_EFFECT_DISPATCHER; rq.erq.opcode = opcode; rq.erq.index = index; rq.erq.value = value; rq.erq.opt = opt; vbe->next_tag += 2; strcpy((char*)rq.erq.data, (const char *)ptr); write(vbe->socket, &rq, VST_BRIDGE_ERQ_LEN(strlen((const char *)ptr) + 1)); if (!vst_bridge_wait_response(vbe, &rq, rq.tag)) return 0; return rq.amrq.value; case effGetMidiKeyName: rq.tag = vbe->next_tag; rq.cmd = VST_BRIDGE_CMD_EFFECT_DISPATCHER; rq.erq.opcode = opcode; rq.erq.index = index; rq.erq.value = value; rq.erq.opt = opt; vbe->next_tag += 2; memcpy(rq.erq.data, ptr, sizeof (MidiKeyName)); write(vbe->socket, &rq, VST_BRIDGE_ERQ_LEN(sizeof (MidiKeyName))); if (!vst_bridge_wait_response(vbe, &rq, rq.tag)) return 0; memcpy(ptr, rq.erq.data, sizeof (MidiKeyName)); return rq.erq.value; case effGetProgramName: case effGetParamLabel: case effGetParamDisplay: case effGetParamName: case effGetEffectName: case effGetVendorString: case effGetProductString: case effGetProgramNameIndexed: rq.tag = vbe->next_tag; rq.cmd = VST_BRIDGE_CMD_EFFECT_DISPATCHER; rq.erq.opcode = opcode; rq.erq.index = index; rq.erq.value = value; rq.erq.opt = opt; vbe->next_tag += 2; write(vbe->socket, &rq, VST_BRIDGE_ERQ_LEN(0)); if (!vst_bridge_wait_response(vbe, &rq, rq.tag)) return 0; strcpy((char*)ptr, (const char *)rq.erq.data); LOG("Got string: %s\n", (char *)ptr); return rq.amrq.value; case effCanDo: rq.tag = vbe->next_tag; rq.cmd = VST_BRIDGE_CMD_EFFECT_DISPATCHER; rq.erq.opcode = opcode; rq.erq.index = index; rq.erq.value = value; rq.erq.opt = opt; vbe->next_tag += 2; strcpy((char*)rq.erq.data, (const char *)ptr); write(vbe->socket, &rq, sizeof (rq)); if (!vst_bridge_wait_response(vbe, &rq, rq.tag)) return 0; return rq.erq.value; case effGetParameterProperties: rq.tag = vbe->next_tag; rq.cmd = VST_BRIDGE_CMD_EFFECT_DISPATCHER; rq.erq.opcode = opcode; rq.erq.index = index; rq.erq.value = value; rq.erq.opt = opt; vbe->next_tag += 2; write(vbe->socket, &rq, VST_BRIDGE_ERQ_LEN(0)); if (!vst_bridge_wait_response(vbe, &rq, rq.tag)) return 0; if (ptr && rq.amrq.value) memcpy(ptr, rq.erq.data, sizeof (VstParameterProperties)); return rq.amrq.value; case effGetChunk: { rq.tag = vbe->next_tag; rq.cmd = VST_BRIDGE_CMD_EFFECT_DISPATCHER; rq.erq.opcode = opcode; rq.erq.index = index; rq.erq.value = value; rq.erq.opt = opt; vbe->next_tag += 2; write(vbe->socket, &rq, sizeof (rq)); if (!vst_bridge_wait_response(vbe, &rq, rq.tag)) return 0; void *chunk = realloc(vbe->chunk, rq.erq.value); if (!chunk) return 0; vbe->chunk = chunk; for (size_t off = 0; rq.erq.value > 0; ) { size_t can_read = MIN(VST_BRIDGE_CHUNK_SIZE, rq.erq.value - off); memcpy(static_cast<uint8_t *>(vbe->chunk) + off, rq.erq.data, can_read); off += can_read; if (off == static_cast<size_t>(rq.erq.value)) break; if (!vst_bridge_wait_response(vbe, &rq, rq.tag)) return 0; } *((void **)ptr) = chunk; return rq.erq.value; } case effSetChunk: { rq.tag = vbe->next_tag; rq.cmd = VST_BRIDGE_CMD_EFFECT_DISPATCHER; rq.erq.opcode = opcode; rq.erq.index = index; rq.erq.value = value; rq.erq.opt = opt; vbe->next_tag += 2; for (size_t off = 0; off < static_cast<size_t>(value); ) { size_t can_write = MIN(VST_BRIDGE_CHUNK_SIZE, value - off); memcpy(rq.erq.data, static_cast<uint8_t *>(ptr) + off, can_write); write(vbe->socket, &rq, VST_BRIDGE_ERQ_LEN(can_write)); off += can_write; } vst_bridge_wait_response(vbe, &rq, rq.tag); return rq.erq.value; } case effSetSpeakerArrangement: { struct VstSpeakerArrangement *ar = (struct VstSpeakerArrangement *)value; rq.tag = vbe->next_tag; rq.cmd = VST_BRIDGE_CMD_EFFECT_DISPATCHER; rq.erq.opcode = opcode; rq.erq.index = index; rq.erq.value = value; rq.erq.opt = opt; vbe->next_tag += 2; size_t len = 8 + ar->numChannels * sizeof (ar->speakers[0]); memcpy(rq.erq.data, ptr, len); write(vbe->socket, &rq, VST_BRIDGE_ERQ_LEN(len)); if (!vst_bridge_wait_response(vbe, &rq, rq.tag)) return 0; memcpy(ptr, rq.erq.data, 8 + ar->numChannels * sizeof (ar->speakers[0])); return rq.amrq.value; } case effProcessEvents: { // compute the size struct VstEvents *evs = (struct VstEvents *)ptr; struct vst_bridge_midi_events *mes = (struct vst_bridge_midi_events *)rq.erq.data; rq.tag = vbe->next_tag; rq.cmd = VST_BRIDGE_CMD_EFFECT_DISPATCHER; rq.erq.opcode = opcode; rq.erq.index = index; rq.erq.value = value; rq.erq.opt = opt; vbe->next_tag += 2; mes->nb = evs->numEvents; struct vst_bridge_midi_event *me = mes->events; for (int i = 0; i < evs->numEvents; ++i) { memcpy(me, evs->events[i], sizeof (*me) + evs->events[i]->byteSize); me = (struct vst_bridge_midi_event *)(me->data + me->byteSize); } write(vbe->socket, &rq, VST_BRIDGE_ERQ_LEN(((uint8_t *)me) - rq.erq.data)); if (!vst_bridge_wait_response(vbe, &rq, rq.tag)) return 0; return rq.amrq.value; } case effVendorSpecific: { switch (index) { case effGetParamDisplay: rq.tag = vbe->next_tag; rq.cmd = VST_BRIDGE_CMD_EFFECT_DISPATCHER; rq.erq.opcode = opcode; rq.erq.index = index; rq.erq.value = value; rq.erq.opt = opt; vbe->next_tag += 2; write(vbe->socket, &rq, VST_BRIDGE_ERQ_LEN(0)); if (!vst_bridge_wait_response(vbe, &rq, rq.tag)) return 0; strcpy((char*)ptr, (const char *)rq.erq.data); LOG("Got string: %s\n", (char *)ptr); return rq.amrq.value; default: // fall through break; } } default: CRIT("[%p] !!!!!!!!!! UNHANDLED effect_dispatcher(%s, %d, %d, %p, %f)\n", pthread_self(), vst_bridge_effect_opcode_name[opcode], index, value, ptr); return 0; } } VstIntPtr vst_bridge_call_effect_dispatcher(AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt) { struct vst_bridge_effect *vbe = container_of(effect, struct vst_bridge_effect, e); pthread_mutex_lock(&vbe->lock); VstIntPtr ret = vst_bridge_call_effect_dispatcher2( effect, opcode, index, value, ptr, opt); pthread_mutex_unlock(&vbe->lock); if (!vbe->close_flag) return ret; delete vbe; return ret; } bool vst_bridge_call_plugin_main(struct vst_bridge_effect *vbe) { struct vst_bridge_request rq; rq.tag = 0; rq.cmd = VST_BRIDGE_CMD_PLUGIN_MAIN; if (write(vbe->socket, &rq, sizeof (rq)) != sizeof (rq)) return false; while (true) { ssize_t rbytes = read(vbe->socket, &rq, sizeof (rq)); if (rbytes <= 0) return false; LOG("cmd: %d, tag: %d, bytes: %d\n", rq.cmd, rq.tag, rbytes); switch (rq.cmd) { case VST_BRIDGE_CMD_PLUGIN_DATA: copy_plugin_data(vbe, &rq); break; case VST_BRIDGE_CMD_PLUGIN_MAIN: copy_plugin_data(vbe, &rq); return true; case VST_BRIDGE_CMD_AUDIO_MASTER_CALLBACK: vst_bridge_handle_audio_master(vbe, &rq); break; default: LOG("UNEXPECTED COMMAND: %d\n", rq.cmd); break; } } } extern "C" { AEffect* VSTPluginMain(audioMasterCallback audio_master); AEffect* VSTPluginMain2(audioMasterCallback audio_master) asm ("main"); } AEffect* VSTPluginMain2(audioMasterCallback audio_master) { return VSTPluginMain(audio_master); } AEffect* VSTPluginMain(audioMasterCallback audio_master) { struct vst_bridge_effect *vbe = NULL; int fds[2]; if (!g_log) { #ifdef DEBUG char path[128]; snprintf(path, sizeof (path), "/tmp/vst-bridge-plugin.%d.log", getpid()); g_log = fopen(path, "w+"); #else g_log = stdout; #endif } // allocate the context vbe = new vst_bridge_effect; if (!vbe) goto failed; // XXX move to the class description vbe->audio_master = audio_master; vbe->e.user = NULL; vbe->e.magic = kEffectMagic; vbe->e.dispatcher = vst_bridge_call_effect_dispatcher; vbe->e.setParameter = vst_bridge_call_set_parameter; vbe->e.getParameter = vst_bridge_call_get_parameter; vbe->e.processReplacing = vst_bridge_call_process; vbe->e.processDoubleReplacing = vst_bridge_call_process_double; vbe->close_flag = false; vbe->show_window = false; vbe->display = NULL; // initialize sockets if (socketpair(AF_UNIX, SOCK_SEQPACKET, 0, fds)) goto failed_sockets; vbe->socket = fds[0]; // fork vbe->child = fork(); if (vbe->child == -1) goto failed_fork; if (!vbe->child) { // in the child // A hack to cheat GCC optimisation. If we'd simply compare // g_plugin_wineprefix to VST_BRIDGE_TPL_WINEPREFIX, the // whole if(strcmp(...)) {} will disappear in the assembly. char *local_plugin_wineprefix = strdup(g_plugin_wineprefix); if (strcmp(local_plugin_wineprefix, VST_BRIDGE_TPL_WINEPREFIX) != 0) setenv("WINEPREFIX", local_plugin_wineprefix, 1); // Should we really override an existing var? free(local_plugin_wineprefix); char buff[8]; close(fds[0]); snprintf(buff, sizeof (buff), "%d", fds[1]); execl("/bin/sh", "/bin/sh", g_host_path, g_plugin_path, buff, NULL); CRIT("Failed to spawn child process: /bin/sh %s %s %s\n", g_host_path, g_plugin_path, buff); exit(1); } // in the father close(fds[1]); // forward plugin main if (!vst_bridge_call_plugin_main(vbe)) { close(vbe->socket); delete vbe; return NULL; } LOG(" => PluginMain done!\n"); // Return the VST AEffect structure return &vbe->e; failed_fork: close(fds[0]); close(fds[1]); failed_sockets: failed: delete vbe; return NULL; }
29.971363
101
0.610587
abique
3b97f16d567a84132aa5436e779ecbccf7fe2e2d
3,357
cpp
C++
src/Linear/EqualConstrOptimize.cpp
alibabach/deformabletracker
1ef5631f7d91488da27abd83b468e2668670ad9d
[ "BSD-2-Clause-FreeBSD" ]
29
2015-09-07T17:51:22.000Z
2022-01-14T08:48:11.000Z
src/Linear/EqualConstrOptimize.cpp
alibabach/deformabletracker
1ef5631f7d91488da27abd83b468e2668670ad9d
[ "BSD-2-Clause-FreeBSD" ]
1
2017-12-07T07:58:19.000Z
2017-12-07T09:26:39.000Z
src/Linear/EqualConstrOptimize.cpp
alibabach/deformabletracker
1ef5631f7d91488da27abd83b468e2668670ad9d
[ "BSD-2-Clause-FreeBSD" ]
5
2016-08-10T05:16:18.000Z
2020-12-30T20:13:31.000Z
////////////////////////////////////////////////////////////////////////// // Author : Ngo Tien Dat // Email : dat.ngo@epfl.ch // Organization : EPFL // Purpose : Solve generic EQUALITY constrained optimization problem // Date : 30 March 2012 ////////////////////////////////////////////////////////////////////////// #include "EqualConstrOptimize.h" using namespace arma; vec EqualConstrOptimize::OptimizeNullSpace(const vec& xInit, Function& objtFunction, Function& cstrFunction) { vec x = xInit; // Variables to be found for (int i = 0; i < nIters; i++) { // Update x step by step EqualConstrOptimize::takeAStepNullSpace( x, objtFunction, cstrFunction ); } return x; } vec EqualConstrOptimize::OptimizeLagrange(const vec& xInit, Function& objtFunction, Function& cstrFunction) { vec x = xInit; // Variables to be found for (int i = 0; i < nIters; i++) { // Update x step by step EqualConstrOptimize::takeAStepLagrange( x, objtFunction, cstrFunction ); } return x; } void EqualConstrOptimize::takeAStepLagrange(vec& x, Function& objtFunction, Function& cstrFunction) { // Evaluate functions objtFunction.Evaluate(x); cstrFunction.Evaluate(x); const vec& F = objtFunction.GetF(); // Function value const mat& J = objtFunction.GetJ(); // Jacobian. F and J are reference to function.J and function.F // We only need to GetF() and GetJ() once const vec& C = cstrFunction.GetF(); // Function value of constraints const mat& A = cstrFunction.GetJ(); // Jacobian of constraints // Find dx int m = A.n_rows; int n = A.n_cols; double lambda = 1e-6; // Calculate some terms mat t1 = join_rows(J.t()*J, A.t()); // t1 = [J'*J A'] // TODO: CAN improve here by precomputed J'*J mat t2 = join_rows(A, zeros(m,m)); // t2 = [A zeros(m,m)] mat t3 = join_cols(t1, t2); // t3 = [t1; t2] mat t4 = join_cols(J.t()*F, C); // t4 = [J'*F C] vec dXLambda = -LinearAlgebraUtils::LeastSquareSolve(t3, t4, lambda); // Compute: -t3 \ t4 vec dX = dXLambda.subvec(0, n-1); // Update x x = x + dX; } void EqualConstrOptimize::takeAStepNullSpace(vec& x, Function& objtFunction, Function& cstrFunction) { // Evaluate functions objtFunction.Evaluate(x); cstrFunction.Evaluate(x); const vec& F = objtFunction.GetF(); // Function value const mat& J = objtFunction.GetJ(); // Jacobian. F and J are reference to function.J and function.F // We only need to GetF() and GetJ() once const vec& C = cstrFunction.GetF(); // Function value of constraints const mat& A = cstrFunction.GetJ(); // Jacobian of constraints // Find dx int n = A.n_cols; double lambda = 1e-6; // Compute pseudo inverse and projector mat pinvA = LinearAlgebraUtils::PseudoInverse(A, lambda); mat Proj = eye(n, n) - pinvA * A; // Compute projection increment vec dX = -pinvA * C; // Compute objective function increment mat JP = J * Proj; mat FJdX = F + J * dX; vec dZ = LinearAlgebraUtils::LeastSquareSolve(JP, FJdX, lambda); dX = dX - Proj * dZ; // Update x x = x + dX; // dX.t().print("dX:"); }
30.798165
113
0.583855
alibabach
3b98ff0957863265a00e6cb4c3e060a38294ca65
13,936
cc
C++
lib/sanitizer_common/sanitizer_procmaps_mac.cc
hfinkel/compiler-rt-bgq
5c116694a5ed7267288d9ea5723b6a651321d271
[ "MIT" ]
null
null
null
lib/sanitizer_common/sanitizer_procmaps_mac.cc
hfinkel/compiler-rt-bgq
5c116694a5ed7267288d9ea5723b6a651321d271
[ "MIT" ]
null
null
null
lib/sanitizer_common/sanitizer_procmaps_mac.cc
hfinkel/compiler-rt-bgq
5c116694a5ed7267288d9ea5723b6a651321d271
[ "MIT" ]
null
null
null
//===-- sanitizer_procmaps_mac.cc -----------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Information about the process mappings (Mac-specific parts). //===----------------------------------------------------------------------===// #include "sanitizer_platform.h" #if SANITIZER_MAC #include "sanitizer_common.h" #include "sanitizer_placement_new.h" #include "sanitizer_procmaps.h" #include <mach-o/dyld.h> #include <mach-o/loader.h> #include <mach/mach.h> // These are not available in older macOS SDKs. #ifndef CPU_SUBTYPE_X86_64_H #define CPU_SUBTYPE_X86_64_H ((cpu_subtype_t)8) /* Haswell */ #endif #ifndef CPU_SUBTYPE_ARM_V7S #define CPU_SUBTYPE_ARM_V7S ((cpu_subtype_t)11) /* Swift */ #endif #ifndef CPU_SUBTYPE_ARM_V7K #define CPU_SUBTYPE_ARM_V7K ((cpu_subtype_t)12) #endif #ifndef CPU_TYPE_ARM64 #define CPU_TYPE_ARM64 (CPU_TYPE_ARM | CPU_ARCH_ABI64) #endif namespace __sanitizer { // Contains information used to iterate through sections. struct MemoryMappedSegmentData { char name[kMaxSegName]; uptr nsects; char *current_load_cmd_addr; u32 lc_type; uptr base_virt_addr; uptr addr_mask; }; template <typename Section> static void NextSectionLoad(LoadedModule *module, MemoryMappedSegmentData *data, bool isWritable) { const Section *sc = (const Section *)data->current_load_cmd_addr; data->current_load_cmd_addr += sizeof(Section); uptr sec_start = (sc->addr & data->addr_mask) + data->base_virt_addr; uptr sec_end = sec_start + sc->size; module->addAddressRange(sec_start, sec_end, /*executable=*/false, isWritable, sc->sectname); } void MemoryMappedSegment::AddAddressRanges(LoadedModule *module) { // Don't iterate over sections when the caller hasn't set up the // data pointer, when there are no sections, or when the segment // is executable. Avoid iterating over executable sections because // it will confuse libignore, and because the extra granularity // of information is not needed by any sanitizers. if (!data_ || !data_->nsects || IsExecutable()) { module->addAddressRange(start, end, IsExecutable(), IsWritable(), data_ ? data_->name : nullptr); return; } do { if (data_->lc_type == LC_SEGMENT) { NextSectionLoad<struct section>(module, data_, IsWritable()); #ifdef MH_MAGIC_64 } else if (data_->lc_type == LC_SEGMENT_64) { NextSectionLoad<struct section_64>(module, data_, IsWritable()); #endif } } while (--data_->nsects); } MemoryMappingLayout::MemoryMappingLayout(bool cache_enabled) { Reset(); } MemoryMappingLayout::~MemoryMappingLayout() { } // More information about Mach-O headers can be found in mach-o/loader.h // Each Mach-O image has a header (mach_header or mach_header_64) starting with // a magic number, and a list of linker load commands directly following the // header. // A load command is at least two 32-bit words: the command type and the // command size in bytes. We're interested only in segment load commands // (LC_SEGMENT and LC_SEGMENT_64), which tell that a part of the file is mapped // into the task's address space. // The |vmaddr|, |vmsize| and |fileoff| fields of segment_command or // segment_command_64 correspond to the memory address, memory size and the // file offset of the current memory segment. // Because these fields are taken from the images as is, one needs to add // _dyld_get_image_vmaddr_slide() to get the actual addresses at runtime. void MemoryMappingLayout::Reset() { // Count down from the top. // TODO(glider): as per man 3 dyld, iterating over the headers with // _dyld_image_count is thread-unsafe. We need to register callbacks for // adding and removing images which will invalidate the MemoryMappingLayout // state. data_.current_image = _dyld_image_count(); data_.current_load_cmd_count = -1; data_.current_load_cmd_addr = 0; data_.current_magic = 0; data_.current_filetype = 0; data_.current_arch = kModuleArchUnknown; internal_memset(data_.current_uuid, 0, kModuleUUIDSize); } // The dyld load address should be unchanged throughout process execution, // and it is expensive to compute once many libraries have been loaded, // so cache it here and do not reset. static mach_header *dyld_hdr = 0; static const char kDyldPath[] = "/usr/lib/dyld"; static const int kDyldImageIdx = -1; // static void MemoryMappingLayout::CacheMemoryMappings() { // No-op on Mac for now. } void MemoryMappingLayout::LoadFromCache() { // No-op on Mac for now. } // _dyld_get_image_header() and related APIs don't report dyld itself. // We work around this by manually recursing through the memory map // until we hit a Mach header matching dyld instead. These recurse // calls are expensive, but the first memory map generation occurs // early in the process, when dyld is one of the only images loaded, // so it will be hit after only a few iterations. static mach_header *get_dyld_image_header() { mach_port_name_t port; if (task_for_pid(mach_task_self(), internal_getpid(), &port) != KERN_SUCCESS) { return nullptr; } unsigned depth = 1; vm_size_t size = 0; vm_address_t address = 0; kern_return_t err = KERN_SUCCESS; mach_msg_type_number_t count = VM_REGION_SUBMAP_INFO_COUNT_64; while (true) { struct vm_region_submap_info_64 info; err = vm_region_recurse_64(port, &address, &size, &depth, (vm_region_info_t)&info, &count); if (err != KERN_SUCCESS) return nullptr; if (size >= sizeof(mach_header) && info.protection & kProtectionRead) { mach_header *hdr = (mach_header *)address; if ((hdr->magic == MH_MAGIC || hdr->magic == MH_MAGIC_64) && hdr->filetype == MH_DYLINKER) { return hdr; } } address += size; } } const mach_header *get_dyld_hdr() { if (!dyld_hdr) dyld_hdr = get_dyld_image_header(); return dyld_hdr; } // Next and NextSegmentLoad were inspired by base/sysinfo.cc in // Google Perftools, https://github.com/gperftools/gperftools. // NextSegmentLoad scans the current image for the next segment load command // and returns the start and end addresses and file offset of the corresponding // segment. // Note that the segment addresses are not necessarily sorted. template <u32 kLCSegment, typename SegmentCommand> static bool NextSegmentLoad(MemoryMappedSegment *segment, MemoryMappedSegmentData *seg_data, MemoryMappingLayoutData &layout_data) { const char *lc = layout_data.current_load_cmd_addr; layout_data.current_load_cmd_addr += ((const load_command *)lc)->cmdsize; if (((const load_command *)lc)->cmd == kLCSegment) { const SegmentCommand* sc = (const SegmentCommand *)lc; uptr base_virt_addr, addr_mask; if (layout_data.current_image == kDyldImageIdx) { base_virt_addr = (uptr)get_dyld_hdr(); // vmaddr is masked with 0xfffff because on macOS versions < 10.12, // it contains an absolute address rather than an offset for dyld. // To make matters even more complicated, this absolute address // isn't actually the absolute segment address, but the offset portion // of the address is accurate when combined with the dyld base address, // and the mask will give just this offset. addr_mask = 0xfffff; } else { base_virt_addr = (uptr)_dyld_get_image_vmaddr_slide(layout_data.current_image); addr_mask = ~0; } segment->start = (sc->vmaddr & addr_mask) + base_virt_addr; segment->end = segment->start + sc->vmsize; // Most callers don't need section information, so only fill this struct // when required. if (seg_data) { seg_data->nsects = sc->nsects; seg_data->current_load_cmd_addr = (char *)lc + sizeof(SegmentCommand); seg_data->lc_type = kLCSegment; seg_data->base_virt_addr = base_virt_addr; seg_data->addr_mask = addr_mask; internal_strncpy(seg_data->name, sc->segname, ARRAY_SIZE(seg_data->name)); } // Return the initial protection. segment->protection = sc->initprot; segment->offset = (layout_data.current_filetype == /*MH_EXECUTE*/ 0x2) ? sc->vmaddr : sc->fileoff; if (segment->filename) { const char *src = (layout_data.current_image == kDyldImageIdx) ? kDyldPath : _dyld_get_image_name(layout_data.current_image); internal_strncpy(segment->filename, src, segment->filename_size); } segment->arch = layout_data.current_arch; internal_memcpy(segment->uuid, layout_data.current_uuid, kModuleUUIDSize); return true; } return false; } ModuleArch ModuleArchFromCpuType(cpu_type_t cputype, cpu_subtype_t cpusubtype) { cpusubtype = cpusubtype & ~CPU_SUBTYPE_MASK; switch (cputype) { case CPU_TYPE_I386: return kModuleArchI386; case CPU_TYPE_X86_64: if (cpusubtype == CPU_SUBTYPE_X86_64_ALL) return kModuleArchX86_64; if (cpusubtype == CPU_SUBTYPE_X86_64_H) return kModuleArchX86_64H; CHECK(0 && "Invalid subtype of x86_64"); return kModuleArchUnknown; case CPU_TYPE_ARM: if (cpusubtype == CPU_SUBTYPE_ARM_V6) return kModuleArchARMV6; if (cpusubtype == CPU_SUBTYPE_ARM_V7) return kModuleArchARMV7; if (cpusubtype == CPU_SUBTYPE_ARM_V7S) return kModuleArchARMV7S; if (cpusubtype == CPU_SUBTYPE_ARM_V7K) return kModuleArchARMV7K; CHECK(0 && "Invalid subtype of ARM"); return kModuleArchUnknown; case CPU_TYPE_ARM64: return kModuleArchARM64; default: CHECK(0 && "Invalid CPU type"); return kModuleArchUnknown; } } static const load_command *NextCommand(const load_command *lc) { return (const load_command *)((char *)lc + lc->cmdsize); } static void FindUUID(const load_command *first_lc, u8 *uuid_output) { for (const load_command *lc = first_lc; lc->cmd != 0; lc = NextCommand(lc)) { if (lc->cmd != LC_UUID) continue; const uuid_command *uuid_lc = (const uuid_command *)lc; const uint8_t *uuid = &uuid_lc->uuid[0]; internal_memcpy(uuid_output, uuid, kModuleUUIDSize); return; } } static bool IsModuleInstrumented(const load_command *first_lc) { for (const load_command *lc = first_lc; lc->cmd != 0; lc = NextCommand(lc)) { if (lc->cmd != LC_LOAD_DYLIB) continue; const dylib_command *dylib_lc = (const dylib_command *)lc; uint32_t dylib_name_offset = dylib_lc->dylib.name.offset; const char *dylib_name = ((const char *)dylib_lc) + dylib_name_offset; dylib_name = StripModuleName(dylib_name); if (dylib_name != 0 && (internal_strstr(dylib_name, "libclang_rt."))) { return true; } } return false; } bool MemoryMappingLayout::Next(MemoryMappedSegment *segment) { for (; data_.current_image >= kDyldImageIdx; data_.current_image--) { const mach_header *hdr = (data_.current_image == kDyldImageIdx) ? get_dyld_hdr() : _dyld_get_image_header(data_.current_image); if (!hdr) continue; if (data_.current_load_cmd_count < 0) { // Set up for this image; data_.current_load_cmd_count = hdr->ncmds; data_.current_magic = hdr->magic; data_.current_filetype = hdr->filetype; data_.current_arch = ModuleArchFromCpuType(hdr->cputype, hdr->cpusubtype); switch (data_.current_magic) { #ifdef MH_MAGIC_64 case MH_MAGIC_64: { data_.current_load_cmd_addr = (char *)hdr + sizeof(mach_header_64); break; } #endif case MH_MAGIC: { data_.current_load_cmd_addr = (char *)hdr + sizeof(mach_header); break; } default: { continue; } } FindUUID((const load_command *)data_.current_load_cmd_addr, data_.current_uuid); data_.current_instrumented = IsModuleInstrumented( (const load_command *)data_.current_load_cmd_addr); } for (; data_.current_load_cmd_count >= 0; data_.current_load_cmd_count--) { switch (data_.current_magic) { // data_.current_magic may be only one of MH_MAGIC, MH_MAGIC_64. #ifdef MH_MAGIC_64 case MH_MAGIC_64: { if (NextSegmentLoad<LC_SEGMENT_64, struct segment_command_64>( segment, segment->data_, data_)) return true; break; } #endif case MH_MAGIC: { if (NextSegmentLoad<LC_SEGMENT, struct segment_command>( segment, segment->data_, data_)) return true; break; } } } // If we get here, no more load_cmd's in this image talk about // segments. Go on to the next image. } return false; } void MemoryMappingLayout::DumpListOfModules( InternalMmapVectorNoCtor<LoadedModule> *modules) { Reset(); InternalScopedString module_name(kMaxPathLength); MemoryMappedSegment segment(module_name.data(), kMaxPathLength); MemoryMappedSegmentData data; segment.data_ = &data; while (Next(&segment)) { if (segment.filename[0] == '\0') continue; LoadedModule *cur_module = nullptr; if (!modules->empty() && 0 == internal_strcmp(segment.filename, modules->back().full_name())) { cur_module = &modules->back(); } else { modules->push_back(LoadedModule()); cur_module = &modules->back(); cur_module->set(segment.filename, segment.start, segment.arch, segment.uuid, data_.current_instrumented); } segment.AddAddressRanges(cur_module); } } } // namespace __sanitizer #endif // SANITIZER_MAC
36.577428
80
0.67975
hfinkel
3b9c73b53ebe56aca4b24d1c603bae36c5ce69af
6,495
cpp
C++
src/Data.cpp
IgnacioCofre/proyecto_tesis
e26b3fa1a7aba443fda64abfc2dc0208241088d9
[ "MIT" ]
1
2022-03-04T19:10:22.000Z
2022-03-04T19:10:22.000Z
src/Data.cpp
IgnacioCofre/proyecto_tesis
e26b3fa1a7aba443fda64abfc2dc0208241088d9
[ "MIT" ]
null
null
null
src/Data.cpp
IgnacioCofre/proyecto_tesis
e26b3fa1a7aba443fda64abfc2dc0208241088d9
[ "MIT" ]
null
null
null
#include "../includes/data.h" void Data::read_input_file(const char * input_path) { FILE * pFile; pFile = fopen (input_path,"r"); //lectura del archivo if(!pFile) { std::cerr << "Problem while reading instance" << std::endl; exit(EXIT_FAILURE); } //numero de articulos if(fscanf(pFile, "%d", &number_articles) != 1) { std::cerr << "Problem while reading number of articles" << std::endl; exit(EXIT_FAILURE); } //matriz de similaridad for (int _ = 0; _ < number_articles; _++) { std::vector <int> new_row(number_articles); for(int i = 0; i < number_articles; i++) { if(fscanf(pFile, "%d", &new_row[i]) != 1){ std::cerr << "Problem while reading similarity matrix" << std::endl; exit(EXIT_FAILURE); } } similarity_matrix.push_back(new_row); } //numero de tipo de sesiones if(fscanf(pFile, "%d", &number_type_sessions) != 1) { std::cerr << "Problem while reading session number" << std::endl; exit(EXIT_FAILURE); } //informacio del tipo de sesiones for(int i = 0; i<number_type_sessions; i++) { int input_per_session = 3; std::vector<int> new_session_data(input_per_session); if(fscanf(pFile, "%d %d %d", &new_session_data[0],&new_session_data[1],&new_session_data[2])!= input_per_session) { std::cerr << "Problem while reading session tipe data" << std::endl; exit(EXIT_FAILURE); } } //numero de dias if(fscanf(pFile, "%d", &number_days) != 1) { std::cerr << "Problem while reading number days" << std::endl; exit(EXIT_FAILURE); } for(int day = 0; day<number_days; day++) { int number_blocks; int number_sessions; if(fscanf(pFile, "%d %d", &number_blocks, &number_sessions) != 2) { std::cerr << "Problem while reading session tipe data" << std::endl; exit(EXIT_FAILURE); } std::vector<int> new_data_log = {number_blocks,number_sessions}; data_days.push_back(new_data_log); std::vector<std::vector<int>> new_data_day(number_blocks); for(int session = 0; session < number_sessions; session++) { int block; int max_number_articles; if(fscanf(pFile, "%d %d", &block, &max_number_articles) != 2) { std::cerr << "Problem while reading data block" << std::endl; exit(EXIT_FAILURE); } new_data_day[block-1].push_back(max_number_articles); //std::cout<<"si pasa esto 2"<<std::endl; } max_assign_per_session.push_back(new_data_day); } //numero de articulos y numero de topicos int aux; if(fscanf(pFile, "%d %d", &aux , &number_topics) != 2) { std::cerr << "Problem while reading number topics" << std::endl; exit(EXIT_FAILURE); } //topicos por articulo for(int i = 0; i < number_articles; i++) { int number_article_topics; if(fscanf(pFile, "%d",&number_article_topics) != 1) { std::cerr << "Problem while reading number of topics per article" << std::endl; exit(EXIT_FAILURE); } number_topics_articles.push_back(number_article_topics); std::vector<int> topics_article(number_article_topics); for(int j = 0; j<number_article_topics; j++) { if(fscanf(pFile, "%d",&topics_article[j]) != 1){ std::cerr << "Problem while reading topics per article" << std::endl; exit(EXIT_FAILURE); } } articles_topics.push_back(topics_article); } //numero de articulos y numero de autores int aux2; if(fscanf(pFile, "%d %d", &aux2 , &number_authors) != 2) { std::cerr << "Problem while reading number authors" << std::endl; exit(EXIT_FAILURE); } //autores por articulo for(int i = 0; i < number_articles; i++) { int new_number_article_authors; if(fscanf(pFile, "%d",&new_number_article_authors) != 1) { std::cerr << "Problem while reading number of authors per article" << std::endl; exit(EXIT_FAILURE); } number_articles_authors.push_back(new_number_article_authors); std::vector<int> new_articles_authors(new_number_article_authors); for(int j = 0; j<new_number_article_authors; j++) { if(fscanf(pFile, "%d",&new_articles_authors[j]) != 1){ std::cerr << "Problem while reading author per article" << std::endl; exit(EXIT_FAILURE); } } articles_authors.push_back(new_articles_authors); } fclose(pFile); } int Data::get_similarity(int id_article_1, int id_article_2) { if((id_article_1 <number_articles) & (id_article_2<number_articles)) { return similarity_matrix[id_article_1][id_article_2]; } std::cerr << "Problem while reading number of article" << std::endl; exit(EXIT_FAILURE); } void Data::show_data() { std::cout << number_articles << std::endl; for(int i = 0; i<number_articles; i++) { for(int j = 0; j<number_articles; j++) { std::cout << similarity_matrix[i][j] << " "; } std::cout << std::endl; } std::cout << number_type_sessions << std::endl; std::cout << number_days << std::endl; std::cout << number_topics << std::endl; std::cout << number_authors << std::endl; std::cout<< "max_assign_per_session"<<std::endl; int number_days = max_assign_per_session.size(); for(int day=0; day<number_days; day++) { int number_blocks = max_assign_per_session[day].size(); for(int block=0; block<number_blocks; block++) { int number_sessions = max_assign_per_session[day][block].size(); for(int session=0; session<number_sessions; session++) { int max_session = max_assign_per_session[day][block][session]; std::cout<<day<<","<<block<<","<<session<<","<<max_session<<std::endl; } } } } int Data::get_number_days() { return number_days; } int Data::get_number_articles() { return number_articles; }
29.522727
121
0.570285
IgnacioCofre
3b9cfda324df3847fa21884757a5432c49bcc3b3
1,459
hpp
C++
src/lib/storage/chunk.hpp
lawben/DYOD_WS1718_Sprint1
3b70ac6603fe108cfe76cc81fed763c5d3c7cd84
[ "MIT" ]
null
null
null
src/lib/storage/chunk.hpp
lawben/DYOD_WS1718_Sprint1
3b70ac6603fe108cfe76cc81fed763c5d3c7cd84
[ "MIT" ]
null
null
null
src/lib/storage/chunk.hpp
lawben/DYOD_WS1718_Sprint1
3b70ac6603fe108cfe76cc81fed763c5d3c7cd84
[ "MIT" ]
null
null
null
#pragma once // the linter wants this to be above everything else #include <shared_mutex> #include <atomic> #include <memory> #include <string> #include <vector> #include "all_type_variant.hpp" #include "types.hpp" namespace opossum { class BaseIndex; class BaseColumn; // A chunk is a horizontal partition of a table. // It stores the data column by column. // // Find more information about this in our wiki: https://github.com/hyrise/zweirise/wiki/chunk-concept class Chunk : private Noncopyable { public: Chunk() = default; // we need to explicitly set the move constructor to default when // we overwrite the copy constructor Chunk(Chunk&&) = default; Chunk& operator=(Chunk&&) = default; // adds a column to the "right" of the chunk void add_column(std::shared_ptr<BaseColumn> column); // returns the number of columns (cannot exceed ColumnID (uint16_t)) uint16_t col_count() const; // returns the number of rows (cannot exceed ChunkOffset (uint32_t)) uint32_t size() const; // adds a new row, given as a list of values, to the chunk // note this is slow and not thread-safe and should be used for testing purposes only void append(const std::vector<AllTypeVariant>& values); // Returns the column at a given position std::shared_ptr<BaseColumn> get_column(ColumnID column_id) const; protected: // Implementation goes here std::vector<std::shared_ptr<BaseColumn>> _columns; }; } // namespace opossum
27.018519
102
0.732008
lawben
3b9f2a094c4999dc0e3b8e9841087037c00e2094
530
hpp
C++
include/mtac/Pass.hpp
wichtounet/eddic
66398a493a499eab5d1f465f93f9f099a2140d59
[ "MIT" ]
24
2015-10-08T23:08:50.000Z
2021-09-18T21:15:01.000Z
include/mtac/Pass.hpp
wichtounet/eddic
66398a493a499eab5d1f465f93f9f099a2140d59
[ "MIT" ]
1
2016-02-29T20:20:45.000Z
2016-03-03T07:16:53.000Z
include/mtac/Pass.hpp
wichtounet/eddic
66398a493a499eab5d1f465f93f9f099a2140d59
[ "MIT" ]
5
2015-08-09T09:53:52.000Z
2021-09-18T21:15:05.000Z
//======================================================================= // Copyright Baptiste Wicht 2011-2016. // Distributed under the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #ifndef MTAC_PASS_H #define MTAC_PASS_H namespace eddic { namespace mtac { //Use for two pass optimization enum class Pass : unsigned int { DATA_MINING, OPTIMIZE }; } //end of mtac } //end of eddic #endif
20.384615
73
0.516981
wichtounet
3ba0e30c39e4243ec34c08e80036d27eee070040
10,174
cpp
C++
src/scripts/scripts/eastern_kingdoms/zulgurub/boss_jindo.cpp
Subv/diamondcore
e11891587736b6308e554f71cb56e8df1a1812ad
[ "OpenSSL" ]
1
2018-01-17T08:11:17.000Z
2018-01-17T08:11:17.000Z
src/scripts/scripts/eastern_kingdoms/zulgurub/boss_jindo.cpp
Subv/diamondcore
e11891587736b6308e554f71cb56e8df1a1812ad
[ "OpenSSL" ]
null
null
null
src/scripts/scripts/eastern_kingdoms/zulgurub/boss_jindo.cpp
Subv/diamondcore
e11891587736b6308e554f71cb56e8df1a1812ad
[ "OpenSSL" ]
null
null
null
/* Copyright (C) 2006 - 2010 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/> * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* ScriptData SDName: Boss_Jin'do the Hexxer SD%Complete: 85 SDComment: Mind Control not working because of core bug. Shades visible for all. SDCategory: Zul'Gurub EndScriptData */ #include "precompiled.h" #include "zulgurub.h" #define SAY_AGGRO -1309014 #define SPELL_BRAINWASHTOTEM 24262 #define SPELL_POWERFULLHEALINGWARD 24309 //We will not use this spell. We will summon a totem by script cause the spell totems will not cast. #define SPELL_HEX 24053 #define SPELL_DELUSIONSOFJINDO 24306 #define SPELL_SHADEOFJINDO 24308 //We will not use this spell. We will summon a shade by script. //Healing Ward Spell #define SPELL_HEAL 38588 //Totems are not working right. Right heal spell ID is 24311 but this spell is not casting... //Shade of Jindo Spell #define SPELL_SHADOWSHOCK 19460 #define SPELL_INVISIBLE 24699 struct boss_jindoAI : public ScriptedAI { boss_jindoAI(Creature* pCreature) : ScriptedAI(pCreature) { m_pInstance = (ScriptedInstance*)pCreature->GetInstanceData(); Reset(); } ScriptedInstance* m_pInstance; uint32 BrainWashTotem_Timer; uint32 HealingWard_Timer; uint32 Hex_Timer; uint32 Delusions_Timer; uint32 Teleport_Timer; void Reset() { BrainWashTotem_Timer = 20000; HealingWard_Timer = 16000; Hex_Timer = 8000; Delusions_Timer = 10000; Teleport_Timer = 5000; } void Aggro(Unit *who) { DoScriptText(SAY_AGGRO, m_creature); } void UpdateAI(const uint32 diff) { if (!m_creature->SelectHostileTarget() || !m_creature->getVictim()) return; //BrainWashTotem_Timer if (BrainWashTotem_Timer < diff) { DoCastSpellIfCan(m_creature, SPELL_BRAINWASHTOTEM); BrainWashTotem_Timer = urand(18000, 26000); }else BrainWashTotem_Timer -= diff; //HealingWard_Timer if (HealingWard_Timer < diff) { //DoCastSpellIfCan(m_creature, SPELL_POWERFULLHEALINGWARD); m_creature->SummonCreature(14987, m_creature->GetPositionX()+3, m_creature->GetPositionY()-2, m_creature->GetPositionZ(), 0, TEMPSUMMON_TIMED_OR_DEAD_DESPAWN,30000); HealingWard_Timer = urand(14000, 20000); }else HealingWard_Timer -= diff; //Hex_Timer if (Hex_Timer < diff) { DoCastSpellIfCan(m_creature->getVictim(), SPELL_HEX); if (m_creature->getThreatManager().getThreat(m_creature->getVictim())) m_creature->getThreatManager().modifyThreatPercent(m_creature->getVictim(),-80); Hex_Timer = urand(12000, 20000); }else Hex_Timer -= diff; //Casting the delusion curse with a shade. So shade will attack the same target with the curse. if (Delusions_Timer < diff) { if (Unit* target = SelectUnit(SELECT_TARGET_RANDOM,0)) { DoCastSpellIfCan(target, SPELL_DELUSIONSOFJINDO); Creature *Shade = m_creature->SummonCreature(14986, target->GetPositionX(), target->GetPositionY(), target->GetPositionZ(), 0, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 15000); if (Shade) Shade->AI()->AttackStart(target); } Delusions_Timer = urand(4000, 12000); }else Delusions_Timer -= diff; //Teleporting a random gamer and spawning 9 skeletons that will attack this gamer if (Teleport_Timer < diff) { Unit* target = NULL; target = SelectUnit(SELECT_TARGET_RANDOM,0); if (target && target->GetTypeId() == TYPEID_PLAYER) { DoTeleportPlayer(target, -11583.7783f, -1249.4278f, 77.5471f, 4.745f); if (m_creature->getThreatManager().getThreat(m_creature->getVictim())) m_creature->getThreatManager().modifyThreatPercent(target,-100); Creature *Skeletons; Skeletons = m_creature->SummonCreature(14826, target->GetPositionX()+2, target->GetPositionY(), target->GetPositionZ(), 0, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 15000); if (Skeletons) Skeletons->AI()->AttackStart(target); Skeletons = m_creature->SummonCreature(14826, target->GetPositionX()-2, target->GetPositionY(), target->GetPositionZ(), 0, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 15000); if (Skeletons) Skeletons->AI()->AttackStart(target); Skeletons = m_creature->SummonCreature(14826, target->GetPositionX()+4, target->GetPositionY(), target->GetPositionZ(), 0, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 15000); if (Skeletons) Skeletons->AI()->AttackStart(target); Skeletons = m_creature->SummonCreature(14826, target->GetPositionX()-4, target->GetPositionY(), target->GetPositionZ(), 0, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 15000); if (Skeletons) Skeletons->AI()->AttackStart(target); Skeletons = m_creature->SummonCreature(14826, target->GetPositionX(), target->GetPositionY()+2, target->GetPositionZ(), 0, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 15000); if (Skeletons) Skeletons->AI()->AttackStart(target); Skeletons = m_creature->SummonCreature(14826, target->GetPositionX(), target->GetPositionY()-2, target->GetPositionZ(), 0, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 15000); if (Skeletons) Skeletons->AI()->AttackStart(target); Skeletons = m_creature->SummonCreature(14826, target->GetPositionX(), target->GetPositionY()+4, target->GetPositionZ(), 0, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 15000); if (Skeletons) Skeletons->AI()->AttackStart(target); Skeletons = m_creature->SummonCreature(14826, target->GetPositionX(), target->GetPositionY()-4, target->GetPositionZ(), 0, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 15000); if (Skeletons) Skeletons->AI()->AttackStart(target); Skeletons = m_creature->SummonCreature(14826, target->GetPositionX()+3, target->GetPositionY(), target->GetPositionZ(), 0, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 15000); if (Skeletons) Skeletons->AI()->AttackStart(target); } Teleport_Timer = urand(15000, 23000); }else Teleport_Timer -= diff; DoMeleeAttackIfReady(); } }; //Healing Ward struct mob_healing_wardAI : public ScriptedAI { mob_healing_wardAI(Creature* pCreature) : ScriptedAI(pCreature) { m_pInstance = (ScriptedInstance*)pCreature->GetInstanceData(); Reset(); } ScriptedInstance* m_pInstance; uint32 Heal_Timer; void Reset() { Heal_Timer = 2000; } void UpdateAI (const uint32 diff) { //Heal_Timer if (Heal_Timer < diff) { if (m_pInstance) { if (Unit *pJindo = m_pInstance->instance->GetCreature(m_pInstance->GetData64(DATA_JINDO))) { if (pJindo->isAlive()) DoCastSpellIfCan(pJindo, SPELL_HEAL); } } Heal_Timer = 3000; }else Heal_Timer -= diff; if (!m_creature->SelectHostileTarget() || !m_creature->getVictim()) return; DoMeleeAttackIfReady(); } }; //Shade of Jindo struct mob_shade_of_jindoAI : public ScriptedAI { mob_shade_of_jindoAI(Creature* pCreature) : ScriptedAI(pCreature) { m_pInstance = (ScriptedInstance*)pCreature->GetInstanceData(); Reset(); } ScriptedInstance* m_pInstance; uint32 ShadowShock_Timer; void Reset() { ShadowShock_Timer = 1000; m_creature->CastSpell(m_creature, SPELL_INVISIBLE,true); } void UpdateAI (const uint32 diff) { if (!m_creature->SelectHostileTarget() || !m_creature->getVictim()) return; //ShadowShock_Timer if (ShadowShock_Timer < diff) { DoCastSpellIfCan(m_creature->getVictim(), SPELL_SHADOWSHOCK); ShadowShock_Timer = 2000; }else ShadowShock_Timer -= diff; DoMeleeAttackIfReady(); } }; CreatureAI* GetAI_boss_jindo(Creature* pCreature) { return new boss_jindoAI(pCreature); } CreatureAI* GetAI_mob_healing_ward(Creature* pCreature) { return new mob_healing_wardAI(pCreature); } CreatureAI* GetAI_mob_shade_of_jindo(Creature* pCreature) { return new mob_shade_of_jindoAI(pCreature); } void AddSC_boss_jindo() { Script *newscript; newscript = new Script; newscript->Name = "boss_jindo"; newscript->GetAI = &GetAI_boss_jindo; newscript->RegisterSelf(); newscript = new Script; newscript->Name = "mob_healing_ward"; newscript->GetAI = &GetAI_mob_healing_ward; newscript->RegisterSelf(); newscript = new Script; newscript->Name = "mob_shade_of_jindo"; newscript->GetAI = &GetAI_mob_shade_of_jindo; newscript->RegisterSelf(); }
36.729242
190
0.637311
Subv
3ba56f4f1dddd083eaae7359df3c4759ba0e0d29
4,111
cpp
C++
src/org/apache/poi/ss/formula/UserDefinedFunction.cpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
src/org/apache/poi/ss/formula/UserDefinedFunction.cpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
src/org/apache/poi/ss/formula/UserDefinedFunction.cpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
// Generated from /POI/java/org/apache/poi/ss/formula/UserDefinedFunction.java #include <org/apache/poi/ss/formula/UserDefinedFunction.hpp> #include <java/lang/ArrayStoreException.hpp> #include <java/lang/Class.hpp> #include <java/lang/ClassCastException.hpp> #include <java/lang/NullPointerException.hpp> #include <java/lang/RuntimeException.hpp> #include <java/lang/String.hpp> #include <java/lang/StringBuilder.hpp> #include <java/lang/System.hpp> #include <org/apache/poi/ss/formula/OperationEvaluationContext.hpp> #include <org/apache/poi/ss/formula/eval/FunctionNameEval.hpp> #include <org/apache/poi/ss/formula/eval/NotImplementedFunctionException.hpp> #include <org/apache/poi/ss/formula/eval/ValueEval.hpp> #include <org/apache/poi/ss/formula/functions/FreeRefFunction.hpp> #include <ObjectArray.hpp> #include <SubArray.hpp> template<typename ComponentType, typename... Bases> struct SubArray; namespace poi { namespace ss { namespace formula { namespace eval { typedef ::SubArray< ::poi::ss::formula::eval::ValueEval, ::java::lang::ObjectArray > ValueEvalArray; } // eval } // formula } // ss } // poi template<typename T, typename U> static T java_cast(U* u) { if(!u) return static_cast<T>(nullptr); auto t = dynamic_cast<T>(u); if(!t) throw new ::java::lang::ClassCastException(); return t; } template<typename T> static T* npc(T* t) { if(!t) throw new ::java::lang::NullPointerException(); return t; } poi::ss::formula::UserDefinedFunction::UserDefinedFunction(const ::default_init_tag&) : super(*static_cast< ::default_init_tag* >(0)) { clinit(); } poi::ss::formula::UserDefinedFunction::UserDefinedFunction() : UserDefinedFunction(*static_cast< ::default_init_tag* >(0)) { ctor(); } poi::ss::formula::functions::FreeRefFunction*& poi::ss::formula::UserDefinedFunction::instance() { clinit(); return instance_; } poi::ss::formula::functions::FreeRefFunction* poi::ss::formula::UserDefinedFunction::instance_; void poi::ss::formula::UserDefinedFunction::ctor() { super::ctor(); } poi::ss::formula::eval::ValueEval* poi::ss::formula::UserDefinedFunction::evaluate(::poi::ss::formula::eval::ValueEvalArray* args, OperationEvaluationContext* ec) { auto nIncomingArgs = npc(args)->length; if(nIncomingArgs < 1) { throw new ::java::lang::RuntimeException(u"function name argument missing"_j); } auto nameArg = (*args)[int32_t(0)]; ::java::lang::String* functionName; if(dynamic_cast< ::poi::ss::formula::eval::FunctionNameEval* >(nameArg) != nullptr) { functionName = npc((java_cast< ::poi::ss::formula::eval::FunctionNameEval* >(nameArg)))->getFunctionName(); } else { throw new ::java::lang::RuntimeException(::java::lang::StringBuilder().append(u"First argument should be a NameEval, but got ("_j)->append(npc(npc(nameArg)->getClass())->getName()) ->append(u")"_j)->toString()); } auto targetFunc = npc(ec)->findUserDefinedFunction(functionName); if(targetFunc == nullptr) { throw new ::poi::ss::formula::eval::NotImplementedFunctionException(functionName); } auto nOutGoingArgs = nIncomingArgs - int32_t(1); auto outGoingArgs = new ::poi::ss::formula::eval::ValueEvalArray(nOutGoingArgs); ::java::lang::System::arraycopy(args, 1, outGoingArgs, 0, nOutGoingArgs); return npc(targetFunc)->evaluate(outGoingArgs, ec); } extern java::lang::Class *class_(const char16_t *c, int n); java::lang::Class* poi::ss::formula::UserDefinedFunction::class_() { static ::java::lang::Class* c = ::class_(u"org.apache.poi.ss.formula.UserDefinedFunction", 45); return c; } void poi::ss::formula::UserDefinedFunction::clinit() { super::clinit(); static bool in_cl_init = false; struct clinit_ { clinit_() { in_cl_init = true; instance_ = new UserDefinedFunction(); } }; if(!in_cl_init) { static clinit_ clinit_instance; } } java::lang::Class* poi::ss::formula::UserDefinedFunction::getClass0() { return class_(); }
32.117188
188
0.689856
pebble2015
3ba5a1fe2d80001dd4ac49930452d6a544ebf7b4
1,453
cpp
C++
trunk/src/bls/BlsServerSelector.cpp
almondyoung/Bull-Live-Server
b2ad5ad0968318c2821f63adedbc83286a6d7c22
[ "BSD-2-Clause" ]
141
2015-01-07T15:54:55.000Z
2021-09-21T13:56:30.000Z
trunk/src/bls/BlsServerSelector.cpp
mol310/Bull-Live-Server
b2ad5ad0968318c2821f63adedbc83286a6d7c22
[ "BSD-2-Clause" ]
5
2015-03-02T09:22:26.000Z
2018-10-18T08:13:50.000Z
trunk/src/bls/BlsServerSelector.cpp
mol310/Bull-Live-Server
b2ad5ad0968318c2821f63adedbc83286a6d7c22
[ "BSD-2-Clause" ]
84
2015-01-15T07:04:25.000Z
2020-08-09T16:14:58.000Z
#include "BlsServerSelector.hpp" #include <MStringList> #include "BlsConf.hpp" BlsServerSelector::BlsServerSelector() { m_conhash = conhash_init(NULL); } BlsServerSelector::~BlsServerSelector() { conhash_fini(m_conhash); } BlsServerSelector *BlsServerSelector::instance() { static BlsServerSelector *ss = NULL; if (!ss) { ss = new BlsServerSelector; ss->init(); } return ss; } void BlsServerSelector::addServer(const MString &host, muint16 port) { node_s *node = new node_s; // ip:port MString info = host; info.append(":"); info.append(MString::number(port)); conhash_set_node(node, info.c_str(), 4800); conhash_add_node(m_conhash, node); m_nodes.push_back(node); } void BlsServerSelector::removeServer(const MString &host, muint16 port) { } muint16 BlsServerSelector::lookUp(const MString &info) { const node_s *node = conhash_lookup(m_conhash, info.c_str()); if(node) { MStringList ip_port = MString(node->iden).split(":"); return (muint16)ip_port.at(1).toInt(); } return -1; } void BlsServerSelector::init() { vector<BlsHostInfo> back_source_infos = BlsConf::instance()->getBackSourceInfo(); for (unsigned int i = 0; i < back_source_infos.size(); ++i) { BlsHostInfo &info = back_source_infos.at(i); addServer(info.addr, info.port); } }
21.686567
86
0.636614
almondyoung
3ba6cf7e75f18e1276020255d3225ca2c9687582
828
cpp
C++
AOJ/ALDS1/4/d/main.cpp
eduidl/procon
a95d33074771281ff135bf199ded8b57788c151d
[ "MIT" ]
null
null
null
AOJ/ALDS1/4/d/main.cpp
eduidl/procon
a95d33074771281ff135bf199ded8b57788c151d
[ "MIT" ]
null
null
null
AOJ/ALDS1/4/d/main.cpp
eduidl/procon
a95d33074771281ff135bf199ded8b57788c151d
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define FOR(i, a, b) for (int i = (a), i##_max = (b); i < i##_max; ++i) #define REP(i, n) for (int i = 0, i##_len = (n); i < i##_len; ++i) #define ALL(obj) (obj).begin(), (obj).end() using namespace std; using i64 = int64_t; constexpr int INF = 1 << 30; constexpr int MOD = 1000000007; int check(vector<int> &W, i64 P, int n, int k) { int i = 0; REP(j, k) { i64 s = 0; while (s + W[i] <= P) { s += W[i]; ++i; if (i == n) return n; } } return i; } int main() { int n, k; cin >> n >> k; vector<int> W(n); REP(i, n) cin >> W[i]; i64 left = 0, mid, right = n * 10000; while (right - left > 1) { mid = (left + right) / 2; int v = check(W, mid, n, k); if (v >= n) right = mid; else left = mid; } cout << right << endl; }
19.255814
71
0.479469
eduidl
3ba96ffacd1797c174228c069609e349b61f6d0f
366
cpp
C++
CodeForces.com/educational_rounds/er3/B.cpp
mstrechen/cp
ffac439840a71f70580a0ef197e47479e167a0eb
[ "MIT" ]
null
null
null
CodeForces.com/educational_rounds/er3/B.cpp
mstrechen/cp
ffac439840a71f70580a0ef197e47479e167a0eb
[ "MIT" ]
null
null
null
CodeForces.com/educational_rounds/er3/B.cpp
mstrechen/cp
ffac439840a71f70580a0ef197e47479e167a0eb
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> using namespace std; vector<int> genres(10); int main(){ ios::sync_with_stdio(false); int n,m,tmp; int answer=0; cin >> n >> m; for(int i=0;i<n; i++) { cin >> tmp; genres[tmp-1]++; } for(int i =0; i<m; i++) for(int j=i+1; j<m; j++) answer+=genres[i]*genres[j]; cout << answer; return 0; }
17.428571
32
0.551913
mstrechen
3baab6069e5228d4dbe314cb9c6a8a3ba7534765
5,705
cc
C++
runtime/src/iree/vm/bytecode_dispatch_async_test.cc
nithinsubbiah/iree
719856b9f45a5e3685a37bd87db62081a53cb4f9
[ "Apache-2.0" ]
null
null
null
runtime/src/iree/vm/bytecode_dispatch_async_test.cc
nithinsubbiah/iree
719856b9f45a5e3685a37bd87db62081a53cb4f9
[ "Apache-2.0" ]
null
null
null
runtime/src/iree/vm/bytecode_dispatch_async_test.cc
nithinsubbiah/iree
719856b9f45a5e3685a37bd87db62081a53cb4f9
[ "Apache-2.0" ]
null
null
null
// Copyright 2022 The IREE Authors // // Licensed under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // Tests covering the dispatch logic for individual ops. // // iree/vm/test/async_ops.mlir contains the functions used here for testing. We // avoid defining the IR inline here so that we can run this test on platforms // that we can't run the full MLIR compiler stack on. #include "iree/base/logging.h" #include "iree/base/status_cc.h" #include "iree/testing/gtest.h" #include "iree/testing/status_matchers.h" #include "iree/vm/api.h" #include "iree/vm/bytecode_module.h" // Compiled module embedded here to avoid file IO: #include "iree/vm/test/async_bytecode_modules.h" namespace iree { namespace { using iree::testing::status::StatusIs; class VMBytecodeDispatchAsyncTest : public ::testing::Test { protected: static void SetUpTestSuite() { IREE_CHECK_OK(iree_vm_register_builtin_types()); } void SetUp() override { IREE_TRACE_SCOPE(); const iree_file_toc_t* file = async_bytecode_modules_c_create(); IREE_CHECK_OK(iree_vm_instance_create(iree_allocator_system(), &instance_)); IREE_CHECK_OK(iree_vm_bytecode_module_create( iree_const_byte_span_t{reinterpret_cast<const uint8_t*>(file->data), file->size}, iree_allocator_null(), iree_allocator_system(), &bytecode_module_)); std::vector<iree_vm_module_t*> modules = {bytecode_module_}; IREE_CHECK_OK(iree_vm_context_create_with_modules( instance_, IREE_VM_CONTEXT_FLAG_NONE, modules.size(), modules.data(), iree_allocator_system(), &context_)); } void TearDown() override { IREE_TRACE_SCOPE(); iree_vm_module_release(bytecode_module_); iree_vm_context_release(context_); iree_vm_instance_release(instance_); } iree_vm_instance_t* instance_ = nullptr; iree_vm_context_t* context_ = nullptr; iree_vm_module_t* bytecode_module_ = nullptr; }; // Tests a simple straight-line yield sequence that requires 3 resumes. // See iree/vm/test/async_ops.mlir > @yield_sequence TEST_F(VMBytecodeDispatchAsyncTest, YieldSequence) { IREE_TRACE_SCOPE(); iree_vm_function_t function; IREE_ASSERT_OK(iree_vm_module_lookup_function_by_name( bytecode_module_, IREE_VM_FUNCTION_LINKAGE_EXPORT, IREE_SV("yield_sequence"), &function)); IREE_VM_INLINE_STACK_INITIALIZE( stack, IREE_VM_CONTEXT_FLAG_NONE, iree_vm_context_id(context_), iree_vm_context_state_resolver(context_), iree_allocator_system()); uint32_t arg_value = 97; uint32_t ret_value = 0; iree_vm_function_call_t call; memset(&call, 0, sizeof(call)); call.function = function; call.arguments = iree_make_byte_span(&arg_value, sizeof(arg_value)); call.results = iree_make_byte_span(&ret_value, sizeof(ret_value)); iree_vm_execution_result_t result; // 0/3 ASSERT_THAT( function.module->begin_call(function.module->self, stack, &call, &result), StatusIs(StatusCode::kDeferred)); // 1/3 ASSERT_THAT(function.module->resume_call(function.module->self, stack, call.results, &result), StatusIs(StatusCode::kDeferred)); // 2/3 ASSERT_THAT(function.module->resume_call(function.module->self, stack, call.results, &result), StatusIs(StatusCode::kDeferred)); // 3/3 IREE_ASSERT_OK(function.module->resume_call(function.module->self, stack, call.results, &result)); ASSERT_EQ(ret_value, arg_value + 3); iree_vm_stack_deinitialize(stack); } // Tests a yield with data-dependent control, ensuring that we run the // alternating branches and pass along branch args on resume. // See iree/vm/test/async_ops.mlir > @yield_divergent TEST_F(VMBytecodeDispatchAsyncTest, YieldDivergent) { IREE_TRACE_SCOPE(); iree_vm_function_t function; IREE_ASSERT_OK(iree_vm_module_lookup_function_by_name( bytecode_module_, IREE_VM_FUNCTION_LINKAGE_EXPORT, IREE_SV("yield_divergent"), &function)); IREE_VM_INLINE_STACK_INITIALIZE( stack, IREE_VM_CONTEXT_FLAG_NONE, iree_vm_context_id(context_), iree_vm_context_state_resolver(context_), iree_allocator_system()); // result = %arg0 ? %arg1 : %arg2 struct { uint32_t arg0; uint32_t arg1; uint32_t arg2; } arg_values = { 0, 100, 200, }; uint32_t ret_value = 0; iree_vm_function_call_t call; memset(&call, 0, sizeof(call)); call.function = function; call.arguments = iree_make_byte_span(&arg_values, sizeof(arg_values)); call.results = iree_make_byte_span(&ret_value, sizeof(ret_value)); iree_vm_execution_result_t result; // arg0=0: result = %arg0 ? %arg1 : %arg2 => %arg2 arg_values.arg0 = 0; ASSERT_THAT( function.module->begin_call(function.module->self, stack, &call, &result), StatusIs(StatusCode::kDeferred)); IREE_ASSERT_OK(function.module->resume_call(function.module->self, stack, call.results, &result)); ASSERT_EQ(ret_value, arg_values.arg2); // arg0=1: result = %arg0 ? %arg1 : %arg2 => %arg1 arg_values.arg0 = 1; ASSERT_THAT( function.module->begin_call(function.module->self, stack, &call, &result), StatusIs(StatusCode::kDeferred)); IREE_ASSERT_OK(function.module->resume_call(function.module->self, stack, call.results, &result)); ASSERT_EQ(ret_value, arg_values.arg1); iree_vm_stack_deinitialize(stack); } } // namespace } // namespace iree
34.36747
80
0.709202
nithinsubbiah
3bacd0b6c5523beea6a162f135dcc168f2f462d6
46,095
cpp
C++
src/Meta_Auto_Code.cpp
ciyam/ciyam
f25d25145caca7e75de11ba0a3dac818254eb61a
[ "MIT" ]
15
2015-02-22T19:45:05.000Z
2020-04-12T01:50:57.000Z
src/Meta_Auto_Code.cpp
ciyam/ciyam
f25d25145caca7e75de11ba0a3dac818254eb61a
[ "MIT" ]
1
2017-04-15T15:58:43.000Z
2017-04-15T15:58:43.000Z
src/Meta_Auto_Code.cpp
ciyam/ciyam
f25d25145caca7e75de11ba0a3dac818254eb61a
[ "MIT" ]
14
2016-11-06T18:20:06.000Z
2021-06-27T13:01:50.000Z
// Copyright (c) 2012-2021 CIYAM Developers // // Distributed under the MIT/X11 software license, please refer to the file license.txt // in the root project directory or http://www.opensource.org/licenses/mit-license.php. #ifdef PRECOMPILE_H # include "precompile.h" #endif #pragma hdrstop #ifndef HAS_PRECOMPILED_STD_HEADERS # include <cstring> # include <fstream> # include <iostream> # include <algorithm> # include <stdexcept> #endif #define CIYAM_BASE_LIB #define MODULE_META_IMPL // [<start macros>] // [<finish macros>] #include "Meta_Auto_Code.h" #include "ciyam_base.h" #include "ciyam_common.h" #include "class_domains.h" #include "module_strings.h" #include "ciyam_constants.h" #include "ciyam_variables.h" #include "class_utilities.h" #include "command_handler.h" #include "module_interface.h" // [<start includes>] // [<finish includes>] using namespace std; // [<start namespaces>] // [<finish namespaces>] inline int system( const string& cmd ) { return exec_system( cmd ); } namespace { template< typename T > inline void sanity_check( const T& t ) { } inline void sanity_check( const string& s ) { if( s.length( ) > c_max_string_length_limit ) throw runtime_error( "unexpected max string length limit exceeded with: " + s ); } #include "Meta_Auto_Code.cmh" const int32_t c_version = 1; const char* const c_field_id_Exhausted = "125103"; const char* const c_field_id_Mask = "125101"; const char* const c_field_id_Next = "125102"; const char* const c_field_name_Exhausted = "Exhausted"; const char* const c_field_name_Mask = "Mask"; const char* const c_field_name_Next = "Next"; const char* const c_field_display_name_Exhausted = "field_auto_code_exhausted"; const char* const c_field_display_name_Mask = "field_auto_code_mask"; const char* const c_field_display_name_Next = "field_auto_code_next"; const int c_num_fields = 3; const char* const c_all_sorted_field_ids[ ] = { "125101", "125102", "125103" }; const char* const c_all_sorted_field_names[ ] = { "Exhausted", "Mask", "Next" }; inline bool compare( const char* p_s1, const char* p_s2 ) { return strcmp( p_s1, p_s2 ) < 0; } inline bool has_field( const string& field ) { return binary_search( c_all_sorted_field_ids, c_all_sorted_field_ids + c_num_fields, field.c_str( ), compare ) || binary_search( c_all_sorted_field_names, c_all_sorted_field_names + c_num_fields, field.c_str( ), compare ); } const int c_num_encrypted_fields = 0; bool is_encrypted_field( const string& ) { static bool false_value( false ); return false_value; } const int c_num_transient_fields = 0; bool is_transient_field( const string& ) { static bool false_value( false ); return false_value; } const char* const c_procedure_id_Increment = "125410"; domain_string_max_size< 30 > g_Mask_domain; domain_string_max_size< 30 > g_Next_domain; string g_order_field_name; string g_owner_field_name; string g_state_names_variable; set< string > g_derivations; set< string > g_file_field_ids; set< string > g_file_field_names; typedef map< string, Meta_Auto_Code* > external_aliases_container; typedef external_aliases_container::const_iterator external_aliases_const_iterator; typedef external_aliases_container::value_type external_aliases_value_type; typedef map< size_t, Meta_Auto_Code* > external_aliases_lookup_container; typedef external_aliases_lookup_container::const_iterator external_aliases_lookup_const_iterator; external_aliases_container g_external_aliases; external_aliases_lookup_container g_external_aliases_lookup; struct validate_formatter { validate_formatter( ) : num( 0 ) { } string get( const string& name ) { return masks[ name ]; } void set( const string& name, const string& mask ) { masks.insert( make_pair( name, mask ) ); } int num; map< string, string > masks; }; inline validation_error_value_type construct_validation_error( int& num, const string& field_name, const string& error_message ) { return validation_error_value_type( construct_key_from_int( "", ++num, 4 ) + ':' + field_name, error_message ); } bool g_default_Exhausted = bool( 0 ); string g_default_Mask = string( ); string g_default_Next = string( ); // [<start anonymous>] // [<finish anonymous>] } registration< Meta_Auto_Code > Auto_Code_registration( get_class_registry( ), "125100" ); class Meta_Auto_Code_command_functor; class Meta_Auto_Code_command_handler : public command_handler { friend class Meta_Auto_Code_command_functor; public: Meta_Auto_Code_command_handler( ) : p_Meta_Auto_Code( 0 ) { } void set_Meta_Auto_Code( Meta_Auto_Code* p_new_Meta_Auto_Code ) { p_Meta_Auto_Code = p_new_Meta_Auto_Code; } void handle_unknown_command( const string& command, const string& cmd_and_args ) { throw runtime_error( "unknown command '" + command + "'" ); } void handle_invalid_command( const command_parser& parser, const string& cmd_and_args ) { throw runtime_error( "invalid command usage '" + cmd_and_args + "'" ); } private: Meta_Auto_Code* p_Meta_Auto_Code; protected: string retval; }; class Meta_Auto_Code_command_functor : public command_functor { public: Meta_Auto_Code_command_functor( Meta_Auto_Code_command_handler& handler ) : command_functor( handler ), cmd_handler( handler ) { } void operator ( )( const string& command, const parameter_info& parameters ); private: Meta_Auto_Code_command_handler& cmd_handler; }; command_functor* Meta_Auto_Code_command_functor_factory( const string& /*name*/, command_handler& handler ) { return new Meta_Auto_Code_command_functor( dynamic_cast< Meta_Auto_Code_command_handler& >( handler ) ); } void Meta_Auto_Code_command_functor::operator ( )( const string& command, const parameter_info& parameters ) { if( command == c_cmd_Meta_Auto_Code_key ) { bool want_fixed( has_parm_val( parameters, c_cmd_Meta_Auto_Code_key_fixed ) ); if( !want_fixed ) cmd_handler.retval = cmd_handler.p_Meta_Auto_Code->get_key( ); else cmd_handler.retval = cmd_handler.p_Meta_Auto_Code->get_fixed_key( ); } else if( command == c_cmd_Meta_Auto_Code_ver ) { string ver_rev( to_string( cmd_handler.p_Meta_Auto_Code->get_version( ) ) ); ver_rev += "." + to_string( cmd_handler.p_Meta_Auto_Code->get_revision( ) ); cmd_handler.retval = ver_rev; } else if( command == c_cmd_Meta_Auto_Code_get ) { string field_name( get_parm_val( parameters, c_cmd_Meta_Auto_Code_get_field_name ) ); bool handled = false; if( field_name.empty( ) ) throw runtime_error( "field name must not be empty for getter call" ); if( !handled && field_name == c_field_id_Exhausted || field_name == c_field_name_Exhausted ) { handled = true; string_getter< bool >( cmd_handler.p_Meta_Auto_Code->Exhausted( ), cmd_handler.retval ); } if( !handled && field_name == c_field_id_Mask || field_name == c_field_name_Mask ) { handled = true; string_getter< string >( cmd_handler.p_Meta_Auto_Code->Mask( ), cmd_handler.retval ); } if( !handled && field_name == c_field_id_Next || field_name == c_field_name_Next ) { handled = true; string_getter< string >( cmd_handler.p_Meta_Auto_Code->Next( ), cmd_handler.retval ); } if( !handled ) throw runtime_error( "unknown field name '" + field_name + "' for getter call" ); } else if( command == c_cmd_Meta_Auto_Code_set ) { string field_name( get_parm_val( parameters, c_cmd_Meta_Auto_Code_set_field_name ) ); string field_value( get_parm_val( parameters, c_cmd_Meta_Auto_Code_set_field_value ) ); bool handled = false; if( field_name.empty( ) ) throw runtime_error( "field name must not be empty for setter call" ); if( !handled && field_name == c_field_id_Exhausted || field_name == c_field_name_Exhausted ) { handled = true; func_string_setter< Meta_Auto_Code, bool >( *cmd_handler.p_Meta_Auto_Code, &Meta_Auto_Code::Exhausted, field_value ); } if( !handled && field_name == c_field_id_Mask || field_name == c_field_name_Mask ) { handled = true; func_string_setter< Meta_Auto_Code, string >( *cmd_handler.p_Meta_Auto_Code, &Meta_Auto_Code::Mask, field_value ); } if( !handled && field_name == c_field_id_Next || field_name == c_field_name_Next ) { handled = true; func_string_setter< Meta_Auto_Code, string >( *cmd_handler.p_Meta_Auto_Code, &Meta_Auto_Code::Next, field_value ); } if( !handled ) throw runtime_error( "unknown field name '" + field_name + "' for setter call" ); cmd_handler.retval = c_okay; } else if( command == c_cmd_Meta_Auto_Code_cmd ) { string field_name( get_parm_val( parameters, c_cmd_Meta_Auto_Code_cmd_field_name ) ); string cmd_and_args( get_parm_val( parameters, c_cmd_Meta_Auto_Code_cmd_cmd_and_args ) ); cmd_handler.retval.erase( ); if( field_name.empty( ) ) throw runtime_error( "field name must not be empty for command call" ); else throw runtime_error( "unknown field name '" + field_name + "' for command call" ); } else if( command == c_cmd_Meta_Auto_Code_Increment ) { string Next_Value; cmd_handler.p_Meta_Auto_Code->Increment( Next_Value ); cmd_handler.retval.erase( ); append_value( cmd_handler.retval, Next_Value ); } } struct Meta_Auto_Code::impl : public Meta_Auto_Code_command_handler { impl( Meta_Auto_Code& o ) : cp_obj( &o ), total_child_relationships( 0 ) { p_obj = &o; set_Meta_Auto_Code( &o ); add_commands( 0, Meta_Auto_Code_command_functor_factory, ARRAY_PTR_AND_SIZE( Meta_Auto_Code_command_definitions ) ); } Meta_Auto_Code& get_obj( ) const { return *cp_obj; } bool impl_Exhausted( ) const { return lazy_fetch( p_obj ), v_Exhausted; } void impl_Exhausted( bool Exhausted ) { v_Exhausted = Exhausted; } const string& impl_Mask( ) const { return lazy_fetch( p_obj ), v_Mask; } void impl_Mask( const string& Mask ) { sanity_check( Mask ); v_Mask = Mask; } const string& impl_Next( ) const { return lazy_fetch( p_obj ), v_Next; } void impl_Next( const string& Next ) { sanity_check( Next ); v_Next = Next; } void impl_Increment( string& Next_Value ); string get_field_value( int field ) const; void set_field_value( int field, const string& value ); void set_field_default( int field ); bool is_field_default( int field ) const; uint64_t get_state( ) const; string get_state_names( ) const; const string& execute( const string& cmd_and_args ); void clear_foreign_key( const string& field ); void set_foreign_key_value( const string& field, const string& value ); const string& get_foreign_key_value( const string& field ); void get_foreign_key_values( foreign_key_data_container& foreign_key_values ) const; void add_extra_fixed_info( vector< pair< string, string > >& fixed_info ) const; void add_extra_paging_info( vector< pair< string, string > >& paging_info ) const; void clear( ); bool value_will_be_provided( const string& field_name ); void validate( uint64_t state, bool is_internal, validation_error_container* p_validation_errors ); void validate_set_fields( set< string >& fields_set, validation_error_container* p_validation_errors ); void after_fetch( ); void finalise_fetch( bool skip_set_original ); void at_create( ); void post_init( ); void to_store( bool is_create, bool is_internal ); void for_store( bool is_create, bool is_internal ); void after_store( bool is_create, bool is_internal ); bool can_destroy( bool is_internal ); void for_destroy( bool is_internal ); void after_destroy( bool is_internal ); void set_default_values( ); bool is_filtered( ) const; void get_required_transients( ) const; Meta_Auto_Code* p_obj; class_pointer< Meta_Auto_Code > cp_obj; mutable set< string > required_transients; // [<start members>] // [<finish members>] size_t total_child_relationships; bool v_Exhausted; string v_Mask; string v_Next; }; void Meta_Auto_Code::impl::impl_Increment( string& Next_Value ) { uint64_t state = p_obj->get_state( ); ( void )state; // [(start for_auto_code)] 600295 get_obj( ).op_update( ); if( !get_obj( ).Exhausted( ) ) { string mask( get_obj( ).Mask( ) ); if( is_null( get_obj( ).Next( ) ) ) { string str; for( size_t i = 0; i < mask.size( ); i++ ) { if( mask[ i ] == '?' ) str += 'A'; else if( mask[ i ] == '#' ) str += '0'; else str += mask[ i ]; } get_obj( ).Next( str ); } Next_Value = get_obj( ).Next( ); if( mask.size( ) != get_obj( ).Next( ).size( ) ) { get_obj( ).op_cancel( ); throw runtime_error( "unexpected mask/next size mismatch" ); } bool finished = false; string str( get_obj( ).Next( ) ); for( size_t i = mask.size( ); i > 0; i-- ) { if( mask[ i - 1 ] == '?' ) { if( str[ i - 1 ] == 'Z' ) str[ i - 1 ] = 'A'; else { ++str[ i - 1 ]; finished = true; } } else if( mask[ i - 1 ] == '#' ) { if( str[ i - 1 ] == '9' ) str[ i - 1 ] = '0'; else { ++str[ i - 1 ]; finished = true; } } if( finished ) { get_obj( ).Next( str ); break; } } if( !finished ) { get_obj( ).Next( "" ); get_obj( ).Exhausted( true ); } get_obj( ).op_apply( ); } else get_obj( ).op_cancel( ); // [(finish for_auto_code)] 600295 // [<start Increment_impl>] // [<finish Increment_impl>] } string Meta_Auto_Code::impl::get_field_value( int field ) const { string retval; switch( field ) { case 0: retval = to_string( impl_Exhausted( ) ); break; case 1: retval = to_string( impl_Mask( ) ); break; case 2: retval = to_string( impl_Next( ) ); break; default: throw runtime_error( "field #" + to_string( field ) + " is out of range in get field value" ); } return retval; } void Meta_Auto_Code::impl::set_field_value( int field, const string& value ) { switch( field ) { case 0: func_string_setter< Meta_Auto_Code::impl, bool >( *this, &Meta_Auto_Code::impl::impl_Exhausted, value ); break; case 1: func_string_setter< Meta_Auto_Code::impl, string >( *this, &Meta_Auto_Code::impl::impl_Mask, value ); break; case 2: func_string_setter< Meta_Auto_Code::impl, string >( *this, &Meta_Auto_Code::impl::impl_Next, value ); break; default: throw runtime_error( "field #" + to_string( field ) + " is out of range in set field value" ); } } void Meta_Auto_Code::impl::set_field_default( int field ) { switch( field ) { case 0: impl_Exhausted( g_default_Exhausted ); break; case 1: impl_Mask( g_default_Mask ); break; case 2: impl_Next( g_default_Next ); break; default: throw runtime_error( "field #" + to_string( field ) + " is out of range in set field default" ); } } bool Meta_Auto_Code::impl::is_field_default( int field ) const { bool retval = false; switch( field ) { case 0: retval = ( v_Exhausted == g_default_Exhausted ); break; case 1: retval = ( v_Mask == g_default_Mask ); break; case 2: retval = ( v_Next == g_default_Next ); break; default: throw runtime_error( "field #" + to_string( field ) + " is out of range in is_field_default" ); } return retval; } uint64_t Meta_Auto_Code::impl::get_state( ) const { uint64_t state = 0; // [<start get_state>] // [<finish get_state>] return state; } string Meta_Auto_Code::impl::get_state_names( ) const { string state_names; uint64_t state = get_state( ); return state_names.empty( ) ? state_names : state_names.substr( 1 ); } const string& Meta_Auto_Code::impl::execute( const string& cmd_and_args ) { execute_command( cmd_and_args ); return retval; } void Meta_Auto_Code::impl::clear_foreign_key( const string& field ) { if( field.empty( ) ) throw runtime_error( "unexpected empty field name/id" ); else throw runtime_error( "unknown foreign key field '" + field + "'" ); } void Meta_Auto_Code::impl::set_foreign_key_value( const string& field, const string& value ) { if( field.empty( ) ) throw runtime_error( "unexpected empty field name/id for value: " + value ); else throw runtime_error( "unknown foreign key field '" + field + "'" ); } const string& Meta_Auto_Code::impl::get_foreign_key_value( const string& field ) { if( field.empty( ) ) throw runtime_error( "unexpected empty field name/id" ); else throw runtime_error( "unknown foreign key field '" + field + "'" ); } void Meta_Auto_Code::impl::get_foreign_key_values( foreign_key_data_container& foreign_key_values ) const { ( void )foreign_key_values; } void Meta_Auto_Code::impl::add_extra_fixed_info( vector< pair< string, string > >& fixed_info ) const { ( void )fixed_info; // [<start add_extra_fixed_info>] // [<finish add_extra_fixed_info>] } void Meta_Auto_Code::impl::add_extra_paging_info( vector< pair< string, string > >& paging_info ) const { ( void )paging_info; // [<start add_extra_paging_info>] // [<finish add_extra_paging_info>] } void Meta_Auto_Code::impl::clear( ) { v_Exhausted = g_default_Exhausted; v_Mask = g_default_Mask; v_Next = g_default_Next; } bool Meta_Auto_Code::impl::value_will_be_provided( const string& field_name ) { ( void )field_name; // [<start value_will_be_provided>] // [<finish value_will_be_provided>] return false; } void Meta_Auto_Code::impl::validate( uint64_t state, bool is_internal, validation_error_container* p_validation_errors ) { ( void )state; ( void )is_internal; if( !p_validation_errors ) throw runtime_error( "unexpected null validation_errors container" ); string error_message; validate_formatter vf; if( is_null( v_Mask ) && !value_will_be_provided( c_field_name_Mask ) ) p_validation_errors->insert( construct_validation_error( vf.num, c_field_name_Mask, get_string_message( GS( c_str_field_must_not_be_empty ), make_pair( c_str_parm_field_must_not_be_empty_field, get_module_string( c_field_display_name_Mask ) ) ) ) ); if( !is_null( v_Mask ) && ( v_Mask != g_default_Mask || !value_will_be_provided( c_field_name_Mask ) ) && !g_Mask_domain.is_valid( v_Mask, error_message = "" ) ) p_validation_errors->insert( construct_validation_error( vf.num, c_field_name_Mask, get_module_string( c_field_display_name_Mask ) + " " + error_message ) ); if( !is_null( v_Next ) && ( v_Next != g_default_Next || !value_will_be_provided( c_field_name_Next ) ) && !g_Next_domain.is_valid( v_Next, error_message = "" ) ) p_validation_errors->insert( construct_validation_error( vf.num, c_field_name_Next, get_module_string( c_field_display_name_Next ) + " " + error_message ) ); // [(start for_auto_code)] 600295 if( !get_obj( ).Next( ).empty( ) ) { bool okay = true; string next( get_obj( ).Next( ) ); string mask( get_obj( ).Mask( ) ); if( next.length( ) != mask.length( ) ) okay = false; else { for( size_t i = 0; i < next.length( ); i++ ) { if( next[ i ] != mask[ i ] ) { if( mask[ i ] == '?' ) { if( next[ i ] < 'A' || next[ i ] > 'Z' ) okay = false; } else if( mask[ i ] == '#' ) { if( next[ i ] < '0' || next[ i ] > '9' ) okay = false; } else okay = false; } if( !okay ) break; } } if( !okay ) p_validation_errors->insert( validation_error_value_type( c_field_name_Next, get_string_message( GS( c_str_field_mismatch ), make_pair( c_str_parm_field_mismatch_field, get_module_string( c_field_display_name_Next ) ), make_pair( c_str_parm_field_mismatch_field2, get_module_string( c_field_display_name_Mask ) ) ) ) ); } // [(finish for_auto_code)] 600295 // [<start validate>] // [<finish validate>] } void Meta_Auto_Code::impl::validate_set_fields( set< string >& fields_set, validation_error_container* p_validation_errors ) { ( void )fields_set; if( !p_validation_errors ) throw runtime_error( "unexpected null validation_errors container" ); string error_message; validate_formatter vf; if( !is_null( v_Mask ) && ( fields_set.count( c_field_id_Mask ) || fields_set.count( c_field_name_Mask ) ) && !g_Mask_domain.is_valid( v_Mask, error_message = "" ) ) p_validation_errors->insert( construct_validation_error( vf.num, c_field_name_Mask, get_module_string( c_field_display_name_Mask ) + " " + error_message ) ); if( !is_null( v_Next ) && ( fields_set.count( c_field_id_Next ) || fields_set.count( c_field_name_Next ) ) && !g_Next_domain.is_valid( v_Next, error_message = "" ) ) p_validation_errors->insert( construct_validation_error( vf.num, c_field_name_Next, get_module_string( c_field_display_name_Next ) + " " + error_message ) ); } void Meta_Auto_Code::impl::after_fetch( ) { if( !get_obj( ).get_is_iterating( ) || get_obj( ).get_is_starting_iteration( ) ) get_required_transients( ); post_init( ); uint64_t state = p_obj->get_state( ); ( void )state; // [<start after_fetch>] // [<finish after_fetch>] } void Meta_Auto_Code::impl::finalise_fetch( bool skip_set_original ) { if( !skip_set_original && !get_obj( ).get_key( ).empty( ) ) get_obj( ).set_new_original_values( ); uint64_t state = p_obj->get_state( ); ( void )state; // [<start finalise_fetch>] // [<finish finalise_fetch>] } void Meta_Auto_Code::impl::at_create( ) { // [<start at_create>] // [<finish at_create>] } void Meta_Auto_Code::impl::post_init( ) { uint64_t state = p_obj->get_state( ); ( void )state; // [<start post_init>] // [<finish post_init>] } void Meta_Auto_Code::impl::to_store( bool is_create, bool is_internal ) { ( void )is_create; ( void )is_internal; if( !get_obj( ).get_is_preparing( ) ) post_init( ); uint64_t state = p_obj->get_state( ); ( void )state; // [<start to_store>] // [<finish to_store>] } void Meta_Auto_Code::impl::for_store( bool is_create, bool is_internal ) { ( void )is_create; ( void )is_internal; uint64_t state = p_obj->get_state( ); ( void )state; // [<start for_store>] // [<finish for_store>] } void Meta_Auto_Code::impl::after_store( bool is_create, bool is_internal ) { ( void )is_create; ( void )is_internal; uint64_t state = p_obj->get_state( ); ( void )state; // [<start after_store>] // [<finish after_store>] } bool Meta_Auto_Code::impl::can_destroy( bool is_internal ) { uint64_t state = p_obj->get_state( ); bool retval = is_internal || !( state & c_state_undeletable ); // [<start can_destroy>] // [<finish can_destroy>] return retval; } void Meta_Auto_Code::impl::for_destroy( bool is_internal ) { ( void )is_internal; uint64_t state = p_obj->get_state( ); ( void )state; // [<start for_destroy>] // [<finish for_destroy>] } void Meta_Auto_Code::impl::after_destroy( bool is_internal ) { ( void )is_internal; uint64_t state = p_obj->get_state( ); ( void )state; // [<start after_destroy>] // [<finish after_destroy>] } void Meta_Auto_Code::impl::set_default_values( ) { clear( ); } bool Meta_Auto_Code::impl::is_filtered( ) const { uint64_t state = p_obj->get_state( ); ( void )state; // [<start is_filtered>] // [<finish is_filtered>] return false; } void Meta_Auto_Code::impl::get_required_transients( ) const { required_transients.clear( ); get_obj( ).add_required_transients( required_transients ); set< string > dependents( required_transients.begin( ), required_transients.end( ) ); p_obj->get_required_field_names( required_transients, true, &dependents ); int iterations = 0; // NOTE: It is possible that due to "interdependent" required fields // some required fields may not have been added in the first or even // later calls to "get_required_field_names" so continue calling the // function until no further field names have been added. size_t num_required = required_transients.size( ); while( num_required ) { p_obj->get_required_field_names( required_transients, true, &dependents ); if( required_transients.size( ) == num_required ) break; if( ++iterations > 100 ) throw runtime_error( "unexpected excessive get_required_field_names( ) iterations in get_required_transients( )" ); num_required = required_transients.size( ); } } #undef MODULE_TRACE #define MODULE_TRACE( x ) trace( x ) Meta_Auto_Code::Meta_Auto_Code( ) { set_version( c_version ); p_impl = new impl( *this ); } Meta_Auto_Code::~Meta_Auto_Code( ) { cleanup( ); delete p_impl; } bool Meta_Auto_Code::Exhausted( ) const { return p_impl->impl_Exhausted( ); } void Meta_Auto_Code::Exhausted( bool Exhausted ) { p_impl->impl_Exhausted( Exhausted ); } const string& Meta_Auto_Code::Mask( ) const { return p_impl->impl_Mask( ); } void Meta_Auto_Code::Mask( const string& Mask ) { p_impl->impl_Mask( Mask ); } const string& Meta_Auto_Code::Next( ) const { return p_impl->impl_Next( ); } void Meta_Auto_Code::Next( const string& Next ) { p_impl->impl_Next( Next ); } void Meta_Auto_Code::Increment( string& Next_Value ) { p_impl->impl_Increment( Next_Value ); } string Meta_Auto_Code::get_field_value( int field ) const { return p_impl->get_field_value( field ); } void Meta_Auto_Code::set_field_value( int field, const string& value ) { p_impl->set_field_value( field, value ); } void Meta_Auto_Code::set_field_default( int field ) { return set_field_default( ( field_id )( field + 1 ) ); } void Meta_Auto_Code::set_field_default( field_id id ) { p_impl->set_field_default( ( int )id - 1 ); } void Meta_Auto_Code::set_field_default( const string& field ) { p_impl->set_field_default( get_field_num( field ) ); } bool Meta_Auto_Code::is_field_default( int field ) const { return is_field_default( ( field_id )( field + 1 ) ); } bool Meta_Auto_Code::is_field_default( field_id id ) const { return p_impl->is_field_default( ( int )id - 1 ); } bool Meta_Auto_Code::is_field_default( const string& field ) const { return p_impl->is_field_default( get_field_num( field ) ); } bool Meta_Auto_Code::is_field_encrypted( int field ) const { return static_is_field_encrypted( ( field_id )( field + 1 ) ); } bool Meta_Auto_Code::is_field_transient( int field ) const { return static_is_field_transient( ( field_id )( field + 1 ) ); } string Meta_Auto_Code::get_field_id( int field ) const { return static_get_field_id( ( field_id )( field + 1 ) ); } string Meta_Auto_Code::get_field_name( int field ) const { return static_get_field_name( ( field_id )( field + 1 ) ); } int Meta_Auto_Code::get_field_num( const string& field ) const { int rc = static_get_field_num( field ); if( rc < 0 ) throw runtime_error( "unknown field name/id '" + field + "' in get_field_num( )" ); return rc; } bool Meta_Auto_Code::has_field_changed( const string& field ) const { return class_base::has_field_changed( get_field_num( field ) ); } uint64_t Meta_Auto_Code::get_state( ) const { uint64_t state = 0; state |= p_impl->get_state( ); return state; } const string& Meta_Auto_Code::execute( const string& cmd_and_args ) { return p_impl->execute( cmd_and_args ); } void Meta_Auto_Code::clear( ) { p_impl->clear( ); } void Meta_Auto_Code::validate( uint64_t state, bool is_internal ) { p_impl->validate( state, is_internal, &validation_errors ); } void Meta_Auto_Code::validate_set_fields( set< string >& fields_set ) { p_impl->validate_set_fields( fields_set, &validation_errors ); } void Meta_Auto_Code::after_fetch( ) { p_impl->after_fetch( ); } void Meta_Auto_Code::finalise_fetch( bool skip_set_original ) { p_impl->finalise_fetch( skip_set_original ); } void Meta_Auto_Code::at_create( ) { p_impl->at_create( ); } void Meta_Auto_Code::post_init( ) { p_impl->post_init( ); } void Meta_Auto_Code::to_store( bool is_create, bool is_internal ) { p_impl->to_store( is_create, is_internal ); } void Meta_Auto_Code::for_store( bool is_create, bool is_internal ) { p_impl->for_store( is_create, is_internal ); } void Meta_Auto_Code::after_store( bool is_create, bool is_internal ) { p_impl->after_store( is_create, is_internal ); } bool Meta_Auto_Code::can_destroy( bool is_internal ) { return p_impl->can_destroy( is_internal ); } void Meta_Auto_Code::for_destroy( bool is_internal ) { p_impl->for_destroy( is_internal ); } void Meta_Auto_Code::after_destroy( bool is_internal ) { p_impl->after_destroy( is_internal ); } void Meta_Auto_Code::set_default_values( ) { p_impl->set_default_values( ); } bool Meta_Auto_Code::is_filtered( ) const { return p_impl->is_filtered( ); } const char* Meta_Auto_Code::get_field_id( const string& name, bool* p_sql_numeric, string* p_type_name ) const { const char* p_id( 0 ); if( name.empty( ) ) throw runtime_error( "unexpected empty field name for get_field_id" ); else if( name == c_field_name_Exhausted ) { p_id = c_field_id_Exhausted; if( p_type_name ) *p_type_name = "bool"; if( p_sql_numeric ) *p_sql_numeric = true; } else if( name == c_field_name_Mask ) { p_id = c_field_id_Mask; if( p_type_name ) *p_type_name = "string"; if( p_sql_numeric ) *p_sql_numeric = false; } else if( name == c_field_name_Next ) { p_id = c_field_id_Next; if( p_type_name ) *p_type_name = "string"; if( p_sql_numeric ) *p_sql_numeric = false; } return p_id; } const char* Meta_Auto_Code::get_field_name( const string& id, bool* p_sql_numeric, string* p_type_name ) const { const char* p_name( 0 ); if( id.empty( ) ) throw runtime_error( "unexpected empty field id for get_field_name" ); else if( id == c_field_id_Exhausted ) { p_name = c_field_name_Exhausted; if( p_type_name ) *p_type_name = "bool"; if( p_sql_numeric ) *p_sql_numeric = true; } else if( id == c_field_id_Mask ) { p_name = c_field_name_Mask; if( p_type_name ) *p_type_name = "string"; if( p_sql_numeric ) *p_sql_numeric = false; } else if( id == c_field_id_Next ) { p_name = c_field_name_Next; if( p_type_name ) *p_type_name = "string"; if( p_sql_numeric ) *p_sql_numeric = false; } return p_name; } string& Meta_Auto_Code::get_order_field_name( ) const { return g_order_field_name; } string& Meta_Auto_Code::get_owner_field_name( ) const { return g_owner_field_name; } bool Meta_Auto_Code::is_file_field( const string& id_or_name ) const { return g_file_field_ids.count( id_or_name ) || g_file_field_names.count( id_or_name ); } void Meta_Auto_Code::get_file_field_names( vector< string >& file_field_names ) const { for( set< string >::const_iterator ci = g_file_field_names.begin( ); ci != g_file_field_names.end( ); ++ci ) file_field_names.push_back( *ci ); } string Meta_Auto_Code::get_field_uom_symbol( const string& id_or_name ) const { string uom_symbol; string name; pair< string, string > next; if( id_or_name.empty( ) ) throw runtime_error( "unexpected empty field id_or_name for get_field_uom_symbol" ); else if( id_or_name == c_field_id_Exhausted || id_or_name == c_field_name_Exhausted ) { name = string( c_field_display_name_Exhausted ); get_module_string( c_field_display_name_Exhausted, &next ); } else if( id_or_name == c_field_id_Mask || id_or_name == c_field_name_Mask ) { name = string( c_field_display_name_Mask ); get_module_string( c_field_display_name_Mask, &next ); } else if( id_or_name == c_field_id_Next || id_or_name == c_field_name_Next ) { name = string( c_field_display_name_Next ); get_module_string( c_field_display_name_Next, &next ); } // NOTE: It is being assumed here that the customised UOM symbol for a field (if it // has one) will be in the module string that immediately follows that of its name. if( next.first.find( name + "_(" ) == 0 ) uom_symbol = next.second; return uom_symbol; } string Meta_Auto_Code::get_field_display_name( const string& id_or_name ) const { string display_name; if( id_or_name.empty( ) ) throw runtime_error( "unexpected empty field id_or_name for get_field_display_name" ); else if( id_or_name == c_field_id_Exhausted || id_or_name == c_field_name_Exhausted ) display_name = get_module_string( c_field_display_name_Exhausted ); else if( id_or_name == c_field_id_Mask || id_or_name == c_field_name_Mask ) display_name = get_module_string( c_field_display_name_Mask ); else if( id_or_name == c_field_id_Next || id_or_name == c_field_name_Next ) display_name = get_module_string( c_field_display_name_Next ); return display_name; } void Meta_Auto_Code::clear_foreign_key( const string& field ) { p_impl->clear_foreign_key( field ); } void Meta_Auto_Code::set_foreign_key_value( const string& field, const string& value ) { p_impl->set_foreign_key_value( field, value ); } const string& Meta_Auto_Code::get_foreign_key_value( const string& field ) { return p_impl->get_foreign_key_value( field ); } void Meta_Auto_Code::get_foreign_key_values( foreign_key_data_container& foreign_key_values ) const { p_impl->get_foreign_key_values( foreign_key_values ); } size_t Meta_Auto_Code::get_total_child_relationships( ) const { return p_impl->total_child_relationships; } void Meta_Auto_Code::set_total_child_relationships( size_t new_total_child_relationships ) const { p_impl->total_child_relationships = new_total_child_relationships; } size_t Meta_Auto_Code::get_num_foreign_key_children( bool is_internal ) const { size_t rc = 0; if( !is_internal ) { g_external_aliases_lookup.clear( ); for( external_aliases_const_iterator eaci = g_external_aliases.begin( ), end = g_external_aliases.end( ); eaci != end; ++eaci ) { size_t num_extra = eaci->second->get_num_foreign_key_children( true ); if( num_extra ) { eaci->second->set_key( get_key( ) ); eaci->second->copy_all_field_values( *this ); g_external_aliases_lookup.insert( make_pair( rc, eaci->second ) ); rc += num_extra; } } } set_total_child_relationships( rc ); return rc; } class_base* Meta_Auto_Code::get_next_foreign_key_child( size_t child_num, string& next_child_field, cascade_op op, bool is_internal ) { class_base* p_class_base = 0; ( void )child_num; ( void )next_child_field; ( void )op; return p_class_base; } void Meta_Auto_Code::add_extra_fixed_info( vector< pair< string, string > >& fixed_info ) const { p_impl->add_extra_fixed_info( fixed_info ); } void Meta_Auto_Code::add_extra_paging_info( vector< pair< string, string > >& paging_info ) const { p_impl->add_extra_paging_info( paging_info ); } string Meta_Auto_Code::get_class_id( ) const { return static_class_id( ); } string Meta_Auto_Code::get_class_name( ) const { return static_class_name( ); } string Meta_Auto_Code::get_plural_name( ) const { return static_plural_name( ); } string Meta_Auto_Code::get_module_id( ) const { return static_module_id( ); } string Meta_Auto_Code::get_module_name( ) const { return static_module_name( ); } string Meta_Auto_Code::get_display_name( bool plural ) const { string key( plural ? "plural_" : "class_" ); key += "auto_code"; return get_module_string( key ); } string Meta_Auto_Code::get_raw_variable( const std::string& name ) const { if( name == g_state_names_variable ) return p_impl->get_state_names( ); else return class_base::get_raw_variable( name ); } string Meta_Auto_Code::get_create_instance_info( ) const { return ""; } string Meta_Auto_Code::get_update_instance_info( ) const { return ""; } string Meta_Auto_Code::get_destroy_instance_info( ) const { return ""; } string Meta_Auto_Code::get_execute_procedure_info( const string& procedure_id ) const { string retval; if( procedure_id.empty( ) ) throw runtime_error( "unexpected empty procedure_id for get_execute_procedure_info" ); else if( procedure_id == "125410" ) // i.e. Increment retval = ""; return retval; } bool Meta_Auto_Code::get_is_alias( ) const { return false; } void Meta_Auto_Code::get_alias_base_info( pair< string, string >& alias_base_info ) const { ( void )alias_base_info; } void Meta_Auto_Code::get_base_class_info( vector< pair< string, string > >& base_class_info ) const { ( void )base_class_info; } class_base& Meta_Auto_Code::get_or_create_graph_child( const string& context ) { class_base* p_class_base( 0 ); string::size_type pos = context.find( '.' ); string sub_context( context.substr( 0, pos ) ); if( sub_context.empty( ) ) throw runtime_error( "unexpected empty sub-context" ); if( !p_class_base ) throw runtime_error( "unknown sub-context '" + sub_context + "'" ); if( pos != string::npos ) p_class_base = &p_class_base->get_or_create_graph_child( context.substr( pos + 1 ) ); return *p_class_base; } void Meta_Auto_Code::get_sql_column_names( vector< string >& names, bool* p_done, const string* p_class_name ) const { if( p_done && *p_done ) return; names.push_back( "C_Exhausted" ); names.push_back( "C_Mask" ); names.push_back( "C_Next" ); if( p_done && p_class_name && *p_class_name == static_class_name( ) ) *p_done = true; } void Meta_Auto_Code::get_sql_column_values( vector< string >& values, bool* p_done, const string* p_class_name ) const { if( p_done && *p_done ) return; values.push_back( to_string( Exhausted( ) ) ); values.push_back( sql_quote( to_string( Mask( ) ) ) ); values.push_back( sql_quote( to_string( Next( ) ) ) ); if( p_done && p_class_name && *p_class_name == static_class_name( ) ) *p_done = true; } void Meta_Auto_Code::get_required_field_names( set< string >& names, bool use_transients, set< string >* p_dependents ) const { set< string > local_dependents; set< string >& dependents( p_dependents ? *p_dependents : local_dependents ); get_always_required_field_names( names, use_transients, dependents ); // [<start get_required_field_names>] // [<finish get_required_field_names>] } void Meta_Auto_Code::get_always_required_field_names( set< string >& names, bool use_transients, set< string >& dependents ) const { ( void )names; ( void )dependents; ( void )use_transients; // [<start get_always_required_field_names>] // [<finish get_always_required_field_names>] } void Meta_Auto_Code::get_transient_replacement_field_names( const string& name, vector< string >& names ) const { ( void )name; ( void )names; // [<start get_transient_replacement_field_names>] // [<finish get_transient_replacement_field_names>] } void Meta_Auto_Code::do_generate_sql( generate_sql_type type, vector< string >& sql_stmts, set< string >& tx_key_info, vector< string >* p_sql_undo_stmts ) const { generate_sql( static_class_name( ), type, sql_stmts, tx_key_info, p_sql_undo_stmts ); } const char* Meta_Auto_Code::static_resolved_module_id( ) { return static_module_id( ); } const char* Meta_Auto_Code::static_resolved_module_name( ) { return static_module_name( ); } const char* Meta_Auto_Code::static_lock_class_id( ) { return "125100"; } const char* Meta_Auto_Code::static_check_class_name( ) { return "Auto_Code"; } const char* Meta_Auto_Code::static_persistence_extra( ) { return ""; } bool Meta_Auto_Code::static_has_derivations( ) { return !g_derivations.empty( ); } void Meta_Auto_Code::static_get_class_info( class_info_container& class_info ) { class_info.push_back( "100.125100" ); } void Meta_Auto_Code::static_get_field_info( field_info_container& all_field_info ) { all_field_info.push_back( field_info( "125103", "Exhausted", "bool", false, "", "" ) ); all_field_info.push_back( field_info( "125101", "Mask", "string", false, "", "" ) ); all_field_info.push_back( field_info( "125102", "Next", "string", false, "", "" ) ); } void Meta_Auto_Code::static_get_foreign_key_info( foreign_key_info_container& foreign_key_info ) { ( void )foreign_key_info; } int Meta_Auto_Code::static_get_num_fields( bool* p_done, const string* p_class_name ) { if( p_done && p_class_name && *p_class_name == static_class_name( ) ) *p_done = true; return c_num_fields; } bool Meta_Auto_Code::static_is_field_encrypted( field_id id ) { return is_encrypted_field( static_get_field_id( id ) ); } bool Meta_Auto_Code::static_is_field_transient( field_id id ) { return is_transient_field( static_get_field_id( id ) ); } const char* Meta_Auto_Code::static_get_field_id( field_id id ) { const char* p_id = 0; switch( id ) { case 1: p_id = "125103"; break; case 2: p_id = "125101"; break; case 3: p_id = "125102"; break; } if( !p_id ) throw runtime_error( "unknown field id #" + to_string( id ) + " for class Auto_Code" ); return p_id; } const char* Meta_Auto_Code::static_get_field_name( field_id id ) { const char* p_id = 0; switch( id ) { case 1: p_id = "Exhausted"; break; case 2: p_id = "Mask"; break; case 3: p_id = "Next"; break; } if( !p_id ) throw runtime_error( "unknown field id #" + to_string( id ) + " for class Auto_Code" ); return p_id; } int Meta_Auto_Code::static_get_field_num( const string& field ) { int rc = 0; if( field.empty( ) ) throw runtime_error( "unexpected empty field name/id for static_get_field_num( )" ); else if( field == c_field_id_Exhausted || field == c_field_name_Exhausted ) rc += 1; else if( field == c_field_id_Mask || field == c_field_name_Mask ) rc += 2; else if( field == c_field_id_Next || field == c_field_name_Next ) rc += 3; return rc - 1; } procedure_info_container& Meta_Auto_Code::static_get_procedure_info( ) { static bool initialised = false; static procedure_info_container procedures; if( !initialised ) { initialised = true; procedures.insert( make_pair( "125410", procedure_info( "Increment" ) ) ); } return procedures; } string Meta_Auto_Code::static_get_sql_columns( ) { string sql_columns; sql_columns += "C_Key_ VARCHAR(75)," "C_Ver_ SMALLINT UNSIGNED NOT NULL," "C_Rev_ BIGINT UNSIGNED NOT NULL," "C_Typ_ VARCHAR(24) NOT NULL," "C_Exhausted INTEGER NOT NULL," "C_Mask VARCHAR(200) NOT NULL," "C_Next VARCHAR(200) NOT NULL," "PRIMARY KEY(C_Key_)"; return sql_columns; } void Meta_Auto_Code::static_get_text_search_fields( vector< string >& fields ) { ( void )fields; } void Meta_Auto_Code::static_get_all_enum_pairs( vector< pair< string, string > >& pairs ) { ( void )pairs; } void Meta_Auto_Code::static_get_sql_indexes( vector< string >& indexes ) { ( void )indexes; } void Meta_Auto_Code::static_get_sql_unique_indexes( vector< string >& indexes ) { ( void )indexes; } void Meta_Auto_Code::static_insert_derivation( const string& module_and_class_id ) { g_derivations.insert( module_and_class_id ); } void Meta_Auto_Code::static_remove_derivation( const string& module_and_class_id ) { if( g_derivations.count( module_and_class_id ) ) g_derivations.erase( module_and_class_id ); } void Meta_Auto_Code::static_insert_external_alias( const string& module_and_class_id, Meta_Auto_Code* p_instance ) { g_external_aliases.insert( external_aliases_value_type( module_and_class_id, p_instance ) ); } void Meta_Auto_Code::static_remove_external_alias( const string& module_and_class_id ) { if( g_external_aliases.count( module_and_class_id ) ) { delete g_external_aliases[ module_and_class_id ]; g_external_aliases.erase( module_and_class_id ); } } void Meta_Auto_Code::static_class_init( const char* p_module_name ) { if( !p_module_name ) throw runtime_error( "unexpected null module name pointer for init" ); g_state_names_variable = get_special_var_name( e_special_var_state_names ); // [<start static_class_init>] // [<finish static_class_init>] } void Meta_Auto_Code::static_class_term( const char* p_module_name ) { if( !p_module_name ) throw runtime_error( "unexpected null module name pointer for term" ); // [<start static_class_term>] // [<finish static_class_term>] }
25.910624
124
0.67708
ciyam
3bb205d82c7a90242d419db7e5da2db8fca07f7b
420
cpp
C++
src/roq/samples/example-4/config.cpp
roq-trading/examples
1e8ac9f5a960378ae4dc4d4a6b83f8daf6a65cba
[ "BSD-3-Clause" ]
null
null
null
src/roq/samples/example-4/config.cpp
roq-trading/examples
1e8ac9f5a960378ae4dc4d4a6b83f8daf6a65cba
[ "BSD-3-Clause" ]
null
null
null
src/roq/samples/example-4/config.cpp
roq-trading/examples
1e8ac9f5a960378ae4dc4d4a6b83f8daf6a65cba
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 2017-2022, Hans Erik Thrane */ #include "roq/samples/example-4/config.hpp" #include "roq/samples/example-4/flags.hpp" namespace roq { namespace samples { namespace example_4 { void Config::dispatch(Handler &handler) const { handler(client::Symbol{ .regex = Flags::symbols(), .exchange = Flags::exchange(), }); } } // namespace example_4 } // namespace samples } // namespace roq
20
47
0.678571
roq-trading
3bb247c2a2669ee3b24f359d2639d9bb0dbdbb0d
7,737
hxx
C++
OCC/inc/Prs3d_DatumAspect.hxx
cy15196/FastCAE
0870752ec2e590f3ea6479e909ebf6c345ac2523
[ "BSD-3-Clause" ]
117
2020-03-07T12:07:05.000Z
2022-03-27T07:35:22.000Z
opencascade/Prs3d_DatumAspect.hxx
CadQuery/cpp-py-bindgen
66e7376d3a27444393fc99acbdbef40bbc7031ae
[ "Apache-2.0" ]
33
2019-11-13T18:09:51.000Z
2021-11-26T17:24:12.000Z
opencascade/Prs3d_DatumAspect.hxx
CadQuery/cpp-py-bindgen
66e7376d3a27444393fc99acbdbef40bbc7031ae
[ "Apache-2.0" ]
76
2020-03-16T01:47:46.000Z
2022-03-21T16:37:07.000Z
// Created on: 1993-07-30 // Created by: Jean-Louis FRENKEL // Copyright (c) 1993-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _Prs3d_DatumAspect_HeaderFile #define _Prs3d_DatumAspect_HeaderFile #include <NCollection_DataMap.hxx> #include <Prs3d_ArrowAspect.hxx> #include <Prs3d_DatumAttribute.hxx> #include <Prs3d_DatumAxes.hxx> #include <Prs3d_DatumMode.hxx> #include <Prs3d_DatumParts.hxx> #include <Prs3d_LineAspect.hxx> #include <Prs3d_PointAspect.hxx> #include <Prs3d_ShadingAspect.hxx> #include <Prs3d_TextAspect.hxx> //! A framework to define the display of datums. class Prs3d_DatumAspect : public Prs3d_BasicAspect { DEFINE_STANDARD_RTTIEXT(Prs3d_DatumAspect, Prs3d_BasicAspect) public: //! An empty framework to define the display of datums. Standard_EXPORT Prs3d_DatumAspect(); //! Returns the right-handed coordinate system set in SetComponent. Standard_EXPORT Handle(Prs3d_LineAspect) LineAspect (Prs3d_DatumParts thePart) const; //! Returns the right-handed coordinate system set in SetComponent. Standard_EXPORT Handle(Prs3d_ShadingAspect) ShadingAspect (Prs3d_DatumParts thePart) const; //! Returns the text attributes for rendering labels. const Handle(Prs3d_TextAspect)& TextAspect() const { return myTextAspect; } //! Sets text attributes for rendering labels. void SetTextAspect (const Handle(Prs3d_TextAspect)& theTextAspect) { myTextAspect = theTextAspect; } //! Returns the point aspect of origin wireframe presentation const Handle(Prs3d_PointAspect)& PointAspect() const { return myPointAspect; } //! Returns the point aspect of origin wireframe presentation void SetPointAspect (const Handle(Prs3d_PointAspect)& theAspect) { myPointAspect = theAspect; } //! Returns the arrow aspect of presentation const Handle(Prs3d_ArrowAspect)& ArrowAspect() const { return myArrowAspect; } //! Sets the arrow aspect of presentation void SetArrowAspect (const Handle(Prs3d_ArrowAspect)& theAspect) { myArrowAspect = theAspect; } //! Returns the attributes for display of the first axis. Standard_DEPRECATED("This method is deprecated - LineAspect() should be called instead") const Handle(Prs3d_LineAspect)& FirstAxisAspect() const { return myLineAspects.Find (Prs3d_DP_XAxis); } //! Returns the attributes for display of the second axis. Standard_DEPRECATED("This method is deprecated - LineAspect() should be called instead") const Handle(Prs3d_LineAspect)& SecondAxisAspect() const { return myLineAspects.Find (Prs3d_DP_YAxis); } //! Returns the attributes for display of the third axis. Standard_DEPRECATED("This method is deprecated - LineAspect() should be called instead") const Handle(Prs3d_LineAspect)& ThirdAxisAspect() const { return myLineAspects.Find (Prs3d_DP_ZAxis); } //! Sets the DrawFirstAndSecondAxis attributes to active. Standard_DEPRECATED("This method is deprecated - SetDrawDatumAxes() should be called instead") Standard_EXPORT void SetDrawFirstAndSecondAxis (Standard_Boolean theToDraw); //! Returns true if the first and second axes can be drawn. Standard_DEPRECATED("This method is deprecated - DatumAxes() should be called instead") Standard_Boolean DrawFirstAndSecondAxis() const { return (myAxes & Prs3d_DA_XAxis) != 0 && (myAxes & Prs3d_DA_YAxis) != 0; } //! Sets the DrawThirdAxis attributes to active. Standard_DEPRECATED("This method is deprecated - SetDrawDatumAxes() should be called instead") Standard_EXPORT void SetDrawThirdAxis (Standard_Boolean theToDraw); //! Returns true if the third axis can be drawn. Standard_DEPRECATED("This method is deprecated - DatumAxes() should be called instead") Standard_Boolean DrawThirdAxis() const { return (myAxes & Prs3d_DA_ZAxis) != 0; } //! Returns true if the given part is used in axes of aspect Standard_EXPORT Standard_Boolean DrawDatumPart (Prs3d_DatumParts thePart) const; //! Sets the axes used in the datum aspect void SetDrawDatumAxes (Prs3d_DatumAxes theType) { myAxes = theType; } //! Returns axes used in the datum aspect Prs3d_DatumAxes DatumAxes() const { return myAxes; } //! Sets the attribute of the datum type void SetAttribute (Prs3d_DatumAttribute theType, const Standard_Real& theValue) { myAttributes.Bind (theType, theValue); } //! Returns the attribute of the datum type Standard_Real Attribute (Prs3d_DatumAttribute theType) const { return myAttributes.Find (theType); } //! Sets the lengths of the three axes. void SetAxisLength (Standard_Real theL1, Standard_Real theL2, Standard_Real theL3) { myAttributes.Bind (Prs3d_DA_XAxisLength, theL1); myAttributes.Bind (Prs3d_DA_YAxisLength, theL2); myAttributes.Bind (Prs3d_DA_ZAxisLength, theL3); } //! Returns the length of the displayed first axis. Standard_EXPORT Standard_Real AxisLength (Prs3d_DatumParts thePart) const; //! Returns the length of the displayed first axis. Standard_DEPRECATED("This method is deprecated - AxisLength() should be called instead") Standard_Real FirstAxisLength() const { return myAttributes.Find (Prs3d_DA_XAxisLength); } //! Returns the length of the displayed second axis. Standard_DEPRECATED("This method is deprecated - AxisLength() should be called instead") Standard_Real SecondAxisLength() const { return myAttributes.Find (Prs3d_DA_YAxisLength); } //! Returns the length of the displayed third axis. Standard_DEPRECATED("This method is deprecated - AxisLength() should be called instead") Standard_Real ThirdAxisLength() const { return myAttributes.Find (Prs3d_DA_ZAxisLength); } //! @return true if axes labels are drawn; TRUE by default. Standard_Boolean ToDrawLabels() const { return myToDrawLabels; } //! Sets option to draw or not to draw text labels for axes void SetDrawLabels (Standard_Boolean theToDraw) { myToDrawLabels = theToDraw; } void SetToDrawLabels (Standard_Boolean theToDraw) { myToDrawLabels = theToDraw; } //! @return true if axes arrows are drawn; TRUE by default. Standard_Boolean ToDrawArrows() const { return myToDrawArrows; } //! Sets option to draw or not arrows for axes void SetDrawArrows (Standard_Boolean theToDraw) { myToDrawArrows = theToDraw; } //! Returns type of arrow for a type of axis Standard_EXPORT Prs3d_DatumParts ArrowPartForAxis (Prs3d_DatumParts thePart) const; //! Dumps the content of me into the stream Standard_EXPORT virtual void DumpJson (Standard_OStream& theOStream, const Standard_Integer theDepth = -1) const Standard_OVERRIDE; private: Prs3d_DatumAxes myAxes; Standard_Boolean myToDrawLabels; Standard_Boolean myToDrawArrows; NCollection_DataMap<Prs3d_DatumAttribute, Standard_Real> myAttributes; NCollection_DataMap<Prs3d_DatumParts, Handle(Prs3d_ShadingAspect)> myShadedAspects; NCollection_DataMap<Prs3d_DatumParts, Handle(Prs3d_LineAspect)> myLineAspects; Handle(Prs3d_TextAspect) myTextAspect; Handle(Prs3d_PointAspect) myPointAspect; Handle(Prs3d_ArrowAspect) myArrowAspect; }; DEFINE_STANDARD_HANDLE(Prs3d_DatumAspect, Prs3d_BasicAspect) #endif // _Prs3d_DatumAspect_HeaderFile
43.960227
133
0.779113
cy15196
3bb4800991fff29b1a82a180d581df476a52d2f0
2,401
cpp
C++
geomFuncs.cpp
kamino410/CudaSift
21d98443f919f877246aadde1d5e1c16fb7afa14
[ "MIT" ]
null
null
null
geomFuncs.cpp
kamino410/CudaSift
21d98443f919f877246aadde1d5e1c16fb7afa14
[ "MIT" ]
null
null
null
geomFuncs.cpp
kamino410/CudaSift
21d98443f919f877246aadde1d5e1c16fb7afa14
[ "MIT" ]
null
null
null
#include <Eigen/Dense> #include <cmath> #include <iostream> #include "cudaSift.h" int ImproveHomography(SiftData &data, float *homography, int numLoops, float minScore, float maxAmbiguity, float thresh) { #ifdef MANAGEDMEM SiftPoint *mpts = data.m_data; #else if (data.h_data == NULL) return 0; SiftPoint *mpts = data.h_data; #endif float limit = thresh * thresh; int numPts = data.numPts; Eigen::MatrixXd M(8, 8); Eigen::VectorXd A(8); Eigen::VectorXd X(8); Eigen::VectorXd Y(8); for (int i = 0; i < 8; i++) A(i) = homography[i] / homography[8]; for (int loop = 0; loop < numLoops; loop++) { M = Eigen::MatrixXd::Zero(8, 8); X = Eigen::VectorXd::Zero(8); for (int i = 0; i < numPts; i++) { SiftPoint &pt = mpts[i]; if (pt.score < minScore || pt.ambiguity > maxAmbiguity) continue; float den = A(6) * pt.xpos + A(7) * pt.ypos + 1.0f; float dx = (A(0) * pt.xpos + A(1) * pt.ypos + A(2)) / den - pt.match_xpos; float dy = (A(3) * pt.xpos + A(4) * pt.ypos + A(5)) / den - pt.match_ypos; float err = dx * dx + dy * dy; float wei = (err < limit ? 1.0f : 0.0f); // limit / (err + limit); Y(0) = pt.xpos; Y(1) = pt.ypos; Y(2) = 1.0; Y(3) = Y(4) = Y(5) = 0.0; Y(6) = -pt.xpos * pt.match_xpos; Y(7) = -pt.ypos * pt.match_xpos; for (int c = 0; c < 8; c++) for (int r = 0; r < 8; r++) M(r, c) += (Y(c) * Y(r) * wei); X += (Y * pt.match_xpos * wei); Y(0) = Y(1) = Y(2) = 0.0; Y(3) = pt.xpos; Y(4) = pt.ypos; Y(5) = 1.0; Y(6) = -pt.xpos * pt.match_ypos; Y(7) = -pt.ypos * pt.match_ypos; for (int c = 0; c < 8; c++) for (int r = 0; r < 8; r++) M(r, c) += (Y(c) * Y(r) * wei); X += (Y * pt.match_ypos * wei); } // cv::solve(M, X, A, cv::DECOMP_CHOLESKY); A = M.colPivHouseholderQr().solve(X); } int numfit = 0; for (int i = 0; i < numPts; i++) { SiftPoint &pt = mpts[i]; float den = A(6) * pt.xpos + A(7) * pt.ypos + 1.0; float dx = (A(0) * pt.xpos + A(1) * pt.ypos + A(2)) / den - pt.match_xpos; float dy = (A(3) * pt.xpos + A(4) * pt.ypos + A(5)) / den - pt.match_ypos; float err = dx * dx + dy * dy; if (err < limit) numfit++; pt.match_error = sqrt(err); } for (int i = 0; i < 8; i++) homography[i] = A(i); homography[8] = 1.0f; return numfit; }
34.797101
86
0.512703
kamino410
3bb8f845ec8bb4eff8981c1f6ee8a36d679cf795
6,242
cpp
C++
lib/Dialect/SV/Transforms/PrettifyVerilog.cpp
mwachs5/circt
bd7edb5c449921cb36939ebb5943e4fe73f72899
[ "Apache-2.0" ]
null
null
null
lib/Dialect/SV/Transforms/PrettifyVerilog.cpp
mwachs5/circt
bd7edb5c449921cb36939ebb5943e4fe73f72899
[ "Apache-2.0" ]
null
null
null
lib/Dialect/SV/Transforms/PrettifyVerilog.cpp
mwachs5/circt
bd7edb5c449921cb36939ebb5943e4fe73f72899
[ "Apache-2.0" ]
null
null
null
//===- PrettifyVerilog.cpp - Transformations to improve Verilog quality ---===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This pass contains elective transformations that improve the quality of // SystemVerilog generated by the ExportVerilog library. This pass is not // compulsory: things that are required for ExportVerilog to be correct should // be included as part of the ExportVerilog pass itself to make sure it is self // contained. // //===----------------------------------------------------------------------===// #include "PassDetail.h" #include "circt/Dialect/Comb/CombOps.h" #include "circt/Dialect/HW/HWOps.h" #include "circt/Dialect/SV/SVPasses.h" #include "mlir/IR/Builders.h" #include "mlir/IR/ImplicitLocOpBuilder.h" #include "mlir/IR/Matchers.h" using namespace circt; //===----------------------------------------------------------------------===// // PrettifyVerilogPass //===----------------------------------------------------------------------===// namespace { struct PrettifyVerilogPass : public sv::PrettifyVerilogBase<PrettifyVerilogPass> { void runOnOperation() override; private: void prettifyUnaryOperator(Operation *op); void sinkOpToUses(Operation *op); bool anythingChanged; }; } // end anonymous namespace /// Return true if this is something that will get printed as a unary operator /// by the Verilog printer. static bool isVerilogUnaryOperator(Operation *op) { if (isa<comb::ParityOp>(op)) return true; if (auto xorOp = dyn_cast<comb::XorOp>(op)) return xorOp.isBinaryNot(); if (auto icmpOp = dyn_cast<comb::ICmpOp>(op)) return icmpOp.isEqualAllOnes() || icmpOp.isNotEqualZero(); return false; } /// Sink an operation into the same block where it is used. This will clone the /// operation so it can be sunk into multiple blocks. If there are no more uses /// in the current block, the op will be removed. void PrettifyVerilogPass::sinkOpToUses(Operation *op) { assert(mlir::MemoryEffectOpInterface::hasNoEffect(op) && "Op with side effects cannot be sunk to its uses."); auto block = op->getBlock(); // This maps a block to the block local instance of the op. SmallDenseMap<Block *, Value, 8> blockLocalValues; for (auto &use : llvm::make_early_inc_range(op->getUses())) { // If the current use is in the same block as the operation, there is // nothing to do. auto localBlock = use.getOwner()->getBlock(); if (block == localBlock) continue; // Find the block local clone of the operation. If there is not one already, // the op will be cloned in to the block. auto &localValue = blockLocalValues[localBlock]; if (!localValue) { // Clone the operation and insert it to the beginning of the block. localValue = OpBuilder::atBlockBegin(localBlock).clone(*op)->getResult(0); } // Replace the current use, removing it from the use list. use.set(localValue); anythingChanged = true; } // If this op is no longer used, drop it. if (op->use_empty()) { op->erase(); anythingChanged = true; } } /// This is called on unary operators. void PrettifyVerilogPass::prettifyUnaryOperator(Operation *op) { // If this is a multiple use unary operator, duplicate it and move it into the // block corresponding to the user. This avoids emitting a temporary just for // a unary operator. Instead of: // // tmp1 = ^(thing+thing); // = tmp1 + 42 // // we get: // // tmp2 = thing+thing; // = ^tmp2 + 42 // // This is particularly helpful when the operand of the unary op has multiple // uses as well. if (op->use_empty() || op->hasOneUse()) return; while (!op->hasOneUse()) { OpOperand &use = *op->use_begin(); Operation *user = use.getOwner(); // Clone the operation and insert before this user. auto *cloned = op->clone(); user->getBlock()->getOperations().insert(Block::iterator(user), cloned); // Update user's operand to the new value. use.set(cloned->getResult(0)); } // There is exactly one user left, so move this before it. Operation *user = *op->user_begin(); op->moveBefore(user); anythingChanged = true; } /// Transform "a + -cst" ==> "a - cst" for prettier output. static void rewriteAddWithNegativeConstant(comb::AddOp add, hw::ConstantOp rhsCst) { ImplicitLocOpBuilder builder(add.getLoc(), add); // Get the positive constant. auto negCst = builder.create<hw::ConstantOp>(-rhsCst.getValue()); auto sub = builder.create<comb::SubOp>(add.getOperand(0), negCst); add.getResult().replaceAllUsesWith(sub); add.erase(); if (rhsCst.use_empty()) rhsCst.erase(); } void PrettifyVerilogPass::runOnOperation() { // Keeps track if anything changed during this pass, used to determine if // the analyses were preserved. anythingChanged = false; // Walk the operations in post-order, transforming any that are interesting. getOperation()->walk([&](Operation *op) { if (isVerilogUnaryOperator(op)) return prettifyUnaryOperator(op); // Sink or duplicate constant ops into the same block as their use. This // will allow the verilog emitter to inline constant expressions. if (matchPattern(op, mlir::m_Constant())) return sinkOpToUses(op); // Sink "free" operations which make Verilog prettier. if (isa<sv::ReadInOutOp>(op)) return sinkOpToUses(op); // Turn a + -cst ==> a - cst if (auto addOp = dyn_cast<comb::AddOp>(op)) if (auto cst = addOp.getOperand(1).getDefiningOp<hw::ConstantOp>()) if (addOp.getNumOperands() == 2 && cst.getValue().isNegative()) return rewriteAddWithNegativeConstant(addOp, cst); }); // If we did not change anything in the graph mark all analysis as // preserved. if (!anythingChanged) markAllAnalysesPreserved(); } std::unique_ptr<Pass> circt::sv::createPrettifyVerilogPass() { return std::make_unique<PrettifyVerilogPass>(); }
35.265537
80
0.652515
mwachs5
3bb95502baba167e88252c98f10a78d2b1cfe69e
6,052
cc
C++
third_party/blink/renderer/core/layout/jank_tracker.cc
zipated/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
third_party/blink/renderer/core/layout/jank_tracker.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
third_party/blink/renderer/core/layout/jank_tracker.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.000Z
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "third_party/blink/renderer/core/layout/jank_tracker.h" #include "third_party/blink/renderer/core/frame/local_dom_window.h" #include "third_party/blink/renderer/core/frame/local_frame.h" #include "third_party/blink/renderer/core/frame/location.h" #include "third_party/blink/renderer/core/layout/layout_object.h" #include "third_party/blink/renderer/core/layout/layout_view.h" #include "third_party/blink/renderer/core/paint/paint_layer.h" #include "third_party/blink/renderer/platform/graphics/paint/geometry_mapper.h" namespace blink { static const float kTimerDelay = 3.0; static FloatPoint LogicalStart(const FloatRect& rect, const LayoutObject& object) { const ComputedStyle* style = object.Style(); DCHECK(style); auto logical = PhysicalToLogical<float>(style->GetWritingMode(), style->Direction(), rect.Y(), rect.MaxX(), rect.MaxY(), rect.X()); return FloatPoint(logical.InlineStart(), logical.BlockStart()); } static float GetMoveDistance(const FloatRect& old_rect, const FloatRect& new_rect, const LayoutObject& object) { FloatSize location_delta = LogicalStart(new_rect, object) - LogicalStart(old_rect, object); return std::max(fabs(location_delta.Width()), fabs(location_delta.Height())); } JankTracker::JankTracker(LocalFrameView* frame_view) : frame_view_(frame_view), score_(0.0), timer_(frame_view->GetFrame().GetTaskRunner(TaskType::kInternalDefault), this, &JankTracker::TimerFired), has_fired_(false), max_distance_(0.0) {} void JankTracker::NotifyObjectPrePaint(const LayoutObject& object, const LayoutRect& old_visual_rect, const PaintLayer& painting_layer) { if (!IsActive()) return; LayoutRect new_visual_rect = object.FirstFragment().VisualRect(); if (old_visual_rect.IsEmpty() || new_visual_rect.IsEmpty()) return; if (LogicalStart(FloatRect(old_visual_rect), object) == LogicalStart(FloatRect(new_visual_rect), object)) return; const auto* local_transform = painting_layer.GetLayoutObject() .FirstFragment() .LocalBorderBoxProperties() .Transform(); const auto* ancestor_transform = painting_layer.GetLayoutObject() .View() ->FirstFragment() .LocalBorderBoxProperties() .Transform(); FloatRect old_visual_rect_abs = FloatRect(old_visual_rect); GeometryMapper::SourceToDestinationRect(local_transform, ancestor_transform, old_visual_rect_abs); FloatRect new_visual_rect_abs = FloatRect(new_visual_rect); GeometryMapper::SourceToDestinationRect(local_transform, ancestor_transform, new_visual_rect_abs); // TOOD(crbug.com/842282): Consider tracking a separate jank score for each // transform space to avoid these local-to-absolute conversions, once we have // a better idea of how to aggregate multiple scores for a page. // See review thread of http://crrev.com/c/1046155 for more details. IntRect viewport = frame_view_->GetScrollableArea()->VisibleContentRect(); if (!old_visual_rect_abs.Intersects(viewport) && !new_visual_rect_abs.Intersects(viewport)) return; DVLOG(2) << object.DebugName() << " moved from " << old_visual_rect_abs.ToString() << " to " << new_visual_rect_abs.ToString(); max_distance_ = std::max( max_distance_, GetMoveDistance(old_visual_rect_abs, new_visual_rect_abs, object)); IntRect visible_old_visual_rect = RoundedIntRect(old_visual_rect_abs); visible_old_visual_rect.Intersect(viewport); IntRect visible_new_visual_rect = RoundedIntRect(new_visual_rect_abs); visible_new_visual_rect.Intersect(viewport); region_.Unite(Region(visible_old_visual_rect)); region_.Unite(Region(visible_new_visual_rect)); } void JankTracker::NotifyPrePaintFinished() { if (!IsActive()) return; if (region_.IsEmpty()) { if (!timer_.IsActive()) timer_.StartOneShot(kTimerDelay, FROM_HERE); return; } IntRect viewport = frame_view_->GetScrollableArea()->VisibleContentRect(); double viewport_area = double(viewport.Width()) * double(viewport.Height()); double jank_fraction = region_.Area() / viewport_area; score_ += jank_fraction; DVLOG(1) << "viewport " << (jank_fraction * 100) << "% janked, raising score to " << score_; TRACE_EVENT_INSTANT1("blink", "FrameLayoutJank", TRACE_EVENT_SCOPE_THREAD, "viewportFraction", jank_fraction); region_ = Region(); // This cancels any previously scheduled task from the same timer. timer_.StartOneShot(kTimerDelay, FROM_HERE); } bool JankTracker::IsActive() { // This eliminates noise from the private Page object created by // SVGImage::DataChanged. if (frame_view_->GetFrame().GetChromeClient().IsSVGImageChromeClient()) return false; if (has_fired_) return false; return true; } void JankTracker::TimerFired(TimerBase* timer) { has_fired_ = true; // TODO(skobes): Aggregate jank scores from iframes. if (!frame_view_->GetFrame().IsMainFrame()) return; DVLOG(1) << "final jank score for " << frame_view_->GetFrame().DomWindow()->location()->toString() << " is " << score_ << " with max move distance of " << max_distance_; TRACE_EVENT_INSTANT2("blink", "TotalLayoutJank", TRACE_EVENT_SCOPE_THREAD, "score", score_, "maxDistance", max_distance_); } } // namespace blink
37.358025
79
0.667878
zipated
3bb99a1bef9765fa1b27d0d99e5462aad873ef39
4,201
cpp
C++
android/android_42/native/libs/utils/WorkQueue.cpp
yakuizhao/intel-vaapi-driver
b2bb0383352694941826543a171b557efac2219b
[ "MIT" ]
null
null
null
android/android_42/native/libs/utils/WorkQueue.cpp
yakuizhao/intel-vaapi-driver
b2bb0383352694941826543a171b557efac2219b
[ "MIT" ]
null
null
null
android/android_42/native/libs/utils/WorkQueue.cpp
yakuizhao/intel-vaapi-driver
b2bb0383352694941826543a171b557efac2219b
[ "MIT" ]
null
null
null
/* * Copyright (C) 2012 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. */ // #define LOG_NDEBUG 0 #define LOG_TAG "WorkQueue" #include <utils/Log.h> #include <utils/WorkQueue.h> namespace android { // --- WorkQueue --- WorkQueue::WorkQueue(size_t maxThreads, bool canCallJava) : mMaxThreads(maxThreads), mCanCallJava(canCallJava), mCanceled(false), mFinished(false), mIdleThreads(0) { } WorkQueue::~WorkQueue() { if (!cancel()) { finish(); } } status_t WorkQueue::schedule(WorkUnit* workUnit, size_t backlog) { AutoMutex _l(mLock); if (mFinished || mCanceled) { return INVALID_OPERATION; } if (mWorkThreads.size() < mMaxThreads && mIdleThreads < mWorkUnits.size() + 1) { sp<WorkThread> workThread = new WorkThread(this, mCanCallJava); status_t status = workThread->run("WorkQueue::WorkThread"); if (status) { return status; } mWorkThreads.add(workThread); mIdleThreads += 1; } else if (backlog) { while (mWorkUnits.size() >= mMaxThreads * backlog) { mWorkDequeuedCondition.wait(mLock); if (mFinished || mCanceled) { return INVALID_OPERATION; } } } mWorkUnits.add(workUnit); mWorkChangedCondition.broadcast(); return OK; } status_t WorkQueue::cancel() { AutoMutex _l(mLock); return cancelLocked(); } status_t WorkQueue::cancelLocked() { if (mFinished) { return INVALID_OPERATION; } if (!mCanceled) { mCanceled = true; size_t count = mWorkUnits.size(); for (size_t i = 0; i < count; i++) { delete mWorkUnits.itemAt(i); } mWorkUnits.clear(); mWorkChangedCondition.broadcast(); mWorkDequeuedCondition.broadcast(); } return OK; } status_t WorkQueue::finish() { { // acquire lock AutoMutex _l(mLock); if (mFinished) { return INVALID_OPERATION; } mFinished = true; mWorkChangedCondition.broadcast(); } // release lock // It is not possible for the list of work threads to change once the mFinished // flag has been set, so we can access mWorkThreads outside of the lock here. size_t count = mWorkThreads.size(); for (size_t i = 0; i < count; i++) { mWorkThreads.itemAt(i)->join(); } mWorkThreads.clear(); return OK; } bool WorkQueue::threadLoop() { WorkUnit* workUnit; { // acquire lock AutoMutex _l(mLock); for (;;) { if (mCanceled) { return false; } if (!mWorkUnits.isEmpty()) { workUnit = mWorkUnits.itemAt(0); mWorkUnits.removeAt(0); mIdleThreads -= 1; mWorkDequeuedCondition.broadcast(); break; } if (mFinished) { return false; } mWorkChangedCondition.wait(mLock); } } // release lock bool shouldContinue = workUnit->run(); delete workUnit; { // acquire lock AutoMutex _l(mLock); mIdleThreads += 1; if (!shouldContinue) { cancelLocked(); return false; } } // release lock return true; } // --- WorkQueue::WorkThread --- WorkQueue::WorkThread::WorkThread(WorkQueue* workQueue, bool canCallJava) : Thread(canCallJava), mWorkQueue(workQueue) { } WorkQueue::WorkThread::~WorkThread() { } bool WorkQueue::WorkThread::threadLoop() { return mWorkQueue->threadLoop(); } }; // namespace android
24.424419
83
0.597001
yakuizhao
3bba94a2dc61eae4b9c5ed9bb65bc515ea0ed1c7
1,953
cpp
C++
snippets/cpp/VS_Snippets_CLR_System/system.Array.Resize/CPP/System.Array.Resize.cpp
BohdanMosiyuk/samples
59d435ba9e61e0fc19f5176c96b1cdbd53596142
[ "CC-BY-4.0", "MIT" ]
2
2020-02-22T09:30:21.000Z
2021-08-02T23:44:31.000Z
snippets/cpp/VS_Snippets_CLR_System/system.Array.Resize/CPP/System.Array.Resize.cpp
BohdanMosiyuk/samples
59d435ba9e61e0fc19f5176c96b1cdbd53596142
[ "CC-BY-4.0", "MIT" ]
555
2019-09-23T22:22:58.000Z
2021-07-15T18:51:12.000Z
snippets/cpp/VS_Snippets_CLR_System/system.Array.Resize/CPP/System.Array.Resize.cpp
BohdanMosiyuk/samples
59d435ba9e61e0fc19f5176c96b1cdbd53596142
[ "CC-BY-4.0", "MIT" ]
3
2020-01-29T16:31:15.000Z
2021-08-24T07:00:15.000Z
// The following example shows how resizing affects the array. // <Snippet1> using namespace System; static void PrintIndexAndValues(array<String^>^myArr) { for(int i = 0; i < myArr->Length; i++) { Console::WriteLine(L" [{0}] : {1}", i, myArr[i]); } Console::WriteLine(); } int main() { // Create and initialize a new string array. array<String^>^myArr = {L"The", L"quick", L"brown", L"fox", L"jumps", L"over", L"the", L"lazy", L"dog"}; // Display the values of the array. Console::WriteLine( L"The string array initially contains the following values:"); PrintIndexAndValues(myArr); // Resize the array to a bigger size (five elements larger). Array::Resize(myArr, myArr->Length + 5); // Display the values of the array. Console::WriteLine(L"After resizing to a larger size, "); Console::WriteLine(L"the string array contains the following values:"); PrintIndexAndValues(myArr); // Resize the array to a smaller size (four elements). Array::Resize(myArr, 4); // Display the values of the array. Console::WriteLine(L"After resizing to a smaller size, "); Console::WriteLine(L"the string array contains the following values:"); PrintIndexAndValues(myArr); return 1; } /* This code produces the following output. The string array initially contains the following values: [0] : The [1] : quick [2] : brown [3] : fox [4] : jumps [5] : over [6] : the [7] : lazy [8] : dog After resizing to a larger size, the string array contains the following values: [0] : The [1] : quick [2] : brown [3] : fox [4] : jumps [5] : over [6] : the [7] : lazy [8] : dog [9] : [10] : [11] : [12] : [13] : After resizing to a smaller size, the string array contains the following values: [0] : The [1] : quick [2] : brown [3] : fox */ // </Snippet1>
23.25
75
0.605223
BohdanMosiyuk
3bbcec8abd7bb34587856268c2da025b8bec56d4
615
cc
C++
flow/layers/layer.cc
abarth/sky_engine
e55063b0026f7a1aeda87ccb92fe5d9d09e8fc2e
[ "BSD-3-Clause" ]
1
2021-08-13T08:19:40.000Z
2021-08-13T08:19:40.000Z
flow/layers/layer.cc
abarth/sky_engine
e55063b0026f7a1aeda87ccb92fe5d9d09e8fc2e
[ "BSD-3-Clause" ]
null
null
null
flow/layers/layer.cc
abarth/sky_engine
e55063b0026f7a1aeda87ccb92fe5d9d09e8fc2e
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2015 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 "flutter/flow/layers/layer.h" #include "third_party/skia/include/core/SkColorFilter.h" namespace flow { Layer::Layer() : parent_(nullptr), has_paint_bounds_(false), paint_bounds_() {} Layer::~Layer() {} void Layer::Preroll(PrerollContext* context, const SkMatrix& matrix) {} void Layer::UpdateScene(mojo::gfx::composition::SceneUpdate* update, mojo::gfx::composition::Node* container) {} } // namespace flow
29.285714
79
0.713821
abarth
3bc0b13dff18c8ab8d1ed82e90de4608b4e55925
13,346
cpp
C++
src/observation/observation.cpp
bburns/cppagent
c1891c631465ebc9b63a4b3c627727ca3da14ee8
[ "Apache-2.0" ]
null
null
null
src/observation/observation.cpp
bburns/cppagent
c1891c631465ebc9b63a4b3c627727ca3da14ee8
[ "Apache-2.0" ]
null
null
null
src/observation/observation.cpp
bburns/cppagent
c1891c631465ebc9b63a4b3c627727ca3da14ee8
[ "Apache-2.0" ]
null
null
null
// // Copyright Copyright 2009-2022, AMT – The Association For Manufacturing Technology (“AMT”) // 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 "observation.hpp" #include <mutex> #include <regex> #include "device_model/data_item/data_item.hpp" #include "entity/factory.hpp" #include "logging.hpp" #ifdef _WINDOWS #define strcasecmp stricmp #define strncasecmp strnicmp #define strtof strtod #endif using namespace std; namespace mtconnect { using namespace entity; namespace observation { FactoryPtr Observation::getFactory() { static FactoryPtr factory; if (!factory) { factory = make_shared<Factory>(Requirements({{"dataItemId", true}, {"timestamp", TIMESTAMP, true}, {"sequence", false}, {"subType", false}, {"name", false}, {"compositionId", false}}), [](const std::string &name, Properties &props) -> EntityPtr { return make_shared<Observation>(name, props); }); factory->registerFactory("Events:Message", Message::getFactory()); factory->registerFactory("Events:MessageDiscrete", Message::getFactory()); factory->registerFactory("Events:AssetChanged", AssetEvent::getFactory()); factory->registerFactory("Events:AssetRemoved", AssetEvent::getFactory()); factory->registerFactory("Events:Alarm", Alarm::getFactory()); // regex(".+TimeSeries$") factory->registerFactory( [](const std::string &name) { return ends_with(name, "TimeSeries"); }, Timeseries::getFactory()); factory->registerFactory([](const std::string &name) { return ends_with(name, "DataSet"); }, DataSetEvent::getFactory()); factory->registerFactory([](const std::string &name) { return ends_with(name, "Table"); }, TableEvent::getFactory()); factory->registerFactory( [](const std::string &name) { return starts_with(name, "Condition:"); }, Condition::getFactory()); factory->registerFactory( [](const std::string &name) { return starts_with(name, "Samples:") && ends_with(name, ":3D"); }, ThreeSpaceSample::getFactory()); factory->registerFactory( [](const std::string &name) { return starts_with(name, "Samples:"); }, Sample::getFactory()); factory->registerFactory( [](const std::string &name) { return starts_with(name, "Events:"); }, Event::getFactory()); } return factory; } ObservationPtr Observation::make(const DataItemPtr dataItem, const Properties &incompingProps, const Timestamp &timestamp, entity::ErrorList &errors) { NAMED_SCOPE("Observation"); auto props = entity::Properties(incompingProps); setProperties(dataItem, props); props.insert_or_assign("timestamp", timestamp); bool unavailable {false}; string level; if (dataItem->isCondition()) { auto l = props.find("level"); if (l != props.end()) { level = std::get<string>(l->second); if (iequals(level, "unavailable")) unavailable = true; props.erase(l); } else if (l == props.end()) { unavailable = true; } } else { // Check for unavailable auto v = props.find("VALUE"); if (v != props.end() && holds_alternative<string>(v->second)) { if (iequals(std::get<string>(v->second), "unavailable")) { unavailable = true; props.erase(v); } } else if (v == props.end()) { unavailable = true; } } string key = string(dataItem->getCategoryText()) + ":" + dataItem->getObservationName(); if (dataItem->isThreeSpace()) key += ":3D"; auto ent = getFactory()->create(key, props, errors); if (!ent) { LOG(warning) << "Could not parse properties for data item: " << dataItem->getId(); for (auto &e : errors) { LOG(warning) << " Error: " << e->what(); } throw EntityError("Invalid properties for data item"); } auto obs = dynamic_pointer_cast<Observation>(ent); obs->m_timestamp = timestamp; obs->m_dataItem = dataItem; if (unavailable) obs->makeUnavailable(); if (!dataItem->isCondition()) obs->setEntityName(); else if (!unavailable) dynamic_pointer_cast<Condition>(obs)->setLevel(level); return obs; } FactoryPtr Event::getFactory() { static FactoryPtr factory; if (!factory) { factory = make_shared<Factory>(*Observation::getFactory()); factory->setFunction([](const std::string &name, Properties &props) -> EntityPtr { return make_shared<Event>(name, props); }); factory->addRequirements( Requirements {{"VALUE", false}, {"resetTriggered", USTRING, false}}); } return factory; } FactoryPtr DataSetEvent::getFactory() { static FactoryPtr factory; if (!factory) { factory = make_shared<Factory>(*Observation::getFactory()); factory->setFunction([](const std::string &name, Properties &props) -> EntityPtr { auto ent = make_shared<DataSetEvent>(name, props); auto v = ent->m_properties.find("VALUE"); if (v != ent->m_properties.end()) { auto &ds = std::get<DataSet>(v->second); ent->m_properties.insert_or_assign("count", int64_t(ds.size())); } return ent; }); factory->addRequirements(Requirements {{"count", INTEGER, false}, {"VALUE", DATA_SET, false}, {"resetTriggered", USTRING, false}}); } return factory; } FactoryPtr TableEvent::getFactory() { static FactoryPtr factory; if (!factory) { factory = make_shared<Factory>(*DataSetEvent::getFactory()); factory->setFunction([](const std::string &name, Properties &props) -> EntityPtr { auto ent = make_shared<TableEvent>(name, props); auto v = ent->m_properties.find("VALUE"); if (v != ent->m_properties.end()) { auto &ds = std::get<DataSet>(v->second); ent->m_properties.insert_or_assign("count", int64_t(ds.size())); } return ent; }); factory->addRequirements(Requirements {{"VALUE", TABLE, false}}); } return factory; } FactoryPtr Sample::getFactory() { static FactoryPtr factory; if (!factory) { factory = make_shared<Factory>(*Observation::getFactory()); factory->setFunction([](const std::string &name, Properties &props) -> EntityPtr { return make_shared<Sample>(name, props); }); factory->addRequirements(Requirements({{"sampleRate", DOUBLE, false}, {"resetTriggered", USTRING, false}, {"statistic", USTRING, false}, {"duration", DOUBLE, false}, {"VALUE", DOUBLE, false}})); } return factory; } FactoryPtr ThreeSpaceSample::getFactory() { static FactoryPtr factory; if (!factory) { factory = make_shared<Factory>(*Sample::getFactory()); factory->setFunction([](const std::string &name, Properties &props) -> EntityPtr { return make_shared<ThreeSpaceSample>(name, props); }); factory->addRequirements(Requirements({{"VALUE", VECTOR, 3, false}})); } return factory; } FactoryPtr Timeseries::getFactory() { static FactoryPtr factory; if (!factory) { factory = make_shared<Factory>(*Sample::getFactory()); factory->setFunction([](const std::string &name, Properties &props) -> EntityPtr { auto ent = make_shared<Timeseries>(name, props); auto v = ent->m_properties.find("VALUE"); if (v != ent->m_properties.end()) { auto &ts = std::get<entity::Vector>(v->second); ent->m_properties.insert_or_assign("sampleCount", int64_t(ts.size())); } return ent; }); factory->addRequirements( Requirements({{"sampleCount", INTEGER, false}, {"VALUE", VECTOR, 0, entity::Requirement::Infinite}})); } return factory; } FactoryPtr Condition::getFactory() { static FactoryPtr factory; if (!factory) { factory = make_shared<Factory>(*Observation::getFactory()); factory->setFunction([](const std::string &name, Properties &props) -> EntityPtr { auto cond = make_shared<Condition>(name, props); if (cond) { auto code = cond->m_properties.find("nativeCode"); if (code != cond->m_properties.end()) cond->m_code = std::get<string>(code->second); } return cond; }); factory->addRequirements(Requirements {{"type", USTRING, true}, {"nativeCode", false}, {"nativeSeverity", false}, {"qualifier", USTRING, false}, {"statistic", USTRING, false}, {"VALUE", false}}); } return factory; } FactoryPtr AssetEvent::getFactory() { static FactoryPtr factory; if (!factory) { factory = make_shared<Factory>(*Event::getFactory()); factory->setFunction([](const std::string &name, Properties &props) -> EntityPtr { auto ent = make_shared<AssetEvent>(name, props); if (!ent->hasProperty("assetType") && !ent->hasValue()) { ent->setProperty("assetType", "UNAVAILABLE"s); } return ent; }); factory->addRequirements(Requirements({{"assetType", false}})); } return factory; } FactoryPtr Message::getFactory() { static FactoryPtr factory; if (!factory) { factory = make_shared<Factory>(*Event::getFactory()); factory->setFunction([](const std::string &name, Properties &props) -> EntityPtr { return make_shared<Message>(name, props); }); factory->addRequirements(Requirements({{"nativeCode", false}})); } return factory; } FactoryPtr Alarm::getFactory() { static FactoryPtr factory; if (!factory) { factory = make_shared<Factory>(*Event::getFactory()); factory->setFunction([](const std::string &name, Properties &props) -> EntityPtr { return make_shared<Alarm>(name, props); }); factory->addRequirements(Requirements({{"code", false}, {"nativeCode", false}, {"state", USTRING, false}, {"severity", false}})); } return factory; } bool Condition::replace(ConditionPtr &old, ConditionPtr &_new) { if (!m_prev) return false; if (m_prev == old) { _new->m_prev = old->m_prev; m_prev = _new; return true; } return m_prev->replace(old, _new); } ConditionPtr Condition::deepCopy() { auto n = make_shared<Condition>(*this); if (m_prev) { n->m_prev = m_prev->deepCopy(); } return n; } ConditionPtr Condition::deepCopyAndRemove(ConditionPtr &old) { if (this->getptr() == old) { if (m_prev) return m_prev->deepCopy(); else return nullptr; } auto n = make_shared<Condition>(*this); if (m_prev) { n->m_prev = m_prev->deepCopyAndRemove(old); } return n; } } // namespace observation } // namespace mtconnect
33.199005
100
0.533119
bburns
3bc59c50dfbbd632d0a260139a89d38c9d9d29f8
1,708
cpp
C++
tests/test/ported_libs/test_ffmpeg.cpp
kubasz/faasm
fa4cec66176c669c161f097d24edce099de66919
[ "Apache-2.0" ]
278
2020-10-01T16:37:06.000Z
2022-03-31T07:06:01.000Z
tests/test/ported_libs/test_ffmpeg.cpp
kubasz/faasm
fa4cec66176c669c161f097d24edce099de66919
[ "Apache-2.0" ]
78
2020-10-01T18:46:16.000Z
2022-03-18T15:39:03.000Z
tests/test/ported_libs/test_ffmpeg.cpp
kubasz/faasm
fa4cec66176c669c161f097d24edce099de66919
[ "Apache-2.0" ]
24
2020-10-21T18:45:48.000Z
2022-03-26T08:59:41.000Z
#include <catch2/catch.hpp> #include "utils.h" #include <boost/filesystem.hpp> #include <fstream> #include <iterator> #include <vector> #include <faabric/util/files.h> #include <storage/FileLoader.h> #include <storage/SharedFiles.h> #include <upload/UploadServer.h> namespace tests { // NOTE: we must be careful with this fixture that we don't have to rerun the // codegen for the ffmpeg function as it's over 40MB of wasm and takes several // minutes. class FFmpegTestFixture { public: FFmpegTestFixture() : loader(storage::getFileLoader()) { storage::SharedFiles::clear(); // Remove the file filePath = loader.getSharedFileFile(relativeSharedFilePath); boost::filesystem::remove(filePath); // Upload the file fileBytes = faabric::util::readFileToBytes(testFilePath); loader.uploadSharedFile(relativeSharedFilePath, fileBytes); } ~FFmpegTestFixture() { storage::SharedFiles::clear(); boost::filesystem::remove(filePath); } protected: storage::FileLoader& loader; std::string testFilePath = "./tests/test/ported_libs/files/ffmpeg_video.mp4"; std::string filePath; std::string relativeSharedFilePath = "ffmpeg/sample_video.mp4"; std::vector<uint8_t> fileBytes; }; TEST_CASE_METHOD(FFmpegTestFixture, "Test executing FFmpeg checks in WAVM", "[libs]") { faabric::Message msg = faabric::util::messageFactory("ffmpeg", "check"); execFunction(msg); } TEST_CASE_METHOD(FFmpegTestFixture, "Test executing FFmpeg checks in WAMR", "[libs][wamr]") { executeWithWamrPool("ffmpeg", "check"); } }
24.753623
78
0.666276
kubasz
3bc6825be74cb2e766fa26ca42ebc8bebc14cf62
673
cpp
C++
Interview Bit/Pick from both sides.cpp
kothariji/Competitive-Programming
c49f8b0135c8e9dd284ce8ab583e85ba3d809b8c
[ "MIT" ]
1
2020-08-27T06:59:52.000Z
2020-08-27T06:59:52.000Z
Interview Bit/Pick from both sides.cpp
kothariji/Competitive-Programming
c49f8b0135c8e9dd284ce8ab583e85ba3d809b8c
[ "MIT" ]
null
null
null
Interview Bit/Pick from both sides.cpp
kothariji/Competitive-Programming
c49f8b0135c8e9dd284ce8ab583e85ba3d809b8c
[ "MIT" ]
null
null
null
void fillSuffix(vector<int> &A,vector<int> &arr){ int n=A.size(); arr[n]=0; for(int i=n-1;i>=0;i--){ arr[i]=arr[i+1]+A[i]; } } void fillPrefix(vector<int> &A,vector<int> &arr){ arr[0]=0; for(int i=1;i<arr.size();i++){ arr[i]=arr[i-1]+A[i-1]; } } int Solution::solve(vector<int> &A, int B) { int sum=INT_MIN; int count=B; int n=A.size(); vector<int> prefixSum(A.size()+1); vector<int> suffixSum(A.size()+1); fillPrefix(A,prefixSum); fillSuffix(A,suffixSum); for(int i=0;i<=B;i++){ int temp=prefixSum[i]+suffixSum[n-B+i]; if(temp>sum) sum=temp; } return sum; }
21.709677
49
0.530461
kothariji
3bc74862820321bf365db6840880b57b73d20018
4,635
cpp
C++
trikGui/communicationSettingsWidget.cpp
Ashatta/trikRuntime
0e08a584b09c6319c7fb3020bcd0df3f27b976b3
[ "Apache-2.0" ]
null
null
null
trikGui/communicationSettingsWidget.cpp
Ashatta/trikRuntime
0e08a584b09c6319c7fb3020bcd0df3f27b976b3
[ "Apache-2.0" ]
null
null
null
trikGui/communicationSettingsWidget.cpp
Ashatta/trikRuntime
0e08a584b09c6319c7fb3020bcd0df3f27b976b3
[ "Apache-2.0" ]
null
null
null
/* Copyright 2014 CyberTech Labs Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "communicationSettingsWidget.h" #include <QtCore/QRegExp> #include <QtGui/QKeyEvent> using namespace trikGui; CommunicationSettingsWidget::CommunicationSettingsWidget(trikControl::Brick &brick , QWidget *parent) : TrikGuiDialog(parent) , mTitle(tr("<b>Comm settings</b>")) , mSelectorsHelpLabel(tr("(Press 'Enter' to edit)")) , mHullNumberLabel(tr("Hull number:")) , mHullNumberSelector(brick.mailbox()->myHullNumber(), 2, 0, 35, this) , mServerIpLabel(tr("Leader IP:")) , mIpHelpLabel(tr("(last two numbers)")) , mServerIpSelector(0, 6, 3, 25, this) , mBrick(brick) { mConnectButton.setText(tr("Connect")); mTitle.setAlignment(Qt::AlignCenter); mHullNumberSelector.setFocus(); mLayout.addWidget(&mTitle); mLayout.addWidget(&mSelectorsHelpLabel); mLayout.addWidget(&mHullNumberLabel); mLayout.addWidget(&mHullNumberSelector); mLayout.addWidget(&mServerIpLabel); mLayout.addWidget(&mIpHelpLabel); mLayout.addWidget(&mServerIpSelector); mLayout.addWidget(&mConnectButton); QFont helpFont = mSelectorsHelpLabel.font(); helpFont.setPixelSize(helpFont.pixelSize() - 7); mSelectorsHelpLabel.setFont(helpFont); mIpHelpLabel.setFont(helpFont); mSelectorsHelpLabel.setAlignment(Qt::AlignHCenter); auto const hostAddressString = brick.mailbox()->serverIp().toString(); if (hostAddressString == QHostAddress().toString()) { mServerIpSelector.setValue(0); } else { auto const parsedAddress = hostAddressString.split('.'); Q_ASSERT(parsedAddress.size() == 4); auto hostAddress = parsedAddress[2].toInt() * 1000 + parsedAddress[3].toInt(); mServerIpSelector.setValue(hostAddress); } setLayout(&mLayout); connect(&mConnectButton, SIGNAL(clicked()), this, SLOT(onConnectButtonClicked())); connect(&mConnectButton, SIGNAL(upPressed()), this, SLOT(focusUp())); connect(&mConnectButton, SIGNAL(downPressed()), this, SLOT(focusDown())); connect(&mHullNumberSelector, SIGNAL(valueChanged(int)), this, SLOT(onHullNumberChanged(int))); connect(&mHullNumberSelector, SIGNAL(upPressed()), this, SLOT(focusUp())); connect(&mHullNumberSelector, SIGNAL(downPressed()), this, SLOT(focusDown())); connect(&mServerIpSelector, SIGNAL(upPressed()), this, SLOT(focusUp())); connect(&mServerIpSelector, SIGNAL(downPressed()), this, SLOT(focusDown())); } QString CommunicationSettingsWidget::menuEntry() { return QString(tr("Comm settings")); } void CommunicationSettingsWidget::renewFocus() { } void CommunicationSettingsWidget::keyPressEvent(QKeyEvent *event) { switch (event->key()) { case Qt::Key_Up: { focusUp(); event->accept(); break; } case Qt::Key_Down: { focusDown(); event->accept(); break; } case Qt::Key_Return: { mConnectButton.animateClick(); event->accept(); break; } default: { TrikGuiDialog::keyPressEvent(event); } } } void CommunicationSettingsWidget::onConnectButtonClicked() { QStringList result = mBrick.mailbox()->myIp().toString().split('.'); if (result.size() != 4) { /// @todo Properly notify user that the robot is not connected. return; } QString const ipSelectorValue = QString("%1").arg(mServerIpSelector.value(), 6, 10, QChar('0')); QString const thirdPart = ipSelectorValue.left(3).replace(QRegExp("^0+"), ""); QString const fourthPart = ipSelectorValue.mid(3).replace(QRegExp("^0+"), ""); result[2] = thirdPart; result[3] = fourthPart; mBrick.mailbox()->connect(result.join(".")); } void CommunicationSettingsWidget::onHullNumberChanged(int newHullNumber) { mBrick.mailbox()->setHullNumber(newHullNumber); } void CommunicationSettingsWidget::focusUp() { if (mHullNumberSelector.hasFocusInside()) { mConnectButton.setFocus(); } else if (mServerIpSelector.hasFocusInside()) { mHullNumberSelector.setFocus(); } else { mServerIpSelector.setFocus(); } } void CommunicationSettingsWidget::focusDown() { if (mHullNumberSelector.hasFocusInside()) { mServerIpSelector.setFocus(); } else if (mServerIpSelector.hasFocusInside()) { mConnectButton.setFocus(); } else { mHullNumberSelector.setFocus(); } }
29.903226
97
0.736354
Ashatta