commit
stringlengths
40
40
old_file
stringlengths
2
205
new_file
stringlengths
2
205
old_contents
stringlengths
0
32.9k
new_contents
stringlengths
1
38.9k
subject
stringlengths
3
9.4k
message
stringlengths
6
9.84k
lang
stringlengths
3
13
license
stringclasses
13 values
repos
stringlengths
6
115k
52a90b51d94214beeef50e9a34daf47dd1a89db2
Modules/MitkExt/DataManagement/mitkPlanarCross.cpp
Modules/MitkExt/DataManagement/mitkPlanarCross.cpp
/*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date: 2010-02-17 23:03:29 +0100 (Mi, 17 Feb 2010) $ Version: $Revision: 18029 $ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "mitkPlanarCross.h" #include "mitkGeometry2D.h" mitk::PlanarCross::PlanarCross() : FEATURE_ID_LONGESTDIAMETER( this->AddFeature( "Longest Diameter", "mm" ) ), FEATURE_ID_SHORTAXISDIAMETER( this->AddFeature( "Short Axis Diameter", "mm" ) ), m_SingleLineMode( false ) { // Cross has two control points at the beginning this->ResetNumberOfControlPoints( 2 ); // Create polyline objects (one for each line of the cross) m_PolyLines->InsertElement( 0, VertexContainerType::New() ); m_PolyLines->InsertElement( 1, VertexContainerType::New() ); // Create helper polyline object (for drawing the orthogonal orientation line) m_HelperPolyLines->InsertElement( 0, VertexContainerType::New()); m_HelperPolyLines->ElementAt( 0 )->Reserve( 2 ); m_HelperPolyLinesToBePainted->InsertElement( 0, false ); } mitk::PlanarCross::~PlanarCross() { } bool mitk::PlanarCross::ResetOnPointSelect() { if ( m_SingleLineMode ) { // In single line mode --> nothing to reset return false; } switch ( m_SelectedControlPoint ) { default: // Nothing selected --> nothing to reset return false; case 0: { // Control point 0 selected: exchange points 0 and 1 Point2D tmpPoint = m_ControlPoints->ElementAt( 0 ); m_ControlPoints->InsertElement( 0, m_ControlPoints->ElementAt( 1 ) ); m_ControlPoints->InsertElement( 1, tmpPoint ); // FALLS THROUGH! } case 1: { // Control point 0 or 1 selected: reset number of control points to two this->ResetNumberOfControlPoints( 2 ); this->SelectControlPoint( 1 ); return true; } case 2: { // Control point 2 selected: replace point 0 with point 3 and point 1 with point 2 m_ControlPoints->InsertElement( 0, m_ControlPoints->ElementAt( 3 ) ); m_ControlPoints->InsertElement( 1, m_ControlPoints->ElementAt( 2 ) ); // Adjust selected control point, reset number of control points to two this->ResetNumberOfControlPoints( 2 ); this->SelectControlPoint( 1 ); return true; } case 3: { // Control point 3 selected: replace point 0 with point 2 and point 1 with point 3 m_ControlPoints->InsertElement( 0, m_ControlPoints->ElementAt( 2 ) ); m_ControlPoints->InsertElement( 1, m_ControlPoints->ElementAt( 3 ) ); // Adjust selected control point, reset number of control points to two this->ResetNumberOfControlPoints( 2 ); this->SelectControlPoint( 1 ); return true; } } } unsigned int mitk::PlanarCross::GetNumberOfFeatures() const { if ( m_SingleLineMode || (this->GetNumberOfControlPoints() < 4) ) { return 1; } else { return 2; } } mitk::Point2D mitk::PlanarCross::ApplyControlPointConstraints( unsigned int index, const Point2D& point ) { // Apply spatial constraints from superclass and from this class until the resulting constrained // point converges. Although not an optimal implementation, this iterative approach // helps to respect both constraints from the superclass and from this class. Without this, // situations may occur where control points are constrained by the superclass, but again // moved out of the superclass bounds by the subclass, or vice versa. unsigned int count = 0; // ensures stop of approach if point does not converge in reasonable time Point2D confinedPoint = point; Point2D superclassConfinedPoint; do { superclassConfinedPoint = Superclass::ApplyControlPointConstraints( index, confinedPoint ); confinedPoint = this->InternalApplyControlPointConstraints( index, superclassConfinedPoint ); ++count; } while ( (confinedPoint.EuclideanDistanceTo( superclassConfinedPoint ) > mitk::eps) && (count < 32) ); return confinedPoint; } mitk::Point2D mitk::PlanarCross::InternalApplyControlPointConstraints( unsigned int index, const Point2D& point ) { // Apply constraints depending on current interaction state switch ( index ) { case 2: { // Check if 3rd control point is outside of the range (2D area) defined by the first // line (via the first two control points); if it is outside, clip it to the bounds const Point2D& p1 = m_ControlPoints->ElementAt( 0 ); const Point2D& p2 = m_ControlPoints->ElementAt( 1 ); Vector2D n1 = p2 - p1; n1.Normalize(); Vector2D v1 = point - p1; double dotProduct = n1 * v1; Point2D crossPoint = p1 + n1 * dotProduct;; Vector2D crossVector = point - crossPoint; if ( dotProduct < 0.0 ) { // Out-of-bounds on the left: clip point to left boundary return (p1 + crossVector); } else if ( dotProduct > p2.EuclideanDistanceTo( p1 ) ) { // Out-of-bounds on the right: clip point to right boundary return (p2 + crossVector); } else { // Pass back original point return point; } } case 3: { // Constrain 4th control point so that with the 3rd control point it forms // a line orthogonal to the first line const Point2D& p1 = m_ControlPoints->ElementAt( 0 ); const Point2D& p2 = m_ControlPoints->ElementAt( 1 ); const Point2D& p3 = m_ControlPoints->ElementAt( 2 ); // Calculate distance of original point from orthogonal line the corrected // point should lie on to project the point onto this line Vector2D n1 = p2 - p1; n1.Normalize(); Vector2D v1 = point - p3; double dotProduct = n1 * v1; return point - n1 * dotProduct; } default: return point; } } void mitk::PlanarCross::GeneratePolyLine() { m_PolyLines->InsertElement( 0, VertexContainerType::New() ); m_PolyLines->InsertElement( 1, VertexContainerType::New() ); m_PolyLines->ElementAt( 0 )->Reserve( 2 ); if ( this->GetNumberOfControlPoints() > 2) { m_PolyLines->ElementAt( 1 )->Reserve( this->GetNumberOfControlPoints() - 2 ); } for ( unsigned int i = 0; i < this->GetNumberOfControlPoints(); ++i ) { if (i < 2) { m_PolyLines->ElementAt( 0 )->ElementAt( i ) = m_ControlPoints->ElementAt( i ); } if (i > 1) { m_PolyLines->ElementAt( 1 )->ElementAt( i-2 ) = m_ControlPoints->ElementAt( i ); } } } void mitk::PlanarCross::GenerateHelperPolyLine(double /*mmPerDisplayUnit*/, unsigned int /*displayHeight*/) { // Generate helper polyline (orientation line orthogonal to first line) // if the third control point is currently being set if ( this->GetNumberOfControlPoints() != 3 ) { m_HelperPolyLinesToBePainted->SetElement( 0, false ); return; } m_HelperPolyLinesToBePainted->SetElement( 0, true ); // Calculate cross point of first line (p1 to p2) and orthogonal line through // the third control point (p3) const Point2D& p1 = m_ControlPoints->ElementAt( 0 ); const Point2D& p2 = m_ControlPoints->ElementAt( 1 ); const Point2D& p3 = m_ControlPoints->ElementAt( 2 ); Vector2D n1 = p2 - p1; n1.Normalize(); Vector2D v1 = p3 - p1; Point2D crossPoint = p1 + n1 * (n1 * v1); // Draw orthogonal "infinite" line through this cross point Vector2D n2 = p3 - crossPoint; n2.Normalize(); m_HelperPolyLines->ElementAt( 0 )->ElementAt( 0 ) = crossPoint - n2 * 10000.0; m_HelperPolyLines->ElementAt( 0 )->ElementAt( 1 ) = crossPoint + n2 * 10000.0; } void mitk::PlanarCross::EvaluateFeaturesInternal() { // Calculate length of first line const Point3D &p0 = this->GetWorldControlPoint( 0 ); const Point3D &p1 = this->GetWorldControlPoint( 1 ); double l1 = p0.EuclideanDistanceTo( p1 ); // Calculate length of second line double l2 = 0.0; if ( !m_SingleLineMode && (this->GetNumberOfControlPoints() > 3) ) { const Point3D &p2 = this->GetWorldControlPoint( 2 ); const Point3D &p3 = this->GetWorldControlPoint( 3 ); l2 = p2.EuclideanDistanceTo( p3 ); } double longestDiameter; double shortAxisDiameter; if ( l1 > l2 ) { longestDiameter = l1; shortAxisDiameter = l2; } else { longestDiameter = l2; shortAxisDiameter = l1; } this->SetQuantity( FEATURE_ID_LONGESTDIAMETER, longestDiameter ); this->SetQuantity( FEATURE_ID_SHORTAXISDIAMETER, shortAxisDiameter ); } void mitk::PlanarCross::PrintSelf( std::ostream& os, itk::Indent indent) const { Superclass::PrintSelf( os, indent ); }
/*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date: 2010-02-17 23:03:29 +0100 (Mi, 17 Feb 2010) $ Version: $Revision: 18029 $ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "mitkPlanarCross.h" #include "mitkGeometry2D.h" mitk::PlanarCross::PlanarCross() : FEATURE_ID_LONGESTDIAMETER( this->AddFeature( "Longest Diameter", "mm" ) ), FEATURE_ID_SHORTAXISDIAMETER( this->AddFeature( "Short Axis Diameter", "mm" ) ), m_SingleLineMode( false ) { // Cross has two control points at the beginning this->ResetNumberOfControlPoints( 2 ); // Create polyline objects (one for each line of the cross) m_PolyLines->InsertElement( 0, VertexContainerType::New() ); m_PolyLines->InsertElement( 1, VertexContainerType::New() ); // Create helper polyline object (for drawing the orthogonal orientation line) m_HelperPolyLines->InsertElement( 0, VertexContainerType::New()); m_HelperPolyLines->ElementAt( 0 )->Reserve( 2 ); m_HelperPolyLinesToBePainted->InsertElement( 0, false ); } mitk::PlanarCross::~PlanarCross() { } bool mitk::PlanarCross::ResetOnPointSelect() { if ( m_SingleLineMode ) { // In single line mode --> nothing to reset return false; } switch ( m_SelectedControlPoint ) { default: // Nothing selected --> nothing to reset return false; case 0: { // Control point 0 selected: exchange points 0 and 1 Point2D tmpPoint = m_ControlPoints->ElementAt( 0 ); m_ControlPoints->InsertElement( 0, m_ControlPoints->ElementAt( 1 ) ); m_ControlPoints->InsertElement( 1, tmpPoint ); // FALLS THROUGH! } case 1: { // Control point 0 or 1 selected: reset number of control points to two this->ResetNumberOfControlPoints( 2 ); this->SelectControlPoint( 1 ); return true; } case 2: { // Control point 2 selected: replace point 0 with point 3 and point 1 with point 2 m_ControlPoints->InsertElement( 0, m_ControlPoints->ElementAt( 3 ) ); m_ControlPoints->InsertElement( 1, m_ControlPoints->ElementAt( 2 ) ); // Adjust selected control point, reset number of control points to two this->ResetNumberOfControlPoints( 2 ); this->SelectControlPoint( 1 ); return true; } case 3: { // Control point 3 selected: replace point 0 with point 2 and point 1 with point 3 m_ControlPoints->InsertElement( 0, m_ControlPoints->ElementAt( 2 ) ); m_ControlPoints->InsertElement( 1, m_ControlPoints->ElementAt( 3 ) ); // Adjust selected control point, reset number of control points to two this->ResetNumberOfControlPoints( 2 ); this->SelectControlPoint( 1 ); return true; } } } unsigned int mitk::PlanarCross::GetNumberOfFeatures() const { if ( m_SingleLineMode || (this->GetNumberOfControlPoints() < 4) ) { return 1; } else { return 2; } } mitk::Point2D mitk::PlanarCross::ApplyControlPointConstraints( unsigned int index, const Point2D& point ) { // Apply spatial constraints from superclass and from this class until the resulting constrained // point converges. Although not an optimal implementation, this iterative approach // helps to respect both constraints from the superclass and from this class. Without this, // situations may occur where control points are constrained by the superclass, but again // moved out of the superclass bounds by the subclass, or vice versa. unsigned int count = 0; // ensures stop of approach if point does not converge in reasonable time Point2D confinedPoint = point; Point2D superclassConfinedPoint; do { superclassConfinedPoint = Superclass::ApplyControlPointConstraints( index, confinedPoint ); confinedPoint = this->InternalApplyControlPointConstraints( index, superclassConfinedPoint ); ++count; } while ( (confinedPoint.EuclideanDistanceTo( superclassConfinedPoint ) > mitk::eps) && (count < 32) ); return confinedPoint; } mitk::Point2D mitk::PlanarCross::InternalApplyControlPointConstraints( unsigned int index, const Point2D& point ) { // Apply constraints depending on current interaction state switch ( index ) { case 2: { // Check if 3rd control point is outside of the range (2D area) defined by the first // line (via the first two control points); if it is outside, clip it to the bounds const Point2D& p1 = m_ControlPoints->ElementAt( 0 ); const Point2D& p2 = m_ControlPoints->ElementAt( 1 ); Vector2D n1 = p2 - p1; n1.Normalize(); Vector2D v1 = point - p1; double dotProduct = n1 * v1; Point2D crossPoint = p1 + n1 * dotProduct;; Vector2D crossVector = point - crossPoint; if ( dotProduct < 0.0 ) { // Out-of-bounds on the left: clip point to left boundary return (p1 + crossVector); } else if ( dotProduct > p2.EuclideanDistanceTo( p1 ) ) { // Out-of-bounds on the right: clip point to right boundary return (p2 + crossVector); } else { // Pass back original point return point; } } case 3: { // Constrain 4th control point so that with the 3rd control point it forms // a line orthogonal to the first line const Point2D& p1 = m_ControlPoints->ElementAt( 0 ); const Point2D& p2 = m_ControlPoints->ElementAt( 1 ); const Point2D& p3 = m_ControlPoints->ElementAt( 2 ); // Calculate distance of original point from orthogonal line the corrected // point should lie on to project the point onto this line Vector2D n1 = p2 - p1; n1.Normalize(); Vector2D v1 = point - p3; double dotProduct = n1 * v1; return point - n1 * dotProduct; } default: return point; } } void mitk::PlanarCross::GeneratePolyLine() { m_PolyLines->InsertElement( 0, VertexContainerType::New() ); m_PolyLines->InsertElement( 1, VertexContainerType::New() ); m_PolyLines->ElementAt( 0 )->Reserve( 2 ); if ( this->GetNumberOfControlPoints() > 2) { m_PolyLines->ElementAt( 1 )->Reserve( this->GetNumberOfControlPoints() - 2 ); } for ( unsigned int i = 0; i < this->GetNumberOfControlPoints(); ++i ) { if (i < 2) { m_PolyLines->ElementAt( 0 )->ElementAt( i ) = m_ControlPoints->ElementAt( i ); } if (i > 1) { m_PolyLines->ElementAt( 1 )->ElementAt( i-2 ) = m_ControlPoints->ElementAt( i ); } } } void mitk::PlanarCross::GenerateHelperPolyLine(double /*mmPerDisplayUnit*/, unsigned int /*displayHeight*/) { // Generate helper polyline (orientation line orthogonal to first line) // if the third control point is currently being set if ( this->GetNumberOfControlPoints() != 3 ) { m_HelperPolyLinesToBePainted->SetElement( 0, false ); return; } m_HelperPolyLinesToBePainted->SetElement( 0, true ); // Calculate cross point of first line (p1 to p2) and orthogonal line through // the third control point (p3) const Point2D& p1 = m_ControlPoints->ElementAt( 0 ); const Point2D& p2 = m_ControlPoints->ElementAt( 1 ); const Point2D& p3 = m_ControlPoints->ElementAt( 2 ); Vector2D n1 = p2 - p1; n1.Normalize(); Vector2D v1 = p3 - p1; Point2D crossPoint = p1 + n1 * (n1 * v1); Vector2D v2 = crossPoint - p3; if ( v2.GetNorm() < 1.0 ) { // If third point is on the first line, draw orthogonal "infinite" line // through cross point on line Vector2D v0; v0[0] = n1[1]; v0[1] = -n1[0]; m_HelperPolyLines->ElementAt( 0 )->ElementAt( 0 ) = p3 - v0 * 10000.0; m_HelperPolyLines->ElementAt( 0 )->ElementAt( 1 ) = p3 + v0 * 10000.0; } else { // Else, draw orthogonal line starting from third point and crossing the // first line, open-ended only on the other side m_HelperPolyLines->ElementAt( 0 )->ElementAt( 0 ) = p3; m_HelperPolyLines->ElementAt( 0 )->ElementAt( 1 ) = p3 + v2 * 10000.0; } } void mitk::PlanarCross::EvaluateFeaturesInternal() { // Calculate length of first line const Point3D &p0 = this->GetWorldControlPoint( 0 ); const Point3D &p1 = this->GetWorldControlPoint( 1 ); double l1 = p0.EuclideanDistanceTo( p1 ); // Calculate length of second line double l2 = 0.0; if ( !m_SingleLineMode && (this->GetNumberOfControlPoints() > 3) ) { const Point3D &p2 = this->GetWorldControlPoint( 2 ); const Point3D &p3 = this->GetWorldControlPoint( 3 ); l2 = p2.EuclideanDistanceTo( p3 ); } double longestDiameter; double shortAxisDiameter; if ( l1 > l2 ) { longestDiameter = l1; shortAxisDiameter = l2; } else { longestDiameter = l2; shortAxisDiameter = l1; } this->SetQuantity( FEATURE_ID_LONGESTDIAMETER, longestDiameter ); this->SetQuantity( FEATURE_ID_SHORTAXISDIAMETER, shortAxisDiameter ); } void mitk::PlanarCross::PrintSelf( std::ostream& os, itk::Indent indent) const { Superclass::PrintSelf( os, indent ); }
FIX (#3830): Make sure that helper line for PlanarCross is drawn at correct angle; start helper line at control point (open-ended only to one side)
FIX (#3830): Make sure that helper line for PlanarCross is drawn at correct angle; start helper line at control point (open-ended only to one side)
C++
bsd-3-clause
lsanzdiaz/MITK-BiiG,NifTK/MITK,fmilano/mitk,NifTK/MITK,danielknorr/MITK,NifTK/MITK,danielknorr/MITK,lsanzdiaz/MITK-BiiG,nocnokneo/MITK,rfloca/MITK,nocnokneo/MITK,rfloca/MITK,lsanzdiaz/MITK-BiiG,RabadanLab/MITKats,danielknorr/MITK,danielknorr/MITK,danielknorr/MITK,rfloca/MITK,RabadanLab/MITKats,iwegner/MITK,rfloca/MITK,nocnokneo/MITK,MITK/MITK,fmilano/mitk,MITK/MITK,MITK/MITK,RabadanLab/MITKats,MITK/MITK,RabadanLab/MITKats,lsanzdiaz/MITK-BiiG,fmilano/mitk,rfloca/MITK,fmilano/mitk,nocnokneo/MITK,MITK/MITK,iwegner/MITK,RabadanLab/MITKats,iwegner/MITK,rfloca/MITK,danielknorr/MITK,RabadanLab/MITKats,rfloca/MITK,MITK/MITK,nocnokneo/MITK,lsanzdiaz/MITK-BiiG,iwegner/MITK,NifTK/MITK,lsanzdiaz/MITK-BiiG,fmilano/mitk,lsanzdiaz/MITK-BiiG,lsanzdiaz/MITK-BiiG,fmilano/mitk,iwegner/MITK,fmilano/mitk,NifTK/MITK,nocnokneo/MITK,iwegner/MITK,danielknorr/MITK,NifTK/MITK,nocnokneo/MITK
caee21f4dce3e9e282d391faaa3984d4e4406559
chrome/browser/extensions/extension_webrequest_apitest.cc
chrome/browser/extensions/extension_webrequest_apitest.cc
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/command_line.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/browser/extensions/extension_webrequest_api.h" #include "chrome/browser/ui/login/login_prompt.h" #include "chrome/common/chrome_notification_types.h" #include "chrome/common/chrome_switches.h" #include "content/common/notification_registrar.h" #include "content/common/notification_service.h" #include "net/base/mock_host_resolver.h" namespace { class CancelLoginDialog : public NotificationObserver { public: CancelLoginDialog() { registrar_.Add(this, chrome::NOTIFICATION_AUTH_NEEDED, NotificationService::AllSources()); } virtual ~CancelLoginDialog() {} virtual void Observe(int type, const NotificationSource& source, const NotificationDetails& details) { LoginHandler* handler = Details<LoginNotificationDetails>(details).ptr()->handler(); handler->CancelAuth(); } private: NotificationRegistrar registrar_; DISALLOW_COPY_AND_ASSIGN(CancelLoginDialog); }; } // namespace class ExtensionWebRequestApiTest : public ExtensionApiTest { public: virtual void SetUpInProcessBrowserTestFixture() { ExtensionApiTest::SetUpInProcessBrowserTestFixture(); ExtensionWebRequestEventRouter::SetAllowChromeExtensionScheme(); host_resolver()->AddRule("*", "127.0.0.1"); ASSERT_TRUE(StartTestServer()); } }; IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, WebRequestApi) { CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableExperimentalExtensionApis); ASSERT_TRUE(RunExtensionSubtest("webrequest", "test_api.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, WebRequestSimple) { CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableExperimentalExtensionApis); ASSERT_TRUE(RunExtensionSubtest("webrequest", "test_simple.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, WebRequestComplex) { CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableExperimentalExtensionApis); // Needed for the auth tests. CancelLoginDialog login_dialog_helper; ASSERT_TRUE(RunExtensionSubtest("webrequest", "test_complex.html")) << message_; } #if defined(OS_CHROMEOS) || defined(OS_MACOSX) // Times out: http://crbug.com/91715 #define MAYBE_WebRequestBlocking DISABLED_WebRequestBlocking #else #define MAYBE_WebRequestBlocking WebRequestBlocking #endif IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, MAYBE_WebRequestBlocking) { CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableExperimentalExtensionApis); ASSERT_TRUE(RunExtensionSubtest("webrequest", "test_blocking.html")) << message_; }
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/command_line.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/browser/extensions/extension_webrequest_api.h" #include "chrome/browser/ui/login/login_prompt.h" #include "chrome/common/chrome_notification_types.h" #include "chrome/common/chrome_switches.h" #include "content/common/notification_registrar.h" #include "content/common/notification_service.h" #include "net/base/mock_host_resolver.h" namespace { class CancelLoginDialog : public NotificationObserver { public: CancelLoginDialog() { registrar_.Add(this, chrome::NOTIFICATION_AUTH_NEEDED, NotificationService::AllSources()); } virtual ~CancelLoginDialog() {} virtual void Observe(int type, const NotificationSource& source, const NotificationDetails& details) { LoginHandler* handler = Details<LoginNotificationDetails>(details).ptr()->handler(); handler->CancelAuth(); } private: NotificationRegistrar registrar_; DISALLOW_COPY_AND_ASSIGN(CancelLoginDialog); }; } // namespace class ExtensionWebRequestApiTest : public ExtensionApiTest { public: virtual void SetUpInProcessBrowserTestFixture() { ExtensionApiTest::SetUpInProcessBrowserTestFixture(); ExtensionWebRequestEventRouter::SetAllowChromeExtensionScheme(); host_resolver()->AddRule("*", "127.0.0.1"); ASSERT_TRUE(StartTestServer()); } }; IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, WebRequestApi) { CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableExperimentalExtensionApis); ASSERT_TRUE(RunExtensionSubtest("webrequest", "test_api.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, WebRequestSimple) { CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableExperimentalExtensionApis); ASSERT_TRUE(RunExtensionSubtest("webrequest", "test_simple.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, WebRequestComplex) { CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableExperimentalExtensionApis); // Needed for the auth tests. CancelLoginDialog login_dialog_helper; ASSERT_TRUE(RunExtensionSubtest("webrequest", "test_complex.html")) << message_; } #if defined(OS_CHROMEOS) || defined(OS_MACOSX) || defined(OS_LINUX) // Times out: http://crbug.com/91715 #define MAYBE_WebRequestBlocking DISABLED_WebRequestBlocking #else #define MAYBE_WebRequestBlocking WebRequestBlocking #endif IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, MAYBE_WebRequestBlocking) { CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableExperimentalExtensionApis); ASSERT_TRUE(RunExtensionSubtest("webrequest", "test_blocking.html")) << message_; }
Disable ExtensionWebApiTest.WebRequestBlocking on Linux, it's consistently failing on two bots.
Disable ExtensionWebApiTest.WebRequestBlocking on Linux, it's consistently failing on two bots. BUG=91715 TEST= [email protected], [email protected] Review URL: http://codereview.chromium.org/7618008 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@96365 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
Jonekee/chromium.src,ChromiumWebApps/chromium,axinging/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,chuan9/chromium-crosswalk,keishi/chromium,Just-D/chromium-1,Pluto-tv/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,hgl888/chromium-crosswalk-efl,junmin-zhu/chromium-rivertrail,jaruba/chromium.src,ChromiumWebApps/chromium,dednal/chromium.src,mogoweb/chromium-crosswalk,hujiajie/pa-chromium,Fireblend/chromium-crosswalk,hujiajie/pa-chromium,keishi/chromium,ltilve/chromium,Chilledheart/chromium,TheTypoMaster/chromium-crosswalk,ltilve/chromium,littlstar/chromium.src,patrickm/chromium.src,PeterWangIntel/chromium-crosswalk,markYoungH/chromium.src,bright-sparks/chromium-spacewalk,Jonekee/chromium.src,dednal/chromium.src,zcbenz/cefode-chromium,timopulkkinen/BubbleFish,junmin-zhu/chromium-rivertrail,ChromiumWebApps/chromium,pozdnyakov/chromium-crosswalk,hgl888/chromium-crosswalk-efl,dednal/chromium.src,mohamed--abdel-maksoud/chromium.src,keishi/chromium,mogoweb/chromium-crosswalk,ltilve/chromium,Chilledheart/chromium,nacl-webkit/chrome_deps,rogerwang/chromium,markYoungH/chromium.src,dushu1203/chromium.src,ondra-novak/chromium.src,robclark/chromium,M4sse/chromium.src,krieger-od/nwjs_chromium.src,chuan9/chromium-crosswalk,Jonekee/chromium.src,axinging/chromium-crosswalk,Just-D/chromium-1,ltilve/chromium,hgl888/chromium-crosswalk-efl,jaruba/chromium.src,chuan9/chromium-crosswalk,robclark/chromium,Chilledheart/chromium,nacl-webkit/chrome_deps,rogerwang/chromium,keishi/chromium,pozdnyakov/chromium-crosswalk,dushu1203/chromium.src,Fireblend/chromium-crosswalk,littlstar/chromium.src,hgl888/chromium-crosswalk,Jonekee/chromium.src,rogerwang/chromium,anirudhSK/chromium,timopulkkinen/BubbleFish,rogerwang/chromium,zcbenz/cefode-chromium,dednal/chromium.src,crosswalk-project/chromium-crosswalk-efl,crosswalk-project/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,patrickm/chromium.src,dednal/chromium.src,Just-D/chromium-1,hgl888/chromium-crosswalk,axinging/chromium-crosswalk,ChromiumWebApps/chromium,Chilledheart/chromium,nacl-webkit/chrome_deps,Just-D/chromium-1,nacl-webkit/chrome_deps,anirudhSK/chromium,krieger-od/nwjs_chromium.src,ChromiumWebApps/chromium,hgl888/chromium-crosswalk,dushu1203/chromium.src,bright-sparks/chromium-spacewalk,markYoungH/chromium.src,dushu1203/chromium.src,junmin-zhu/chromium-rivertrail,ChromiumWebApps/chromium,Fireblend/chromium-crosswalk,zcbenz/cefode-chromium,Pluto-tv/chromium-crosswalk,krieger-od/nwjs_chromium.src,axinging/chromium-crosswalk,rogerwang/chromium,pozdnyakov/chromium-crosswalk,littlstar/chromium.src,pozdnyakov/chromium-crosswalk,littlstar/chromium.src,PeterWangIntel/chromium-crosswalk,dushu1203/chromium.src,dushu1203/chromium.src,dushu1203/chromium.src,pozdnyakov/chromium-crosswalk,krieger-od/nwjs_chromium.src,pozdnyakov/chromium-crosswalk,dushu1203/chromium.src,rogerwang/chromium,Fireblend/chromium-crosswalk,krieger-od/nwjs_chromium.src,mogoweb/chromium-crosswalk,robclark/chromium,rogerwang/chromium,ondra-novak/chromium.src,hujiajie/pa-chromium,hgl888/chromium-crosswalk-efl,bright-sparks/chromium-spacewalk,fujunwei/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,fujunwei/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk,littlstar/chromium.src,ltilve/chromium,bright-sparks/chromium-spacewalk,dednal/chromium.src,chuan9/chromium-crosswalk,anirudhSK/chromium,ltilve/chromium,Jonekee/chromium.src,hujiajie/pa-chromium,jaruba/chromium.src,anirudhSK/chromium,fujunwei/chromium-crosswalk,ChromiumWebApps/chromium,Just-D/chromium-1,Pluto-tv/chromium-crosswalk,anirudhSK/chromium,jaruba/chromium.src,jaruba/chromium.src,axinging/chromium-crosswalk,nacl-webkit/chrome_deps,keishi/chromium,hgl888/chromium-crosswalk-efl,mogoweb/chromium-crosswalk,ChromiumWebApps/chromium,markYoungH/chromium.src,crosswalk-project/chromium-crosswalk-efl,krieger-od/nwjs_chromium.src,hgl888/chromium-crosswalk-efl,pozdnyakov/chromium-crosswalk,dednal/chromium.src,Fireblend/chromium-crosswalk,bright-sparks/chromium-spacewalk,keishi/chromium,ltilve/chromium,Jonekee/chromium.src,timopulkkinen/BubbleFish,zcbenz/cefode-chromium,mohamed--abdel-maksoud/chromium.src,markYoungH/chromium.src,markYoungH/chromium.src,anirudhSK/chromium,crosswalk-project/chromium-crosswalk-efl,hgl888/chromium-crosswalk,hujiajie/pa-chromium,M4sse/chromium.src,robclark/chromium,pozdnyakov/chromium-crosswalk,robclark/chromium,chuan9/chromium-crosswalk,anirudhSK/chromium,hgl888/chromium-crosswalk,jaruba/chromium.src,Chilledheart/chromium,Fireblend/chromium-crosswalk,zcbenz/cefode-chromium,krieger-od/nwjs_chromium.src,fujunwei/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,mohamed--abdel-maksoud/chromium.src,jaruba/chromium.src,patrickm/chromium.src,dushu1203/chromium.src,patrickm/chromium.src,krieger-od/nwjs_chromium.src,M4sse/chromium.src,Pluto-tv/chromium-crosswalk,markYoungH/chromium.src,TheTypoMaster/chromium-crosswalk,ChromiumWebApps/chromium,PeterWangIntel/chromium-crosswalk,junmin-zhu/chromium-rivertrail,krieger-od/nwjs_chromium.src,timopulkkinen/BubbleFish,nacl-webkit/chrome_deps,TheTypoMaster/chromium-crosswalk,zcbenz/cefode-chromium,Just-D/chromium-1,markYoungH/chromium.src,timopulkkinen/BubbleFish,zcbenz/cefode-chromium,hgl888/chromium-crosswalk,M4sse/chromium.src,Chilledheart/chromium,robclark/chromium,keishi/chromium,Pluto-tv/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,nacl-webkit/chrome_deps,TheTypoMaster/chromium-crosswalk,fujunwei/chromium-crosswalk,anirudhSK/chromium,hgl888/chromium-crosswalk,rogerwang/chromium,Chilledheart/chromium,axinging/chromium-crosswalk,hgl888/chromium-crosswalk-efl,Fireblend/chromium-crosswalk,fujunwei/chromium-crosswalk,robclark/chromium,timopulkkinen/BubbleFish,zcbenz/cefode-chromium,junmin-zhu/chromium-rivertrail,PeterWangIntel/chromium-crosswalk,anirudhSK/chromium,TheTypoMaster/chromium-crosswalk,hujiajie/pa-chromium,dushu1203/chromium.src,dednal/chromium.src,axinging/chromium-crosswalk,ondra-novak/chromium.src,Pluto-tv/chromium-crosswalk,markYoungH/chromium.src,M4sse/chromium.src,ChromiumWebApps/chromium,rogerwang/chromium,nacl-webkit/chrome_deps,bright-sparks/chromium-spacewalk,anirudhSK/chromium,junmin-zhu/chromium-rivertrail,hujiajie/pa-chromium,PeterWangIntel/chromium-crosswalk,ondra-novak/chromium.src,jaruba/chromium.src,axinging/chromium-crosswalk,zcbenz/cefode-chromium,TheTypoMaster/chromium-crosswalk,M4sse/chromium.src,Just-D/chromium-1,hgl888/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,PeterWangIntel/chromium-crosswalk,Jonekee/chromium.src,fujunwei/chromium-crosswalk,littlstar/chromium.src,pozdnyakov/chromium-crosswalk,hujiajie/pa-chromium,Chilledheart/chromium,M4sse/chromium.src,mogoweb/chromium-crosswalk,hujiajie/pa-chromium,mogoweb/chromium-crosswalk,patrickm/chromium.src,littlstar/chromium.src,anirudhSK/chromium,mogoweb/chromium-crosswalk,ondra-novak/chromium.src,chuan9/chromium-crosswalk,patrickm/chromium.src,patrickm/chromium.src,Fireblend/chromium-crosswalk,Just-D/chromium-1,Jonekee/chromium.src,timopulkkinen/BubbleFish,zcbenz/cefode-chromium,pozdnyakov/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,Fireblend/chromium-crosswalk,jaruba/chromium.src,hgl888/chromium-crosswalk,nacl-webkit/chrome_deps,PeterWangIntel/chromium-crosswalk,anirudhSK/chromium,chuan9/chromium-crosswalk,markYoungH/chromium.src,M4sse/chromium.src,bright-sparks/chromium-spacewalk,ltilve/chromium,jaruba/chromium.src,ChromiumWebApps/chromium,dednal/chromium.src,axinging/chromium-crosswalk,M4sse/chromium.src,junmin-zhu/chromium-rivertrail,dednal/chromium.src,Jonekee/chromium.src,Pluto-tv/chromium-crosswalk,markYoungH/chromium.src,junmin-zhu/chromium-rivertrail,mogoweb/chromium-crosswalk,axinging/chromium-crosswalk,timopulkkinen/BubbleFish,crosswalk-project/chromium-crosswalk-efl,nacl-webkit/chrome_deps,M4sse/chromium.src,dednal/chromium.src,ondra-novak/chromium.src,Pluto-tv/chromium-crosswalk,keishi/chromium,hujiajie/pa-chromium,krieger-od/nwjs_chromium.src,ondra-novak/chromium.src,crosswalk-project/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,axinging/chromium-crosswalk,ChromiumWebApps/chromium,jaruba/chromium.src,keishi/chromium,rogerwang/chromium,junmin-zhu/chromium-rivertrail,timopulkkinen/BubbleFish,mohamed--abdel-maksoud/chromium.src,mohamed--abdel-maksoud/chromium.src,mogoweb/chromium-crosswalk,ondra-novak/chromium.src,PeterWangIntel/chromium-crosswalk,keishi/chromium,mohamed--abdel-maksoud/chromium.src,M4sse/chromium.src,junmin-zhu/chromium-rivertrail,fujunwei/chromium-crosswalk,krieger-od/nwjs_chromium.src,timopulkkinen/BubbleFish,chuan9/chromium-crosswalk,hujiajie/pa-chromium,fujunwei/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,bright-sparks/chromium-spacewalk,chuan9/chromium-crosswalk,Jonekee/chromium.src,dushu1203/chromium.src,timopulkkinen/BubbleFish,ondra-novak/chromium.src,Jonekee/chromium.src,mogoweb/chromium-crosswalk,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk-efl,robclark/chromium,Just-D/chromium-1,robclark/chromium,pozdnyakov/chromium-crosswalk,ltilve/chromium,littlstar/chromium.src,TheTypoMaster/chromium-crosswalk,robclark/chromium,keishi/chromium,patrickm/chromium.src,Chilledheart/chromium,zcbenz/cefode-chromium,junmin-zhu/chromium-rivertrail,bright-sparks/chromium-spacewalk,nacl-webkit/chrome_deps,patrickm/chromium.src,hgl888/chromium-crosswalk-efl
bcdf3ed41298316d068e6aa4e24eb2781bd92bc4
ppapi/native_client/src/shared/ppapi_proxy/plugin_ppb_audio.cc
ppapi/native_client/src/shared/ppapi_proxy/plugin_ppb_audio.cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "native_client/src/shared/ppapi_proxy/plugin_ppb_audio.h" #include <pthread.h> #include <stdio.h> #include <string.h> #include <sys/errno.h> #include <sys/mman.h> #include "native_client/src/include/nacl_scoped_ptr.h" #include "native_client/src/include/portability.h" #include "native_client/src/shared/ppapi_proxy/plugin_globals.h" #include "native_client/src/shared/ppapi_proxy/plugin_resource.h" #include "native_client/src/shared/ppapi_proxy/utility.h" #include "native_client/src/shared/srpc/nacl_srpc.h" #include "ppapi/c/ppb_audio.h" #include "ppapi/c/ppb_audio_config.h" #include "ppapi/cpp/module_impl.h" #include "srpcgen/ppb_rpc.h" #include "srpcgen/ppp_rpc.h" namespace ppapi_proxy { namespace { // round size up to next 64k size_t ceil64k(size_t n) { return (n + 0xFFFF) & (~0xFFFF); } } // namespace PluginAudio::PluginAudio() : resource_(kInvalidResourceId), socket_(-1), shm_(-1), shm_size_(0), shm_buffer_(NULL), state_(AUDIO_INCOMPLETE), thread_id_(), thread_active_(false), user_callback_(NULL), user_data_(NULL) { DebugPrintf("PluginAudio::PluginAudio\n"); } PluginAudio::~PluginAudio() { DebugPrintf("PluginAudio::~PluginAudio\n"); // Ensure audio thread is not active. if (resource_ != kInvalidResourceId) GetInterface()->StopPlayback(resource_); // Unmap the shared memory buffer, if present. if (shm_buffer_) { munmap(shm_buffer_, ceil64k(shm_size_)); shm_buffer_ = NULL; shm_size_ = 0; } // Close the handles. if (shm_ != -1) { close(shm_); shm_ = -1; } if (socket_ != -1) { close(socket_); socket_ = -1; } } bool PluginAudio::InitFromBrowserResource(PP_Resource resource) { DebugPrintf("PluginAudio::InitFromBrowserResource: resource=%"NACL_PRId32"\n", resource); resource_ = resource; return true; } void PluginAudio::AudioThread(void* self) { PluginAudio* audio = static_cast<PluginAudio*>(self); DebugPrintf("PluginAudio::AudioThread: self=%p\n", self); while (true) { int32_t sync_value; // block on socket read ssize_t r = read(audio->socket_, &sync_value, sizeof(sync_value)); // StopPlayback() will send a value of -1 over the sync_socket if ((sizeof(sync_value) != r) || (-1 == sync_value)) break; // invoke user callback, get next buffer of audio data audio->user_callback_(audio->shm_buffer_, audio->shm_size_, audio->user_data_); } } void PluginAudio::StreamCreated(NaClSrpcImcDescType socket, NaClSrpcImcDescType shm, size_t shm_size) { DebugPrintf("PluginAudio::StreamCreated: shm=%"NACL_PRIu32"" " shm_size=%"NACL_PRIuS"\n", shm, shm_size); socket_ = socket; shm_ = shm; shm_size_ = shm_size; shm_buffer_ = mmap(NULL, ceil64k(shm_size), PROT_READ | PROT_WRITE, MAP_SHARED, shm, 0); if (MAP_FAILED != shm_buffer_) { if (state() == AUDIO_PENDING) { StartAudioThread(); } else { set_state(AUDIO_READY); } } else { shm_buffer_ = NULL; } } bool PluginAudio::StartAudioThread() { // clear contents of shm buffer before spinning up audio thread DebugPrintf("PluginAudio::StartAudioThread\n"); memset(shm_buffer_, 0, shm_size_); const struct PP_ThreadFunctions* thread_funcs = GetThreadCreator(); if (NULL == thread_funcs->thread_create || NULL == thread_funcs->thread_join) { return false; } int ret = thread_funcs->thread_create(&thread_id_, AudioThread, this); if (0 == ret) { thread_active_ = true; set_state(AUDIO_PLAYING); return true; } return false; } bool PluginAudio::StopAudioThread() { DebugPrintf("PluginAudio::StopAudioThread\n"); if (thread_active_) { int ret = GetThreadCreator()->thread_join(thread_id_); if (0 == ret) { thread_active_ = false; set_state(AUDIO_READY); return true; } } return false; } // Start of untrusted PPB_Audio functions namespace { PP_Resource Create(PP_Instance instance, PP_Resource config, PPB_Audio_Callback user_callback, void* user_data) { DebugPrintf("PPB_Audio::Create: instance=%"NACL_PRId32" config=%"NACL_PRId32 " user_callback=%p user_data=%p\n", instance, config, user_callback, user_data); PP_Resource audio_resource; // Proxy to browser Create, get audio PP_Resource NaClSrpcError srpc_result = PpbAudioRpcClient::PPB_Audio_Create( GetMainSrpcChannel(), instance, config, &audio_resource); DebugPrintf("PPB_Audio::Create: %s\n", NaClSrpcErrorString(srpc_result)); if (NACL_SRPC_RESULT_OK != srpc_result) { return kInvalidResourceId; } if (kInvalidResourceId == audio_resource) { return kInvalidResourceId; } scoped_refptr<PluginAudio> audio = PluginResource::AdoptAs<PluginAudio>(audio_resource); if (audio.get()) { audio->set_callback(user_callback, user_data); return audio_resource; } return kInvalidResourceId; } PP_Bool IsAudio(PP_Resource resource) { int32_t success; DebugPrintf("PPB_Audio::IsAudio: resource=%"NACL_PRId32"\n", resource); NaClSrpcError srpc_result = PpbAudioRpcClient::PPB_Audio_IsAudio( GetMainSrpcChannel(), resource, &success); DebugPrintf("PPB_Audio::IsAudio: %s\n", NaClSrpcErrorString(srpc_result)); if (NACL_SRPC_RESULT_OK != srpc_result) { return PP_FALSE; } return PP_FromBool(success); } PP_Resource GetCurrentConfig(PP_Resource audio) { DebugPrintf("PPB_Audio::GetCurrentConfig: audio=%"NACL_PRId32"\n", audio); PP_Resource config_resource; NaClSrpcError srpc_result = PpbAudioRpcClient::PPB_Audio_GetCurrentConfig( GetMainSrpcChannel(), audio, &config_resource); DebugPrintf("PPB_Audio::GetCurrentConfig: %s\n", NaClSrpcErrorString(srpc_result)); if (NACL_SRPC_RESULT_OK != srpc_result) { return kInvalidResourceId; } return config_resource; } PP_Bool StartPlayback(PP_Resource audio_resource) { DebugPrintf("PPB_Audio::StartPlayback: audio_resource=%"NACL_PRId32"\n", audio_resource); scoped_refptr<PluginAudio> audio = PluginResource::GetAs<PluginAudio>(audio_resource); if (NULL == audio.get()) { return PP_FALSE; } if (audio->state() == AUDIO_INCOMPLETE) { audio->set_state(AUDIO_PENDING); } if (audio->state() == AUDIO_READY) { if (!audio->StartAudioThread()) { return PP_FALSE; } } int32_t success; NaClSrpcError srpc_result = PpbAudioRpcClient::PPB_Audio_StartPlayback( GetMainSrpcChannel(), audio_resource, &success); DebugPrintf("PPB_Audio::StartPlayback: %s\n", NaClSrpcErrorString(srpc_result)); if (NACL_SRPC_RESULT_OK != srpc_result || !success) { return PP_FALSE; } return PP_TRUE; } PP_Bool StopPlayback(PP_Resource audio_resource) { DebugPrintf("PPB_Audio::StopPlayback: audio_resource=%"NACL_PRId32"\n", audio_resource); scoped_refptr<PluginAudio> audio = PluginResource::GetAs<PluginAudio>(audio_resource); if (NULL == audio.get()) { return PP_FALSE; } if (audio->state() == AUDIO_PENDING) { // audio is pending to start, but StreamCreated() hasn't occurred yet... audio->set_state(AUDIO_INCOMPLETE); } // RPC to trusted side int32_t success; NaClSrpcError srpc_result = PpbAudioRpcClient::PPB_Audio_StopPlayback( GetMainSrpcChannel(), audio_resource, &success); DebugPrintf("PPB_Audio::StopPlayback: %s\n", NaClSrpcErrorString(srpc_result)); if (NACL_SRPC_RESULT_OK != srpc_result) { return PP_FALSE; } if (audio->state() != AUDIO_PLAYING) { return PP_FromBool(success); } // stop and join the audio thread return PP_FromBool(audio->StopAudioThread()); } } // namespace const PPB_Audio* PluginAudio::GetInterface() { DebugPrintf("PluginAudio::GetInterface\n"); static const PPB_Audio audio_interface = { Create, IsAudio, GetCurrentConfig, StartPlayback, StopPlayback, }; return &audio_interface; } } // namespace ppapi_proxy using ppapi_proxy::DebugPrintf; // PppAudioRpcServer::PPP_Audio_StreamCreated() must be in global // namespace. This function receives handles for the socket and shared // memory, provided by the trusted audio implementation. void PppAudioRpcServer::PPP_Audio_StreamCreated( NaClSrpcRpc* rpc, NaClSrpcClosure* done, PP_Resource audio_resource, NaClSrpcImcDescType shm, int32_t shm_size, NaClSrpcImcDescType sync_socket) { NaClSrpcClosureRunner runner(done); rpc->result = NACL_SRPC_RESULT_APP_ERROR; DebugPrintf("PPP_Audio::StreamCreated: audio_resource=%"NACL_PRId32 " shm=%"NACL_PRIx32" shm_size=%"NACL_PRIuS " sync_socket=%"NACL_PRIx32"\n", audio_resource, shm, shm_size, sync_socket); scoped_refptr<ppapi_proxy::PluginAudio> audio = ppapi_proxy::PluginResource:: GetAs<ppapi_proxy::PluginAudio>(audio_resource); if (NULL == audio.get()) { // Ignore if no audio_resource -> audio_instance mapping exists, // the app may have shutdown audio before StreamCreated() invoked. rpc->result = NACL_SRPC_RESULT_OK; return; } audio->StreamCreated(sync_socket, shm, shm_size); rpc->result = NACL_SRPC_RESULT_OK; }
// 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 "native_client/src/shared/ppapi_proxy/plugin_ppb_audio.h" #include <pthread.h> #include <stdio.h> #include <string.h> #include <sys/errno.h> #include <sys/mman.h> #include "native_client/src/include/nacl_scoped_ptr.h" #include "native_client/src/include/portability.h" #include "native_client/src/shared/ppapi_proxy/plugin_globals.h" #include "native_client/src/shared/ppapi_proxy/plugin_resource.h" #include "native_client/src/shared/ppapi_proxy/utility.h" #include "native_client/src/shared/srpc/nacl_srpc.h" #include "ppapi/c/ppb_audio.h" #include "ppapi/c/ppb_audio_config.h" #include "ppapi/cpp/module_impl.h" #include "srpcgen/ppb_rpc.h" #include "srpcgen/ppp_rpc.h" namespace ppapi_proxy { namespace { // Round size up to next 64k; required for NaCl's version of mmap(). size_t ceil64k(size_t n) { return (n + 0xFFFF) & (~0xFFFF); } // The following two functions (TotalSharedMemorySizeInBytes, // SetActualDataSizeInBytes) are copied & similar to audio_util.cc. uint32_t TotalSharedMemorySizeInBytes(size_t packet_size) { // Need to reserve extra 4 bytes for size of data. return ceil64k(packet_size + sizeof(uint32_t)); } void SetActualDataSizeInBytes(void* audio_buffer, uint32_t buffer_size_in_bytes, uint32_t actual_size_in_bytes) { char* end = static_cast<char*>(audio_buffer) + buffer_size_in_bytes; DCHECK(0 == (reinterpret_cast<size_t>(end) & 3)); volatile uint32_t* end32 = reinterpret_cast<volatile uint32_t*>(end); // Set actual data size at the end of the buffer. __sync_synchronize(); *end32 = actual_size_in_bytes; } } // namespace PluginAudio::PluginAudio() : resource_(kInvalidResourceId), socket_(-1), shm_(-1), shm_size_(0), shm_buffer_(NULL), state_(AUDIO_INCOMPLETE), thread_id_(), thread_active_(false), user_callback_(NULL), user_data_(NULL) { DebugPrintf("PluginAudio::PluginAudio\n"); } PluginAudio::~PluginAudio() { DebugPrintf("PluginAudio::~PluginAudio\n"); // Ensure audio thread is not active. if (resource_ != kInvalidResourceId) GetInterface()->StopPlayback(resource_); // Unmap the shared memory buffer, if present. if (shm_buffer_) { munmap(shm_buffer_, TotalSharedMemorySizeInBytes(shm_size_)); shm_buffer_ = NULL; shm_size_ = 0; } // Close the handles. if (shm_ != -1) { close(shm_); shm_ = -1; } if (socket_ != -1) { close(socket_); socket_ = -1; } } bool PluginAudio::InitFromBrowserResource(PP_Resource resource) { DebugPrintf("PluginAudio::InitFromBrowserResource: resource=%"NACL_PRId32"\n", resource); resource_ = resource; return true; } void PluginAudio::AudioThread(void* self) { PluginAudio* audio = static_cast<PluginAudio*>(self); DebugPrintf("PluginAudio::AudioThread: self=%p\n", self); while (true) { int32_t sync_value; // Block on socket read. ssize_t r = read(audio->socket_, &sync_value, sizeof(sync_value)); // StopPlayback() will send a value of -1 over the sync_socket. if ((sizeof(sync_value) != r) || (-1 == sync_value)) break; // Invoke user callback, get next buffer of audio data. audio->user_callback_(audio->shm_buffer_, audio->shm_size_, audio->user_data_); // Signal audio backend by writing buffer length at end of buffer. // (Note: NaCl applications will always write the entire buffer.) SetActualDataSizeInBytes(audio->shm_buffer_, audio->shm_size_, audio->shm_size_); } } void PluginAudio::StreamCreated(NaClSrpcImcDescType socket, NaClSrpcImcDescType shm, size_t shm_size) { DebugPrintf("PluginAudio::StreamCreated: shm=%"NACL_PRIu32"" " shm_size=%"NACL_PRIuS"\n", shm, shm_size); socket_ = socket; shm_ = shm; shm_size_ = shm_size; shm_buffer_ = mmap(NULL, TotalSharedMemorySizeInBytes(shm_size), PROT_READ | PROT_WRITE, MAP_SHARED, shm, 0); if (MAP_FAILED != shm_buffer_) { if (state() == AUDIO_PENDING) { StartAudioThread(); } else { set_state(AUDIO_READY); } } else { shm_buffer_ = NULL; } } bool PluginAudio::StartAudioThread() { // clear contents of shm buffer before spinning up audio thread DebugPrintf("PluginAudio::StartAudioThread\n"); memset(shm_buffer_, 0, shm_size_); const struct PP_ThreadFunctions* thread_funcs = GetThreadCreator(); if (NULL == thread_funcs->thread_create || NULL == thread_funcs->thread_join) { return false; } int ret = thread_funcs->thread_create(&thread_id_, AudioThread, this); if (0 == ret) { thread_active_ = true; set_state(AUDIO_PLAYING); return true; } return false; } bool PluginAudio::StopAudioThread() { DebugPrintf("PluginAudio::StopAudioThread\n"); if (thread_active_) { int ret = GetThreadCreator()->thread_join(thread_id_); if (0 == ret) { thread_active_ = false; set_state(AUDIO_READY); return true; } } return false; } // Start of untrusted PPB_Audio functions namespace { PP_Resource Create(PP_Instance instance, PP_Resource config, PPB_Audio_Callback user_callback, void* user_data) { DebugPrintf("PPB_Audio::Create: instance=%"NACL_PRId32" config=%"NACL_PRId32 " user_callback=%p user_data=%p\n", instance, config, user_callback, user_data); PP_Resource audio_resource; // Proxy to browser Create, get audio PP_Resource NaClSrpcError srpc_result = PpbAudioRpcClient::PPB_Audio_Create( GetMainSrpcChannel(), instance, config, &audio_resource); DebugPrintf("PPB_Audio::Create: %s\n", NaClSrpcErrorString(srpc_result)); if (NACL_SRPC_RESULT_OK != srpc_result) { return kInvalidResourceId; } if (kInvalidResourceId == audio_resource) { return kInvalidResourceId; } scoped_refptr<PluginAudio> audio = PluginResource::AdoptAs<PluginAudio>(audio_resource); if (audio.get()) { audio->set_callback(user_callback, user_data); return audio_resource; } return kInvalidResourceId; } PP_Bool IsAudio(PP_Resource resource) { int32_t success; DebugPrintf("PPB_Audio::IsAudio: resource=%"NACL_PRId32"\n", resource); NaClSrpcError srpc_result = PpbAudioRpcClient::PPB_Audio_IsAudio( GetMainSrpcChannel(), resource, &success); DebugPrintf("PPB_Audio::IsAudio: %s\n", NaClSrpcErrorString(srpc_result)); if (NACL_SRPC_RESULT_OK != srpc_result) { return PP_FALSE; } return PP_FromBool(success); } PP_Resource GetCurrentConfig(PP_Resource audio) { DebugPrintf("PPB_Audio::GetCurrentConfig: audio=%"NACL_PRId32"\n", audio); PP_Resource config_resource; NaClSrpcError srpc_result = PpbAudioRpcClient::PPB_Audio_GetCurrentConfig( GetMainSrpcChannel(), audio, &config_resource); DebugPrintf("PPB_Audio::GetCurrentConfig: %s\n", NaClSrpcErrorString(srpc_result)); if (NACL_SRPC_RESULT_OK != srpc_result) { return kInvalidResourceId; } return config_resource; } PP_Bool StartPlayback(PP_Resource audio_resource) { DebugPrintf("PPB_Audio::StartPlayback: audio_resource=%"NACL_PRId32"\n", audio_resource); scoped_refptr<PluginAudio> audio = PluginResource::GetAs<PluginAudio>(audio_resource); if (NULL == audio.get()) { return PP_FALSE; } if (audio->state() == AUDIO_INCOMPLETE) { audio->set_state(AUDIO_PENDING); } if (audio->state() == AUDIO_READY) { if (!audio->StartAudioThread()) { return PP_FALSE; } } int32_t success; NaClSrpcError srpc_result = PpbAudioRpcClient::PPB_Audio_StartPlayback( GetMainSrpcChannel(), audio_resource, &success); DebugPrintf("PPB_Audio::StartPlayback: %s\n", NaClSrpcErrorString(srpc_result)); if (NACL_SRPC_RESULT_OK != srpc_result || !success) { return PP_FALSE; } return PP_TRUE; } PP_Bool StopPlayback(PP_Resource audio_resource) { DebugPrintf("PPB_Audio::StopPlayback: audio_resource=%"NACL_PRId32"\n", audio_resource); scoped_refptr<PluginAudio> audio = PluginResource::GetAs<PluginAudio>(audio_resource); if (NULL == audio.get()) { return PP_FALSE; } if (audio->state() == AUDIO_PENDING) { // audio is pending to start, but StreamCreated() hasn't occurred yet... audio->set_state(AUDIO_INCOMPLETE); } // RPC to trusted side int32_t success; NaClSrpcError srpc_result = PpbAudioRpcClient::PPB_Audio_StopPlayback( GetMainSrpcChannel(), audio_resource, &success); DebugPrintf("PPB_Audio::StopPlayback: %s\n", NaClSrpcErrorString(srpc_result)); if (NACL_SRPC_RESULT_OK != srpc_result) { return PP_FALSE; } if (audio->state() != AUDIO_PLAYING) { return PP_FromBool(success); } // stop and join the audio thread return PP_FromBool(audio->StopAudioThread()); } } // namespace const PPB_Audio* PluginAudio::GetInterface() { DebugPrintf("PluginAudio::GetInterface\n"); static const PPB_Audio audio_interface = { Create, IsAudio, GetCurrentConfig, StartPlayback, StopPlayback, }; return &audio_interface; } } // namespace ppapi_proxy using ppapi_proxy::DebugPrintf; // PppAudioRpcServer::PPP_Audio_StreamCreated() must be in global // namespace. This function receives handles for the socket and shared // memory, provided by the trusted audio implementation. void PppAudioRpcServer::PPP_Audio_StreamCreated( NaClSrpcRpc* rpc, NaClSrpcClosure* done, PP_Resource audio_resource, NaClSrpcImcDescType shm, int32_t shm_size, NaClSrpcImcDescType sync_socket) { NaClSrpcClosureRunner runner(done); rpc->result = NACL_SRPC_RESULT_APP_ERROR; DebugPrintf("PPP_Audio::StreamCreated: audio_resource=%"NACL_PRId32 " shm=%"NACL_PRIx32" shm_size=%"NACL_PRIuS " sync_socket=%"NACL_PRIx32"\n", audio_resource, shm, shm_size, sync_socket); scoped_refptr<ppapi_proxy::PluginAudio> audio = ppapi_proxy::PluginResource:: GetAs<ppapi_proxy::PluginAudio>(audio_resource); if (NULL == audio.get()) { // Ignore if no audio_resource -> audio_instance mapping exists, // the app may have shutdown audio before StreamCreated() invoked. rpc->result = NACL_SRPC_RESULT_OK; return; } audio->StreamCreated(sync_socket, shm, shm_size); rpc->result = NACL_SRPC_RESULT_OK; }
Add audio buffer size notification to NaCl proxy. BUG=http://code.google.com/p/chromium/issues/detail?id=120837 TEST=variuos nacl audio samples
Add audio buffer size notification to NaCl proxy. BUG=http://code.google.com/p/chromium/issues/detail?id=120837 TEST=variuos nacl audio samples Review URL: http://codereview.chromium.org/10165016 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@133502 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
adobe/chromium,ropik/chromium,adobe/chromium,yitian134/chromium,adobe/chromium,yitian134/chromium,ropik/chromium,yitian134/chromium,yitian134/chromium,ropik/chromium,yitian134/chromium,ropik/chromium,ropik/chromium,adobe/chromium,adobe/chromium,adobe/chromium,adobe/chromium,yitian134/chromium,ropik/chromium,adobe/chromium,yitian134/chromium,ropik/chromium,yitian134/chromium,ropik/chromium,adobe/chromium,adobe/chromium,ropik/chromium,yitian134/chromium,yitian134/chromium,adobe/chromium
1b1c64805fc222038a4d3c8d0e0f6ac049020998
xml11/xml11_associativearray.hpp
xml11/xml11_associativearray.hpp
#pragma once namespace { template<class T> inline auto to_lower(T s) -> std::string { std::transform(s.begin(), s.end(), s.begin(), ::tolower); return s; } } // anonymous namespace template <class T> struct AssociativeArray { public: using ValuePointerT = std::shared_ptr<T>; using ValuesListT = std::vector<ValuePointerT>; using iterator = typename ValuesListT::iterator; using const_iterator = typename ValuesListT::const_iterator; using ThisType = AssociativeArray<T>; public: inline AssociativeArray(const bool isCaseInsensitive = true) noexcept(noexcept(ValuesListT())) : m_data{}, m_isCaseInsensitive{isCaseInsensitive} { } inline AssociativeArray(std::initializer_list<T>&& list, const bool isCaseInsensitive = true) noexcept(noexcept(ValuesListT())) : m_isCaseInsensitive{isCaseInsensitive} { for (auto&& p : std::move(list)) { m_data.emplace_back(std::make_shared<T>(std::move(p))); } } AssociativeArray(const AssociativeArray& arr) = default; AssociativeArray(AssociativeArray&& arr) = default; AssociativeArray& operator = (const AssociativeArray& arr) = default; AssociativeArray& operator = (AssociativeArray&& arr) = default; public: /******************************************************************************** * Main functions. ********************************************************************************/ template< class T1, class T2, class = std::enable_if_t< !std::is_same<std::decay_t<T2>, std::decay_t<T>>::value && !std::is_same<std::decay_t<T2>, std::decay_t<ValuePointerT>>::value, void >, class = void > inline void insert(T1&& name, T2&& value) noexcept { const auto& link = m_data.emplace_back(std::make_shared<T>(std::forward<T1>(name), std::forward<T2>(value))); if (m_isCaseInsensitive) { link->isCaseInsensitive(true); } } template< class T2, class = std::enable_if_t< std::is_same<std::decay_t<T2>, std::decay_t<T>>::value && !std::is_same<std::decay_t<T2>, std::decay_t<ValuePointerT>>::value, void >, class = void, class = void > inline void insert(T2&& value) noexcept { const auto& link = m_data.emplace_back(std::make_shared<T>(std::forward<T2>(value))); if (m_isCaseInsensitive) { link->isCaseInsensitive(true); } } template< class T2, class = std::enable_if_t< !std::is_same<std::decay_t<T2>, std::decay_t<T>>::value && std::is_same<std::decay_t<T2>, std::decay_t<ValuePointerT>>::value, void >, class = void, class = void, class = void > inline void insert(T2&& value) noexcept { const auto& link = m_data.emplace_back(std::forward<T2>(value)); if (m_isCaseInsensitive) { link->isCaseInsensitive(true); } } template <class T1> inline void erase(T1&& node) noexcept { for (auto it = m_data.begin(); it != m_data.end(); ++it) { if (*it and *it == node) { m_data.erase(it); break; } } } template <class T1> inline const ValuesListT findNodes(T1&& name) const noexcept { return const_cast<ThisType>(this)->findNodes(std::forward<T1>(name)); } template<class T1> inline ValuesListT findNodes(T1&& name_) noexcept { ValuesListT result; const T1 name = m_isCaseInsensitive ? to_lower(std::forward<T1>(name_)) : std::forward<T1>(name_); for (const auto& value : m_data) { if (m_isCaseInsensitive) { if (to_lower(value->name()) == name) { result.emplace_back(value); } } else if (value->name() == name) { result.emplace_back(value); } } return result; } template <class T1> inline const ValuePointerT findNode(T1&& name) const noexcept { return const_cast<ThisType>(this)->findNode(std::forward<T1>(name)); } template <class T1> inline ValuePointerT findNode(T1&& name_) noexcept { const T1 name = m_isCaseInsensitive ? to_lower(std::forward<T1>(name_)) : std::forward<T1>(name_); for (const auto& value : m_data) { if (m_isCaseInsensitive) { if (to_lower(value->name()) == name) { return value; } } else if (value->name() == name) { return value; } } return nullptr; } /******************************************************************************** * Syntactic sugar. ********************************************************************************/ template <class T1> inline const ValuePointerT operator() (T1&& name) const noexcept { return const_cast<ThisType>(this)(std::forward<T1>(name)); } template <class T1> inline ValuePointerT operator() (T1&& name) noexcept { return findNode(std::forward<T1>(name)); } template <class T1> inline const ValuesListT operator[] (T1&& name) const noexcept { return const_cast<ThisType>(this)[std::forward<T1>(name)]; } template <class T1> inline ValuesListT operator[] (T1&& name) noexcept { return findNodes(std::forward<T1>(name)); } /******************************************************************************** * Misc functions. ********************************************************************************/ inline iterator begin() noexcept(noexcept(ValuesListT().begin())) { return m_data.begin(); } inline iterator end() noexcept(noexcept(ValuesListT().end())) { return m_data.end(); } inline const_iterator begin() const noexcept(noexcept(ValuesListT().begin())) { return m_data.begin(); } inline const_iterator end() const noexcept(noexcept(ValuesListT().end())) { return m_data.end(); } inline size_t size() const noexcept(noexcept(ValuesListT().size())) { return m_data.size(); } inline bool empty() const noexcept(noexcept(ValuesListT().empty())) { return m_data.empty(); } inline ValuePointerT& back() noexcept(noexcept(ValuesListT().back())) { return m_data.back(); } inline const ValuePointerT& back() const noexcept(noexcept(ValuesListT().back())) { return m_data.back(); } inline ValuePointerT& front() noexcept(noexcept(ValuesListT().front())) { return m_data.front(); } inline const ValuePointerT& front() const noexcept(noexcept(ValuesListT().front())) { return m_data.front(); } inline ValuesListT& nodes() noexcept { return m_data; } inline const ValuesListT& nodes() const noexcept { return m_data; } inline bool operator == (const AssociativeArray& right) const noexcept(noexcept(ValuesListT() == ValuesListT())) { return right.m_data == m_data; } inline bool operator != (const AssociativeArray& right) const noexcept(noexcept(ValuesListT() == ValuesListT())) { return not (*this == right); } inline void isCaseInsensitive(const bool isCaseInsensitive) noexcept { m_isCaseInsensitive = isCaseInsensitive; } inline bool isCaseInsensitive() const noexcept { return m_isCaseInsensitive; } private: ValuesListT m_data; bool m_isCaseInsensitive {true}; };
#pragma once namespace { template<class T> inline auto to_lower1(T s) -> std::string { std::transform(s.begin(), s.end(), s.begin(), ::tolower); return s; } template<class T> inline auto to_lower2(T&& s) -> void { std::transform(s.begin(), s.end(), s.begin(), ::tolower); } } // anonymous namespace template <class T> struct AssociativeArray { public: using ValuePointerT = std::shared_ptr<T>; using ValuesListT = std::vector<ValuePointerT>; using iterator = typename ValuesListT::iterator; using const_iterator = typename ValuesListT::const_iterator; using ThisType = AssociativeArray<T>; public: inline AssociativeArray(const bool isCaseInsensitive = true) noexcept(noexcept(ValuesListT())) : m_data{}, m_isCaseInsensitive{isCaseInsensitive} { } inline AssociativeArray(std::initializer_list<T>&& list, const bool isCaseInsensitive = true) noexcept(noexcept(ValuesListT())) : m_isCaseInsensitive{isCaseInsensitive} { for (auto&& p : std::move(list)) { m_data.emplace_back(std::make_shared<T>(std::move(p))); } } AssociativeArray(const AssociativeArray& arr) = default; AssociativeArray(AssociativeArray&& arr) = default; AssociativeArray& operator = (const AssociativeArray& arr) = default; AssociativeArray& operator = (AssociativeArray&& arr) = default; public: /******************************************************************************** * Main functions. ********************************************************************************/ template< class T1, class T2, class = std::enable_if_t< !std::is_same<std::decay_t<T2>, std::decay_t<T>>::value && !std::is_same<std::decay_t<T2>, std::decay_t<ValuePointerT>>::value, void >, class = void > inline void insert(T1&& name, T2&& value) noexcept { const auto& link = m_data.emplace_back(std::make_shared<T>(std::forward<T1>(name), std::forward<T2>(value))); if (m_isCaseInsensitive) { link->isCaseInsensitive(true); } } template< class T2, class = std::enable_if_t< std::is_same<std::decay_t<T2>, std::decay_t<T>>::value && !std::is_same<std::decay_t<T2>, std::decay_t<ValuePointerT>>::value, void >, class = void, class = void > inline void insert(T2&& value) noexcept { const auto& link = m_data.emplace_back(std::make_shared<T>(std::forward<T2>(value))); if (m_isCaseInsensitive) { link->isCaseInsensitive(true); } } template< class T2, class = std::enable_if_t< !std::is_same<std::decay_t<T2>, std::decay_t<T>>::value && std::is_same<std::decay_t<T2>, std::decay_t<ValuePointerT>>::value, void >, class = void, class = void, class = void > inline void insert(T2&& value) noexcept { const auto& link = m_data.emplace_back(std::forward<T2>(value)); if (m_isCaseInsensitive) { link->isCaseInsensitive(true); } } template <class T1> inline void erase(T1&& node) noexcept { for (auto it = m_data.begin(); it != m_data.end(); ++it) { if (*it and *it == node) { m_data.erase(it); break; } } } inline const ValuesListT findNodes(const std::string& name) const noexcept { return const_cast<ThisType>(this)->findNodes(name); } inline const ValuesListT findNodes(std::string&& name) const noexcept { return const_cast<ThisType>(this)->findNodes(std::move(name)); } inline ValuesListT findNodes(const std::string& name) noexcept { ValuesListT result; if (m_isCaseInsensitive) { const auto lowerName = to_lower1(name); for (const auto& value : m_data) { if (to_lower1(value->name()) == lowerName) { result.emplace_back(value); } } } else { for (const auto& value : m_data) { if (value->name() == name) { result.emplace_back(value); } } } return result; } inline ValuesListT findNodes(std::string&& name) noexcept { ValuesListT result; if (m_isCaseInsensitive) { to_lower2(std::move(name)); for (const auto& value : m_data) { if (to_lower1(value->name()) == name) { result.emplace_back(value); } } } else { for (const auto& value : m_data) { if (value->name() == name) { result.emplace_back(value); } } } return result; } inline const ValuePointerT findNode(const std::string& name) const noexcept { return const_cast<ThisType>(this)->findNode(name); } inline const ValuePointerT findNode(std::string&& name) const noexcept { return const_cast<ThisType>(this)->findNode(std::move(name)); } inline ValuePointerT findNode(const std::string& name) noexcept { if (m_isCaseInsensitive) { const auto lowerName = to_lower1(name); for (const auto& value : m_data) { if (to_lower1(value->name()) == lowerName) { return value; } } } else { for (const auto& value : m_data) { if (value->name() == name) { return value; } } } return nullptr; } inline ValuePointerT findNode(std::string&& name) noexcept { if (m_isCaseInsensitive) { to_lower2(std::move(name)); for (const auto& value : m_data) { if (to_lower1(value->name()) == name) { return value; } } } else { for (const auto& value : m_data) { if (value->name() == name) { return value; } } } return nullptr; } /******************************************************************************** * Syntactic sugar. ********************************************************************************/ template <class T1> inline const ValuePointerT operator() (T1&& name) const noexcept { return const_cast<ThisType>(this)(std::forward<T1>(name)); } template <class T1> inline ValuePointerT operator() (T1&& name) noexcept { return findNode(std::forward<T1>(name)); } template <class T1> inline const ValuesListT operator[] (T1&& name) const noexcept { return const_cast<ThisType>(this)[std::forward<T1>(name)]; } template <class T1> inline ValuesListT operator[] (T1&& name) noexcept { return findNodes(std::forward<T1>(name)); } /******************************************************************************** * Misc functions. ********************************************************************************/ inline iterator begin() noexcept(noexcept(ValuesListT().begin())) { return m_data.begin(); } inline iterator end() noexcept(noexcept(ValuesListT().end())) { return m_data.end(); } inline const_iterator begin() const noexcept(noexcept(ValuesListT().begin())) { return m_data.begin(); } inline const_iterator end() const noexcept(noexcept(ValuesListT().end())) { return m_data.end(); } inline size_t size() const noexcept(noexcept(ValuesListT().size())) { return m_data.size(); } inline bool empty() const noexcept(noexcept(ValuesListT().empty())) { return m_data.empty(); } inline ValuePointerT& back() noexcept(noexcept(ValuesListT().back())) { return m_data.back(); } inline const ValuePointerT& back() const noexcept(noexcept(ValuesListT().back())) { return m_data.back(); } inline ValuePointerT& front() noexcept(noexcept(ValuesListT().front())) { return m_data.front(); } inline const ValuePointerT& front() const noexcept(noexcept(ValuesListT().front())) { return m_data.front(); } inline ValuesListT& nodes() noexcept { return m_data; } inline const ValuesListT& nodes() const noexcept { return m_data; } inline bool operator == (const AssociativeArray& right) const noexcept(noexcept(ValuesListT() == ValuesListT())) { return right.m_data == m_data; } inline bool operator != (const AssociativeArray& right) const noexcept(noexcept(ValuesListT() == ValuesListT())) { return not (*this == right); } inline void isCaseInsensitive(const bool isCaseInsensitive) noexcept { m_isCaseInsensitive = isCaseInsensitive; } inline bool isCaseInsensitive() const noexcept { return m_isCaseInsensitive; } private: ValuesListT m_data; bool m_isCaseInsensitive {true}; };
Add an ability to use rvalue name values when finding nodes
Add an ability to use rvalue name values when finding nodes
C++
mit
idfumg/xml11,idfumg/xml11
1437f25f05ea9a3c7c14213a3ba1227b3b8a5d43
chrome/browser/extensions/theme_installed_infobar_delegate.cc
chrome/browser/extensions/theme_installed_infobar_delegate.cc
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/theme_installed_infobar_delegate.h" #include "app/l10n_util.h" #include "app/resource_bundle.h" #include "base/string_util.h" #include "chrome/browser/extensions/extensions_service.h" #include "chrome/browser/profile.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/common/extensions/extension.h" #include "grit/generated_resources.h" #include "grit/theme_resources.h" ThemeInstalledInfoBarDelegate::ThemeInstalledInfoBarDelegate( TabContents* tab_contents, const Extension* new_theme, const std::string& previous_theme_id) : ConfirmInfoBarDelegate(tab_contents), was_canceled_(false), profile_(tab_contents->profile()), name_(new_theme->name()), new_theme_id_(new_theme->id()), previous_theme_id_(previous_theme_id) { } void ThemeInstalledInfoBarDelegate::InfoBarClosed() { ExtensionsService* service = profile_->GetExtensionsService(); if (service) { std::string uninstall_id; if (was_canceled_) uninstall_id = new_theme_id_; else if (!previous_theme_id_.empty()) uninstall_id = previous_theme_id_; // It's possible that the theme was already uninstalled by someone so make // sure it exists. if (!uninstall_id.empty() && service->GetExtensionById(uninstall_id)) service->UninstallExtension(uninstall_id, false); } delete this; } std::wstring ThemeInstalledInfoBarDelegate::GetMessageText() const { return l10n_util::GetStringF(IDS_THEME_INSTALL_INFOBAR_LABEL, UTF8ToWide(name_)); } SkBitmap* ThemeInstalledInfoBarDelegate::GetIcon() const { // TODO(aa): Reply with the theme's icon, but this requires reading it // asynchronously from disk. return ResourceBundle::GetSharedInstance().GetBitmapNamed( IDR_INFOBAR_THEME); } ThemeInstalledInfoBarDelegate* ThemeInstalledInfoBarDelegate::AsThemePreviewInfobarDelegate() { return this; } int ThemeInstalledInfoBarDelegate::GetButtons() const { return BUTTON_CANCEL; } std::wstring ThemeInstalledInfoBarDelegate::GetButtonLabel( ConfirmInfoBarDelegate::InfoBarButton button) const { switch (button) { case BUTTON_CANCEL: { return l10n_util::GetString(IDS_THEME_INSTALL_INFOBAR_UNDO_BUTTON); } default: NOTREACHED(); return L""; } } bool ThemeInstalledInfoBarDelegate::Cancel() { was_canceled_ = true; if (!previous_theme_id_.empty()) { ExtensionsService* service = profile_->GetExtensionsService(); if (service) { Extension* previous_theme = service->GetExtensionById(previous_theme_id_); if (previous_theme) { profile_->SetTheme(previous_theme); return true; } } } profile_->ClearTheme(); return true; }
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/theme_installed_infobar_delegate.h" #include "app/l10n_util.h" #include "app/resource_bundle.h" #include "base/string_util.h" #include "chrome/browser/extensions/extensions_service.h" #include "chrome/browser/profile.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/common/extensions/extension.h" #include "grit/generated_resources.h" #include "grit/theme_resources.h" ThemeInstalledInfoBarDelegate::ThemeInstalledInfoBarDelegate( TabContents* tab_contents, const Extension* new_theme, const std::string& previous_theme_id) : ConfirmInfoBarDelegate(tab_contents), was_canceled_(false), profile_(tab_contents->profile()), name_(new_theme->name()), new_theme_id_(new_theme->id()), previous_theme_id_(previous_theme_id) { } void ThemeInstalledInfoBarDelegate::InfoBarClosed() { ExtensionsService* service = profile_->GetExtensionsService(); if (service) { std::string uninstall_id; if (was_canceled_) uninstall_id = new_theme_id_; else if (!previous_theme_id_.empty()) uninstall_id = previous_theme_id_; // It's possible that the theme was already uninstalled by someone so make // sure it exists. if (!uninstall_id.empty() && service->GetExtensionById(uninstall_id)) service->UninstallExtension(uninstall_id, false); } delete this; } std::wstring ThemeInstalledInfoBarDelegate::GetMessageText() const { return l10n_util::GetStringF(IDS_THEME_INSTALL_INFOBAR_LABEL, UTF8ToWide(name_)); } SkBitmap* ThemeInstalledInfoBarDelegate::GetIcon() const { // TODO(aa): Reply with the theme's icon, but this requires reading it // asynchronously from disk. return ResourceBundle::GetSharedInstance().GetBitmapNamed( IDR_INFOBAR_THEME); } ThemeInstalledInfoBarDelegate* ThemeInstalledInfoBarDelegate::AsThemePreviewInfobarDelegate() { return this; } int ThemeInstalledInfoBarDelegate::GetButtons() const { return BUTTON_CANCEL; } std::wstring ThemeInstalledInfoBarDelegate::GetButtonLabel( ConfirmInfoBarDelegate::InfoBarButton button) const { switch (button) { case BUTTON_CANCEL: { return l10n_util::GetString(IDS_THEME_INSTALL_INFOBAR_UNDO_BUTTON); } default: // The InfoBar will create a default OK button and make it invisible. // TODO(mirandac): remove the default OK button from ConfirmInfoBar. return L""; } } bool ThemeInstalledInfoBarDelegate::Cancel() { was_canceled_ = true; if (!previous_theme_id_.empty()) { ExtensionsService* service = profile_->GetExtensionsService(); if (service) { Extension* previous_theme = service->GetExtensionById(previous_theme_id_); if (previous_theme) { profile_->SetTheme(previous_theme); return true; } } } profile_->ClearTheme(); return true; }
Fix theme install crasher.
Fix theme install crasher. BUG= 26704 TEST= change themes. browser does not crash. Review URL: http://codereview.chromium.org/366015 git-svn-id: dd90618784b6a4b323ea0c23a071cb1c9e6f2ac7@31036 4ff67af0-8c30-449e-8e8b-ad334ec8d88c
C++
bsd-3-clause
wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser
dd7e9907aa9c01390d9623ce55b1f44e99ae5870
src/openMVG_Samples/image_spherical_to_pinholes/main_pano_converter.cpp
src/openMVG_Samples/image_spherical_to_pinholes/main_pano_converter.cpp
// Copyright (c) 2016 Pierre MOULON. // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include <openMVG/numeric/numeric.h> #include <openMVG/image/image.hpp> #include "./panorama_helper.hpp" #include "third_party/vectorGraphics/svgDrawer.hpp" using namespace svg; #include "third_party/stlplus3/filesystemSimplified/file_system.hpp" #include "third_party/cmdLine/cmdLine.h" #include <string> #include <iostream> #include <iterator> #include <fstream> #include <vector> using namespace std; // Convert spherical panorama to rectilinear images int main(int argc, char **argv) { CmdLine cmd; std::string s_directory_in, s_directory_out; int image_resolution = 1200, nb_split = 5; // required cmd.add( make_option('i', s_directory_in, "input_dir") ); cmd.add( make_option('o', s_directory_out, "output_dir") ); // Optional cmd.add( make_option('r', image_resolution, "image_resolution") ); cmd.add( make_option('n', nb_split, "nb_split") ); cmd.add( make_switch('D', "demo_mode") ); try { if (argc == 1) throw std::string("Invalid command line parameter."); cmd.process(argc, argv); } catch(const std::string& s) { std::cerr << "Usage: " << argv[0] << '\n' << "[-i|--input_dir] the path where the spherical panoramic image are saved \n" << "[-o|--output_dir] the path where output rectilinear image will be saved \n" << " OPTIONAL:\n" << "[-r|--image_resolution] the rectilinear image size (default:" << image_resolution << ") \n" << "[-n|--nb_split] the number of rectilinear image along the X axis (default:" << nb_split << ") \n" << "[-D|--demo_mode] switch parameter, export a SVG file that simulate asked rectilinear\n" << " frustum configuration on the spherical image.\n" << std::endl; } // Input parameter checking if (image_resolution < 0) { std::cerr << "image_resolution must be larger than 0" << std::endl; return EXIT_FAILURE; } if (nb_split < 0) { std::cerr << "nb_split must be larger than 0" << std::endl; return EXIT_FAILURE; } if (s_directory_in.empty() || s_directory_out.empty()) { std::cerr << "input_dir and output_dir option must not be empty" << std::endl; return EXIT_FAILURE; } if (!stlplus::is_folder(s_directory_out)) { if (!stlplus::folder_create(s_directory_out)) { std::cerr << "Cannot create the output_dir directory" << std::endl; return EXIT_FAILURE; } } // List images from the input directory const std::vector<std::string> vec_filenames = stlplus::folder_wildcard(s_directory_in, "*.jpg", false, true); if (vec_filenames.empty()) { std::cerr << "Did not find any jpg image in the provided input_dir" << std::endl; return EXIT_FAILURE; } using namespace openMVG; //----------------- //-- Create N rectilinear cameras // (according the number of asked split along the X axis) //-- For each camera // -- Forward mapping // -- Save resulting images to disk //----------------- typedef CsphericalMapping CGeomFunctor; //-- Generate N cameras along the X axis std::vector< openMVG::PinholeCamera_R > vec_cam; const double twoPi = M_PI * 2.0; const double alpha = twoPi / static_cast<double>(nb_split); const int wIma = image_resolution, hIma = image_resolution; const double focal = openMVG::focalFromPinholeHeight(hIma, openMVG::D2R(60)); double angle = 0.0; for (int i = 0; i < nb_split; ++i, angle += alpha) { vec_cam.emplace_back(focal, wIma, hIma, RotationAroundY(angle)); } if (cmd.used('D')) // Demo mode: { const int wPano = 4096, hPano = wPano / 2; svgDrawer svgStream(wPano, hPano); svgStream.drawLine(0,0,wPano,hPano, svgStyle()); svgStream.drawLine(wPano,0, 0, hPano, svgStyle()); //--> For each cam, reproject the image borders onto the panoramic image for (const openMVG::PinholeCamera_R & cam_it : vec_cam) { //draw the shot border with the givenStep: const int step = 10; Vec3 ray; // Vertical rectilinear image border: for (double j = 0; j <= image_resolution; j += image_resolution/(double)step) { Vec2 pt(0.,j); ray = cam_it.getRay(pt(0), pt(1)); Vec2 x = CGeomFunctor::Get2DPoint( ray, wPano, hPano); svgStream.drawCircle(x(0), x(1), 4, svgStyle().fill("green")); pt[0] = image_resolution; ray = cam_it.getRay(pt(0), pt(1)); x = CGeomFunctor::Get2DPoint( ray, wPano, hPano); svgStream.drawCircle(x(0), x(1), 4, svgStyle().fill("green")); } // Horizontal rectilinear image border: for (double j = 0; j <= image_resolution; j += image_resolution/(double)step) { Vec2 pt(j,0.); ray = cam_it.getRay(pt(0), pt(1)); Vec2 x = CGeomFunctor::Get2DPoint( ray, wPano, hPano); svgStream.drawCircle(x(0), x(1), 4, svgStyle().fill("yellow")); pt[1] = image_resolution; ray = cam_it.getRay(pt(0), pt(1)); x = CGeomFunctor::Get2DPoint( ray, wPano, hPano); svgStream.drawCircle(x(0), x(1), 4, svgStyle().fill("yellow")); } } std::ofstream svgFile( stlplus::create_filespec(s_directory_out, "test.svg" )); svgFile << svgStream.closeSvgFile().str(); return EXIT_SUCCESS; } //-- For each input image extract multiple pinhole images for (const std::string & filename_it : vec_filenames) { image::Image<image::RGBColor> imageSource; if (!ReadImage(stlplus::create_filespec(s_directory_in,filename_it).c_str(), &imageSource)) { std::cerr << "Cannot read the image" << std::endl; continue; } const int wPano = imageSource.Width(), hPano = imageSource.Height(); const image::Sampler2d<image::SamplerLinear> sampler; image::Image<image::RGBColor> imaOut(wIma, hIma, image::BLACK); size_t index = 0; for (const PinholeCamera_R & cam_it : vec_cam) { imaOut.fill(image::BLACK); // Backward mapping: // - Find for each pixels of the pinhole image where it comes from the panoramic image for (int j = 0; j < hIma; ++j) { for (int i = 0; i < wIma; ++i) { const Vec3 ray = cam_it.getRay(i, j); const Vec2 x = CGeomFunctor::Get2DPoint(ray, wPano, hPano); imaOut(j,i) = sampler(imageSource, x(1), x(0)); } } //-- save image const std::string basename = stlplus::basename_part(filename_it); std::cout << basename << " cam index: " << index << std::endl; std::ostringstream os; os << s_directory_out << "/" << basename << "_" << index << ".jpg"; WriteImage(os.str().c_str(), imaOut); ++index; } } std::ofstream fileFocalOut(stlplus::create_filespec(s_directory_out, "focal.txt")); fileFocalOut << focal; fileFocalOut.close(); return EXIT_SUCCESS; }
// Copyright (c) 2016 Pierre MOULON. // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include <openMVG/numeric/numeric.h> #include <openMVG/image/image.hpp> #include "./panorama_helper.hpp" #include "third_party/vectorGraphics/svgDrawer.hpp" using namespace svg; #include "third_party/stlplus3/filesystemSimplified/file_system.hpp" #include "third_party/cmdLine/cmdLine.h" #include <string> #include <iostream> #include <iterator> #include <fstream> #include <vector> using namespace std; // Convert spherical panorama to rectilinear images int main(int argc, char **argv) { CmdLine cmd; std::string s_directory_in, s_directory_out; int image_resolution = 1200, nb_split = 5; // required cmd.add( make_option('i', s_directory_in, "input_dir") ); cmd.add( make_option('o', s_directory_out, "output_dir") ); // Optional cmd.add( make_option('r', image_resolution, "image_resolution") ); cmd.add( make_option('n', nb_split, "nb_split") ); cmd.add( make_switch('D', "demo_mode") ); try { if (argc == 1) throw std::string("Invalid command line parameter."); cmd.process(argc, argv); } catch(const std::string& s) { std::cerr << "Usage: " << argv[0] << '\n' << "[-i|--input_dir] the path where the spherical panoramic image are saved \n" << "[-o|--output_dir] the path where output rectilinear image will be saved \n" << " OPTIONAL:\n" << "[-r|--image_resolution] the rectilinear image size (default:" << image_resolution << ") \n" << "[-n|--nb_split] the number of rectilinear image along the X axis (default:" << nb_split << ") \n" << "[-D|--demo_mode] switch parameter, export a SVG file that simulate asked rectilinear\n" << " frustum configuration on the spherical image.\n" << std::endl; } // Input parameter checking if (image_resolution < 0) { std::cerr << "image_resolution must be larger than 0" << std::endl; return EXIT_FAILURE; } if (nb_split < 0) { std::cerr << "nb_split must be larger than 0" << std::endl; return EXIT_FAILURE; } if (s_directory_in.empty() || s_directory_out.empty()) { std::cerr << "input_dir and output_dir option must not be empty" << std::endl; return EXIT_FAILURE; } if (!stlplus::is_folder(s_directory_out)) { if (!stlplus::folder_create(s_directory_out)) { std::cerr << "Cannot create the output_dir directory" << std::endl; return EXIT_FAILURE; } } // List images from the input directory const std::vector<std::string> vec_filenames = stlplus::folder_wildcard(s_directory_in, "*.jpg", false, true); if (vec_filenames.empty()) { std::cerr << "Did not find any jpg image in the provided input_dir" << std::endl; return EXIT_FAILURE; } using namespace openMVG; //----------------- //-- Create N rectilinear cameras // (according the number of asked split along the X axis) //-- For each camera // -- Forward mapping // -- Save resulting images to disk //----------------- using CGeomFunctor = CsphericalMapping; //-- Generate N cameras along the X axis std::vector< openMVG::PinholeCamera_R > vec_cam; const double twoPi = M_PI * 2.0; const double alpha = twoPi / static_cast<double>(nb_split); const int wIma = image_resolution, hIma = image_resolution; const double focal = openMVG::focalFromPinholeHeight(hIma, openMVG::D2R(60)); double angle = 0.0; for (int i = 0; i < nb_split; ++i, angle += alpha) { vec_cam.emplace_back(focal, wIma, hIma, RotationAroundY(angle)); } if (cmd.used('D')) // Demo mode: { const int wPano = 4096, hPano = wPano / 2; svgDrawer svgStream(wPano, hPano); svgStream.drawLine(0,0,wPano,hPano, svgStyle()); svgStream.drawLine(wPano,0, 0, hPano, svgStyle()); //--> For each cam, reproject the image borders onto the panoramic image for (const openMVG::PinholeCamera_R & cam_it : vec_cam) { //draw the shot border with the givenStep: const int step = 10; Vec3 ray; // Vertical rectilinear image border: for (double j = 0; j <= image_resolution; j += image_resolution/(double)step) { Vec2 pt(0.,j); ray = cam_it.getRay(pt(0), pt(1)); Vec2 x = CGeomFunctor::Get2DPoint( ray, wPano, hPano); svgStream.drawCircle(x(0), x(1), 4, svgStyle().fill("green")); pt[0] = image_resolution; ray = cam_it.getRay(pt(0), pt(1)); x = CGeomFunctor::Get2DPoint( ray, wPano, hPano); svgStream.drawCircle(x(0), x(1), 4, svgStyle().fill("green")); } // Horizontal rectilinear image border: for (double j = 0; j <= image_resolution; j += image_resolution/(double)step) { Vec2 pt(j,0.); ray = cam_it.getRay(pt(0), pt(1)); Vec2 x = CGeomFunctor::Get2DPoint( ray, wPano, hPano); svgStream.drawCircle(x(0), x(1), 4, svgStyle().fill("yellow")); pt[1] = image_resolution; ray = cam_it.getRay(pt(0), pt(1)); x = CGeomFunctor::Get2DPoint( ray, wPano, hPano); svgStream.drawCircle(x(0), x(1), 4, svgStyle().fill("yellow")); } } std::ofstream svgFile( stlplus::create_filespec(s_directory_out, "test.svg" )); svgFile << svgStream.closeSvgFile().str(); return EXIT_SUCCESS; } //-- For each input image extract multiple pinhole images for (const std::string & filename_it : vec_filenames) { image::Image<image::RGBColor> imageSource; if (!ReadImage(stlplus::create_filespec(s_directory_in,filename_it).c_str(), &imageSource)) { std::cerr << "Cannot read the image" << std::endl; continue; } const int wPano = imageSource.Width(), hPano = imageSource.Height(); const image::Sampler2d<image::SamplerLinear> sampler; image::Image<image::RGBColor> imaOut(wIma, hIma, image::BLACK); size_t index = 0; for (const PinholeCamera_R & cam_it : vec_cam) { imaOut.fill(image::BLACK); // Backward mapping: // - Find for each pixels of the pinhole image where it comes from the panoramic image for (int j = 0; j < hIma; ++j) { for (int i = 0; i < wIma; ++i) { const Vec3 ray = cam_it.getRay(i, j); const Vec2 x = CGeomFunctor::Get2DPoint(ray, wPano, hPano); imaOut(j,i) = sampler(imageSource, x(1), x(0)); } } //-- save image const std::string basename = stlplus::basename_part(filename_it); std::cout << basename << " cam index: " << index << std::endl; std::ostringstream os; os << s_directory_out << "/" << basename << "_" << index << ".jpg"; WriteImage(os.str().c_str(), imaOut); ++index; } } std::ofstream fileFocalOut(stlplus::create_filespec(s_directory_out, "focal.txt")); fileFocalOut << focal; fileFocalOut.close(); return EXIT_SUCCESS; }
Use type_alias #708
[c++11] Use type_alias #708
C++
mpl-2.0
openMVG/openMVG,openMVG/openMVG,openMVG/openMVG,openMVG/openMVG,openMVG/openMVG
e7c7ac10a4fa141be1c4eac67562fd673171fb41
C++/unique-word-abbreviation.cpp
C++/unique-word-abbreviation.cpp
// Time: O(n) for constructor, n is number of words in the dictionary. // O(1) for lookup // Space: O(k), k is number of unique words. class ValidWordAbbr { public: ValidWordAbbr(vector<string> &dictionary) { for (string& word : dictionary) { const string hash_val = word.front() + to_string(word.length()) + word.back(); lookup_[hash_val].emplace(word); } } bool isUnique(string word) { const string hash_val = word.front() + to_string(word.length()) + word.back(); return lookup_[hash_val].empty() || (lookup_[hash_val].count(word) == lookup_[hash_val].size()); } private: unordered_map<string, unordered_set<string>> lookup_; }; // Your ValidWordAbbr object will be instantiated and called as such: // ValidWordAbbr vwa(dictionary); // vwa.isUnique("hello"); // vwa.isUnique("anotherWord");
// Time: O(n) for constructor, n is number of words in the dictionary. // O(1) for lookup // Space: O(k), k is number of unique words. class ValidWordAbbr { public: ValidWordAbbr(vector<string> &dictionary) { for (string& word : dictionary) { const string hash_word = hash(word); lookup_[hash_word].emplace(word); } } bool isUnique(string word) { const string hash_word = hash(word); return lookup_[hash_word].empty() || (lookup_[hash_word].count(word) == lookup_[hash_word].size()); } string hash(const string& word) { return word.front() + to_string(word.length()) + word.back();; } private: unordered_map<string, unordered_set<string>> lookup_; }; // Your ValidWordAbbr object will be instantiated and called as such: // ValidWordAbbr vwa(dictionary); // vwa.isUnique("hello"); // vwa.isUnique("anotherWord");
Update unique-word-abbreviation.cpp
Update unique-word-abbreviation.cpp
C++
mit
kamyu104/LeetCode,jaredkoontz/leetcode,tudennis/LeetCode---kamyu104-11-24-2015,yiwen-luo/LeetCode,kamyu104/LeetCode,kamyu104/LeetCode,jaredkoontz/leetcode,githubutilities/LeetCode,yiwen-luo/LeetCode,jaredkoontz/leetcode,githubutilities/LeetCode,githubutilities/LeetCode,tudennis/LeetCode---kamyu104-11-24-2015,yiwen-luo/LeetCode,kamyu104/LeetCode,jaredkoontz/leetcode,kamyu104/LeetCode,githubutilities/LeetCode,githubutilities/LeetCode,tudennis/LeetCode---kamyu104-11-24-2015,yiwen-luo/LeetCode,jaredkoontz/leetcode,yiwen-luo/LeetCode,tudennis/LeetCode---kamyu104-11-24-2015,tudennis/LeetCode---kamyu104-11-24-2015
c0f8f87b771d62386fe651f20ea6e87ef1f4742d
2D-Game-Engine/TextureManager.cpp
2D-Game-Engine/TextureManager.cpp
#include "TextureManager.h" #include "RawImage.h" TextureManager::TextureManager() {} TextureManager::~TextureManager() { for (Texture* tex : m_textures) { delete tex; } } Texture* TextureManager::createTexture2D(const RawImage& img, Texture::Filter filtering, Texture::Wrap textureWrapS, Texture::Wrap textureWrapT) { Texture* tex = new Texture(Texture::Target::TEXTURE_2D, GL_TEXTURE0); //Texture tex(name, Texture::TEXTURE_2D, Texture::UNIT_0); tex->bind(); //glBindTexture(Texture::TEXTURE_2D, name); glTexImage2D(tex->m_target, 0, GL_RGBA, img.getWidth(), img.getHeight(), 0, GL_RGBA, GL_UNSIGNED_BYTE, img.getData()); glTexParameteri(tex->m_target, GL_TEXTURE_MIN_FILTER, filtering); glTexParameteri(tex->m_target, GL_TEXTURE_MAG_FILTER, filtering); glTexParameteri(tex->m_target, GL_TEXTURE_WRAP_S, textureWrapS); glTexParameteri(tex->m_target, GL_TEXTURE_WRAP_T, textureWrapT); //glBindTexture(Texture::Target::TEXTURE_2D, 0); tex->unbind(); //Texture tex(name, Texture::TEXTURE_2D, Texture::UNIT_0); //m_loadedTextures.push_back(tex); m_textures.push_back(tex); return tex; } Texture* TextureManager::createTexture2DArray(RawImage* imgs, uint32 layers, Texture::Filter filtering, Texture::Wrap textureWrapS, Texture::Wrap textureWrapT) { uint32 width = imgs[0].getWidth(); uint32 height = imgs[0].getHeight(); uint32 subImgSize = width * height * imgs[0].getChannels(); uint8* data = new uint8[subImgSize * layers]; // TODO Ensure all images are the same size for (uint32 i = 0; i < layers; i++) { uint8* subImgData = imgs[layers].getData(); for (uint32 j = 0; j < subImgSize; j++) { data[(i * subImgSize) + j] = subImgData[j]; } } Texture* tex = new Texture(Texture::Target::TEXTURE_2D_ARRAY, GL_TEXTURE0); //Texture tex(name, Texture::Target::TEXTURE_2D_ARRAY, Texture::UNIT_0); tex->bind(); glTexImage3D(tex->m_target, 0, GL_RGBA, width, height, layers, 0, GL_RGBA, GL_UNSIGNED_BYTE, data); glTexParameteri(tex->m_target, GL_TEXTURE_MIN_FILTER, filtering); glTexParameteri(tex->m_target, GL_TEXTURE_MAG_FILTER, filtering); glTexParameteri(tex->m_target, GL_TEXTURE_WRAP_S, textureWrapS); glTexParameteri(tex->m_target, GL_TEXTURE_WRAP_T, textureWrapT); tex->unbind(); delete data; m_textures.push_back(tex); return tex; }
#include "TextureManager.h" #include "RawImage.h" TextureManager::TextureManager() {} TextureManager::~TextureManager() { for (Texture* tex : m_textures) { delete tex; } } Texture* TextureManager::createTexture2D(const RawImage& img, Texture::Filter filtering, Texture::Wrap textureWrapS, Texture::Wrap textureWrapT) { Texture* tex = new Texture(Texture::Target::TEXTURE_2D, GL_TEXTURE0); //Texture tex(name, Texture::TEXTURE_2D, Texture::UNIT_0); tex->bind(); //glBindTexture(Texture::TEXTURE_2D, name); glTexImage2D(tex->m_target, 0, GL_RGBA, img.getWidth(), img.getHeight(), 0, GL_RGBA, GL_UNSIGNED_BYTE, img.getData()); glTexParameteri(tex->m_target, GL_TEXTURE_MIN_FILTER, filtering); glTexParameteri(tex->m_target, GL_TEXTURE_MAG_FILTER, filtering); glTexParameteri(tex->m_target, GL_TEXTURE_WRAP_S, textureWrapS); glTexParameteri(tex->m_target, GL_TEXTURE_WRAP_T, textureWrapT); //glBindTexture(Texture::Target::TEXTURE_2D, 0); tex->unbind(); //Texture tex(name, Texture::TEXTURE_2D, Texture::UNIT_0); //m_loadedTextures.push_back(tex); m_textures.push_back(tex); return tex; } Texture* TextureManager::createTexture2DArray(RawImage* imgs, uint32 layers, Texture::Filter filtering, Texture::Wrap textureWrapS, Texture::Wrap textureWrapT) { uint32 width = imgs[0].getWidth(); uint32 height = imgs[0].getHeight(); uint32 subImgSize = width * height * imgs[0].getChannels(); uint8* data = new uint8[subImgSize * layers]; // TODO Ensure all images are the same size for (uint32 i = 0; i < layers; i++) { uint8* subImgData = imgs[layers].getData(); for (uint32 j = 0; j < subImgSize; j++) { data[(i * subImgSize) + j] = subImgData[j]; } } Texture* tex = new Texture(Texture::Target::TEXTURE_2D_ARRAY, GL_TEXTURE0); //Texture tex(name, Texture::Target::TEXTURE_2D_ARRAY, Texture::UNIT_0); tex->bind(); glTexImage3D(tex->m_target, 0, GL_RGBA, width, height, layers, 0, GL_RGBA, GL_UNSIGNED_BYTE, data); glTexParameteri(tex->m_target, GL_TEXTURE_MIN_FILTER, filtering); glTexParameteri(tex->m_target, GL_TEXTURE_MAG_FILTER, filtering); glTexParameteri(tex->m_target, GL_TEXTURE_WRAP_S, textureWrapS); glTexParameteri(tex->m_target, GL_TEXTURE_WRAP_T, textureWrapT); tex->unbind(); delete[] data; m_textures.push_back(tex); return tex; }
Fix it again
Fix it again
C++
mit
simon-bourque/2D-Game-Engine-Cpp,simon-bourque/2D-Game-Engine-Cpp
d77d376858d33fd10dcf3392ad18854a8caa724f
plugins/videobasedtracker/BeaconBasedPoseEstimator_Kalman.cpp
plugins/videobasedtracker/BeaconBasedPoseEstimator_Kalman.cpp
/** @file @brief Implementation of Kalman-specific code in beacon-based pose estimator, to reduce incremental build times. @date 2015 @author Sensics, Inc. <http://sensics.com/osvr> */ // Copyright 2015 Sensics, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <iostream> #include <osvr/Util/EigenCoreGeometry.h> #if 0 template <typename T> inline void dumpKalmanDebugOuput(const char name[], const char expr[], T const &value) { std::cout << "\n(Kalman Debug Output) " << name << " [" << expr << "]:\n" << value << std::endl; } #endif // Internal Includes #include "BeaconBasedPoseEstimator.h" #include "ImagePointMeasurement.h" #include "cvToEigen.h" // Library/third-party includes #include <osvr/Kalman/FlexibleKalmanFilter.h> #include <osvr/Kalman/AugmentedProcessModel.h> #include <osvr/Kalman/AugmentedState.h> #include <osvr/Kalman/ConstantProcess.h> #include <osvr/Util/EigenInterop.h> #include <opencv2/core/eigen.hpp> // Standard includes // - none namespace osvr { namespace vbtracker { static const auto LOW_BEACON_CUTOFF = 5; static const auto DIM_BEACON_CUTOFF_TO_SKIP_BRIGHTS = 4; bool BeaconBasedPoseEstimator::m_kalmanAutocalibEstimator(LedGroup &leds, double dt) { auto const beaconsSize = m_beacons.size(); // Default measurement variance (for now, factor) per axis. double varianceFactor = 1; auto maxBoxRatio = m_params.boundingBoxFilterRatio; auto minBoxRatio = 1.f / m_params.boundingBoxFilterRatio; // Default to using all the measurements we can auto skipBright = false; { auto totalLeds = leds.size(); auto identified = std::size_t{0}; auto inBoundsID = std::size_t{0}; auto inBoundsBright = std::size_t{0}; auto inBoundsRound = std::size_t{0}; for (auto const &led : leds) { if (!led.identified()) { continue; } identified++; auto id = led.getID(); if (id >= beaconsSize) { continue; } inBoundsID++; if (led.isBright()) { inBoundsBright++; } if (led.getMeasurement().knowBoundingBox) { auto boundingBoxRatio = led.getMeasurement().boundingBox.height / led.getMeasurement().boundingBox.width; if (boundingBoxRatio > minBoxRatio && boundingBoxRatio < maxBoxRatio) { inBoundsRound++; } } } // Now we decide if we want to cut the variance artificially to // reduce latency in low-beacon situations if (inBoundsID < LOW_BEACON_CUTOFF) { varianceFactor = 0.5; } if (inBoundsID - inBoundsBright > DIM_BEACON_CUTOFF_TO_SKIP_BRIGHTS) { skipBright = true; } else { #if 0 if (m_params.debug) { std::cout << "Can't afford to skip brights this frame" << std::endl; } #endif } } CameraModel cam; cam.focalLength = m_camParams.focalLength(); cam.principalPoint = cvToVector(m_camParams.principalPoint()); ImagePointMeasurement meas{cam}; kalman::ConstantProcess<kalman::PureVectorState<>> beaconProcess; Eigen::Vector2d pt; const auto maxSquaredResidual = m_params.maxResidual * m_params.maxResidual; kalman::predict(m_state, m_model, dt); auto numBad = std::size_t{0}; auto numGood = std::size_t{0}; for (auto &led : leds) { if (!led.identified()) { continue; } auto id = led.getID(); if (id >= beaconsSize) { continue; } auto &debug = m_beaconDebugData[id]; debug.seen = true; debug.measurement = led.getLocation(); if (skipBright && led.isBright()) { continue; } if (led.getMeasurement().knowBoundingBox) { /// @todo For right now, if we don't have a bounding box, we're /// assuming it's square enough (and only testing for /// non-squareness on those who actually do have bounding /// boxes). This is very much a temporary situation. auto boundingBoxRatio = led.getMeasurement().boundingBox.height / led.getMeasurement().boundingBox.width; if (boundingBoxRatio < minBoxRatio || boundingBoxRatio > maxBoxRatio) { /// skip non-circular blobs. continue; } } auto localVarianceFactor = varianceFactor; auto newIdentificationVariancePenalty = std::pow(2.0, led.novelty()); /// Stick a little bit of process model uncertainty in the beacon, /// if it's meant to have some if (m_beaconFixed[id]) { beaconProcess.setNoiseAutocorrelation(0); } else { beaconProcess.setNoiseAutocorrelation( m_params.beaconProcessNoise); kalman::predict(*(m_beacons[id]), beaconProcess, dt); } meas.setMeasurement( Eigen::Vector2d(led.getLocation().x, led.getLocation().y)); led.markAsUsed(); auto state = kalman::makeAugmentedState(m_state, *(m_beacons[id])); meas.updateFromState(state); Eigen::Vector2d residual = meas.getResidual(state); if (residual.squaredNorm() > maxSquaredResidual) { // probably bad numBad++; localVarianceFactor *= m_params.highResidualVariancePenalty; } else { numGood++; } debug.residual.x = residual.x(); debug.residual.y = residual.y(); auto effectiveVariance = localVarianceFactor * m_params.measurementVarianceScaleFactor * newIdentificationVariancePenalty * m_beaconMeasurementVariance[id] / led.getMeasurement().area; debug.variance = effectiveVariance; meas.setVariance(effectiveVariance); /// Now, do the correction. auto model = kalman::makeAugmentedProcessModel(m_model, beaconProcess); kalman::correct(state, model, meas); m_gotMeasurement = true; } bool incrementProbation = false; if (0 == m_framesInProbation) { // Let's try to keep a 3:2 ratio of good to bad when not "in // probation" incrementProbation = (numBad * 3 > numGood * 2); } else { // Already in trouble, add a bit of hysteresis and raising the bar // so we don't hop out easily. incrementProbation = numBad * 2 > numGood; if (!incrementProbation) { // OK, we're good again m_framesInProbation = 0; } } if (incrementProbation) { m_framesInProbation++; } /// Output to the OpenCV state types so we can see the reprojection /// debug view. m_rvec = eiQuatToRotVec(m_state.getQuaternion()); cv::eigen2cv(m_state.position().eval(), m_tvec); return true; } OSVR_PoseState BeaconBasedPoseEstimator::GetPredictedState(double dt) const { auto state = m_state; auto model = m_model; kalman::predict(state, model, dt); state.postCorrect(); OSVR_PoseState ret; util::eigen_interop::map(ret).rotation() = state.getQuaternion(); util::eigen_interop::map(ret).translation() = m_convertInternalPositionRepToExternal(state.position()); return ret; } } // namespace vbtracker } // namespace osvr
/** @file @brief Implementation of Kalman-specific code in beacon-based pose estimator, to reduce incremental build times. @date 2015 @author Sensics, Inc. <http://sensics.com/osvr> */ // Copyright 2015 Sensics, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <iostream> #include <osvr/Util/EigenCoreGeometry.h> #if 0 template <typename T> inline void dumpKalmanDebugOuput(const char name[], const char expr[], T const &value) { std::cout << "\n(Kalman Debug Output) " << name << " [" << expr << "]:\n" << value << std::endl; } #endif // Internal Includes #include "BeaconBasedPoseEstimator.h" #include "ImagePointMeasurement.h" #include "cvToEigen.h" // Library/third-party includes #include <osvr/Kalman/FlexibleKalmanFilter.h> #include <osvr/Kalman/AugmentedProcessModel.h> #include <osvr/Kalman/AugmentedState.h> #include <osvr/Kalman/ConstantProcess.h> #include <osvr/Util/EigenInterop.h> #include <opencv2/core/eigen.hpp> // Standard includes // - none namespace osvr { namespace vbtracker { static const auto LOW_BEACON_CUTOFF = 5; static const auto DIM_BEACON_CUTOFF_TO_SKIP_BRIGHTS = 4; static const auto MAX_Z_COMPONENT = -0.3; bool BeaconBasedPoseEstimator::m_kalmanAutocalibEstimator(LedGroup &leds, double dt) { auto const beaconsSize = m_beacons.size(); // Default measurement variance (for now, factor) per axis. double varianceFactor = 1; auto maxBoxRatio = m_params.boundingBoxFilterRatio; auto minBoxRatio = 1.f / m_params.boundingBoxFilterRatio; // Default to using all the measurements we can auto skipBright = false; { auto totalLeds = leds.size(); auto identified = std::size_t{0}; auto inBoundsID = std::size_t{0}; auto inBoundsBright = std::size_t{0}; auto inBoundsRound = std::size_t{0}; for (auto const &led : leds) { if (!led.identified()) { continue; } identified++; auto id = led.getID(); if (id >= beaconsSize) { continue; } inBoundsID++; if (led.isBright()) { inBoundsBright++; } if (led.getMeasurement().knowBoundingBox) { auto boundingBoxRatio = led.getMeasurement().boundingBox.height / led.getMeasurement().boundingBox.width; if (boundingBoxRatio > minBoxRatio && boundingBoxRatio < maxBoxRatio) { inBoundsRound++; } } } // Now we decide if we want to cut the variance artificially to // reduce latency in low-beacon situations if (inBoundsID < LOW_BEACON_CUTOFF) { varianceFactor = 0.5; } if (inBoundsID - inBoundsBright > DIM_BEACON_CUTOFF_TO_SKIP_BRIGHTS) { skipBright = true; } else { #if 0 if (m_params.debug) { std::cout << "Can't afford to skip brights this frame" << std::endl; } #endif } } CameraModel cam; cam.focalLength = m_camParams.focalLength(); cam.principalPoint = cvToVector(m_camParams.principalPoint()); ImagePointMeasurement meas{cam}; kalman::ConstantProcess<kalman::PureVectorState<>> beaconProcess; Eigen::Vector2d pt; const auto maxSquaredResidual = m_params.maxResidual * m_params.maxResidual; kalman::predict(m_state, m_model, dt); /// @todo should we be recalculating this for each beacon after each /// correction step? The order we filter them in is rather arbitrary... Eigen::Matrix3d rotate = Eigen::Matrix3d(m_state.getCombinedQuaternion()); auto numBad = std::size_t{0}; auto numGood = std::size_t{0}; for (auto &led : leds) { if (!led.identified()) { continue; } auto id = led.getID(); if (id >= beaconsSize) { continue; } auto &debug = m_beaconDebugData[id]; debug.seen = true; debug.measurement = led.getLocation(); if (skipBright && led.isBright()) { continue; } // Angle of emission checking // If we transform the body-local emission vector, an LED pointed // right at the camera will be -Z. Anything with a 0 or positive z // component is clearly out, and realistically, anything with a z // component over -0.5 is probably fairly oblique. We don't want to // use such beacons since they can easily introduce substantial // error. double zComponent = (rotate * cvToVector(m_beaconEmissionDirection[id])).z(); /// @todo if z component is positive, we shouldn't even be able to /// see this since it's pointed away from us. if (zComponent > MAX_Z_COMPONENT) { continue; } if (led.getMeasurement().knowBoundingBox) { /// @todo For right now, if we don't have a bounding box, we're /// assuming it's square enough (and only testing for /// non-squareness on those who actually do have bounding /// boxes). This is very much a temporary situation. auto boundingBoxRatio = led.getMeasurement().boundingBox.height / led.getMeasurement().boundingBox.width; if (boundingBoxRatio < minBoxRatio || boundingBoxRatio > maxBoxRatio) { /// skip non-circular blobs. continue; } } auto localVarianceFactor = varianceFactor; auto newIdentificationVariancePenalty = std::pow(2.0, led.novelty()); /// Stick a little bit of process model uncertainty in the beacon, /// if it's meant to have some if (m_beaconFixed[id]) { beaconProcess.setNoiseAutocorrelation(0); } else { beaconProcess.setNoiseAutocorrelation( m_params.beaconProcessNoise); kalman::predict(*(m_beacons[id]), beaconProcess, dt); } meas.setMeasurement( Eigen::Vector2d(led.getLocation().x, led.getLocation().y)); led.markAsUsed(); auto state = kalman::makeAugmentedState(m_state, *(m_beacons[id])); meas.updateFromState(state); Eigen::Vector2d residual = meas.getResidual(state); if (residual.squaredNorm() > maxSquaredResidual) { // probably bad numBad++; localVarianceFactor *= m_params.highResidualVariancePenalty; } else { numGood++; } debug.residual.x = residual.x(); debug.residual.y = residual.y(); auto effectiveVariance = localVarianceFactor * m_params.measurementVarianceScaleFactor * newIdentificationVariancePenalty * m_beaconMeasurementVariance[id] / led.getMeasurement().area; debug.variance = effectiveVariance; meas.setVariance(effectiveVariance); /// Now, do the correction. auto model = kalman::makeAugmentedProcessModel(m_model, beaconProcess); kalman::correct(state, model, meas); m_gotMeasurement = true; } bool incrementProbation = false; if (0 == m_framesInProbation) { // Let's try to keep a 3:2 ratio of good to bad when not "in // probation" incrementProbation = (numBad * 3 > numGood * 2); } else { // Already in trouble, add a bit of hysteresis and raising the bar // so we don't hop out easily. incrementProbation = numBad * 2 > numGood; if (!incrementProbation) { // OK, we're good again m_framesInProbation = 0; } } if (incrementProbation) { m_framesInProbation++; } /// Output to the OpenCV state types so we can see the reprojection /// debug view. m_rvec = eiQuatToRotVec(m_state.getQuaternion()); cv::eigen2cv(m_state.position().eval(), m_tvec); return true; } OSVR_PoseState BeaconBasedPoseEstimator::GetPredictedState(double dt) const { auto state = m_state; auto model = m_model; kalman::predict(state, model, dt); state.postCorrect(); OSVR_PoseState ret; util::eigen_interop::map(ret).rotation() = state.getQuaternion(); util::eigen_interop::map(ret).translation() = m_convertInternalPositionRepToExternal(state.position()); return ret; } } // namespace vbtracker } // namespace osvr
Add some simple emission direction checking for the LEDs to prune out those facing away from the camera.
Add some simple emission direction checking for the LEDs to prune out those facing away from the camera.
C++
apache-2.0
leemichaelRazer/OSVR-Core,godbyk/OSVR-Core,OSVR/OSVR-Core,leemichaelRazer/OSVR-Core,OSVR/OSVR-Core,godbyk/OSVR-Core,OSVR/OSVR-Core,OSVR/OSVR-Core,godbyk/OSVR-Core,leemichaelRazer/OSVR-Core,leemichaelRazer/OSVR-Core,godbyk/OSVR-Core,OSVR/OSVR-Core,leemichaelRazer/OSVR-Core,godbyk/OSVR-Core,godbyk/OSVR-Core,OSVR/OSVR-Core
3dcf6647109feeaa199e64d30a71407e225be582
sal/qa/osl/profile/osl_old_testprofile.cxx
sal/qa/osl/profile/osl_old_testprofile.cxx
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ #include <sal/types.h> #include "cppunit/TestAssert.h" #include "cppunit/TestFixture.h" #include "cppunit/extensions/HelperMacros.h" #include "cppunit/plugin/TestPlugIn.h" #include <stdio.h> #include <osl/profile.h> namespace osl_Profile { class oldtests : public CppUnit::TestFixture { public: void test_profile(); CPPUNIT_TEST_SUITE( oldtests ); CPPUNIT_TEST( test_profile ); CPPUNIT_TEST_SUITE_END( ); }; void oldtests::test_profile(void) { oslProfile hProfile; rtl_uString* ustrProfileName=0; rtl_uString* ustrProfileName2=0; rtl_uString_newFromAscii(&ustrProfileName,"//./tmp/soffice.ini"); rtl_uString_newFromAscii(&ustrProfileName2,"//./tmp/not_existing_path/soffice.ini"); // successful write hProfile = osl_openProfile( ustrProfileName, 0 ); if (hProfile != 0) { if (! osl_writeProfileBool( hProfile, "testsection", "testbool", 1 )) printf( "### cannot write into init file!\n" ); osl_closeProfile( hProfile ); } // unsuccessful write hProfile = osl_openProfile( ustrProfileName2, 0 ); if (hProfile != 0) { if (osl_writeProfileBool( hProfile, "testsection", "testbool", 1 )) printf( "### unexpected success writing into test2.ini!\n" ); osl_closeProfile( hProfile ); } rtl_uString_release(ustrProfileName); rtl_uString_release(ustrProfileName2); } } // namespace osl_Profile CPPUNIT_TEST_SUITE_REGISTRATION( osl_Profile::oldtests ); CPPUNIT_PLUGIN_IMPLEMENT(); /* vim:set shiftwidth=4 softtabstop=4 expandtab: */
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ #include <sal/types.h> #include "cppunit/TestAssert.h" #include "cppunit/TestFixture.h" #include "cppunit/extensions/HelperMacros.h" #include "cppunit/plugin/TestPlugIn.h" #include <osl/profile.h> #include <rtl/bootstrap.hxx> namespace osl_Profile { class oldtests : public CppUnit::TestFixture { public: void test_profile(); CPPUNIT_TEST_SUITE( oldtests ); CPPUNIT_TEST( test_profile ); CPPUNIT_TEST_SUITE_END( ); }; void oldtests::test_profile(void) { rtl::OUString baseUrl; CPPUNIT_ASSERT(rtl::Bootstrap::get("UserInstallation", baseUrl)); // successful write oslProfile hProfile = osl_openProfile( rtl::OUString(baseUrl + "/soffice.ini").pData, osl_Profile_WRITELOCK ); CPPUNIT_ASSERT(hProfile != 0); CPPUNIT_ASSERT_MESSAGE( "cannot write into init file", osl_writeProfileBool( hProfile, "testsection", "testbool", 1 )); CPPUNIT_ASSERT(osl_closeProfile( hProfile )); // unsuccessful open CPPUNIT_ASSERT_EQUAL(oslProfile(0), osl_openProfile( rtl::OUString(baseUrl + "/not_existing_path/soffice.ini").pData, osl_Profile_WRITELOCK )); } } // namespace osl_Profile CPPUNIT_TEST_SUITE_REGISTRATION( osl_Profile::oldtests ); CPPUNIT_PLUGIN_IMPLEMENT(); /* vim:set shiftwidth=4 softtabstop=4 expandtab: */
Fix CppunitTest_sal_osl_profile
Fix CppunitTest_sal_osl_profile Change-Id: Ie66636881a2e4c754bd95f9d1d72e0b4fc2828df
C++
mpl-2.0
JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core
e1aa9b9403698d73045bf54bab6267d6854785d0
lib/Target/WebAssembly/MCTargetDesc/WebAssemblyAsmBackend.cpp
lib/Target/WebAssembly/MCTargetDesc/WebAssemblyAsmBackend.cpp
//===-- WebAssemblyAsmBackend.cpp - WebAssembly Assembler Backend ---------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// /// \file /// \brief This file implements the WebAssemblyAsmBackend class. /// //===----------------------------------------------------------------------===// #include "MCTargetDesc/WebAssemblyMCTargetDesc.h" #include "llvm/MC/MCAsmBackend.h" #include "llvm/MC/MCAssembler.h" #include "llvm/MC/MCDirectives.h" #include "llvm/MC/MCELFObjectWriter.h" #include "llvm/MC/MCExpr.h" #include "llvm/MC/MCFixupKindInfo.h" #include "llvm/MC/MCObjectWriter.h" #include "llvm/MC/MCSubtargetInfo.h" #include "llvm/MC/MCSymbol.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/raw_ostream.h" using namespace llvm; namespace { class WebAssemblyAsmBackend final : public MCAsmBackend { bool Is64Bit; public: explicit WebAssemblyAsmBackend(bool Is64Bit) : MCAsmBackend(), Is64Bit(Is64Bit) {} ~WebAssemblyAsmBackend() override {} void applyFixup(const MCFixup &Fixup, char *Data, unsigned DataSize, uint64_t Value, bool IsPCRel) const override; MCObjectWriter *createObjectWriter(raw_pwrite_stream &OS) const override; // No instruction requires relaxation bool fixupNeedsRelaxation(const MCFixup &Fixup, uint64_t Value, const MCRelaxableFragment *DF, const MCAsmLayout &Layout) const override { return false; } unsigned getNumFixupKinds() const override { // We currently just use the generic fixups in MCFixup.h and don't have any // target-specific fixups. return 0; } bool mayNeedRelaxation(const MCInst &Inst) const override { return false; } void relaxInstruction(const MCInst &Inst, MCInst &Res) const override {} bool writeNopData(uint64_t Count, MCObjectWriter *OW) const override; }; bool WebAssemblyAsmBackend::writeNopData(uint64_t Count, MCObjectWriter *OW) const { if (Count == 0) return true; // FIXME: Do something. return false; } void WebAssemblyAsmBackend::applyFixup(const MCFixup &Fixup, char *Data, unsigned DataSize, uint64_t Value, bool IsPCRel) const { const MCFixupKindInfo &Info = getFixupKindInfo(Fixup.getKind()); unsigned NumBytes = (Info.TargetSize + 7) / 8; if (Value == 0) return; // Doesn't change encoding. // Shift the value into position. Value <<= Info.TargetOffset; unsigned Offset = Fixup.getOffset(); assert(Offset + NumBytes <= DataSize && "Invalid fixup offset!"); // For each byte of the fragment that the fixup touches, mask in the // bits from the fixup value. for (unsigned i = 0; i != NumBytes; ++i) Data[Offset + i] |= uint8_t((Value >> (i * 8)) & 0xff); } MCObjectWriter * WebAssemblyAsmBackend::createObjectWriter(raw_pwrite_stream &OS) const { return createWebAssemblyELFObjectWriter(OS, Is64Bit, 0); } } // end anonymous namespace MCAsmBackend *llvm::createWebAssemblyAsmBackend(const Triple &TT) { return new WebAssemblyAsmBackend(TT.isArch64Bit()); }
//===-- WebAssemblyAsmBackend.cpp - WebAssembly Assembler Backend ---------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// /// \file /// \brief This file implements the WebAssemblyAsmBackend class. /// //===----------------------------------------------------------------------===// #include "MCTargetDesc/WebAssemblyMCTargetDesc.h" #include "llvm/MC/MCAsmBackend.h" #include "llvm/MC/MCAssembler.h" #include "llvm/MC/MCDirectives.h" #include "llvm/MC/MCELFObjectWriter.h" #include "llvm/MC/MCExpr.h" #include "llvm/MC/MCFixupKindInfo.h" #include "llvm/MC/MCObjectWriter.h" #include "llvm/MC/MCSubtargetInfo.h" #include "llvm/MC/MCSymbol.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/raw_ostream.h" using namespace llvm; namespace { class WebAssemblyAsmBackend final : public MCAsmBackend { bool Is64Bit; public: explicit WebAssemblyAsmBackend(bool Is64Bit) : MCAsmBackend(), Is64Bit(Is64Bit) {} ~WebAssemblyAsmBackend() override {} void applyFixup(const MCFixup &Fixup, char *Data, unsigned DataSize, uint64_t Value, bool IsPCRel) const override; MCObjectWriter *createObjectWriter(raw_pwrite_stream &OS) const override; // No instruction requires relaxation bool fixupNeedsRelaxation(const MCFixup &Fixup, uint64_t Value, const MCRelaxableFragment *DF, const MCAsmLayout &Layout) const override { return false; } unsigned getNumFixupKinds() const override { // We currently just use the generic fixups in MCFixup.h and don't have any // target-specific fixups. return 0; } bool mayNeedRelaxation(const MCInst &Inst) const override { return false; } void relaxInstruction(const MCInst &Inst, MCInst &Res) const override {} bool writeNopData(uint64_t Count, MCObjectWriter *OW) const override; }; bool WebAssemblyAsmBackend::writeNopData(uint64_t Count, MCObjectWriter *OW) const { if (Count == 0) return true; // FIXME: Do something. return false; } void WebAssemblyAsmBackend::applyFixup(const MCFixup &Fixup, char *Data, unsigned DataSize, uint64_t Value, bool IsPCRel) const { const MCFixupKindInfo &Info = getFixupKindInfo(Fixup.getKind()); assert(Info.Flags == 0 && "WebAssembly does not use MCFixupKindInfo flags"); unsigned NumBytes = (Info.TargetSize + 7) / 8; if (Value == 0) return; // Doesn't change encoding. // Shift the value into position. Value <<= Info.TargetOffset; unsigned Offset = Fixup.getOffset(); assert(Offset + NumBytes <= DataSize && "Invalid fixup offset!"); // For each byte of the fragment that the fixup touches, mask in the // bits from the fixup value. for (unsigned i = 0; i != NumBytes; ++i) Data[Offset + i] |= uint8_t((Value >> (i * 8)) & 0xff); } MCObjectWriter * WebAssemblyAsmBackend::createObjectWriter(raw_pwrite_stream &OS) const { return createWebAssemblyELFObjectWriter(OS, Is64Bit, 0); } } // end anonymous namespace MCAsmBackend *llvm::createWebAssemblyAsmBackend(const Triple &TT) { return new WebAssemblyAsmBackend(TT.isArch64Bit()); }
Add an assertion to catch unexpected MCFixupKindInfo flags.
[WebAssembly] Add an assertion to catch unexpected MCFixupKindInfo flags. git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@257657 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
llvm-mirror/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,llvm-mirror/llvm,llvm-mirror/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,apple/swift-llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,apple/swift-llvm,llvm-mirror/llvm
f8974fb72e90eeeada3cc3a347afcc3321d7c42a
src/GameStyle.cpp
src/GameStyle.cpp
#include "GameStyle.h" #include <TranslationUtils.h> #include <Application.h> #include <Directory.h> #include <Path.h> #include <Roster.h> #include <String.h> #include <TranslatorFormats.h> GameStyle::GameStyle(const char *path) : fSmileyUp(NULL), fSmileyDown(NULL), fWinUp(NULL), fWinDown(NULL), fLoseUp(NULL), fLoseDown(NULL), fWorry(NULL), fBoxSprite(NULL), fBoxDownSprite(NULL), fBaseSprite(NULL), fHitSprite(NULL), fMineSprite(NULL), fNotMineSprite(NULL), fFlagSprite(NULL), fQuestionSprite(NULL), fStyleList(20,true), fStyleName("Default") { int32 i; for (i = 0; i < 8; i++) fNumbers[i] = NULL; for (i = 0; i < 10; i++) fLEDNumbers[i] = NULL; ScanStyles(); if (!path || !SetStyle(path)) SetStyle(NULL); } GameStyle::~GameStyle(void) { MakeEmpty(); } int32 GameStyle::CountStyles(void) { return fStyleList.CountItems(); } const char * GameStyle::StyleAt(const int32 &index) { StyleData *data = fStyleList.ItemAt(index); return data ? data->name.String() : NULL; } bool GameStyle::SetStyle(const char *stylename) { StyleData *data = NULL; entry_ref ref; BString name; if (stylename) { for (int32 i = 0; i < fStyleList.CountItems(); i++) { StyleData *item = fStyleList.ItemAt(i); if (item->name.Compare(stylename) == 0) { data = item; break; } } if (data) { BEntry entry(data->path.String()); entry.GetRef(&ref); name = ref.name; } else { fStyleName = "Default"; return false; } } MakeEmpty(); fBoxSprite = GetStyleBitmap(ref,"unmarked.png"); fBoxDownSprite = GetStyleBitmap(ref,"down.png"); fBaseSprite = GetStyleBitmap(ref,"tilebase.png"); fHitSprite = GetStyleBitmap(ref,"hit.png"); fMineSprite = GetStyleBitmap(ref,"mine.png"); fNotMineSprite = GetStyleBitmap(ref,"notmine.png"); fFlagSprite = GetStyleBitmap(ref,"flag.png"); fQuestionSprite = GetStyleBitmap(ref,"question.png"); fSmileyUp = GetStyleBitmap(ref,"smileybase.png"); fSmileyDown = GetStyleBitmap(ref,"smileybasedown.png"); fWinUp = GetStyleBitmap(ref,"smiley-win.png"); fWinDown = GetStyleBitmap(ref,"smiley-windown.png"); fLoseUp = GetStyleBitmap(ref,"smiley-lose.png"); fLoseDown = GetStyleBitmap(ref,"smiley-losedown.png"); fWorry = GetStyleBitmap(ref,"smiley-worry.png"); int32 i; for (i = 1; i < 9; i++) { BString bmpname = "mine"; bmpname << i << ".png"; fNumbers[i - 1] = GetStyleBitmap(ref,bmpname.String()); } for (i = 0; i < 10; i++) { BString ledname = "led"; ledname << i << ".png"; fLEDNumbers[i] = GetStyleBitmap(ref,ledname.String()); } fStyleName = data ? data->name : "Default"; return true; } const char * GameStyle::StyleName(void) { return fStyleName.String(); } BRect GameStyle::TileSize(void) { return fBoxSprite->Bounds(); } BRect GameStyle::TileRect(int x, int y) { BRect r = TileSize(); r.OffsetBy( ( (r.Width() + 1.0) * x), ( (r.Height() + 1.0) * y)); return r; } BBitmap * GameStyle::BaseSprite(void) { return fBaseSprite; } BBitmap * GameStyle::BoxSprite(void) { return fBoxSprite; } BBitmap * GameStyle::BoxDownSprite(void) { return fBoxDownSprite; } BBitmap * GameStyle::MineSprite(void) { return fMineSprite; } BBitmap * GameStyle::NotMineSprite(void) { return fNotMineSprite; } BBitmap * GameStyle::QuestionSprite(void) { return fQuestionSprite; } BBitmap * GameStyle::FlagSprite(void) { return fFlagSprite; } BBitmap * GameStyle::HitSprite(void) { return fHitSprite; } BBitmap * GameStyle::LEDSprite(uint8 value) { return fLEDNumbers[value]; } BBitmap * GameStyle::NumberSprite(uint8 count) { if (count < 1 || count > 8) debugger("Bad number sprite value"); return fNumbers[count - 1]; } BBitmap * GameStyle::SmileyUp(void) { return fSmileyUp; } BBitmap * GameStyle::SmileyDown(void) { return fSmileyDown; } BBitmap * GameStyle::WinUp(void) { return fWinUp; } BBitmap * GameStyle::WinDown(void) { return fWinDown; } BBitmap * GameStyle::LoseUp(void) { return fLoseUp; } BBitmap * GameStyle::LoseDown(void) { return fLoseDown; } BBitmap * GameStyle::Worry(void) { return fWorry; } BBitmap ** GameStyle::LEDSprites(void) { return fLEDNumbers; } BBitmap ** GameStyle::NumberSprites(void) { return fNumbers; } void GameStyle::MakeEmpty(void) { delete fBoxSprite; delete fBoxDownSprite; delete fBaseSprite; delete fHitSprite; delete fMineSprite; delete fNotMineSprite; delete fFlagSprite; delete fQuestionSprite; int32 i; for (i = 0; i < 8; i++) delete fNumbers[i]; for (i = 0; i < 10; i++) delete fLEDNumbers[i]; } void GameStyle::ScanStyles(void) { static const char * bitmapNames[] = { "tilebase.png", "unmarked.png", "down.png", "mine.png", "notmine.png", "question.png", "flag.png", "hit.png", "smileybase.png", "smileybasedown.png", "smiley-worry.png", "smiley-win.png", "smiley-windown.png", "smiley-lose.png", "smiley-losedown.png", NULL }; app_info ai; be_app->GetAppInfo(&ai); BPath path(&ai.ref); path.GetParent(&path); path.Append("themes"); BDirectory dir(path.Path()); dir.Rewind(); BEntry entry; while (dir.GetNextEntry(&entry) == B_OK) { if (!entry.IsDirectory()) continue; BString styleName,stylePath; bool is_broken = false; entry_ref ref; entry.GetRef(&ref); styleName = ref.name; path.SetTo(&ref); stylePath = path.Path(); // Scan for the existence of all the necessary files. We can function without // a style being complete, but the user should be notified about the problems BPath temppath; for (int8 i = 0; bitmapNames[i] != NULL; i++) { temppath.SetTo(&ref); temppath.Append(bitmapNames[i]); if (!BEntry(temppath.Path()).Exists()) { is_broken = true; break; } } int32 i; if (!is_broken) { for (i = 1; i < 9; i++) { BString bmpname = "mine"; bmpname << i << ".png"; temppath.SetTo(&ref); bmpname.Prepend("/"); bmpname.Prepend(temppath.Path()); if (!BEntry(bmpname.String()).Exists()) { is_broken = true; break; } } } if (!is_broken) { for (i = 0; i < 10; i++) { BString ledname = "led"; ledname << i << ".png"; temppath.SetTo(&ref); ledname.Prepend("/"); ledname.Prepend(temppath.Path()); if (!BEntry(ledname.String()).Exists()) { is_broken = true; break; } } } fStyleList.AddItem(new StyleData(styleName.String(),stylePath.String(),is_broken)); } // end style directory scanning loop } BBitmap * GameStyle::GetStyleBitmap(entry_ref dir, const char *name) { BPath path(&dir); path.Append(name); BBitmap *bmp = NULL; bmp = BTranslationUtils::GetBitmap(path.Path()); if (!bmp) bmp = BTranslationUtils::GetBitmap(B_PNG_FORMAT,name); return bmp; } StyleData::StyleData(void) : broken(false) { } StyleData:: StyleData(const char *stylename, const char *stylepath, bool is_broken) : name(stylename), path(stylepath), broken(is_broken) { }
#include "GameStyle.h" #include <TranslationUtils.h> #include <Application.h> #include <Directory.h> #include <Path.h> #include <Roster.h> #include <String.h> #include <TranslatorFormats.h> GameStyle::GameStyle(const char *path) : fSmileyUp(NULL), fSmileyDown(NULL), fWinUp(NULL), fWinDown(NULL), fLoseUp(NULL), fLoseDown(NULL), fWorry(NULL), fBoxSprite(NULL), fBoxDownSprite(NULL), fBaseSprite(NULL), fHitSprite(NULL), fMineSprite(NULL), fNotMineSprite(NULL), fFlagSprite(NULL), fQuestionSprite(NULL), fStyleList(20,true), fStyleName("Default") { int32 i; for (i = 0; i < 8; i++) fNumbers[i] = NULL; for (i = 0; i < 10; i++) fLEDNumbers[i] = NULL; ScanStyles(); if (!path || !SetStyle(path)) SetStyle(NULL); } GameStyle::~GameStyle(void) { MakeEmpty(); } int32 GameStyle::CountStyles(void) { return fStyleList.CountItems(); } const char * GameStyle::StyleAt(const int32 &index) { StyleData *data = fStyleList.ItemAt(index); return data ? data->name.String() : NULL; } bool GameStyle::SetStyle(const char *stylename) { StyleData *data = NULL; entry_ref ref; BString name; if (stylename) { for (int32 i = 0; i < fStyleList.CountItems(); i++) { StyleData *item = fStyleList.ItemAt(i); if (item->name.Compare(stylename) == 0) { data = item; break; } } if (data) { BEntry entry(data->path.String()); entry.GetRef(&ref); name = ref.name; } else { fStyleName = "Default"; return false; } } MakeEmpty(); fBoxSprite = GetStyleBitmap(ref,"unmarked.png"); fBoxDownSprite = GetStyleBitmap(ref,"down.png"); fBaseSprite = GetStyleBitmap(ref,"tilebase.png"); fHitSprite = GetStyleBitmap(ref,"hit.png"); fMineSprite = GetStyleBitmap(ref,"mine.png"); fNotMineSprite = GetStyleBitmap(ref,"notmine.png"); fFlagSprite = GetStyleBitmap(ref,"flag.png"); fQuestionSprite = GetStyleBitmap(ref,"question.png"); fSmileyUp = GetStyleBitmap(ref,"smileybase.png"); fSmileyDown = GetStyleBitmap(ref,"smileybasedown.png"); fWinUp = GetStyleBitmap(ref,"smiley-win.png"); fWinDown = GetStyleBitmap(ref,"smiley-windown.png"); fLoseUp = GetStyleBitmap(ref,"smiley-lose.png"); fLoseDown = GetStyleBitmap(ref,"smiley-losedown.png"); fWorry = GetStyleBitmap(ref,"smiley-worry.png"); int32 i; for (i = 1; i < 9; i++) { BString bmpname = "mine"; bmpname << i << ".png"; fNumbers[i - 1] = GetStyleBitmap(ref,bmpname.String()); } for (i = 0; i < 10; i++) { BString ledname = "led"; ledname << i << ".png"; fLEDNumbers[i] = GetStyleBitmap(ref,ledname.String()); } fStyleName = data ? data->name : BString("Default"); return true; } const char * GameStyle::StyleName(void) { return fStyleName.String(); } BRect GameStyle::TileSize(void) { return fBoxSprite->Bounds(); } BRect GameStyle::TileRect(int x, int y) { BRect r = TileSize(); r.OffsetBy( ( (r.Width() + 1.0) * x), ( (r.Height() + 1.0) * y)); return r; } BBitmap * GameStyle::BaseSprite(void) { return fBaseSprite; } BBitmap * GameStyle::BoxSprite(void) { return fBoxSprite; } BBitmap * GameStyle::BoxDownSprite(void) { return fBoxDownSprite; } BBitmap * GameStyle::MineSprite(void) { return fMineSprite; } BBitmap * GameStyle::NotMineSprite(void) { return fNotMineSprite; } BBitmap * GameStyle::QuestionSprite(void) { return fQuestionSprite; } BBitmap * GameStyle::FlagSprite(void) { return fFlagSprite; } BBitmap * GameStyle::HitSprite(void) { return fHitSprite; } BBitmap * GameStyle::LEDSprite(uint8 value) { return fLEDNumbers[value]; } BBitmap * GameStyle::NumberSprite(uint8 count) { if (count < 1 || count > 8) debugger("Bad number sprite value"); return fNumbers[count - 1]; } BBitmap * GameStyle::SmileyUp(void) { return fSmileyUp; } BBitmap * GameStyle::SmileyDown(void) { return fSmileyDown; } BBitmap * GameStyle::WinUp(void) { return fWinUp; } BBitmap * GameStyle::WinDown(void) { return fWinDown; } BBitmap * GameStyle::LoseUp(void) { return fLoseUp; } BBitmap * GameStyle::LoseDown(void) { return fLoseDown; } BBitmap * GameStyle::Worry(void) { return fWorry; } BBitmap ** GameStyle::LEDSprites(void) { return fLEDNumbers; } BBitmap ** GameStyle::NumberSprites(void) { return fNumbers; } void GameStyle::MakeEmpty(void) { delete fBoxSprite; delete fBoxDownSprite; delete fBaseSprite; delete fHitSprite; delete fMineSprite; delete fNotMineSprite; delete fFlagSprite; delete fQuestionSprite; int32 i; for (i = 0; i < 8; i++) delete fNumbers[i]; for (i = 0; i < 10; i++) delete fLEDNumbers[i]; } void GameStyle::ScanStyles(void) { static const char * bitmapNames[] = { "tilebase.png", "unmarked.png", "down.png", "mine.png", "notmine.png", "question.png", "flag.png", "hit.png", "smileybase.png", "smileybasedown.png", "smiley-worry.png", "smiley-win.png", "smiley-windown.png", "smiley-lose.png", "smiley-losedown.png", NULL }; app_info ai; be_app->GetAppInfo(&ai); BPath path(&ai.ref); path.GetParent(&path); path.Append("themes"); BDirectory dir(path.Path()); dir.Rewind(); BEntry entry; while (dir.GetNextEntry(&entry) == B_OK) { if (!entry.IsDirectory()) continue; BString styleName,stylePath; bool is_broken = false; entry_ref ref; entry.GetRef(&ref); styleName = ref.name; path.SetTo(&ref); stylePath = path.Path(); // Scan for the existence of all the necessary files. We can function without // a style being complete, but the user should be notified about the problems BPath temppath; for (int8 i = 0; bitmapNames[i] != NULL; i++) { temppath.SetTo(&ref); temppath.Append(bitmapNames[i]); if (!BEntry(temppath.Path()).Exists()) { is_broken = true; break; } } int32 i; if (!is_broken) { for (i = 1; i < 9; i++) { BString bmpname = "mine"; bmpname << i << ".png"; temppath.SetTo(&ref); bmpname.Prepend("/"); bmpname.Prepend(temppath.Path()); if (!BEntry(bmpname.String()).Exists()) { is_broken = true; break; } } } if (!is_broken) { for (i = 0; i < 10; i++) { BString ledname = "led"; ledname << i << ".png"; temppath.SetTo(&ref); ledname.Prepend("/"); ledname.Prepend(temppath.Path()); if (!BEntry(ledname.String()).Exists()) { is_broken = true; break; } } } fStyleList.AddItem(new StyleData(styleName.String(),stylePath.String(),is_broken)); } // end style directory scanning loop } BBitmap * GameStyle::GetStyleBitmap(entry_ref dir, const char *name) { BPath path(&dir); path.Append(name); BBitmap *bmp = NULL; bmp = BTranslationUtils::GetBitmap(path.Path()); if (!bmp) bmp = BTranslationUtils::GetBitmap(B_PNG_FORMAT,name); return bmp; } StyleData::StyleData(void) : broken(false) { } StyleData:: StyleData(const char *stylename, const char *stylepath, bool is_broken) : name(stylename), path(stylepath), broken(is_broken) { }
Build fix.
Build fix.
C++
mit
HaikuArchives/BeMines
a94a92af7fdba018e87f048cf05b7b5fc1b16c14
src/Geo/QGCGeo.cc
src/Geo/QGCGeo.cc
/**************************************************************************** * * (c) 2009-2016 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org> * * QGroundControl is licensed according to the terms in the file * COPYING.md in the root of the source code directory. * ****************************************************************************/ #include <QDebug> #include <QString> #include <cmath> #include <limits> #include "QGCGeo.h" #include "UTMUPS.hpp" #include "MGRS.hpp" // These defines are private #define M_DEG_TO_RAD (M_PI / 180.0) #define M_RAD_TO_DEG (180.0 / M_PI) #define CONSTANTS_RADIUS_OF_EARTH 6371000 // meters (m) static const double epsilon = std::numeric_limits<double>::epsilon(); void convertGeoToNed(QGeoCoordinate coord, QGeoCoordinate origin, double* x, double* y, double* z) { if (coord == origin) { // Short circuit to prevent NaNs in calculation *x = *y = *z = 0; return; } double lat_rad = coord.latitude() * M_DEG_TO_RAD; double lon_rad = coord.longitude() * M_DEG_TO_RAD; double ref_lon_rad = origin.longitude() * M_DEG_TO_RAD; double ref_lat_rad = origin.latitude() * M_DEG_TO_RAD; double sin_lat = sin(lat_rad); double cos_lat = cos(lat_rad); double cos_d_lon = cos(lon_rad - ref_lon_rad); double ref_sin_lat = sin(ref_lat_rad); double ref_cos_lat = cos(ref_lat_rad); double c = acos(ref_sin_lat * sin_lat + ref_cos_lat * cos_lat * cos_d_lon); double k = (abs(c) < epsilon) ? 1.0 : (c / sin(c)); *x = k * (ref_cos_lat * sin_lat - ref_sin_lat * cos_lat * cos_d_lon) * CONSTANTS_RADIUS_OF_EARTH; *y = k * cos_lat * sin(lon_rad - ref_lon_rad) * CONSTANTS_RADIUS_OF_EARTH; *z = -(coord.altitude() - origin.altitude()); } void convertNedToGeo(double x, double y, double z, QGeoCoordinate origin, QGeoCoordinate *coord) { double x_rad = x / CONSTANTS_RADIUS_OF_EARTH; double y_rad = y / CONSTANTS_RADIUS_OF_EARTH; double c = sqrt(x_rad * x_rad + y_rad * y_rad); double sin_c = sin(c); double cos_c = cos(c); double ref_lon_rad = origin.longitude() * M_DEG_TO_RAD; double ref_lat_rad = origin.latitude() * M_DEG_TO_RAD; double ref_sin_lat = sin(ref_lat_rad); double ref_cos_lat = cos(ref_lat_rad); double lat_rad; double lon_rad; if (abs(c) > epsilon) { lat_rad = asin(cos_c * ref_sin_lat + (x_rad * sin_c * ref_cos_lat) / c); lon_rad = (ref_lon_rad + atan2(y_rad * sin_c, c * ref_cos_lat * cos_c - x_rad * ref_sin_lat * sin_c)); } else { lat_rad = ref_lat_rad; lon_rad = ref_lon_rad; } coord->setLatitude(lat_rad * M_RAD_TO_DEG); coord->setLongitude(lon_rad * M_RAD_TO_DEG); coord->setAltitude(-z + origin.altitude()); } int convertGeoToUTM(const QGeoCoordinate& coord, double& easting, double& northing) { try { int zone; bool northp; GeographicLib::UTMUPS::Forward(coord.latitude(), coord.longitude(), zone, northp, easting, northing); return zone; } catch(...) { return 0; } } bool convertUTMToGeo(double easting, double northing, int zone, bool southhemi, QGeoCoordinate& coord) { double lat, lon; try { GeographicLib::UTMUPS::Reverse(zone, !southhemi, easting, northing, lat, lon); } catch(...) { return false; } coord.setLatitude(lat); coord.setLongitude(lon); return true; } QString convertGeoToMGRS(const QGeoCoordinate& coord) { int zone; bool northp; double x, y; std::string mgrs; try { GeographicLib::UTMUPS::Forward(coord.latitude(), coord.longitude(), zone, northp, x, y); GeographicLib::MGRS::Forward(zone, northp, x, y, coord.latitude(), 5, mgrs); } catch(...) { mgrs = ""; } QString qstr = QString::fromStdString(mgrs); for (int i = qstr.length() - 1; i >= 0; i--) { if (!qstr.at(i).isDigit()) { int l = (qstr.length() - i) / 2; return qstr.left(i + 1) + " " + qstr.mid(i + 1, l) + " " + qstr.mid(i + 1 + l); } } return qstr; } bool convertMGRSToGeo(QString mgrs, QGeoCoordinate& coord) { int zone, prec; bool northp; double x, y; double lat, lon; try { GeographicLib::MGRS::Reverse(mgrs.simplified().replace(" ", "").toStdString(), zone, northp, x, y, prec); GeographicLib::UTMUPS::Reverse(zone, northp, x, y, lat, lon); } catch(...) { return false; } coord.setLatitude(lat); coord.setLongitude(lon); return true; }
/**************************************************************************** * * (c) 2009-2016 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org> * * QGroundControl is licensed according to the terms in the file * COPYING.md in the root of the source code directory. * ****************************************************************************/ #include <QDebug> #include <QString> #include <cmath> #include <limits> #include "QGCGeo.h" #include "UTMUPS.hpp" #include "MGRS.hpp" // These defines are private #define M_DEG_TO_RAD (M_PI / 180.0) #define M_RAD_TO_DEG (180.0 / M_PI) #define CONSTANTS_RADIUS_OF_EARTH 6371000 // meters (m) static const double epsilon = std::numeric_limits<double>::epsilon(); void convertGeoToNed(QGeoCoordinate coord, QGeoCoordinate origin, double* x, double* y, double* z) { if (coord == origin) { // Short circuit to prevent NaNs in calculation *x = *y = *z = 0; return; } double lat_rad = coord.latitude() * M_DEG_TO_RAD; double lon_rad = coord.longitude() * M_DEG_TO_RAD; double ref_lon_rad = origin.longitude() * M_DEG_TO_RAD; double ref_lat_rad = origin.latitude() * M_DEG_TO_RAD; double sin_lat = sin(lat_rad); double cos_lat = cos(lat_rad); double cos_d_lon = cos(lon_rad - ref_lon_rad); double ref_sin_lat = sin(ref_lat_rad); double ref_cos_lat = cos(ref_lat_rad); double c = acos(ref_sin_lat * sin_lat + ref_cos_lat * cos_lat * cos_d_lon); double k = (fabs(c) < epsilon) ? 1.0 : (c / sin(c)); *x = k * (ref_cos_lat * sin_lat - ref_sin_lat * cos_lat * cos_d_lon) * CONSTANTS_RADIUS_OF_EARTH; *y = k * cos_lat * sin(lon_rad - ref_lon_rad) * CONSTANTS_RADIUS_OF_EARTH; *z = -(coord.altitude() - origin.altitude()); } void convertNedToGeo(double x, double y, double z, QGeoCoordinate origin, QGeoCoordinate *coord) { double x_rad = x / CONSTANTS_RADIUS_OF_EARTH; double y_rad = y / CONSTANTS_RADIUS_OF_EARTH; double c = sqrt(x_rad * x_rad + y_rad * y_rad); double sin_c = sin(c); double cos_c = cos(c); double ref_lon_rad = origin.longitude() * M_DEG_TO_RAD; double ref_lat_rad = origin.latitude() * M_DEG_TO_RAD; double ref_sin_lat = sin(ref_lat_rad); double ref_cos_lat = cos(ref_lat_rad); double lat_rad; double lon_rad; if (fabs(c) > epsilon) { lat_rad = asin(cos_c * ref_sin_lat + (x_rad * sin_c * ref_cos_lat) / c); lon_rad = (ref_lon_rad + atan2(y_rad * sin_c, c * ref_cos_lat * cos_c - x_rad * ref_sin_lat * sin_c)); } else { lat_rad = ref_lat_rad; lon_rad = ref_lon_rad; } coord->setLatitude(lat_rad * M_RAD_TO_DEG); coord->setLongitude(lon_rad * M_RAD_TO_DEG); coord->setAltitude(-z + origin.altitude()); } int convertGeoToUTM(const QGeoCoordinate& coord, double& easting, double& northing) { try { int zone; bool northp; GeographicLib::UTMUPS::Forward(coord.latitude(), coord.longitude(), zone, northp, easting, northing); return zone; } catch(...) { return 0; } } bool convertUTMToGeo(double easting, double northing, int zone, bool southhemi, QGeoCoordinate& coord) { double lat, lon; try { GeographicLib::UTMUPS::Reverse(zone, !southhemi, easting, northing, lat, lon); } catch(...) { return false; } coord.setLatitude(lat); coord.setLongitude(lon); return true; } QString convertGeoToMGRS(const QGeoCoordinate& coord) { int zone; bool northp; double x, y; std::string mgrs; try { GeographicLib::UTMUPS::Forward(coord.latitude(), coord.longitude(), zone, northp, x, y); GeographicLib::MGRS::Forward(zone, northp, x, y, coord.latitude(), 5, mgrs); } catch(...) { mgrs = ""; } QString qstr = QString::fromStdString(mgrs); for (int i = qstr.length() - 1; i >= 0; i--) { if (!qstr.at(i).isDigit()) { int l = (qstr.length() - i) / 2; return qstr.left(i + 1) + " " + qstr.mid(i + 1, l) + " " + qstr.mid(i + 1 + l); } } return qstr; } bool convertMGRSToGeo(QString mgrs, QGeoCoordinate& coord) { int zone, prec; bool northp; double x, y; double lat, lon; try { GeographicLib::MGRS::Reverse(mgrs.simplified().replace(" ", "").toStdString(), zone, northp, x, y, prec); GeographicLib::UTMUPS::Reverse(zone, northp, x, y, lat, lon); } catch(...) { return false; } coord.setLatitude(lat); coord.setLongitude(lon); return true; }
Fix convertGeoToNed and convertNedToGeo
Fix convertGeoToNed and convertNedToGeo
C++
agpl-3.0
Hunter522/qgroundcontrol,Hunter522/qgroundcontrol,Hunter522/qgroundcontrol,Hunter522/qgroundcontrol,Hunter522/qgroundcontrol,Hunter522/qgroundcontrol
d16db11657a6815cf062d33391885a1d57aeadf1
modules/stochastic_tools/src/controls/MultiAppCommandLineControl.C
modules/stochastic_tools/src/controls/MultiAppCommandLineControl.C
//* This file is part of the MOOSE framework //* https://www.mooseframework.org //* //* All rights reserved, see COPYRIGHT for full restrictions //* https://github.com/idaholab/moose/blob/master/COPYRIGHT //* //* Licensed under LGPL 2.1, please see LICENSE for details //* https://www.gnu.org/licenses/lgpl-2.1.html // MOOSE includes #include "MultiAppCommandLineControl.h" #include "Function.h" #include "Sampler.h" #include "MultiApp.h" #include "SamplerFullSolveMultiApp.h" registerMooseObject("StochasticToolsApp", MultiAppCommandLineControl); template <> InputParameters validParams<MultiAppCommandLineControl>() { InputParameters params = validParams<Control>(); params += validParams<SamplerInterface>(); params.addClassDescription("Control for modifying the command line arguments of MultiApps."); // Set and suppress the 'execute_on' flag, it doesn't work with any other flag params.set<ExecFlagEnum>("execute_on") = {EXEC_PRE_MULTIAPP_SETUP}; params.suppressParameter<ExecFlagEnum>("execute_on"); params.addRequiredParam<MultiAppName>("multi_app", "The name of the MultiApp to control."); params.addParam<SamplerName>( "sampler", "The Sampler object to utilize for altering the command line options of the MultiApp."); params.addParam<std::vector<std::string>>( "param_names", "The names of the command line parameters to set via the sampled data."); return params; } MultiAppCommandLineControl::MultiAppCommandLineControl(const InputParameters & parameters) : Control(parameters), SamplerInterface(this), _multi_app(_fe_problem.getMultiApp(getParam<MultiAppName>("multi_app"))), _sampler(SamplerInterface::getSampler("sampler")), _param_names(getParam<std::vector<std::string>>("param_names")) { if (!_sampler.getParamTempl<ExecFlagEnum>("execute_on").contains(EXEC_PRE_MULTIAPP_SETUP)) _sampler.paramError( "execute_on", "The sampler object, '", _sampler.name(), "', is being used by the '", name(), "' object, thus the 'execute_on' of the sampler must include 'PRE_MULTIAPP_SETUP'."); bool batch_reset = _multi_app->isParamValid("mode") && (_multi_app->getParamTempl<MooseEnum>("mode") == "batch-reset"); bool batch_restore = _multi_app->isParamValid("mode") && (_multi_app->getParamTempl<MooseEnum>("mode") == "batch-restore"); if (batch_reset) ; // Do not perform the App count test, because in batch mode there is only one else if (batch_restore) _multi_app->paramError( "mode", "The MultiApp object, '", _multi_app->name(), "', supplied to the '", name(), "' object is setup to run in 'batch-restore' mode, when using this mode command line " "arguments cannot be modified; batch-reset mode should be used instead."); else if (_multi_app->numGlobalApps() != _sampler.getNumberOfRows()) mooseError("The number of sub apps (", _multi_app->numGlobalApps(), ") created by MultiApp object '", _multi_app->name(), "' must be equal to the number for rows (", _sampler.getNumberOfRows(), ") for the '", _sampler.name(), "' Sampler object."); } void MultiAppCommandLineControl::initialSetup() { // Do not put anything here, this method is being called after execute because the execute_on // is set to PRE_MULTIAPP_SETUP for this class. It won't work any other way. } void MultiAppCommandLineControl::execute() { std::vector<std::string> cli_args; DenseMatrix<Real> matrix = _sampler.getLocalSamples(); if (matrix.n() != _param_names.size()) paramError("param_names", "The number of columns (", matrix.n(), ") must match the number of parameters (", _param_names.size(), ")."); // For SamplerFullSolveMultiApp, to avoid storing duplicated param_names for each sampler, we // store only param_names once in "cli_args". For other MultApp, we store the full information // of params_names and values for each sampler. if (std::dynamic_pointer_cast<SamplerFullSolveMultiApp>(_multi_app) == nullptr) { for (unsigned int row = 0; row < matrix.m(); ++row) { std::ostringstream oss; for (unsigned int col = 0; col < matrix.n(); ++col) { if (col > 0) oss << ";"; oss << _param_names[col] << "=" << Moose::stringify(matrix(row, col)); } cli_args.push_back(oss.str()); } } else { std::ostringstream oss; for (unsigned int col = 0; col < matrix.n(); ++col) { if (col > 0) oss << ";"; oss << _param_names[col]; } cli_args.push_back(oss.str()); } setControllableValueByName<std::vector<std::string>>( "MultiApp", _multi_app->name(), "cli_args", cli_args); }
//* This file is part of the MOOSE framework //* https://www.mooseframework.org //* //* All rights reserved, see COPYRIGHT for full restrictions //* https://github.com/idaholab/moose/blob/master/COPYRIGHT //* //* Licensed under LGPL 2.1, please see LICENSE for details //* https://www.gnu.org/licenses/lgpl-2.1.html // MOOSE includes #include "MultiAppCommandLineControl.h" #include "Function.h" #include "Sampler.h" #include "MultiApp.h" #include "SamplerFullSolveMultiApp.h" registerMooseObject("StochasticToolsApp", MultiAppCommandLineControl); template <> InputParameters validParams<MultiAppCommandLineControl>() { InputParameters params = validParams<Control>(); params += validParams<SamplerInterface>(); params.addClassDescription("Control for modifying the command line arguments of MultiApps."); // Set and suppress the 'execute_on' flag, it doesn't work with any other flag params.set<ExecFlagEnum>("execute_on") = {EXEC_PRE_MULTIAPP_SETUP}; params.suppressParameter<ExecFlagEnum>("execute_on"); params.addRequiredParam<MultiAppName>("multi_app", "The name of the MultiApp to control."); params.addParam<SamplerName>( "sampler", "The Sampler object to utilize for altering the command line options of the MultiApp."); params.addParam<std::vector<std::string>>( "param_names", "The names of the command line parameters to set via the sampled data."); return params; } MultiAppCommandLineControl::MultiAppCommandLineControl(const InputParameters & parameters) : Control(parameters), SamplerInterface(this), _multi_app(_fe_problem.getMultiApp(getParam<MultiAppName>("multi_app"))), _sampler(SamplerInterface::getSampler("sampler")), _param_names(getParam<std::vector<std::string>>("param_names")) { if (!_sampler.getParamTempl<ExecFlagEnum>("execute_on").contains(EXEC_PRE_MULTIAPP_SETUP)) _sampler.paramError( "execute_on", "The sampler object, '", _sampler.name(), "', is being used by the '", name(), "' object, thus the 'execute_on' of the sampler must include 'PRE_MULTIAPP_SETUP'."); bool batch_reset = _multi_app->isParamValid("mode") && (_multi_app->getParamTempl<MooseEnum>("mode") == "batch-reset"); bool batch_restore = _multi_app->isParamValid("mode") && (_multi_app->getParamTempl<MooseEnum>("mode") == "batch-restore"); if (batch_reset) ; // Do not perform the App count test, because in batch mode there is only one else if (batch_restore) _multi_app->paramError( "mode", "The MultiApp object, '", _multi_app->name(), "', supplied to the '", name(), "' object is setup to run in 'batch-restore' mode, when using this mode command line " "arguments cannot be modified; batch-reset mode should be used instead."); else if (_multi_app->numGlobalApps() != _sampler.getNumberOfRows()) mooseError("The number of sub apps (", _multi_app->numGlobalApps(), ") created by MultiApp object '", _multi_app->name(), "' must be equal to the number for rows (", _sampler.getNumberOfRows(), ") for the '", _sampler.name(), "' Sampler object."); } void MultiAppCommandLineControl::initialSetup() { // Do not put anything here, this method is being called after execute because the execute_on // is set to PRE_MULTIAPP_SETUP for this class. It won't work any other way. } void MultiAppCommandLineControl::execute() { std::vector<std::string> cli_args; if (_sampler.getNumberOfCols() != _param_names.size()) paramError("param_names", "The number of columns (", _sampler.getNumberOfCols(), ") must match the number of parameters (", _param_names.size(), ")."); // For SamplerFullSolveMultiApp, to avoid storing duplicated param_names for each sampler, we // store only param_names once in "cli_args". For other MultApp, we store the full information // of params_names and values for each sampler. if (std::dynamic_pointer_cast<SamplerFullSolveMultiApp>(_multi_app) == nullptr) { for (dof_id_type row = _sampler.getLocalRowBegin(); row < _sampler.getLocalRowEnd(); ++row) { std::vector<Real> data = _sampler.getNextLocalRow(); std::ostringstream oss; for (std::size_t col = 0; col < data.size(); ++col) { if (col > 0) oss << ";"; oss << _param_names[col] << "=" << Moose::stringify(data[col]); } cli_args.push_back(oss.str()); } } else { std::ostringstream oss; for (dof_id_type col = 0; col < _sampler.getNumberOfCols(); ++col) { if (col > 0) oss << ";"; oss << _param_names[col]; } cli_args.push_back(oss.str()); } setControllableValueByName<std::vector<std::string>>( "MultiApp", _multi_app->name(), "cli_args", cli_args); }
Update MultiAppCommandLineControl to use getNextLocalRow
Update MultiAppCommandLineControl to use getNextLocalRow (refs #13906)
C++
lgpl-2.1
milljm/moose,lindsayad/moose,andrsd/moose,laagesen/moose,idaholab/moose,bwspenc/moose,nuclear-wizard/moose,jessecarterMOOSE/moose,idaholab/moose,sapitts/moose,milljm/moose,milljm/moose,sapitts/moose,sapitts/moose,jessecarterMOOSE/moose,dschwen/moose,harterj/moose,laagesen/moose,milljm/moose,bwspenc/moose,bwspenc/moose,lindsayad/moose,nuclear-wizard/moose,jessecarterMOOSE/moose,idaholab/moose,milljm/moose,andrsd/moose,lindsayad/moose,andrsd/moose,harterj/moose,SudiptaBiswas/moose,dschwen/moose,bwspenc/moose,lindsayad/moose,nuclear-wizard/moose,idaholab/moose,bwspenc/moose,nuclear-wizard/moose,jessecarterMOOSE/moose,sapitts/moose,dschwen/moose,SudiptaBiswas/moose,laagesen/moose,harterj/moose,SudiptaBiswas/moose,SudiptaBiswas/moose,idaholab/moose,laagesen/moose,sapitts/moose,dschwen/moose,andrsd/moose,dschwen/moose,jessecarterMOOSE/moose,harterj/moose,harterj/moose,SudiptaBiswas/moose,laagesen/moose,lindsayad/moose,andrsd/moose
91597b2166f7543be56f91bc15046a35f06b7a77
AD/macros/MakeADRecoParamEntry.C
AD/macros/MakeADRecoParamEntry.C
void MakeADRecoParamEntry(AliRecoParam::EventSpecie_t defaultEventSpecie=AliRecoParam::kLowMult, const char *outputCDB = "local:///home/mbroz/OCDB") { //======================================================================== // // Steering macro for AD reconstruction parameters // // Author: Michal Broz // //======================================================================== const char* macroname = "MakeADRecoParam.C"; // Activate CDB storage and load geometry from CDB AliCDBManager* cdb = AliCDBManager::Instance(); cdb->SetDefaultStorage(outputCDB); cdb->SetRun(0); TObjArray *recoParamArray = new TObjArray(); { AliADRecoParam * ADRecoParam = new AliADRecoParam; ADRecoParam->SetEventSpecie(AliRecoParam::kCosmic); ADRecoParam->SetStartClock(0); ADRecoParam->SetEndClock(20); ADRecoParam->SetNPreClocks(1); ADRecoParam->SetNPostClocks(10); ADRecoParam->SetTimeWindowBBALow(-2.5); ADRecoParam->SetTimeWindowBBAUp(2.5); ADRecoParam->SetTimeWindowBGALow(-4.0); ADRecoParam->SetTimeWindowBGAUp(4.0); ADRecoParam->SetTimeWindowBBCLow(-1.5); ADRecoParam->SetTimeWindowBBCUp(1.5); ADRecoParam->SetTimeWindowBGCLow(-2.0); ADRecoParam->SetTimeWindowBGCUp(2.0); ADRecoParam->SetAdcThresHold(5); ADRecoParam->SetMaxResid(5.0); ADRecoParam->SetResidRise(0.02); recoParamArray->AddLast(ADRecoParam); } { AliADRecoParam * ADRecoParam = new AliADRecoParam; ADRecoParam->SetStartClock(0); ADRecoParam->SetEndClock(20); ADRecoParam->SetNPreClocks(1); ADRecoParam->SetNPostClocks(10); ADRecoParam->SetTimeWindowBBALow(-2.5); ADRecoParam->SetTimeWindowBBAUp(2.5); ADRecoParam->SetTimeWindowBGALow(-4.0); ADRecoParam->SetTimeWindowBGAUp(4.0); ADRecoParam->SetTimeWindowBBCLow(-1.5); ADRecoParam->SetTimeWindowBBCUp(1.5); ADRecoParam->SetTimeWindowBGCLow(-2.0); ADRecoParam->SetTimeWindowBGCUp(2.0); ADRecoParam->SetAdcThresHold(5); ADRecoParam->SetMaxResid(5.0); ADRecoParam->SetResidRise(0.02); ADRecoParam->SetEventSpecie(AliRecoParam::kLowMult); recoParamArray->AddLast(ADRecoParam); } { AliADRecoParam * ADRecoParam = new AliADRecoParam; ADRecoParam->SetStartClock(9); ADRecoParam->SetEndClock(11); ADRecoParam->SetNPostClocks(6); ADRecoParam->SetTimeWindowBBALow(-2.5); ADRecoParam->SetTimeWindowBBAUp(2.5); ADRecoParam->SetTimeWindowBGALow(-4.0); ADRecoParam->SetTimeWindowBGAUp(4.0); ADRecoParam->SetTimeWindowBBCLow(-1.5); ADRecoParam->SetTimeWindowBBCUp(1.5); ADRecoParam->SetTimeWindowBGCLow(-2.0); ADRecoParam->SetTimeWindowBGCUp(2.0); ADRecoParam->SetAdcThresHold(5); ADRecoParam->SetMaxResid(5.0); ADRecoParam->SetResidRise(0.02); ADRecoParam->SetEventSpecie(AliRecoParam::kHighMult); recoParamArray->AddLast(ADRecoParam); } // Set the defaultEventSpecie Bool_t defaultIsSet = kFALSE; for(Int_t i =0; i < recoParamArray->GetEntriesFast(); i++) { AliDetectorRecoParam *param = (AliDetectorRecoParam *)recoParamArray->UncheckedAt(i); if (!param) continue; if (defaultEventSpecie & param->GetEventSpecie()) { param->SetAsDefault(); defaultIsSet = kTRUE; } } if (!defaultIsSet) { Error(macroname,"The default reconstruction parameters are not set! Exiting..."); return; } // save in CDB storage AliCDBMetaData *md= new AliCDBMetaData(); md->SetResponsible("Michal Broz"); md->SetComment("Reconstruction parameters for AD"); md->SetAliRootVersion(gSystem->Getenv("ARVERSION")); md->SetBeamPeriod(0); AliCDBId id("AD/Calib/RecoParam", 0, AliCDBRunRange::Infinity()); cdb->Put(recoParamArray, id, md); return; }
void MakeADRecoParamEntry(AliRecoParam::EventSpecie_t defaultEventSpecie=AliRecoParam::kLowMult, const char *outputCDB = "local://$ALICE_ROOT/OCDB") { //======================================================================== // // Steering macro for AD reconstruction parameters // // Author: Michal Broz // //======================================================================== const char* macroname = "MakeADRecoParam.C"; // Activate CDB storage and load geometry from CDB AliCDBManager* cdb = AliCDBManager::Instance(); cdb->SetDefaultStorage(outputCDB); cdb->SetRun(0); TObjArray *recoParamArray = new TObjArray(); { AliADRecoParam * ADRecoParam = new AliADRecoParam; ADRecoParam->SetEventSpecie(AliRecoParam::kCosmic); ADRecoParam->SetStartClock(0); ADRecoParam->SetEndClock(20); ADRecoParam->SetNPreClocks(1); ADRecoParam->SetNPostClocks(10); ADRecoParam->SetTimeWindowBBALow(-2.5); ADRecoParam->SetTimeWindowBBAUp(2.5); ADRecoParam->SetTimeWindowBGALow(-4.0); ADRecoParam->SetTimeWindowBGAUp(4.0); ADRecoParam->SetTimeWindowBBCLow(-1.5); ADRecoParam->SetTimeWindowBBCUp(1.5); ADRecoParam->SetTimeWindowBGCLow(-2.0); ADRecoParam->SetTimeWindowBGCUp(2.0); ADRecoParam->SetAdcThresHold(5); ADRecoParam->SetMaxResid(1.5); ADRecoParam->SetResidRise(0.02); recoParamArray->AddLast(ADRecoParam); } { AliADRecoParam * ADRecoParam = new AliADRecoParam; ADRecoParam->SetStartClock(0); ADRecoParam->SetEndClock(20); ADRecoParam->SetNPreClocks(1); ADRecoParam->SetNPostClocks(10); ADRecoParam->SetTimeWindowBBALow(-2.5); ADRecoParam->SetTimeWindowBBAUp(2.5); ADRecoParam->SetTimeWindowBGALow(-4.0); ADRecoParam->SetTimeWindowBGAUp(4.0); ADRecoParam->SetTimeWindowBBCLow(-1.5); ADRecoParam->SetTimeWindowBBCUp(1.5); ADRecoParam->SetTimeWindowBGCLow(-2.0); ADRecoParam->SetTimeWindowBGCUp(2.0); ADRecoParam->SetAdcThresHold(5); ADRecoParam->SetMaxResid(1.5); ADRecoParam->SetResidRise(0.02); ADRecoParam->SetEventSpecie(AliRecoParam::kLowMult); recoParamArray->AddLast(ADRecoParam); } { AliADRecoParam * ADRecoParam = new AliADRecoParam; ADRecoParam->SetStartClock(9); ADRecoParam->SetEndClock(11); ADRecoParam->SetNPostClocks(6); ADRecoParam->SetTimeWindowBBALow(-2.5); ADRecoParam->SetTimeWindowBBAUp(2.5); ADRecoParam->SetTimeWindowBGALow(-4.0); ADRecoParam->SetTimeWindowBGAUp(4.0); ADRecoParam->SetTimeWindowBBCLow(-1.5); ADRecoParam->SetTimeWindowBBCUp(1.5); ADRecoParam->SetTimeWindowBGCLow(-2.0); ADRecoParam->SetTimeWindowBGCUp(2.0); ADRecoParam->SetAdcThresHold(5); ADRecoParam->SetMaxResid(1.5); ADRecoParam->SetResidRise(0.02); ADRecoParam->SetEventSpecie(AliRecoParam::kHighMult); recoParamArray->AddLast(ADRecoParam); } // Set the defaultEventSpecie Bool_t defaultIsSet = kFALSE; for(Int_t i =0; i < recoParamArray->GetEntriesFast(); i++) { AliDetectorRecoParam *param = (AliDetectorRecoParam *)recoParamArray->UncheckedAt(i); if (!param) continue; if (defaultEventSpecie & param->GetEventSpecie()) { param->SetAsDefault(); defaultIsSet = kTRUE; } } if (!defaultIsSet) { Error(macroname,"The default reconstruction parameters are not set! Exiting..."); return; } // save in CDB storage AliCDBMetaData *md= new AliCDBMetaData(); md->SetResponsible("Michal Broz"); md->SetComment("Reconstruction parameters for AD"); md->SetAliRootVersion(gSystem->Getenv("ARVERSION")); md->SetBeamPeriod(0); AliCDBId id("AD/Calib/RecoParam", 0, AliCDBRunRange::Infinity()); cdb->Put(recoParamArray, id, md); return; }
Cut adjustment
Cut adjustment
C++
bsd-3-clause
miranov25/AliRoot,miranov25/AliRoot,mkrzewic/AliRoot,ALICEHLT/AliRoot,ecalvovi/AliRoot,miranov25/AliRoot,ALICEHLT/AliRoot,sebaleh/AliRoot,ecalvovi/AliRoot,shahor02/AliRoot,mkrzewic/AliRoot,jgrosseo/AliRoot,jgrosseo/AliRoot,ecalvovi/AliRoot,sebaleh/AliRoot,ALICEHLT/AliRoot,ecalvovi/AliRoot,alisw/AliRoot,alisw/AliRoot,mkrzewic/AliRoot,ALICEHLT/AliRoot,coppedis/AliRoot,miranov25/AliRoot,miranov25/AliRoot,alisw/AliRoot,shahor02/AliRoot,alisw/AliRoot,sebaleh/AliRoot,coppedis/AliRoot,ecalvovi/AliRoot,sebaleh/AliRoot,ecalvovi/AliRoot,alisw/AliRoot,shahor02/AliRoot,jgrosseo/AliRoot,mkrzewic/AliRoot,ALICEHLT/AliRoot,sebaleh/AliRoot,sebaleh/AliRoot,miranov25/AliRoot,coppedis/AliRoot,coppedis/AliRoot,ALICEHLT/AliRoot,mkrzewic/AliRoot,miranov25/AliRoot,alisw/AliRoot,coppedis/AliRoot,mkrzewic/AliRoot,jgrosseo/AliRoot,shahor02/AliRoot,miranov25/AliRoot,sebaleh/AliRoot,jgrosseo/AliRoot,mkrzewic/AliRoot,ALICEHLT/AliRoot,jgrosseo/AliRoot,shahor02/AliRoot,alisw/AliRoot,coppedis/AliRoot,coppedis/AliRoot,shahor02/AliRoot,coppedis/AliRoot,alisw/AliRoot,ecalvovi/AliRoot,shahor02/AliRoot,jgrosseo/AliRoot
f489a6606573530cabed24dfdb081853cba49c3f
content/browser/devtools/devtools_frame_trace_recorder.cc
content/browser/devtools/devtools_frame_trace_recorder.cc
// Copyright (c) 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 "content/browser/devtools/devtools_frame_trace_recorder.h" #include <string> #include <vector> #include "base/atomicops.h" #include "base/base64.h" #include "base/bind.h" #include "base/memory/ref_counted.h" #include "base/trace_event/trace_event_impl.h" #include "cc/output/compositor_frame_metadata.h" #include "content/browser/frame_host/render_frame_host_impl.h" #include "content/browser/renderer_host/render_widget_host_view_base.h" #include "content/public/browser/readback_types.h" #include "third_party/skia/include/core/SkBitmap.h" #include "ui/gfx/codec/png_codec.h" #include "ui/gfx/geometry/size.h" #include "ui/gfx/geometry/size_conversions.h" namespace content { namespace { static base::subtle::Atomic32 frame_data_count = 0; static int kMaximumFrameDataCount = 150; static size_t kFrameAreaLimit = 256000; class TraceableDevToolsScreenshot : public base::trace_event::ConvertableToTraceFormat { public: TraceableDevToolsScreenshot(const SkBitmap& bitmap) : frame_(bitmap) {} void AppendAsTraceFormat(std::string* out) const override { out->append("\""); if (!frame_.drawsNothing()) { std::vector<unsigned char> data; SkAutoLockPixels lock_image(frame_); bool encoded = gfx::PNGCodec::Encode( reinterpret_cast<unsigned char*>(frame_.getAddr32(0, 0)), gfx::PNGCodec::FORMAT_SkBitmap, gfx::Size(frame_.width(), frame_.height()), frame_.width() * frame_.bytesPerPixel(), false, std::vector<gfx::PNGCodec::Comment>(), &data); if (encoded) { std::string encoded_data; base::Base64Encode( base::StringPiece(reinterpret_cast<char*>(&data[0]), data.size()), &encoded_data); out->append(encoded_data); } } out->append("\""); } private: ~TraceableDevToolsScreenshot() override { base::subtle::NoBarrier_AtomicIncrement(&frame_data_count, -1); } SkBitmap frame_; }; } // namespace class DevToolsFrameTraceRecorderData : public base::RefCounted<DevToolsFrameTraceRecorderData> { public: DevToolsFrameTraceRecorderData(const cc::CompositorFrameMetadata& metadata) : metadata_(metadata), timestamp_(base::TraceTicks::Now()) {} void FrameCaptured(const SkBitmap& bitmap, ReadbackResponse response) { if (response != READBACK_SUCCESS) return; int current_frame_count = base::subtle::NoBarrier_Load(&frame_data_count); if (current_frame_count >= kMaximumFrameDataCount) return; if (bitmap.drawsNothing()) return; base::subtle::NoBarrier_AtomicIncrement(&frame_data_count, 1); TRACE_EVENT_OBJECT_SNAPSHOT_WITH_ID_AND_TIMESTAMP( TRACE_DISABLED_BY_DEFAULT("devtools.screenshot"), "Screenshot", 1, timestamp_.ToInternalValue(), scoped_refptr<base::trace_event::ConvertableToTraceFormat>( new TraceableDevToolsScreenshot(bitmap))); } void CaptureFrame(RenderFrameHostImpl* host) { RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>(host->GetView()); if (!view) return; int current_frame_count = base::subtle::NoBarrier_Load(&frame_data_count); if (current_frame_count >= kMaximumFrameDataCount) return; float scale = metadata_.page_scale_factor; float area = metadata_.scrollable_viewport_size.GetArea(); if (area * scale * scale > kFrameAreaLimit) scale = sqrt(kFrameAreaLimit / area); gfx::Size snapshot_size(gfx::ToRoundedSize(gfx::ScaleSize( metadata_.scrollable_viewport_size, scale))); view->CopyFromCompositingSurface( gfx::Rect(), snapshot_size, base::Bind(&DevToolsFrameTraceRecorderData::FrameCaptured, this), kN32_SkColorType); } private: friend class base::RefCounted<DevToolsFrameTraceRecorderData>; ~DevToolsFrameTraceRecorderData() {} cc::CompositorFrameMetadata metadata_; base::TraceTicks timestamp_; DISALLOW_COPY_AND_ASSIGN(DevToolsFrameTraceRecorderData); }; DevToolsFrameTraceRecorder::DevToolsFrameTraceRecorder() { } DevToolsFrameTraceRecorder::~DevToolsFrameTraceRecorder() { } void DevToolsFrameTraceRecorder::OnSwapCompositorFrame( RenderFrameHostImpl* host, const cc::CompositorFrameMetadata& frame_metadata, bool do_capture) { if (!host) return; bool enabled; TRACE_EVENT_CATEGORY_GROUP_ENABLED( TRACE_DISABLED_BY_DEFAULT("devtools.screenshot"), &enabled); if (!enabled || !do_capture) { pending_frame_data_ = nullptr; return; } if (pending_frame_data_.get()) pending_frame_data_->CaptureFrame(host); pending_frame_data_ = new DevToolsFrameTraceRecorderData(frame_metadata); } } // namespace content
// Copyright (c) 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 "content/browser/devtools/devtools_frame_trace_recorder.h" #include <string> #include <vector> #include "base/atomicops.h" #include "base/base64.h" #include "base/bind.h" #include "base/memory/ref_counted.h" #include "base/trace_event/trace_event_impl.h" #include "cc/output/compositor_frame_metadata.h" #include "content/browser/frame_host/render_frame_host_impl.h" #include "content/browser/renderer_host/render_widget_host_view_base.h" #include "content/public/browser/readback_types.h" #include "third_party/skia/include/core/SkBitmap.h" #include "ui/gfx/codec/png_codec.h" #include "ui/gfx/geometry/size.h" #include "ui/gfx/geometry/size_conversions.h" namespace content { namespace { static base::subtle::Atomic32 frame_data_count = 0; static int kMaximumFrameDataCount = 150; static size_t kFrameAreaLimit = 256000; class TraceableDevToolsScreenshot : public base::trace_event::ConvertableToTraceFormat { public: TraceableDevToolsScreenshot(const SkBitmap& bitmap) : frame_(bitmap) {} void AppendAsTraceFormat(std::string* out) const override { out->append("\""); if (!frame_.drawsNothing()) { std::vector<unsigned char> data; SkAutoLockPixels lock_image(frame_); bool encoded = gfx::PNGCodec::Encode( reinterpret_cast<unsigned char*>(frame_.getAddr32(0, 0)), gfx::PNGCodec::FORMAT_SkBitmap, gfx::Size(frame_.width(), frame_.height()), frame_.width() * frame_.bytesPerPixel(), false, std::vector<gfx::PNGCodec::Comment>(), &data); if (encoded) { std::string encoded_data; base::Base64Encode( base::StringPiece(reinterpret_cast<char*>(&data[0]), data.size()), &encoded_data); out->append(encoded_data); } } out->append("\""); } private: ~TraceableDevToolsScreenshot() override { base::subtle::NoBarrier_AtomicIncrement(&frame_data_count, -1); } SkBitmap frame_; }; } // namespace class DevToolsFrameTraceRecorderData : public base::RefCounted<DevToolsFrameTraceRecorderData> { public: DevToolsFrameTraceRecorderData(const cc::CompositorFrameMetadata& metadata) : metadata_(metadata), timestamp_(base::TraceTicks::Now()) {} void FrameCaptured(const SkBitmap& bitmap, ReadbackResponse response) { if (response != READBACK_SUCCESS) return; int current_frame_count = base::subtle::NoBarrier_Load(&frame_data_count); if (current_frame_count >= kMaximumFrameDataCount) return; if (bitmap.drawsNothing()) return; base::subtle::NoBarrier_AtomicIncrement(&frame_data_count, 1); TRACE_EVENT_OBJECT_SNAPSHOT_WITH_ID_AND_TIMESTAMP( TRACE_DISABLED_BY_DEFAULT("devtools.screenshot"), "Screenshot", 1, timestamp_.ToInternalValue(), scoped_refptr<base::trace_event::ConvertableToTraceFormat>( new TraceableDevToolsScreenshot(bitmap))); } void CaptureFrame(RenderFrameHostImpl* host) { RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>(host->GetView()); if (!view) return; int current_frame_count = base::subtle::NoBarrier_Load(&frame_data_count); if (current_frame_count >= kMaximumFrameDataCount) return; float scale = metadata_.page_scale_factor; float area = metadata_.scrollable_viewport_size.GetArea(); if (area * scale * scale > kFrameAreaLimit) scale = sqrt(kFrameAreaLimit / area); gfx::Size snapshot_size(gfx::ToRoundedSize(gfx::ScaleSize( metadata_.scrollable_viewport_size, scale))); view->CopyFromCompositingSurface( gfx::Rect(), snapshot_size, base::Bind(&DevToolsFrameTraceRecorderData::FrameCaptured, this), kN32_SkColorType); } private: friend class base::RefCounted<DevToolsFrameTraceRecorderData>; ~DevToolsFrameTraceRecorderData() {} cc::CompositorFrameMetadata metadata_; base::TraceTicks timestamp_; DISALLOW_COPY_AND_ASSIGN(DevToolsFrameTraceRecorderData); }; DevToolsFrameTraceRecorder::DevToolsFrameTraceRecorder() { } DevToolsFrameTraceRecorder::~DevToolsFrameTraceRecorder() { } void DevToolsFrameTraceRecorder::OnSwapCompositorFrame( RenderFrameHostImpl* host, const cc::CompositorFrameMetadata& frame_metadata, bool do_capture) { if (!host) return; bool enabled; TRACE_EVENT_CATEGORY_GROUP_ENABLED( TRACE_DISABLED_BY_DEFAULT("devtools.screenshot"), &enabled); if (!enabled || !do_capture) { pending_frame_data_ = nullptr; return; } bool is_new_trace; TRACE_EVENT_IS_NEW_TRACE(&is_new_trace); if (!is_new_trace && pending_frame_data_) pending_frame_data_->CaptureFrame(host); pending_frame_data_ = new DevToolsFrameTraceRecorderData(frame_metadata); } } // namespace content
fix recording screenshot with stale timestamp
DevTools: fix recording screenshot with stale timestamp This fixes recording of a screenshot with a timestamp and metadata captured during previous tracing session. BUG= Review URL: https://codereview.chromium.org/1215553007 Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#337840}
C++
bsd-3-clause
TheTypoMaster/chromium-crosswalk,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk,Pluto-tv/chromium-crosswalk,Pluto-tv/chromium-crosswalk,axinging/chromium-crosswalk,Chilledheart/chromium,Chilledheart/chromium,chuan9/chromium-crosswalk,Chilledheart/chromium,chuan9/chromium-crosswalk,chuan9/chromium-crosswalk,Just-D/chromium-1,hgl888/chromium-crosswalk,Just-D/chromium-1,TheTypoMaster/chromium-crosswalk,axinging/chromium-crosswalk,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk,axinging/chromium-crosswalk,Just-D/chromium-1,hgl888/chromium-crosswalk,Chilledheart/chromium,Pluto-tv/chromium-crosswalk,Chilledheart/chromium,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk,Chilledheart/chromium,chuan9/chromium-crosswalk,Chilledheart/chromium,Pluto-tv/chromium-crosswalk,Chilledheart/chromium,TheTypoMaster/chromium-crosswalk,axinging/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Pluto-tv/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,axinging/chromium-crosswalk,axinging/chromium-crosswalk,Pluto-tv/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,axinging/chromium-crosswalk,axinging/chromium-crosswalk,Just-D/chromium-1,TheTypoMaster/chromium-crosswalk,Pluto-tv/chromium-crosswalk,axinging/chromium-crosswalk,hgl888/chromium-crosswalk,hgl888/chromium-crosswalk,Just-D/chromium-1,Just-D/chromium-1,Just-D/chromium-1,Pluto-tv/chromium-crosswalk,Chilledheart/chromium,chuan9/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Just-D/chromium-1,hgl888/chromium-crosswalk,hgl888/chromium-crosswalk,axinging/chromium-crosswalk,Just-D/chromium-1,chuan9/chromium-crosswalk,chuan9/chromium-crosswalk,axinging/chromium-crosswalk
d6493677042b0712fc764236079f4d4de8346bf4
opencog/reasoning/RuleEngine/rule-engine-src/pln/ForwardChainer.cc
opencog/reasoning/RuleEngine/rule-engine-src/pln/ForwardChainer.cc
/* * ForwardChainer.cc * * Copyright (C) 2014,2015 Misgana Bayetta * * Author: Misgana Bayetta <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License v3 as * published by the Free Software Foundation and including the exceptions * at http://opencog.org/wiki/Licenses * * 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 Affero General Public License * along with this program; if not, write to: * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <opencog/atoms/bind/SatisfactionLink.h> #include <opencog/atomutils/AtomUtils.h> #include <opencog/query/DefaultImplicator.h> #include <opencog/reasoning/RuleEngine/rule-engine-src/Rule.h> #include <opencog/atoms/bind/BindLink.h> #include "ForwardChainer.h" #include "ForwardChainerCallBack.h" #include "PLNCommons.h" using namespace opencog; ForwardChainer::ForwardChainer(AtomSpace * as, string conf_path /*=""*/) : as_(as), fcmem_(as_) { if (conf_path != "") _conf_path = conf_path; init(); } ForwardChainer::~ForwardChainer() { delete cpolicy_loader_; } void ForwardChainer::init() { cpolicy_loader_ = new JsonicControlPolicyParamLoader(as_, _conf_path); cpolicy_loader_->load_config(); fcmem_.search_in_af_ = cpolicy_loader_->get_attention_alloc(); fcmem_.rules_ = cpolicy_loader_->get_rules(); fcmem_.cur_rule_ = nullptr; // Provide a logger log_ = NULL; setLogger(new opencog::Logger("forward_chainer.log", Logger::FINE, true)); } void ForwardChainer::setLogger(Logger* log) { if (log_) delete log_; log_ = log; } Logger* ForwardChainer::getLogger() { return log_; } void ForwardChainer::do_chain(ForwardChainerCallBack& fcb, Handle hsource/*=Handle::UNDEFINED*/) { PLNCommons pc(as_); if (hsource == Handle::UNDEFINED) { do_pm(); return; } else { // Variable fulfillment query. UnorderedHandleSet var_nodes = get_outgoing_nodes(hsource, { VARIABLE_NODE }); if (not var_nodes.empty()) return do_pm(hsource, var_nodes, fcb); else fcmem_.set_source(hsource); } // Forward chaining on a particular type of atom. int iteration = 0; auto max_iter = cpolicy_loader_->get_max_iter(); while (iteration < max_iter /*OR other termination criteria*/) { log_->info("Iteration %d", iteration); if (fcmem_.cur_source_ == Handle::UNDEFINED) { log_->info("No current source, forward chaining aborted"); break; } log_->info("Next source %s", fcmem_.cur_source_->toString().c_str()); // Add more premise to hcurrent_source by pattern matching. HandleSeq input = fcb.choose_premises(fcmem_); fcmem_.update_premise_list(input); // Choose the best rule to apply. vector<Rule*> rules = fcb.choose_rules(fcmem_); map<Rule*, float> rule_weight; for (Rule* r : rules) { log_->info("Matching rule %s", r->get_name().c_str()); rule_weight[r] = r->get_cost(); } auto r = pc.tournament_select(rule_weight); //! If no rules matches the pattern of the source, choose //! another source if there is, else end forward chaining. if (not r) { auto new_source = fcb.choose_next_source(fcmem_); if (new_source == Handle::UNDEFINED) { log_->info( "No chosen rule and no more target to choose.Aborting forward chaining."); return; } else { log_->info("No matching rule,attempting with another target."); fcmem_.set_source(new_source); continue; } } log_->info("Chosen rule %s", r->get_name().c_str()); fcmem_.cur_rule_ = r; //! Apply rule. log_->info("Applying chosen rule %s", r->get_name().c_str()); HandleSeq product = fcb.apply_rule(fcmem_); log_->info("Results of rule application"); for (auto p : product) log_->info("%s", p->toString().c_str()); fcmem_.add_rules_product(iteration, product); fcmem_.update_premise_list(product); //! Choose next source. fcmem_.set_source(fcb.choose_next_source(fcmem_)); iteration++; } } /** * Does pattern matching for a variable containing query. * @param source a variable containing handle passed as an input to the pattern matcher * @param var_nodes the VariableNodes in @param hsource * @param fcb a forward chainer callback implementation used here only for choosing rules * that contain @param hsource in their implicant */ void ForwardChainer::do_pm(const Handle& hsource, const UnorderedHandleSet& var_nodes, ForwardChainerCallBack& fcb) { DefaultImplicator impl(as_); impl.implicand = hsource; HandleSeq vars; for (auto h : var_nodes) vars.push_back(h); fcmem_.set_source(hsource); Handle hvar_list = as_->addLink(VARIABLE_LIST, vars); Handle hclause = as_->addLink(AND_LINK, hsource); // Run the pattern matcher, find all patterns that satisfy the // the clause, with the given variables in it. SatisfactionLinkPtr sl(createSatisfactionLink(hvar_list, hclause)); sl->satisfy(&impl); // Update result fcmem_.add_rules_product(0, impl.result_list); // Delete the AND_LINK and LIST_LINK as_->removeAtom(hvar_list); as_->removeAtom(hclause); //!Additionally, find applicable rules and apply. vector<Rule*> rules = fcb.choose_rules(fcmem_); for (Rule* rule : rules) { BindLinkPtr bl(BindLinkCast(rule->get_handle())); DefaultImplicator impl(as_); impl.implicand = bl->get_implicand(); impl.set_type_restrictions(bl->get_typemap()); bl->imply(&impl); fcmem_.set_cur_rule(rule); fcmem_.add_rules_product(0, impl.result_list); } } /** * Invokes pattern matcher using each rule declared in the configuration file. */ void ForwardChainer::do_pm() { //! Do pattern matching using the rules declared in the declaration file log_->info( "Forward chaining on the entire atomspace with rules declared in %s", _conf_path.c_str()); vector<Rule*> rules = fcmem_.get_rules(); for (Rule* rule : rules) { log_->info("Applying rule %s on ", rule->get_name().c_str()); BindLinkPtr bl(BindLinkCast(rule->get_handle())); DefaultImplicator impl(as_); impl.implicand = bl->get_implicand(); impl.set_type_restrictions(bl->get_typemap()); bl->imply(&impl); fcmem_.set_cur_rule(rule); log_->info("OUTPUTS"); for (auto h : impl.result_list) log_->info("%s", h->toString().c_str()); fcmem_.add_rules_product(0, impl.result_list); } } HandleSeq ForwardChainer::get_chaining_result() { return fcmem_.get_result(); }
/* * ForwardChainer.cc * * Copyright (C) 2014,2015 Misgana Bayetta * * Author: Misgana Bayetta <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License v3 as * published by the Free Software Foundation and including the exceptions * at http://opencog.org/wiki/Licenses * * 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 Affero General Public License * along with this program; if not, write to: * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <opencog/atoms/bind/SatisfactionLink.h> #include <opencog/atomutils/AtomUtils.h> #include <opencog/query/DefaultImplicator.h> #include <opencog/reasoning/RuleEngine/rule-engine-src/Rule.h> #include <opencog/atoms/bind/BindLink.h> #include "ForwardChainer.h" #include "ForwardChainerCallBack.h" #include "PLNCommons.h" using namespace opencog; ForwardChainer::ForwardChainer(AtomSpace * as, string conf_path /*=""*/) : as_(as), fcmem_(as_) { if (conf_path != "") _conf_path = conf_path; init(); } ForwardChainer::~ForwardChainer() { delete cpolicy_loader_; } void ForwardChainer::init() { cpolicy_loader_ = new JsonicControlPolicyParamLoader(as_, _conf_path); cpolicy_loader_->load_config(); fcmem_.search_in_af_ = cpolicy_loader_->get_attention_alloc(); fcmem_.rules_ = cpolicy_loader_->get_rules(); fcmem_.cur_rule_ = nullptr; // Provide a logger log_ = NULL; setLogger(new opencog::Logger("forward_chainer.log", Logger::FINE, true)); } void ForwardChainer::setLogger(Logger* log) { if (log_) delete log_; log_ = log; } Logger* ForwardChainer::getLogger() { return log_; } void ForwardChainer::do_chain(ForwardChainerCallBack& fcb, Handle hsource/*=Handle::UNDEFINED*/) { PLNCommons pc(as_); if (hsource == Handle::UNDEFINED) { do_pm(); return; } else { // Variable fulfillment query. UnorderedHandleSet var_nodes = get_outgoing_nodes(hsource, { VARIABLE_NODE }); if (not var_nodes.empty()) return do_pm(hsource, var_nodes, fcb); else fcmem_.set_source(hsource); } // Forward chaining on a particular type of atom. int iteration = 0; auto max_iter = cpolicy_loader_->get_max_iter(); while (iteration < max_iter /*OR other termination criteria*/) { log_->info("Iteration %d", iteration); if (fcmem_.cur_source_ == Handle::UNDEFINED) { log_->info("No current source, forward chaining aborted"); break; } log_->info("Next source %s", fcmem_.cur_source_->toString().c_str()); // Add more premise to hcurrent_source by pattern matching. HandleSeq input = fcb.choose_premises(fcmem_); fcmem_.update_premise_list(input); // Choose the best rule to apply. vector<Rule*> rules = fcb.choose_rules(fcmem_); map<Rule*, float> rule_weight; for (Rule* r : rules) { log_->info("Matching rule %s", r->get_name().c_str()); rule_weight[r] = r->get_cost(); } auto r = pc.tournament_select(rule_weight); //! If no rules matches the pattern of the source, choose //! another source if there is, else end forward chaining. if (not r) { auto new_source = fcb.choose_next_source(fcmem_); if (new_source == Handle::UNDEFINED) { log_->info("No chosen rule and no more source to choose. " "Aborting forward chaining."); return; } else { log_->info("No matching rule, attempting with another source."); fcmem_.set_source(new_source); continue; } } log_->info("Chosen rule %s", r->get_name().c_str()); fcmem_.cur_rule_ = r; //! Apply rule. log_->info("Applying chosen rule %s", r->get_name().c_str()); HandleSeq product = fcb.apply_rule(fcmem_); log_->info("Results of rule application"); for (auto p : product) log_->info("%s", p->toString().c_str()); fcmem_.add_rules_product(iteration, product); fcmem_.update_premise_list(product); //! Choose next source. fcmem_.set_source(fcb.choose_next_source(fcmem_)); iteration++; } } /** * Does pattern matching for a variable containing query. * @param source a variable containing handle passed as an input to the pattern matcher * @param var_nodes the VariableNodes in @param hsource * @param fcb a forward chainer callback implementation used here only for choosing rules * that contain @param hsource in their implicant */ void ForwardChainer::do_pm(const Handle& hsource, const UnorderedHandleSet& var_nodes, ForwardChainerCallBack& fcb) { DefaultImplicator impl(as_); impl.implicand = hsource; HandleSeq vars; for (auto h : var_nodes) vars.push_back(h); fcmem_.set_source(hsource); Handle hvar_list = as_->addLink(VARIABLE_LIST, vars); Handle hclause = as_->addLink(AND_LINK, hsource); // Run the pattern matcher, find all patterns that satisfy the // the clause, with the given variables in it. SatisfactionLinkPtr sl(createSatisfactionLink(hvar_list, hclause)); sl->satisfy(&impl); // Update result fcmem_.add_rules_product(0, impl.result_list); // Delete the AND_LINK and LIST_LINK as_->removeAtom(hvar_list); as_->removeAtom(hclause); //!Additionally, find applicable rules and apply. vector<Rule*> rules = fcb.choose_rules(fcmem_); for (Rule* rule : rules) { BindLinkPtr bl(BindLinkCast(rule->get_handle())); DefaultImplicator impl(as_); impl.implicand = bl->get_implicand(); impl.set_type_restrictions(bl->get_typemap()); bl->imply(&impl); fcmem_.set_cur_rule(rule); fcmem_.add_rules_product(0, impl.result_list); } } /** * Invokes pattern matcher using each rule declared in the configuration file. */ void ForwardChainer::do_pm() { //! Do pattern matching using the rules declared in the declaration file log_->info( "Forward chaining on the entire atomspace with rules declared in %s", _conf_path.c_str()); vector<Rule*> rules = fcmem_.get_rules(); for (Rule* rule : rules) { log_->info("Applying rule %s on ", rule->get_name().c_str()); BindLinkPtr bl(BindLinkCast(rule->get_handle())); DefaultImplicator impl(as_); impl.implicand = bl->get_implicand(); impl.set_type_restrictions(bl->get_typemap()); bl->imply(&impl); fcmem_.set_cur_rule(rule); log_->info("OUTPUTS"); for (auto h : impl.result_list) log_->info("%s", h->toString().c_str()); fcmem_.add_rules_product(0, impl.result_list); } } HandleSeq ForwardChainer::get_chaining_result() { return fcmem_.get_result(); }
Replace target by source in ForwardChainer log message
Replace target by source in ForwardChainer log message
C++
agpl-3.0
iAMr00t/opencog,AmeBel/atomspace,misgeatgit/opencog,inflector/opencog,misgeatgit/opencog,printedheart/opencog,printedheart/atomspace,ceefour/atomspace,rohit12/opencog,jlegendary/opencog,gavrieltal/opencog,jlegendary/opencog,Tiggels/opencog,MarcosPividori/atomspace,ruiting/opencog,andre-senna/opencog,kim135797531/opencog,AmeBel/opencog,williampma/opencog,yantrabuddhi/opencog,Selameab/opencog,roselleebarle04/opencog,rohit12/opencog,eddiemonroe/opencog,rohit12/opencog,rohit12/atomspace,eddiemonroe/opencog,yantrabuddhi/atomspace,anitzkin/opencog,rohit12/atomspace,inflector/opencog,rohit12/atomspace,iAMr00t/opencog,williampma/opencog,ceefour/opencog,inflector/opencog,yantrabuddhi/atomspace,shujingke/opencog,shujingke/opencog,prateeksaxena2809/opencog,cosmoharrigan/opencog,yantrabuddhi/atomspace,williampma/atomspace,cosmoharrigan/opencog,Allend575/opencog,tim777z/opencog,AmeBel/opencog,ruiting/opencog,Selameab/opencog,iAMr00t/opencog,anitzkin/opencog,Selameab/atomspace,gavrieltal/opencog,misgeatgit/atomspace,yantrabuddhi/opencog,TheNameIsNigel/opencog,AmeBel/opencog,UIKit0/atomspace,TheNameIsNigel/opencog,shujingke/opencog,rohit12/opencog,inflector/atomspace,misgeatgit/opencog,virneo/opencog,misgeatgit/opencog,ceefour/opencog,MarcosPividori/atomspace,virneo/opencog,shujingke/opencog,eddiemonroe/opencog,williampma/atomspace,AmeBel/atomspace,printedheart/atomspace,yantrabuddhi/opencog,TheNameIsNigel/opencog,Tiggels/opencog,ArvinPan/atomspace,gavrieltal/opencog,inflector/opencog,ruiting/opencog,jlegendary/opencog,printedheart/atomspace,yantrabuddhi/opencog,inflector/atomspace,roselleebarle04/opencog,Selameab/atomspace,sanuj/opencog,kim135797531/opencog,ceefour/opencog,gavrieltal/opencog,prateeksaxena2809/opencog,jswiergo/atomspace,anitzkin/opencog,misgeatgit/opencog,gavrieltal/opencog,kinoc/opencog,williampma/opencog,printedheart/opencog,rTreutlein/atomspace,eddiemonroe/atomspace,Selameab/atomspace,ruiting/opencog,ceefour/atomspace,misgeatgit/opencog,ruiting/opencog,Selameab/opencog,shujingke/opencog,rohit12/opencog,iAMr00t/opencog,tim777z/opencog,kim135797531/opencog,misgeatgit/atomspace,misgeatgit/atomspace,ArvinPan/atomspace,Allend575/opencog,prateeksaxena2809/opencog,shujingke/opencog,virneo/opencog,rTreutlein/atomspace,AmeBel/atomspace,printedheart/opencog,ArvinPan/atomspace,eddiemonroe/atomspace,prateeksaxena2809/opencog,AmeBel/atomspace,eddiemonroe/opencog,eddiemonroe/atomspace,AmeBel/opencog,misgeatgit/atomspace,yantrabuddhi/atomspace,andre-senna/opencog,cosmoharrigan/atomspace,ceefour/opencog,Selameab/atomspace,rodsol/atomspace,rTreutlein/atomspace,yantrabuddhi/opencog,rTreutlein/atomspace,kim135797531/opencog,Allend575/opencog,virneo/opencog,kinoc/opencog,Allend575/opencog,printedheart/opencog,iAMr00t/opencog,roselleebarle04/opencog,tim777z/opencog,ArvinPan/opencog,virneo/atomspace,Tiggels/opencog,Allend575/opencog,MarcosPividori/atomspace,williampma/opencog,kim135797531/opencog,sanuj/opencog,tim777z/opencog,AmeBel/opencog,jswiergo/atomspace,yantrabuddhi/opencog,Tiggels/opencog,UIKit0/atomspace,jlegendary/opencog,UIKit0/atomspace,MarcosPividori/atomspace,ArvinPan/opencog,prateeksaxena2809/opencog,Selameab/opencog,williampma/atomspace,williampma/opencog,roselleebarle04/opencog,roselleebarle04/opencog,cosmoharrigan/atomspace,sanuj/opencog,cosmoharrigan/atomspace,kinoc/opencog,Allend575/opencog,ceefour/atomspace,inflector/opencog,rodsol/atomspace,printedheart/atomspace,ArvinPan/opencog,virneo/atomspace,ruiting/opencog,rodsol/opencog,rodsol/opencog,eddiemonroe/opencog,kinoc/opencog,roselleebarle04/opencog,misgeatgit/atomspace,iAMr00t/opencog,sanuj/opencog,printedheart/opencog,jlegendary/opencog,TheNameIsNigel/opencog,Tiggels/opencog,inflector/opencog,ceefour/atomspace,cosmoharrigan/opencog,andre-senna/opencog,inflector/opencog,Allend575/opencog,anitzkin/opencog,kinoc/opencog,rodsol/opencog,prateeksaxena2809/opencog,misgeatgit/opencog,jswiergo/atomspace,Selameab/opencog,sanuj/opencog,anitzkin/opencog,jlegendary/opencog,williampma/atomspace,anitzkin/opencog,ceefour/opencog,AmeBel/opencog,eddiemonroe/opencog,inflector/atomspace,yantrabuddhi/opencog,rodsol/opencog,cosmoharrigan/opencog,virneo/atomspace,prateeksaxena2809/opencog,rohit12/atomspace,andre-senna/opencog,tim777z/opencog,cosmoharrigan/opencog,virneo/atomspace,AmeBel/opencog,eddiemonroe/atomspace,yantrabuddhi/atomspace,rohit12/opencog,inflector/atomspace,rTreutlein/atomspace,andre-senna/opencog,kim135797531/opencog,gavrieltal/opencog,misgeatgit/opencog,andre-senna/opencog,ArvinPan/opencog,rodsol/atomspace,ArvinPan/opencog,UIKit0/atomspace,virneo/opencog,rodsol/atomspace,kinoc/opencog,virneo/opencog,roselleebarle04/opencog,sanuj/opencog,inflector/atomspace,gavrieltal/opencog,TheNameIsNigel/opencog,rodsol/opencog,ruiting/opencog,virneo/opencog,kinoc/opencog,anitzkin/opencog,andre-senna/opencog,printedheart/opencog,cosmoharrigan/opencog,kim135797531/opencog,Selameab/opencog,AmeBel/atomspace,Tiggels/opencog,jlegendary/opencog,ceefour/opencog,rodsol/opencog,ArvinPan/atomspace,ArvinPan/opencog,misgeatgit/opencog,jswiergo/atomspace,inflector/opencog,williampma/opencog,TheNameIsNigel/opencog,cosmoharrigan/atomspace,eddiemonroe/atomspace,tim777z/opencog,shujingke/opencog,eddiemonroe/opencog,ceefour/opencog
01abe4f436564bd18e77a07c79d7ee49801b47a0
src/zillians-thorscript-compiler/compiler/ThorScriptCompiler.cpp
src/zillians-thorscript-compiler/compiler/ThorScriptCompiler.cpp
/** * Zillians MMO * Copyright (C) 2007-2010 Zillians.com, Inc. * For more information see http://www.zillians.com * * Zillians MMO is the library and runtime for massive multiplayer online game * development in utility computing model, which runs as a service for every * developer to build their virtual world running on our GPU-assisted machines. * * This is a close source library intended to be used solely within Zillians.com * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * COPYRIGHT HOLDER(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * @date Jul 18, 2011 sdk - Initial version created. */ #include "core/Prerequisite.h" #include "utility/UnicodeUtil.h" #include "compiler/ThorScriptCompiler.h" using namespace zillians; using namespace zillians::compiler; namespace { namespace qi = boost::spirit::qi; namespace classic = boost::spirit::classic; // since '\t' may be printed in spaces and I don't know a way to change std::wcout, we simply replace the tab with desired number of spaces // so that we can have correct error pointing cursor // (note that because '\t' equals to 4 spaces reported by spirit, we have to make sure it's printed in the exact same way) void expand_tabs(const std::wstring& input, std::wstring& output, int number_of_space_for_tab = 4) { for(std::wstring::const_iterator it = input.begin(); it != input.end(); ++it) { if(*it == '\t') for(int i=0;i<number_of_space_for_tab;++i) output.push_back(L' '); else output.push_back(*it); } } } int main(int argc, char** argv) { // try to read a file char const* filename; if (argc > 1) filename = argv[1]; else { std::cerr << "Error: No input file provided." << std::endl; return 1; } std::ifstream in(filename, std::ios_base::in); // ignore the BOM marking the beginning of a UTF-8 file in Windows char c = in.peek(); if (c == '\xef') { char s[3]; in >> s[0] >> s[1] >> s[2]; s[3] = '\0'; if (s != std::string("\xef\xbb\xbf")) { std::cerr << "Error: Unexpected characters from input file: " << filename << std::endl; return 1; } } std::string source_code_raw; // We will read the contents here. { in.unsetf(std::ios::skipws); // disable white space skipping std::copy(std::istream_iterator<char>(in), std::istream_iterator<char>(), std::back_inserter(source_code_raw)); } // convert it from UTF8 into UCS4 as a string by using u8_to_u32_iterator std::wstring source_code; utf8_to_ucs4(source_code_raw, source_code); // enable correct locale so that we can print UCS4 characters enable_default_locale(std::wcout); // try to parse typedef classic::position_iterator2<std::wstring::iterator> pos_iterator_type; bool completed; try { pos_iterator_type begin(source_code.begin(), source_code.end(), L"test"); pos_iterator_type end; grammar::ThorScript<pos_iterator_type> parser; grammar::detail::WhiteSpace<pos_iterator_type> skipper; completed = qi::phrase_parse( begin, end, parser, skipper); } catch (const qi::expectation_failure<pos_iterator_type>& e) { const classic::file_position_base<std::wstring>& pos = e.first.get_position(); std::wstring current_line; expand_tabs(e.first.get_currentline(), current_line); std::wcerr << L"parse error at file " << pos.file << L" line " << pos.line << L" column " << pos.column << std::endl << L"'" << current_line << L"'" << std::endl << std::setw(pos.column) << L" " << L"^- here" << std::endl; completed = false; } if(completed) std::cout << "parse completed" << std::endl; else std::cout << "parse failed" << std::endl; return 0; }
/** * Zillians MMO * Copyright (C) 2007-2010 Zillians.com, Inc. * For more information see http://www.zillians.com * * Zillians MMO is the library and runtime for massive multiplayer online game * development in utility computing model, which runs as a service for every * developer to build their virtual world running on our GPU-assisted machines. * * This is a close source library intended to be used solely within Zillians.com * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * COPYRIGHT HOLDER(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * @date Jul 18, 2011 sdk - Initial version created. */ #include "core/Prerequisite.h" #include "utility/UnicodeUtil.h" #include "compiler/ThorScriptCompiler.h" using namespace zillians; using namespace zillians::compiler; namespace { namespace qi = boost::spirit::qi; namespace classic = boost::spirit::classic; // since '\t' may be printed in spaces and I don't know a way to change std::wcout, we simply replace the tab with desired number of spaces // so that we can have correct error pointing cursor // (note that because '\t' equals to 4 spaces reported by spirit, we have to make sure it's printed in the exact same way) void expand_tabs(const std::wstring& input, std::wstring& output, int number_of_space_for_tab = 4) { for(std::wstring::const_iterator it = input.begin(); it != input.end(); ++it) { if(*it == '\t') for(int i=0;i<number_of_space_for_tab;++i) output.push_back(L' '); else output.push_back(*it); } } } int main(int argc, char** argv) { // try to read a file std::string filename; if (argc > 1) filename = argv[1]; else { std::cerr << "Error: No input file provided." << std::endl; return 1; } std::ifstream in(filename, std::ios_base::in); // ignore the BOM marking the beginning of a UTF-8 file in Windows char c = in.peek(); if (c == '\xef') { char s[3]; in >> s[0] >> s[1] >> s[2]; s[3] = '\0'; if (s != std::string("\xef\xbb\xbf")) { std::cerr << "Error: Unexpected characters from input file: " << filename << std::endl; return 1; } } std::string source_code_raw; // We will read the contents here. { in.unsetf(std::ios::skipws); // disable white space skipping std::copy(std::istream_iterator<char>(in), std::istream_iterator<char>(), std::back_inserter(source_code_raw)); } // convert it from UTF8 into UCS4 as a string by using u8_to_u32_iterator std::wstring source_code; utf8_to_ucs4(source_code_raw, source_code); // enable correct locale so that we can print UCS4 characters enable_default_locale(std::wcout); // try to parse typedef classic::position_iterator2<std::wstring::iterator> pos_iterator_type; bool completed; try { pos_iterator_type begin(source_code.begin(), source_code.end(), s_to_ws(filename)); pos_iterator_type end; grammar::ThorScript<pos_iterator_type> parser; grammar::detail::WhiteSpace<pos_iterator_type> skipper; completed = qi::phrase_parse( begin, end, parser, skipper); } catch (const qi::expectation_failure<pos_iterator_type>& e) { const classic::file_position_base<std::wstring>& pos = e.first.get_position(); std::wstring current_line; expand_tabs(e.first.get_currentline(), current_line); std::wcerr << L"parse error at file " << pos.file << L" line " << pos.line << L" column " << pos.column << std::endl << L"'" << current_line << L"'" << std::endl << std::setw(pos.column) << L" " << L"^- here" << std::endl; completed = false; } if(completed) std::cout << "parse completed" << std::endl; else std::cout << "parse failed" << std::endl; return 0; }
update thor compiler -- correctly print filename when error occurs
update thor compiler -- correctly print filename when error occurs
C++
agpl-3.0
zillians/supercell_language,zillians/supercell_language,zillians/supercell_language,zillians/supercell_language,zillians/supercell_language
9b97b17d67e76c6ae7ff02ddec46a79aecde395b
src/RunStyles.cxx
src/RunStyles.cxx
/** @file RunStyles.cxx ** Data structure used to store sparse styles. **/ // Copyright 1998-2007 by Neil Hodgson <[email protected]> // The License.txt file describes the conditions under which this software may be distributed. #include <stdio.h> #include <string.h> #include <stdlib.h> #include <stdarg.h> #include <stdexcept> #include "Platform.h" #include "Scintilla.h" #include "SplitVector.h" #include "Partitioning.h" #include "RunStyles.h" #ifdef SCI_NAMESPACE using namespace Scintilla; #endif // Find the first run at a position int RunStyles::RunFromPosition(int position) const { int run = starts->PartitionFromPosition(position); // Go to first element with this position while ((run > 0) && (position == starts->PositionFromPartition(run-1))) { run--; } return run; } // If there is no run boundary at position, insert one continuing style. int RunStyles::SplitRun(int position) { int run = RunFromPosition(position); int posRun = starts->PositionFromPartition(run); if (posRun < position) { int runStyle = ValueAt(position); run++; starts->InsertPartition(run, position); styles->InsertValue(run, 1, runStyle); } return run; } void RunStyles::RemoveRun(int run) { starts->RemovePartition(run); styles->DeleteRange(run, 1); } void RunStyles::RemoveRunIfEmpty(int run) { if ((run < starts->Partitions()) && (starts->Partitions() > 1)) { if (starts->PositionFromPartition(run) == starts->PositionFromPartition(run+1)) { RemoveRun(run); } } } void RunStyles::RemoveRunIfSameAsPrevious(int run) { if ((run > 0) && (run < starts->Partitions())) { if (styles->ValueAt(run-1) == styles->ValueAt(run)) { RemoveRun(run); } } } RunStyles::RunStyles() { starts = new Partitioning(8); styles = new SplitVector<int>(); styles->InsertValue(0, 2, 0); } RunStyles::~RunStyles() { delete starts; starts = NULL; delete styles; styles = NULL; } int RunStyles::Length() const { return starts->PositionFromPartition(starts->Partitions()); } int RunStyles::ValueAt(int position) const { return styles->ValueAt(starts->PartitionFromPosition(position)); } int RunStyles::FindNextChange(int position, int end) const { int run = starts->PartitionFromPosition(position); if (run < starts->Partitions()) { int runChange = starts->PositionFromPartition(run); if (runChange > position) return runChange; int nextChange = starts->PositionFromPartition(run + 1); if (nextChange > position) { return nextChange; } else if (position < end) { return end; } else { return end + 1; } } else { return end + 1; } } int RunStyles::StartRun(int position) const { return starts->PositionFromPartition(starts->PartitionFromPosition(position)); } int RunStyles::EndRun(int position) const { return starts->PositionFromPartition(starts->PartitionFromPosition(position) + 1); } bool RunStyles::FillRange(int &position, int value, int &fillLength) { if (fillLength <= 0) { return false; } int end = position + fillLength; if (end > Length()) { return false; } int runEnd = RunFromPosition(end); if (styles->ValueAt(runEnd) == value) { // End already has value so trim range. end = starts->PositionFromPartition(runEnd); if (position >= end) { // Whole range is already same as value so no action return false; } fillLength = end - position; } else { runEnd = SplitRun(end); } int runStart = RunFromPosition(position); if (styles->ValueAt(runStart) == value) { // Start is in expected value so trim range. runStart++; position = starts->PositionFromPartition(runStart); fillLength = end - position; } else { if (starts->PositionFromPartition(runStart) < position) { runStart = SplitRun(position); runEnd++; } } if (runStart < runEnd) { styles->SetValueAt(runStart, value); // Remove each old run over the range for (int run=runStart+1; run<runEnd; run++) { RemoveRun(runStart+1); } runEnd = RunFromPosition(end); RemoveRunIfSameAsPrevious(runEnd); RemoveRunIfSameAsPrevious(runStart); runEnd = RunFromPosition(end); RemoveRunIfEmpty(runEnd); return true; } else { return false; } } void RunStyles::SetValueAt(int position, int value) { int len = 1; FillRange(position, value, len); } void RunStyles::InsertSpace(int position, int insertLength) { int runStart = RunFromPosition(position); if (starts->PositionFromPartition(runStart) == position) { int runStyle = ValueAt(position); // Inserting at start of run so make previous longer if (runStart == 0) { // Inserting at start of document so ensure 0 if (runStyle) { styles->SetValueAt(0, 0); starts->InsertPartition(1, 0); styles->InsertValue(1, 1, runStyle); starts->InsertText(0, insertLength); } else { starts->InsertText(runStart, insertLength); } } else { if (runStyle) { starts->InsertText(runStart-1, insertLength); } else { // Insert at end of run so do not extend style starts->InsertText(runStart, insertLength); } } } else { starts->InsertText(runStart, insertLength); } } void RunStyles::DeleteAll() { delete starts; starts = NULL; delete styles; styles = NULL; starts = new Partitioning(8); styles = new SplitVector<int>(); styles->InsertValue(0, 2, 0); } void RunStyles::DeleteRange(int position, int deleteLength) { int end = position + deleteLength; int runStart = RunFromPosition(position); int runEnd = RunFromPosition(end); if (runStart == runEnd) { // Deleting from inside one run starts->InsertText(runStart, -deleteLength); RemoveRunIfEmpty(runStart); } else { runStart = SplitRun(position); runEnd = SplitRun(end); starts->InsertText(runStart, -deleteLength); // Remove each old run over the range for (int run=runStart; run<runEnd; run++) { RemoveRun(runStart); } RemoveRunIfEmpty(runStart); RemoveRunIfSameAsPrevious(runStart); } } int RunStyles::Runs() const { return starts->Partitions(); } bool RunStyles::AllSame() const { for (int run = 1; run < starts->Partitions(); run++) { if (styles->ValueAt(run) != styles->ValueAt(run - 1)) return false; } return true; } bool RunStyles::AllSameAs(int value) const { return AllSame() && (styles->ValueAt(0) == value); } int RunStyles::Find(int value, int start) const { if (start < Length()) { int run = start ? RunFromPosition(start) : 0; if (styles->ValueAt(run) == value) return start; run++; while (run < starts->Partitions()) { if (styles->ValueAt(run) == value) return starts->PositionFromPartition(run); run++; } } return -1; } void RunStyles::Check() const { if (Length() < 0) { throw std::runtime_error("RunStyles: Length can not be negative."); } if (starts->Partitions() < 1) { throw std::runtime_error("RunStyles: Must always have 1 or more partitions."); } if (starts->Partitions() != styles->Length()-1) { throw std::runtime_error("RunStyles: Partitions and styles different lengths."); } int start=0; while (start < Length()) { int end = EndRun(start); if (start >= end) { throw std::runtime_error("RunStyles: Partition is 0 length."); } start = end; } if (styles->ValueAt(styles->Length()-1) != 0) { throw std::runtime_error("RunStyles: Unused style at end changed."); } for (int j=1; j<styles->Length()-1; j++) { if (styles->ValueAt(j) == styles->ValueAt(j-1)) { throw std::runtime_error("RunStyles: Style of a partition same as previous."); } } }
/** @file RunStyles.cxx ** Data structure used to store sparse styles. **/ // Copyright 1998-2007 by Neil Hodgson <[email protected]> // The License.txt file describes the conditions under which this software may be distributed. #include <stdio.h> #include <string.h> #include <stdlib.h> #include <stdarg.h> #include <stdexcept> #include <algorithm> #include "Platform.h" #include "Scintilla.h" #include "SplitVector.h" #include "Partitioning.h" #include "RunStyles.h" #ifdef SCI_NAMESPACE using namespace Scintilla; #endif // Find the first run at a position int RunStyles::RunFromPosition(int position) const { int run = starts->PartitionFromPosition(position); // Go to first element with this position while ((run > 0) && (position == starts->PositionFromPartition(run-1))) { run--; } return run; } // If there is no run boundary at position, insert one continuing style. int RunStyles::SplitRun(int position) { int run = RunFromPosition(position); int posRun = starts->PositionFromPartition(run); if (posRun < position) { int runStyle = ValueAt(position); run++; starts->InsertPartition(run, position); styles->InsertValue(run, 1, runStyle); } return run; } void RunStyles::RemoveRun(int run) { starts->RemovePartition(run); styles->DeleteRange(run, 1); } void RunStyles::RemoveRunIfEmpty(int run) { if ((run < starts->Partitions()) && (starts->Partitions() > 1)) { if (starts->PositionFromPartition(run) == starts->PositionFromPartition(run+1)) { RemoveRun(run); } } } void RunStyles::RemoveRunIfSameAsPrevious(int run) { if ((run > 0) && (run < starts->Partitions())) { if (styles->ValueAt(run-1) == styles->ValueAt(run)) { RemoveRun(run); } } } RunStyles::RunStyles() { starts = new Partitioning(8); styles = new SplitVector<int>(); styles->InsertValue(0, 2, 0); } RunStyles::~RunStyles() { delete starts; starts = NULL; delete styles; styles = NULL; } int RunStyles::Length() const { return starts->PositionFromPartition(starts->Partitions()); } int RunStyles::ValueAt(int position) const { return styles->ValueAt(starts->PartitionFromPosition(position)); } int RunStyles::FindNextChange(int position, int end) const { int run = starts->PartitionFromPosition(position); if (run < starts->Partitions()) { int runChange = starts->PositionFromPartition(run); if (runChange > position) return runChange; int nextChange = starts->PositionFromPartition(run + 1); if (nextChange > position) { return nextChange; } else if (position < end) { return end; } else { return end + 1; } } else { return end + 1; } } int RunStyles::StartRun(int position) const { return starts->PositionFromPartition(starts->PartitionFromPosition(position)); } int RunStyles::EndRun(int position) const { return starts->PositionFromPartition(starts->PartitionFromPosition(position) + 1); } bool RunStyles::FillRange(int &position, int value, int &fillLength) { if (fillLength <= 0) { return false; } int end = position + fillLength; if (end > Length()) { return false; } int runEnd = RunFromPosition(end); if (styles->ValueAt(runEnd) == value) { // End already has value so trim range. end = starts->PositionFromPartition(runEnd); if (position >= end) { // Whole range is already same as value so no action return false; } fillLength = end - position; } else { runEnd = SplitRun(end); } int runStart = RunFromPosition(position); if (styles->ValueAt(runStart) == value) { // Start is in expected value so trim range. runStart++; position = starts->PositionFromPartition(runStart); fillLength = end - position; } else { if (starts->PositionFromPartition(runStart) < position) { runStart = SplitRun(position); runEnd++; } } if (runStart < runEnd) { styles->SetValueAt(runStart, value); // Remove each old run over the range for (int run=runStart+1; run<runEnd; run++) { RemoveRun(runStart+1); } runEnd = RunFromPosition(end); RemoveRunIfSameAsPrevious(runEnd); RemoveRunIfSameAsPrevious(runStart); runEnd = RunFromPosition(end); RemoveRunIfEmpty(runEnd); return true; } else { return false; } } void RunStyles::SetValueAt(int position, int value) { int len = 1; FillRange(position, value, len); } void RunStyles::InsertSpace(int position, int insertLength) { int runStart = RunFromPosition(position); if (starts->PositionFromPartition(runStart) == position) { int runStyle = ValueAt(position); // Inserting at start of run so make previous longer if (runStart == 0) { // Inserting at start of document so ensure 0 if (runStyle) { styles->SetValueAt(0, 0); starts->InsertPartition(1, 0); styles->InsertValue(1, 1, runStyle); starts->InsertText(0, insertLength); } else { starts->InsertText(runStart, insertLength); } } else { if (runStyle) { starts->InsertText(runStart-1, insertLength); } else { // Insert at end of run so do not extend style starts->InsertText(runStart, insertLength); } } } else { starts->InsertText(runStart, insertLength); } } void RunStyles::DeleteAll() { delete starts; starts = NULL; delete styles; styles = NULL; starts = new Partitioning(8); styles = new SplitVector<int>(); styles->InsertValue(0, 2, 0); } void RunStyles::DeleteRange(int position, int deleteLength) { int end = position + deleteLength; int runStart = RunFromPosition(position); int runEnd = RunFromPosition(end); if (runStart == runEnd) { // Deleting from inside one run starts->InsertText(runStart, -deleteLength); RemoveRunIfEmpty(runStart); } else { runStart = SplitRun(position); runEnd = SplitRun(end); starts->InsertText(runStart, -deleteLength); // Remove each old run over the range for (int run=runStart; run<runEnd; run++) { RemoveRun(runStart); } RemoveRunIfEmpty(runStart); RemoveRunIfSameAsPrevious(runStart); } } int RunStyles::Runs() const { return starts->Partitions(); } bool RunStyles::AllSame() const { for (int run = 1; run < starts->Partitions(); run++) { if (styles->ValueAt(run) != styles->ValueAt(run - 1)) return false; } return true; } bool RunStyles::AllSameAs(int value) const { return AllSame() && (styles->ValueAt(0) == value); } int RunStyles::Find(int value, int start) const { if (start < Length()) { int run = start ? RunFromPosition(start) : 0; if (styles->ValueAt(run) == value) return start; run++; while (run < starts->Partitions()) { if (styles->ValueAt(run) == value) return starts->PositionFromPartition(run); run++; } } return -1; } void RunStyles::Check() const { if (Length() < 0) { throw std::runtime_error("RunStyles: Length can not be negative."); } if (starts->Partitions() < 1) { throw std::runtime_error("RunStyles: Must always have 1 or more partitions."); } if (starts->Partitions() != styles->Length()-1) { throw std::runtime_error("RunStyles: Partitions and styles different lengths."); } int start=0; while (start < Length()) { int end = EndRun(start); if (start >= end) { throw std::runtime_error("RunStyles: Partition is 0 length."); } start = end; } if (styles->ValueAt(styles->Length()-1) != 0) { throw std::runtime_error("RunStyles: Unused style at end changed."); } for (int j=1; j<styles->Length()-1; j++) { if (styles->ValueAt(j) == styles->ValueAt(j-1)) { throw std::runtime_error("RunStyles: Style of a partition same as previous."); } } }
Make compile with libc++ on OS X.
Make compile with libc++ on OS X.
C++
isc
windoze/scintilla,windoze/scintilla,windoze/scintilla,windoze/scintilla,windoze/scintilla,windoze/scintilla,windoze/scintilla,windoze/scintilla
421bbc7912df3a147f7b3d7ec54243a1b6ba5978
chrome/browser/views/browser_views_accessibility_browsertest.cc
chrome/browser/views/browser_views_accessibility_browsertest.cc
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <oleacc.h> #include "app/l10n_util.h" #include "chrome/browser/browser.h" #include "chrome/browser/browser_window.h" #include "chrome/browser/view_ids.h" #include "chrome/browser/views/bookmark_bar_view.h" #include "chrome/browser/views/frame/browser_view.h" #include "chrome/browser/views/toolbar_view.h" #include "chrome/test/in_process_browser_test.h" #include "grit/chromium_strings.h" #include "grit/generated_resources.h" #include "views/accessibility/view_accessibility_wrapper.h" #include "views/widget/root_view.h" #include "views/widget/widget_win.h" #include "views/window/window.h" namespace { VARIANT id_self = {VT_I4, CHILDID_SELF}; // Dummy class to force creation of ATL module, needed by COM to instantiate // ViewAccessibility. class TestAtlModule : public CAtlDllModuleT< TestAtlModule > {}; TestAtlModule test_atl_module_; class BrowserViewsAccessibilityTest : public InProcessBrowserTest { public: BrowserViewsAccessibilityTest() { ::CoInitialize(NULL); } ~BrowserViewsAccessibilityTest() { ::CoUninitialize(); } // Retrieves an instance of BrowserWindowTesting BrowserWindowTesting* GetBrowserWindowTesting() { BrowserWindow* browser_window = browser()->window(); if (!browser_window) return NULL; return browser_window->GetBrowserWindowTesting(); } // Retrieve an instance of BrowserView BrowserView* GetBrowserView() { return BrowserView::GetBrowserViewForNativeWindow( browser()->window()->GetNativeHandle()); } // Retrieves and initializes an instance of LocationBarView. LocationBarView* GetLocationBarView() { BrowserWindowTesting* browser_window_testing = GetBrowserWindowTesting(); if (!browser_window_testing) return NULL; return GetBrowserWindowTesting()->GetLocationBarView(); } // Retrieves and initializes an instance of ToolbarView. ToolbarView* GetToolbarView() { BrowserWindowTesting* browser_window_testing = GetBrowserWindowTesting(); if (!browser_window_testing) return NULL; return browser_window_testing->GetToolbarView(); } // Retrieves and initializes an instance of BookmarkBarView. BookmarkBarView* GetBookmarkBarView() { BrowserWindowTesting* browser_window_testing = GetBrowserWindowTesting(); if (!browser_window_testing) return NULL; return browser_window_testing->GetBookmarkBarView(); } // Retrieves and verifies the accessibility object for the given View. void TestViewAccessibilityObject(views::View* view, std::wstring name, int32 role) { ASSERT_TRUE(NULL != view); IAccessible* acc_obj = NULL; HRESULT hr = view->GetViewAccessibilityWrapper()->GetInstance( IID_IAccessible, reinterpret_cast<void**>(&acc_obj)); ASSERT_EQ(S_OK, hr); ASSERT_TRUE(NULL != acc_obj); TestAccessibilityInfo(acc_obj, name, role); } // Verifies MSAA Name and Role properties of the given IAccessible. void TestAccessibilityInfo(IAccessible* acc_obj, std::wstring name, int32 role) { // Verify MSAA Name property. BSTR acc_name; HRESULT hr = acc_obj->get_accName(id_self, &acc_name); ASSERT_EQ(S_OK, hr); EXPECT_STREQ(acc_name, name.c_str()); // Verify MSAA Role property. VARIANT acc_role; ::VariantInit(&acc_role); hr = acc_obj->get_accRole(id_self, &acc_role); ASSERT_EQ(S_OK, hr); EXPECT_EQ(VT_I4, acc_role.vt); EXPECT_EQ(role, acc_role.lVal); ::VariantClear(&acc_role); ::SysFreeString(acc_name); } }; // Retrieve accessibility object for main window and verify accessibility info. IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestChromeWindowAccObj) { BrowserWindow* browser_window = browser()->window(); ASSERT_TRUE(NULL != browser_window); HWND hwnd = browser_window->GetNativeHandle(); ASSERT_TRUE(NULL != hwnd); // Get accessibility object. IAccessible* acc_obj = NULL; HRESULT hr = ::AccessibleObjectFromWindow(hwnd, OBJID_WINDOW, IID_IAccessible, reinterpret_cast<void**>(&acc_obj)); ASSERT_EQ(S_OK, hr); ASSERT_TRUE(NULL != acc_obj); TestAccessibilityInfo(acc_obj, l10n_util::GetString(IDS_PRODUCT_NAME), ROLE_SYSTEM_WINDOW); acc_obj->Release(); } // Retrieve accessibility object for non client view and verify accessibility // info. IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestNonClientViewAccObj) { views::View* non_client_view = GetBrowserView()->GetWindow()->GetNonClientView(); TestViewAccessibilityObject(non_client_view, l10n_util::GetString(IDS_PRODUCT_NAME), ROLE_SYSTEM_WINDOW); } // Retrieve accessibility object for browser root view and verify // accessibility info. IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestBrowserRootViewAccObj) { views::View* browser_root_view = GetBrowserView()->frame()->GetFrameView()->GetRootView(); TestViewAccessibilityObject(browser_root_view, l10n_util::GetString(IDS_PRODUCT_NAME), ROLE_SYSTEM_APPLICATION); } // Retrieve accessibility object for browser view and verify accessibility info. IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestBrowserViewAccObj) { // Verify root view MSAA name and role. TestViewAccessibilityObject(GetBrowserView(), l10n_util::GetString(IDS_PRODUCT_NAME), ROLE_SYSTEM_CLIENT); } // Retrieve accessibility object for toolbar view and verify accessibility info. IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestToolbarViewAccObj) { // Verify toolbar MSAA name and role. TestViewAccessibilityObject(GetToolbarView(), l10n_util::GetString(IDS_ACCNAME_TOOLBAR), ROLE_SYSTEM_TOOLBAR); } // Retrieve accessibility object for Back button and verify accessibility info. IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestBackButtonAccObj) { // Verify Back button MSAA name and role. TestViewAccessibilityObject( GetToolbarView()->GetViewByID(VIEW_ID_BACK_BUTTON), l10n_util::GetString(IDS_ACCNAME_BACK), ROLE_SYSTEM_BUTTONDROPDOWN); } // Retrieve accessibility object for Forward button and verify accessibility // info. IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestForwardButtonAccObj) { // Verify Forward button MSAA name and role. TestViewAccessibilityObject( GetToolbarView()->GetViewByID(VIEW_ID_FORWARD_BUTTON), l10n_util::GetString(IDS_ACCNAME_FORWARD), ROLE_SYSTEM_BUTTONDROPDOWN); } // Retrieve accessibility object for Reload button and verify accessibility // info. IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestReloadButtonAccObj) { // Verify Reload button MSAA name and role. TestViewAccessibilityObject( GetToolbarView()->GetViewByID(VIEW_ID_RELOAD_BUTTON), l10n_util::GetString(IDS_ACCNAME_RELOAD), ROLE_SYSTEM_PUSHBUTTON); } // Retrieve accessibility object for Home button and verify accessibility info. IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestHomeButtonAccObj) { // Verify Home button MSAA name and role. TestViewAccessibilityObject( GetToolbarView()->GetViewByID(VIEW_ID_HOME_BUTTON), l10n_util::GetString(IDS_ACCNAME_HOME), ROLE_SYSTEM_PUSHBUTTON); } // Retrieve accessibility object for Star button and verify accessibility info. IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestStarButtonAccObj) { // Verify Star button MSAA name and role. TestViewAccessibilityObject( GetToolbarView()->GetViewByID(VIEW_ID_STAR_BUTTON), l10n_util::GetString(IDS_ACCNAME_STAR), ROLE_SYSTEM_PUSHBUTTON); } // Retrieve accessibility object for location bar view and verify accessibility // info. IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestLocationBarViewAccObj) { // Verify location bar MSAA name and role. TestViewAccessibilityObject(GetLocationBarView(), l10n_util::GetString(IDS_ACCNAME_LOCATION), ROLE_SYSTEM_GROUPING); } // Retrieve accessibility object for Go button and verify accessibility info. IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestGoButtonAccObj) { // Verify Go button MSAA name and role. TestViewAccessibilityObject(GetToolbarView()->GetViewByID(VIEW_ID_GO_BUTTON), l10n_util::GetString(IDS_ACCNAME_GO), ROLE_SYSTEM_PUSHBUTTON); } // Retrieve accessibility object for Page menu button and verify accessibility // info. IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestPageMenuAccObj) { // Verify Page menu button MSAA name and role. TestViewAccessibilityObject(GetToolbarView()->GetViewByID(VIEW_ID_PAGE_MENU), l10n_util::GetString(IDS_ACCNAME_PAGE), ROLE_SYSTEM_BUTTONMENU); } // Retrieve accessibility object for App menu button and verify accessibility // info. IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestAppMenuAccObj) { // Verify App menu button MSAA name and role. TestViewAccessibilityObject(GetToolbarView()->GetViewByID(VIEW_ID_APP_MENU), l10n_util::GetString(IDS_ACCNAME_APP), ROLE_SYSTEM_BUTTONMENU); } IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestBookmarkBarViewAccObj) { TestViewAccessibilityObject(GetBookmarkBarView(), l10n_util::GetString(IDS_ACCNAME_BOOKMARKS), ROLE_SYSTEM_TOOLBAR); } } // Namespace.
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <oleacc.h> #include "app/l10n_util.h" #include "chrome/browser/browser.h" #include "chrome/browser/browser_window.h" #include "chrome/browser/view_ids.h" #include "chrome/browser/views/bookmark_bar_view.h" #include "chrome/browser/views/frame/browser_view.h" #include "chrome/browser/views/toolbar_view.h" #include "chrome/test/in_process_browser_test.h" #include "grit/chromium_strings.h" #include "grit/generated_resources.h" #include "views/accessibility/view_accessibility_wrapper.h" #include "views/widget/root_view.h" #include "views/widget/widget_win.h" #include "views/window/window.h" namespace { VARIANT id_self = {VT_I4, CHILDID_SELF}; // Dummy class to force creation of ATL module, needed by COM to instantiate // ViewAccessibility. class TestAtlModule : public CAtlDllModuleT< TestAtlModule > {}; TestAtlModule test_atl_module_; class BrowserViewsAccessibilityTest : public InProcessBrowserTest { public: BrowserViewsAccessibilityTest() { ::CoInitialize(NULL); } ~BrowserViewsAccessibilityTest() { ::CoUninitialize(); } // Retrieves an instance of BrowserWindowTesting BrowserWindowTesting* GetBrowserWindowTesting() { BrowserWindow* browser_window = browser()->window(); if (!browser_window) return NULL; return browser_window->GetBrowserWindowTesting(); } // Retrieve an instance of BrowserView BrowserView* GetBrowserView() { return BrowserView::GetBrowserViewForNativeWindow( browser()->window()->GetNativeHandle()); } // Retrieves and initializes an instance of LocationBarView. LocationBarView* GetLocationBarView() { BrowserWindowTesting* browser_window_testing = GetBrowserWindowTesting(); if (!browser_window_testing) return NULL; return GetBrowserWindowTesting()->GetLocationBarView(); } // Retrieves and initializes an instance of ToolbarView. ToolbarView* GetToolbarView() { BrowserWindowTesting* browser_window_testing = GetBrowserWindowTesting(); if (!browser_window_testing) return NULL; return browser_window_testing->GetToolbarView(); } // Retrieves and initializes an instance of BookmarkBarView. BookmarkBarView* GetBookmarkBarView() { BrowserWindowTesting* browser_window_testing = GetBrowserWindowTesting(); if (!browser_window_testing) return NULL; return browser_window_testing->GetBookmarkBarView(); } // Retrieves and verifies the accessibility object for the given View. void TestViewAccessibilityObject(views::View* view, std::wstring name, int32 role) { ASSERT_TRUE(NULL != view); IAccessible* acc_obj = NULL; HRESULT hr = view->GetViewAccessibilityWrapper()->GetInstance( IID_IAccessible, reinterpret_cast<void**>(&acc_obj)); ASSERT_EQ(S_OK, hr); ASSERT_TRUE(NULL != acc_obj); TestAccessibilityInfo(acc_obj, name, role); } // Verifies MSAA Name and Role properties of the given IAccessible. void TestAccessibilityInfo(IAccessible* acc_obj, std::wstring name, int32 role) { // Verify MSAA Name property. BSTR acc_name; HRESULT hr = acc_obj->get_accName(id_self, &acc_name); ASSERT_EQ(S_OK, hr); EXPECT_STREQ(acc_name, name.c_str()); // Verify MSAA Role property. VARIANT acc_role; ::VariantInit(&acc_role); hr = acc_obj->get_accRole(id_self, &acc_role); ASSERT_EQ(S_OK, hr); EXPECT_EQ(VT_I4, acc_role.vt); EXPECT_EQ(role, acc_role.lVal); ::VariantClear(&acc_role); ::SysFreeString(acc_name); } }; // Retrieve accessibility object for main window and verify accessibility info. IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, FLAKY_TestChromeWindowAccObj) { BrowserWindow* browser_window = browser()->window(); ASSERT_TRUE(NULL != browser_window); HWND hwnd = browser_window->GetNativeHandle(); ASSERT_TRUE(NULL != hwnd); // Get accessibility object. IAccessible* acc_obj = NULL; HRESULT hr = ::AccessibleObjectFromWindow(hwnd, OBJID_WINDOW, IID_IAccessible, reinterpret_cast<void**>(&acc_obj)); ASSERT_EQ(S_OK, hr); ASSERT_TRUE(NULL != acc_obj); // TODO(ctguil): Fix. The window title could be "New Tab - Chromium" or // "about:blank - Chromium" TestAccessibilityInfo(acc_obj, l10n_util::GetString(IDS_PRODUCT_NAME), ROLE_SYSTEM_WINDOW); acc_obj->Release(); } // Retrieve accessibility object for non client view and verify accessibility // info. IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestNonClientViewAccObj) { views::View* non_client_view = GetBrowserView()->GetWindow()->GetNonClientView(); TestViewAccessibilityObject(non_client_view, l10n_util::GetString(IDS_PRODUCT_NAME), ROLE_SYSTEM_WINDOW); } // Retrieve accessibility object for browser root view and verify // accessibility info. IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestBrowserRootViewAccObj) { views::View* browser_root_view = GetBrowserView()->frame()->GetFrameView()->GetRootView(); TestViewAccessibilityObject(browser_root_view, l10n_util::GetString(IDS_PRODUCT_NAME), ROLE_SYSTEM_APPLICATION); } // Retrieve accessibility object for browser view and verify accessibility info. IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestBrowserViewAccObj) { // Verify root view MSAA name and role. TestViewAccessibilityObject(GetBrowserView(), l10n_util::GetString(IDS_PRODUCT_NAME), ROLE_SYSTEM_CLIENT); } // Retrieve accessibility object for toolbar view and verify accessibility info. IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestToolbarViewAccObj) { // Verify toolbar MSAA name and role. TestViewAccessibilityObject(GetToolbarView(), l10n_util::GetString(IDS_ACCNAME_TOOLBAR), ROLE_SYSTEM_TOOLBAR); } // Retrieve accessibility object for Back button and verify accessibility info. IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestBackButtonAccObj) { // Verify Back button MSAA name and role. TestViewAccessibilityObject( GetToolbarView()->GetViewByID(VIEW_ID_BACK_BUTTON), l10n_util::GetString(IDS_ACCNAME_BACK), ROLE_SYSTEM_BUTTONDROPDOWN); } // Retrieve accessibility object for Forward button and verify accessibility // info. IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestForwardButtonAccObj) { // Verify Forward button MSAA name and role. TestViewAccessibilityObject( GetToolbarView()->GetViewByID(VIEW_ID_FORWARD_BUTTON), l10n_util::GetString(IDS_ACCNAME_FORWARD), ROLE_SYSTEM_BUTTONDROPDOWN); } // Retrieve accessibility object for Reload button and verify accessibility // info. IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestReloadButtonAccObj) { // Verify Reload button MSAA name and role. TestViewAccessibilityObject( GetToolbarView()->GetViewByID(VIEW_ID_RELOAD_BUTTON), l10n_util::GetString(IDS_ACCNAME_RELOAD), ROLE_SYSTEM_PUSHBUTTON); } // Retrieve accessibility object for Home button and verify accessibility info. IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestHomeButtonAccObj) { // Verify Home button MSAA name and role. TestViewAccessibilityObject( GetToolbarView()->GetViewByID(VIEW_ID_HOME_BUTTON), l10n_util::GetString(IDS_ACCNAME_HOME), ROLE_SYSTEM_PUSHBUTTON); } // Retrieve accessibility object for Star button and verify accessibility info. IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestStarButtonAccObj) { // Verify Star button MSAA name and role. TestViewAccessibilityObject( GetToolbarView()->GetViewByID(VIEW_ID_STAR_BUTTON), l10n_util::GetString(IDS_ACCNAME_STAR), ROLE_SYSTEM_PUSHBUTTON); } // Retrieve accessibility object for location bar view and verify accessibility // info. IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestLocationBarViewAccObj) { // Verify location bar MSAA name and role. TestViewAccessibilityObject(GetLocationBarView(), l10n_util::GetString(IDS_ACCNAME_LOCATION), ROLE_SYSTEM_GROUPING); } // Retrieve accessibility object for Go button and verify accessibility info. IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestGoButtonAccObj) { // Verify Go button MSAA name and role. TestViewAccessibilityObject(GetToolbarView()->GetViewByID(VIEW_ID_GO_BUTTON), l10n_util::GetString(IDS_ACCNAME_GO), ROLE_SYSTEM_PUSHBUTTON); } // Retrieve accessibility object for Page menu button and verify accessibility // info. IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestPageMenuAccObj) { // Verify Page menu button MSAA name and role. TestViewAccessibilityObject(GetToolbarView()->GetViewByID(VIEW_ID_PAGE_MENU), l10n_util::GetString(IDS_ACCNAME_PAGE), ROLE_SYSTEM_BUTTONMENU); } // Retrieve accessibility object for App menu button and verify accessibility // info. IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestAppMenuAccObj) { // Verify App menu button MSAA name and role. TestViewAccessibilityObject(GetToolbarView()->GetViewByID(VIEW_ID_APP_MENU), l10n_util::GetString(IDS_ACCNAME_APP), ROLE_SYSTEM_BUTTONMENU); } IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestBookmarkBarViewAccObj) { TestViewAccessibilityObject(GetBookmarkBarView(), l10n_util::GetString(IDS_ACCNAME_BOOKMARKS), ROLE_SYSTEM_TOOLBAR); } } // Namespace.
Mark BrowserViewsAccessibilityTest.TestChromeWindowAccObj as flaky.
Mark BrowserViewsAccessibilityTest.TestChromeWindowAccObj as flaky. I've seen this fail on my local machine as well as on the try server. Looks like there's a race condition. BUG=none TEST=none [email protected] git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@47424 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
littlstar/chromium.src,crosswalk-project/chromium-crosswalk-efl,nacl-webkit/chrome_deps,nacl-webkit/chrome_deps,robclark/chromium,jaruba/chromium.src,fujunwei/chromium-crosswalk,bright-sparks/chromium-spacewalk,fujunwei/chromium-crosswalk,Jonekee/chromium.src,M4sse/chromium.src,Fireblend/chromium-crosswalk,junmin-zhu/chromium-rivertrail,pozdnyakov/chromium-crosswalk,robclark/chromium,ltilve/chromium,anirudhSK/chromium,ondra-novak/chromium.src,krieger-od/nwjs_chromium.src,patrickm/chromium.src,jaruba/chromium.src,chuan9/chromium-crosswalk,robclark/chromium,patrickm/chromium.src,fujunwei/chromium-crosswalk,junmin-zhu/chromium-rivertrail,axinging/chromium-crosswalk,axinging/chromium-crosswalk,ltilve/chromium,patrickm/chromium.src,zcbenz/cefode-chromium,hgl888/chromium-crosswalk-efl,PeterWangIntel/chromium-crosswalk,Chilledheart/chromium,keishi/chromium,M4sse/chromium.src,hgl888/chromium-crosswalk,timopulkkinen/BubbleFish,mohamed--abdel-maksoud/chromium.src,mohamed--abdel-maksoud/chromium.src,hgl888/chromium-crosswalk,mogoweb/chromium-crosswalk,hgl888/chromium-crosswalk-efl,TheTypoMaster/chromium-crosswalk,ChromiumWebApps/chromium,fujunwei/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,mogoweb/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,Pluto-tv/chromium-crosswalk,pozdnyakov/chromium-crosswalk,Fireblend/chromium-crosswalk,junmin-zhu/chromium-rivertrail,hgl888/chromium-crosswalk-efl,crosswalk-project/chromium-crosswalk-efl,timopulkkinen/BubbleFish,markYoungH/chromium.src,mohamed--abdel-maksoud/chromium.src,TheTypoMaster/chromium-crosswalk,mogoweb/chromium-crosswalk,ltilve/chromium,junmin-zhu/chromium-rivertrail,timopulkkinen/BubbleFish,zcbenz/cefode-chromium,ChromiumWebApps/chromium,krieger-od/nwjs_chromium.src,axinging/chromium-crosswalk,Pluto-tv/chromium-crosswalk,ondra-novak/chromium.src,PeterWangIntel/chromium-crosswalk,littlstar/chromium.src,zcbenz/cefode-chromium,TheTypoMaster/chromium-crosswalk,Chilledheart/chromium,nacl-webkit/chrome_deps,jaruba/chromium.src,junmin-zhu/chromium-rivertrail,chuan9/chromium-crosswalk,littlstar/chromium.src,Jonekee/chromium.src,pozdnyakov/chromium-crosswalk,anirudhSK/chromium,hujiajie/pa-chromium,markYoungH/chromium.src,mogoweb/chromium-crosswalk,M4sse/chromium.src,rogerwang/chromium,dushu1203/chromium.src,Jonekee/chromium.src,dednal/chromium.src,pozdnyakov/chromium-crosswalk,patrickm/chromium.src,Just-D/chromium-1,rogerwang/chromium,nacl-webkit/chrome_deps,rogerwang/chromium,M4sse/chromium.src,hujiajie/pa-chromium,Just-D/chromium-1,hgl888/chromium-crosswalk,markYoungH/chromium.src,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk-efl,robclark/chromium,bright-sparks/chromium-spacewalk,anirudhSK/chromium,M4sse/chromium.src,robclark/chromium,ChromiumWebApps/chromium,littlstar/chromium.src,ltilve/chromium,crosswalk-project/chromium-crosswalk-efl,keishi/chromium,jaruba/chromium.src,jaruba/chromium.src,Just-D/chromium-1,PeterWangIntel/chromium-crosswalk,hujiajie/pa-chromium,nacl-webkit/chrome_deps,hgl888/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,rogerwang/chromium,hujiajie/pa-chromium,ltilve/chromium,crosswalk-project/chromium-crosswalk-efl,ondra-novak/chromium.src,markYoungH/chromium.src,krieger-od/nwjs_chromium.src,rogerwang/chromium,anirudhSK/chromium,zcbenz/cefode-chromium,Chilledheart/chromium,mohamed--abdel-maksoud/chromium.src,dednal/chromium.src,fujunwei/chromium-crosswalk,nacl-webkit/chrome_deps,ltilve/chromium,dushu1203/chromium.src,patrickm/chromium.src,patrickm/chromium.src,fujunwei/chromium-crosswalk,nacl-webkit/chrome_deps,ChromiumWebApps/chromium,Fireblend/chromium-crosswalk,keishi/chromium,bright-sparks/chromium-spacewalk,pozdnyakov/chromium-crosswalk,hgl888/chromium-crosswalk-efl,patrickm/chromium.src,chuan9/chromium-crosswalk,fujunwei/chromium-crosswalk,Pluto-tv/chromium-crosswalk,ondra-novak/chromium.src,zcbenz/cefode-chromium,hgl888/chromium-crosswalk-efl,keishi/chromium,dednal/chromium.src,zcbenz/cefode-chromium,markYoungH/chromium.src,hujiajie/pa-chromium,pozdnyakov/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,anirudhSK/chromium,krieger-od/nwjs_chromium.src,M4sse/chromium.src,timopulkkinen/BubbleFish,dushu1203/chromium.src,Fireblend/chromium-crosswalk,zcbenz/cefode-chromium,axinging/chromium-crosswalk,junmin-zhu/chromium-rivertrail,Jonekee/chromium.src,nacl-webkit/chrome_deps,ChromiumWebApps/chromium,chuan9/chromium-crosswalk,nacl-webkit/chrome_deps,axinging/chromium-crosswalk,Pluto-tv/chromium-crosswalk,pozdnyakov/chromium-crosswalk,pozdnyakov/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,littlstar/chromium.src,anirudhSK/chromium,mohamed--abdel-maksoud/chromium.src,littlstar/chromium.src,TheTypoMaster/chromium-crosswalk,Chilledheart/chromium,axinging/chromium-crosswalk,jaruba/chromium.src,patrickm/chromium.src,Fireblend/chromium-crosswalk,Just-D/chromium-1,timopulkkinen/BubbleFish,Chilledheart/chromium,mogoweb/chromium-crosswalk,Chilledheart/chromium,dednal/chromium.src,anirudhSK/chromium,junmin-zhu/chromium-rivertrail,rogerwang/chromium,axinging/chromium-crosswalk,junmin-zhu/chromium-rivertrail,jaruba/chromium.src,ChromiumWebApps/chromium,dushu1203/chromium.src,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk,Pluto-tv/chromium-crosswalk,Jonekee/chromium.src,markYoungH/chromium.src,chuan9/chromium-crosswalk,ondra-novak/chromium.src,hujiajie/pa-chromium,fujunwei/chromium-crosswalk,jaruba/chromium.src,rogerwang/chromium,jaruba/chromium.src,dednal/chromium.src,ChromiumWebApps/chromium,crosswalk-project/chromium-crosswalk-efl,Jonekee/chromium.src,hujiajie/pa-chromium,anirudhSK/chromium,anirudhSK/chromium,hgl888/chromium-crosswalk-efl,Pluto-tv/chromium-crosswalk,keishi/chromium,littlstar/chromium.src,robclark/chromium,TheTypoMaster/chromium-crosswalk,robclark/chromium,timopulkkinen/BubbleFish,PeterWangIntel/chromium-crosswalk,M4sse/chromium.src,nacl-webkit/chrome_deps,rogerwang/chromium,robclark/chromium,mohamed--abdel-maksoud/chromium.src,robclark/chromium,ondra-novak/chromium.src,PeterWangIntel/chromium-crosswalk,ChromiumWebApps/chromium,krieger-od/nwjs_chromium.src,ondra-novak/chromium.src,mogoweb/chromium-crosswalk,junmin-zhu/chromium-rivertrail,zcbenz/cefode-chromium,timopulkkinen/BubbleFish,ltilve/chromium,PeterWangIntel/chromium-crosswalk,krieger-od/nwjs_chromium.src,dushu1203/chromium.src,markYoungH/chromium.src,M4sse/chromium.src,axinging/chromium-crosswalk,zcbenz/cefode-chromium,krieger-od/nwjs_chromium.src,junmin-zhu/chromium-rivertrail,markYoungH/chromium.src,pozdnyakov/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,littlstar/chromium.src,krieger-od/nwjs_chromium.src,Just-D/chromium-1,anirudhSK/chromium,bright-sparks/chromium-spacewalk,crosswalk-project/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,junmin-zhu/chromium-rivertrail,hujiajie/pa-chromium,timopulkkinen/BubbleFish,jaruba/chromium.src,nacl-webkit/chrome_deps,dednal/chromium.src,markYoungH/chromium.src,patrickm/chromium.src,axinging/chromium-crosswalk,mogoweb/chromium-crosswalk,zcbenz/cefode-chromium,keishi/chromium,hujiajie/pa-chromium,krieger-od/nwjs_chromium.src,Just-D/chromium-1,Fireblend/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,ondra-novak/chromium.src,hgl888/chromium-crosswalk,zcbenz/cefode-chromium,TheTypoMaster/chromium-crosswalk,chuan9/chromium-crosswalk,Just-D/chromium-1,Jonekee/chromium.src,dednal/chromium.src,keishi/chromium,krieger-od/nwjs_chromium.src,hujiajie/pa-chromium,Jonekee/chromium.src,dushu1203/chromium.src,bright-sparks/chromium-spacewalk,timopulkkinen/BubbleFish,Jonekee/chromium.src,keishi/chromium,crosswalk-project/chromium-crosswalk-efl,ondra-novak/chromium.src,Chilledheart/chromium,Just-D/chromium-1,dushu1203/chromium.src,Fireblend/chromium-crosswalk,rogerwang/chromium,axinging/chromium-crosswalk,dednal/chromium.src,mohamed--abdel-maksoud/chromium.src,hgl888/chromium-crosswalk,Just-D/chromium-1,hgl888/chromium-crosswalk,bright-sparks/chromium-spacewalk,ltilve/chromium,Jonekee/chromium.src,M4sse/chromium.src,pozdnyakov/chromium-crosswalk,ChromiumWebApps/chromium,keishi/chromium,M4sse/chromium.src,dednal/chromium.src,timopulkkinen/BubbleFish,axinging/chromium-crosswalk,markYoungH/chromium.src,timopulkkinen/BubbleFish,mogoweb/chromium-crosswalk,jaruba/chromium.src,hgl888/chromium-crosswalk-efl,M4sse/chromium.src,Chilledheart/chromium,mogoweb/chromium-crosswalk,robclark/chromium,PeterWangIntel/chromium-crosswalk,dushu1203/chromium.src,keishi/chromium,dushu1203/chromium.src,Fireblend/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk-efl,markYoungH/chromium.src,bright-sparks/chromium-spacewalk,pozdnyakov/chromium-crosswalk,Pluto-tv/chromium-crosswalk,ChromiumWebApps/chromium,ChromiumWebApps/chromium,TheTypoMaster/chromium-crosswalk,ltilve/chromium,anirudhSK/chromium,Jonekee/chromium.src,hujiajie/pa-chromium,keishi/chromium,chuan9/chromium-crosswalk,dednal/chromium.src,dednal/chromium.src,bright-sparks/chromium-spacewalk,chuan9/chromium-crosswalk,krieger-od/nwjs_chromium.src,bright-sparks/chromium-spacewalk,mogoweb/chromium-crosswalk,fujunwei/chromium-crosswalk,ChromiumWebApps/chromium,rogerwang/chromium,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk-efl,hgl888/chromium-crosswalk,anirudhSK/chromium,dushu1203/chromium.src,Chilledheart/chromium,dushu1203/chromium.src
ffd865a5fe5b54aa18fe9d55fd16a3518b51aa12
ClrPhlib/src/managed/PeImport.cpp
ClrPhlib/src/managed/PeImport.cpp
#include <ClrPhlib.h> #include <UnmanagedPh.h> using namespace Dependencies; using namespace ClrPh; PeImport::PeImport( _In_ const PPH_MAPPED_IMAGE_IMPORT_DLL importDll, _In_ size_t Index ) { PH_MAPPED_IMAGE_IMPORT_ENTRY importEntry; if (NT_SUCCESS(PhGetMappedImageImportEntry((PPH_MAPPED_IMAGE_IMPORT_DLL) importDll, (ULONG)Index, &importEntry))) { this->Hint = importEntry.NameHint; this->Ordinal = importEntry.Ordinal; this->DelayImport = (importDll->Flags) & PH_MAPPED_IMAGE_DELAY_IMPORTS; this->Name = gcnew String(importEntry.Name); this->ModuleName = gcnew String(importDll->Name); this->ImportByOrdinal = (importEntry.Name == nullptr); } } PeImport::PeImport( _In_ const PeImport ^ other ) { this->Hint = other->Hint; this->Ordinal = other->Ordinal; this->DelayImport = other->DelayImport; this->Name = String::Copy(other->Name); this->ModuleName = String::Copy(other->ModuleName); this->ImportByOrdinal = other->ImportByOrdinal; } PeImport::~PeImport() { } PeImportDll::PeImportDll( _In_ const PPH_MAPPED_IMAGE_IMPORTS &PvMappedImports, _In_ size_t ImportDllIndex ) : ImportDll (new PH_MAPPED_IMAGE_IMPORT_DLL) { ImportList = gcnew Collections::Generic::List<PeImport^>(); if (!NT_SUCCESS(PhGetMappedImageImportDll(PvMappedImports, (ULONG)ImportDllIndex, ImportDll))) { return; } Flags = ImportDll->Flags; Name = gcnew String(ImportDll->Name); NumberOfEntries = ImportDll->NumberOfEntries; for (size_t IndexImport = 0; IndexImport < (size_t) NumberOfEntries; IndexImport++) { ImportList->Add(gcnew PeImport(ImportDll, IndexImport)); } } PeImportDll::~PeImportDll() { delete ImportDll; } PeImportDll::!PeImportDll() { delete ImportDll; } PeImportDll::PeImportDll( _In_ const PeImportDll ^ other ) : ImportDll(new PH_MAPPED_IMAGE_IMPORT_DLL) { ImportList = gcnew Collections::Generic::List<PeImport^>(); memcpy(ImportDll, other->ImportDll, sizeof(PH_MAPPED_IMAGE_IMPORT_DLL)); Flags = other->Flags; Name = String::Copy(other->Name); NumberOfEntries = other->NumberOfEntries; for (size_t IndexImport = 0; IndexImport < (size_t)NumberOfEntries; IndexImport++) { ImportList->Add(gcnew PeImport(other->ImportList[(int) IndexImport])); } } bool PeImportDll::IsDelayLoad() { return this->Flags & PH_MAPPED_IMAGE_DELAY_IMPORTS; }
#include <ClrPhlib.h> #include <UnmanagedPh.h> using namespace Dependencies; using namespace ClrPh; PeImport::PeImport( _In_ const PPH_MAPPED_IMAGE_IMPORT_DLL importDll, _In_ size_t Index ) { PH_MAPPED_IMAGE_IMPORT_ENTRY importEntry; if (NT_SUCCESS(PhGetMappedImageImportEntry((PPH_MAPPED_IMAGE_IMPORT_DLL) importDll, (ULONG)Index, &importEntry))) { this->Hint = importEntry.NameHint; this->Ordinal = importEntry.Ordinal; this->DelayImport = (importDll->Flags) & PH_MAPPED_IMAGE_DELAY_IMPORTS; this->Name = gcnew String(importEntry.Name); this->ModuleName = gcnew String(importDll->Name); this->ImportByOrdinal = (importEntry.Name == nullptr); } } PeImport::PeImport( _In_ const PeImport ^ other ) { this->Hint = other->Hint; this->Ordinal = other->Ordinal; this->DelayImport = other->DelayImport; this->Name = String::Copy(other->Name); this->ModuleName = String::Copy(other->ModuleName); this->ImportByOrdinal = other->ImportByOrdinal; } PeImport::~PeImport() { } PeImportDll::PeImportDll( _In_ const PPH_MAPPED_IMAGE_IMPORTS &PvMappedImports, _In_ size_t ImportDllIndex ) : ImportDll (new PH_MAPPED_IMAGE_IMPORT_DLL) { ImportList = gcnew Collections::Generic::List<PeImport^>(); if (!NT_SUCCESS(PhGetMappedImageImportDll(PvMappedImports, (ULONG)ImportDllIndex, ImportDll))) { Flags = 0; Name = gcnew String("## PeImportDll error: Invalid DllName ##"); NumberOfEntries = 0; return; } Flags = ImportDll->Flags; Name = gcnew String(ImportDll->Name); NumberOfEntries = ImportDll->NumberOfEntries; for (size_t IndexImport = 0; IndexImport < (size_t) NumberOfEntries; IndexImport++) { ImportList->Add(gcnew PeImport(ImportDll, IndexImport)); } } PeImportDll::~PeImportDll() { delete ImportDll; } PeImportDll::!PeImportDll() { delete ImportDll; } PeImportDll::PeImportDll( _In_ const PeImportDll ^ other ) : ImportDll(new PH_MAPPED_IMAGE_IMPORT_DLL) { ImportList = gcnew Collections::Generic::List<PeImport^>(); memcpy(ImportDll, other->ImportDll, sizeof(PH_MAPPED_IMAGE_IMPORT_DLL)); Flags = other->Flags; Name = String::Copy(other->Name); NumberOfEntries = other->NumberOfEntries; for (size_t IndexImport = 0; IndexImport < (size_t)NumberOfEntries; IndexImport++) { ImportList->Add(gcnew PeImport(other->ImportList[(int) IndexImport])); } } bool PeImportDll::IsDelayLoad() { return this->Flags & PH_MAPPED_IMAGE_DELAY_IMPORTS; }
Use dummy entries when PE import parsing is failing
[ClrPhLib] Use dummy entries when PE import parsing is failing
C++
mit
lucasg/Dependencies,lucasg/Dependencies,lucasg/Dependencies
00d7c733fafd737d42747a01483ed304cce61e90
sigc++/trackable.cc
sigc++/trackable.cc
/* * Copyright 2002, The libsigc++ Development Team * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ #include <sigc++/trackable.h> #include <iostream> SIGC_USING_STD(ostream) using namespace std; namespace sigc { trackable::trackable() : callback_list_(nullptr) {} /* Don't copy the notification list. The objects watching src don't need to be notified when the new object dies. */ trackable::trackable(const trackable& /*src*/) : callback_list_(nullptr) {} // Don't copy the notification list. // The objects watching src don't need to be notified when the new object dies. // They need to be notified now, because src probably becomes useless. trackable::trackable(trackable&& src) noexcept : callback_list_(nullptr) { src.notify_callbacks(); } trackable& trackable::operator=(const trackable& src) { if(this != &src) notify_callbacks(); //Make sure that we have finished with existing stuff before replacing it. return *this; } trackable& trackable::operator=(trackable&& src) noexcept { if(this != &src) { notify_callbacks(); //Make sure that we have finished with existing stuff before replacing it. src.notify_callbacks(); // src probably becomes useless. } return *this; } trackable::~trackable() { notify_callbacks(); } void trackable::add_destroy_notify_callback(void* data, func_destroy_notify func) const { callback_list()->add_callback(data, func); } void trackable::remove_destroy_notify_callback(void* data) const { callback_list()->remove_callback(data); } void trackable::notify_callbacks() { if (callback_list_) delete callback_list_; //This invokes all of the callbacks. callback_list_ = nullptr; } internal::trackable_callback_list* trackable::callback_list() const { if (!callback_list_) callback_list_ = new internal::trackable_callback_list; return callback_list_; } namespace internal { trackable_callback_list::~trackable_callback_list() { clearing_ = true; for (auto& callback : callbacks_) if (callback.func_) callback.func_(callback.data_); } void trackable_callback_list::add_callback(void* data, func_destroy_notify func) { if (!clearing_) // TODO: Is it okay to silently ignore attempts to add dependencies when the list is being cleared? // I'd consider this a serious application bug, since the app is likely to segfault. // But then, how should we handle it? Throw an exception? Martin. callbacks_.push_back(trackable_callback(data, func)); } void trackable_callback_list::clear() { clearing_ = true; for (auto& callback : callbacks_) if (callback.func_) callback.func_(callback.data_); callbacks_.clear(); clearing_ = false; } void trackable_callback_list::remove_callback(void* data) { for (callback_list::iterator i = callbacks_.begin(); i != callbacks_.end(); ++i) { auto& callback = *i; if (callback.data_ == data && callback.func_ != nullptr) { //Don't remove a list element while the list is being cleared. //It could invalidate the iterator in ~trackable_callback_list() or clear(). //But it may be necessary to invalidate the callback. See bug 589202. if (clearing_) callback.func_ = nullptr; else callbacks_.erase(i); return; } } } } /* namespace internal */ } /* namespace sigc */
/* * Copyright 2002, The libsigc++ Development Team * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ #include <sigc++/trackable.h> #include <iostream> SIGC_USING_STD(ostream) using namespace std; namespace sigc { trackable::trackable() : callback_list_(nullptr) {} /* Don't copy the notification list. The objects watching src don't need to be notified when the new object dies. */ trackable::trackable(const trackable& /*src*/) : callback_list_(nullptr) {} // Don't move the notification list. // The objects watching src don't need to be notified when the new object dies. // They need to be notified now, because src probably becomes useless. // // If trackable's move constructor is modified, check if Glib::Object's // move constructor should be modified similarly. trackable::trackable(trackable&& src) noexcept : callback_list_(nullptr) { src.notify_callbacks(); } trackable& trackable::operator=(const trackable& src) { if(this != &src) notify_callbacks(); //Make sure that we have finished with existing stuff before replacing it. return *this; } trackable& trackable::operator=(trackable&& src) noexcept { if(this != &src) { notify_callbacks(); //Make sure that we have finished with existing stuff before replacing it. src.notify_callbacks(); // src probably becomes useless. } return *this; } trackable::~trackable() { notify_callbacks(); } void trackable::add_destroy_notify_callback(void* data, func_destroy_notify func) const { callback_list()->add_callback(data, func); } void trackable::remove_destroy_notify_callback(void* data) const { callback_list()->remove_callback(data); } void trackable::notify_callbacks() { if (callback_list_) delete callback_list_; //This invokes all of the callbacks. callback_list_ = nullptr; } internal::trackable_callback_list* trackable::callback_list() const { if (!callback_list_) callback_list_ = new internal::trackable_callback_list; return callback_list_; } namespace internal { trackable_callback_list::~trackable_callback_list() { clearing_ = true; for (auto& callback : callbacks_) if (callback.func_) callback.func_(callback.data_); } void trackable_callback_list::add_callback(void* data, func_destroy_notify func) { if (!clearing_) // TODO: Is it okay to silently ignore attempts to add dependencies when the list is being cleared? // I'd consider this a serious application bug, since the app is likely to segfault. // But then, how should we handle it? Throw an exception? Martin. callbacks_.push_back(trackable_callback(data, func)); } void trackable_callback_list::clear() { clearing_ = true; for (auto& callback : callbacks_) if (callback.func_) callback.func_(callback.data_); callbacks_.clear(); clearing_ = false; } void trackable_callback_list::remove_callback(void* data) { for (callback_list::iterator i = callbacks_.begin(); i != callbacks_.end(); ++i) { auto& callback = *i; if (callback.data_ == data && callback.func_ != nullptr) { //Don't remove a list element while the list is being cleared. //It could invalidate the iterator in ~trackable_callback_list() or clear(). //But it may be necessary to invalidate the callback. See bug 589202. if (clearing_) callback.func_ = nullptr; else callbacks_.erase(i); return; } } } } /* namespace internal */ } /* namespace sigc */
Add a comment
trackable: Add a comment
C++
lgpl-2.1
Distrotech/libsigcxx2,Distrotech/libsigcxx2,Distrotech/libsigcxx2
763157ee8d2626cdb2466c08c017bbbee34aadb7
tensorflow_federated/cc/core/impl/executors/executor_bindings.cc
tensorflow_federated/cc/core/impl/executors/executor_bindings.cc
/* Copyright 2021, The TensorFlow Federated 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 ==============================================================================*/ // This file contains the pybind11 defintions for exposing the C++ Executor // interface in Python. // // General principles: // - Python methods defined here (e.g. `.def_*()`) should not contain // "business logic". That should be implemented on the underlying C++ class. // The only logic that may exist here is parameter/result conversions (e.g. // `OwnedValueId` -> `ValueId`, etc). #include <cstdint> #include <limits> #include <memory> #include <string> #include <vector> #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "grpcpp/grpcpp.h" #include "include/pybind11/detail/common.h" #include "include/pybind11/pybind11.h" #include "include/pybind11/pytypes.h" #include "include/pybind11/stl.h" #include "pybind11_abseil/absl_casters.h" #include "pybind11_abseil/status_casters.h" #include "pybind11_protobuf/wrapped_proto_caster.h" #include "tensorflow/c/tf_status.h" #include "tensorflow/c/tf_tensor.h" #include "tensorflow/core/framework/tensor.h" #include "tensorflow/core/platform/status.h" #include "tensorflow/python/lib/core/ndarray_tensor.h" #include "tensorflow/python/lib/core/safe_ptr.h" #include "tensorflow_federated/cc/core/impl/executors/cardinalities.h" #include "tensorflow_federated/cc/core/impl/executors/composing_executor.h" #include "tensorflow_federated/cc/core/impl/executors/executor.h" #include "tensorflow_federated/cc/core/impl/executors/federating_executor.h" #include "tensorflow_federated/cc/core/impl/executors/reference_resolving_executor.h" #include "tensorflow_federated/cc/core/impl/executors/remote_executor.h" #include "tensorflow_federated/cc/core/impl/executors/status_macros.h" #include "tensorflow_federated/cc/core/impl/executors/tensor_serialization.h" #include "tensorflow_federated/cc/core/impl/executors/tensorflow_executor.h" #include "tensorflow_federated/proto/v0/computation.pb.h" #include "tensorflow_federated/proto/v0/executor.pb.h" namespace tensorflow { Status TF_TensorToTensor(const TF_Tensor* src, Tensor* dst); } // namespace tensorflow namespace tensorflow_federated { namespace py = ::pybind11; namespace { //////////////////////////////////////////////////////////////////////////////// // The Python module defintion `executor_bindings`. // // This will be used with `import executor_bindings` on the Python side. This // module should _not_ be directly imported into the public pip API. The methods // here will raise `NotOkStatus` errors from absl, which are not user friendly. //////////////////////////////////////////////////////////////////////////////// PYBIND11_MODULE(executor_bindings, m) { py::google::ImportStatusModule(); pybind11_protobuf::ImportWrappedProtoCasters(); using pybind11_protobuf::WithWrappedProtos; m.doc() = "Bindings for the C++ "; // v0::Value serialization methods. m.def("serialize_tensor_value", py::google::WithWrappedProtos( [](const tensorflow::Tensor& tensor) -> absl::StatusOr<v0::Value> { v0::Value value_pb; TFF_TRY(SerializeTensorValue(tensor, &value_pb)); return value_pb; })); m.def("deserialize_tensor_value", py::google::WithWrappedProtos(&DeserializeTensorValue)); // Provide an `OwnedValueId` class to handle return values from the // `Executor` interface. // // Note: no `init<>()` method defined, this object is only constructor from // Executor instances. py::class_<OwnedValueId>(m, "OwnedValueId") .def_property_readonly("ref", &OwnedValueId::ref) .def("__str__", [](const OwnedValueId& self) { return absl::StrCat(self.ref()); }) .def("__repr__", [](const OwnedValueId& self) { return absl::StrCat("<OwnedValueId: ", self.ref(), ">"); }); // We provide ComposingChild as an opaque object so that they can be returned // from pybind functions. py::class_<ComposingChild>(m, "ComposingChild") .def("__repr__", [](const ComposingChild& self) { return absl::StrCat( "<ComposingChild with num clients: ", self.num_clients(), ">"); }); // Provide the `Executor` interface. // // A `dispose` method is purposely not exposed. Though `Executor::Dispose` // exists in C++, Python should call `Dispose` via the `OwnedValueId` // destructor during garbage collection. // // Note: no `init<>()` method defined, must be constructed useing the create_* // methods defined below. py::class_<Executor, // PyExecutor trampoline goes here when ready std::shared_ptr<Executor>>(m, "Executor") .def("create_value", WithWrappedProtos(&Executor::CreateValue), py::arg("value_pb"), py::return_value_policy::move, py::call_guard<py::gil_scoped_release>()) .def("create_struct", &Executor::CreateStruct, py::return_value_policy::move, py::call_guard<py::gil_scoped_release>()) .def("create_selection", &Executor::CreateSelection, py::return_value_policy::move, py::call_guard<py::gil_scoped_release>()) .def("create_call", &Executor::CreateCall, py::arg("function"), // Allow `argument` to be `None`. py::arg("argument").none(true), py::return_value_policy::move, py::call_guard<py::gil_scoped_release>()) .def("materialize", WithWrappedProtos([](Executor& e, const ValueId& value_id) -> absl::StatusOr<v0::Value> { // Construct a new `v0::Value` to write to and return it to Python. v0::Value value_pb; absl::Status result = e.Materialize(value_id, &value_pb); if (!result.ok()) { return result; } return value_pb; }), py::call_guard<py::gil_scoped_release>()); // Executor construction methods. m.def("create_tensorflow_executor", &CreateTensorFlowExecutor, py::arg("max_concurrent_computation_calls") = py::none(), "Creates a TensorFlowExecutor."); m.def("create_reference_resolving_executor", &CreateReferenceResolvingExecutor, "Creates a ReferenceResolvingExecutor", py::arg("inner_executor")); m.def("create_federating_executor", &CreateFederatingExecutor, py::arg("inner_executor"), py::arg("cardinalities"), "Creates a FederatingExecutor."); m.def("create_composing_child", &ComposingChild::Make, py::arg("executor"), py::arg("cardinalities"), "Creates a ComposingExecutor."); m.def("create_composing_executor", &CreateComposingExecutor, py::arg("server"), py::arg("children"), "Creates a ComposingExecutor."); m.def("create_remote_executor", py::overload_cast<std::shared_ptr<grpc::ChannelInterface>, const CardinalityMap&>(&CreateRemoteExecutor), py::arg("channel"), py::arg("cardinalities"), "Creates a RemoteExecutor."); py::class_<grpc::ChannelInterface, std::shared_ptr<grpc::ChannelInterface>>( m, "GRPCChannelInterface"); m.def( "create_insecure_grpc_channel", [](const std::string& target) -> std::shared_ptr<grpc::ChannelInterface> { auto channel_options = grpc::ChannelArguments(); channel_options.SetMaxSendMessageSize( std::numeric_limits<int32_t>::max()); channel_options.SetMaxReceiveMessageSize( std::numeric_limits<int32_t>::max()); return grpc::CreateCustomChannel( target, grpc::InsecureChannelCredentials(), channel_options); }, pybind11::return_value_policy::take_ownership); } } // namespace } // namespace tensorflow_federated namespace pybind11 { namespace detail { template <> struct type_caster<tensorflow::Tensor> { public: // Macro to create `value` variable which is used in `load` to store the // result of the conversion. PYBIND11_TYPE_CASTER(tensorflow::Tensor, _("Tensor")); // Pybind11 caster for PyArray (Python) -> tensorflow::Tensor (C++). bool load(handle src, bool) { tensorflow::Safe_TF_TensorPtr tf_tensor_ptr; tensorflow::Status status = tensorflow::NdarrayToTensor(/*ctx=*/nullptr, src.ptr(), &tf_tensor_ptr); if (!status.ok()) { LOG(ERROR) << status; return false; } status = TF_TensorToTensor(tf_tensor_ptr.get(), &value); if (!status.ok()) { LOG(ERROR) << status; return false; } return !PyErr_Occurred(); } // Convert tensorflow::Tensor (C++) back to a PyArray (Python). static handle cast(const tensorflow::Tensor tensor, return_value_policy, handle) { PyObject* result = nullptr; tensorflow::Status status = tensorflow::TensorToNdarray(tensor, &result); if (!status.ok()) { PyErr_SetString(PyExc_ValueError, "Failed to create np.ndarray"); return nullptr; } return result; } }; } // namespace detail } // namespace pybind11
/* Copyright 2021, The TensorFlow Federated 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 ==============================================================================*/ // This file contains the pybind11 defintions for exposing the C++ Executor // interface in Python. // // General principles: // - Python methods defined here (e.g. `.def_*()`) should not contain // "business logic". That should be implemented on the underlying C++ class. // The only logic that may exist here is parameter/result conversions (e.g. // `OwnedValueId` -> `ValueId`, etc). #include <cstdint> #include <limits> #include <memory> #include <string> #include <vector> #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "grpcpp/grpcpp.h" #include "include/pybind11/detail/common.h" #include "include/pybind11/pybind11.h" #include "include/pybind11/pytypes.h" #include "include/pybind11/stl.h" #include "pybind11_abseil/absl_casters.h" #include "pybind11_abseil/status_casters.h" #include "pybind11_protobuf/wrapped_proto_caster.h" #include "tensorflow/c/tf_status.h" #include "tensorflow/c/tf_tensor.h" #include "tensorflow/core/framework/tensor.h" #include "tensorflow/core/platform/status.h" #include "tensorflow/python/lib/core/ndarray_tensor.h" #include "tensorflow/python/lib/core/safe_ptr.h" #include "tensorflow_federated/cc/core/impl/executors/cardinalities.h" #include "tensorflow_federated/cc/core/impl/executors/composing_executor.h" #include "tensorflow_federated/cc/core/impl/executors/executor.h" #include "tensorflow_federated/cc/core/impl/executors/federating_executor.h" #include "tensorflow_federated/cc/core/impl/executors/reference_resolving_executor.h" #include "tensorflow_federated/cc/core/impl/executors/remote_executor.h" #include "tensorflow_federated/cc/core/impl/executors/status_macros.h" #include "tensorflow_federated/cc/core/impl/executors/tensor_serialization.h" #include "tensorflow_federated/cc/core/impl/executors/tensorflow_executor.h" #include "tensorflow_federated/proto/v0/computation.pb.h" #include "tensorflow_federated/proto/v0/executor.pb.h" namespace tensorflow { Status TF_TensorToTensor(const TF_Tensor* src, Tensor* dst); } // namespace tensorflow namespace tensorflow_federated { namespace py = ::pybind11; namespace { //////////////////////////////////////////////////////////////////////////////// // The Python module defintion `executor_bindings`. // // This will be used with `import executor_bindings` on the Python side. This // module should _not_ be directly imported into the public pip API. The methods // here will raise `NotOkStatus` errors from absl, which are not user friendly. //////////////////////////////////////////////////////////////////////////////// PYBIND11_MODULE(executor_bindings, m) { py::google::ImportStatusModule(); pybind11_protobuf::ImportWrappedProtoCasters(); using pybind11_protobuf::WithWrappedProtos; m.doc() = "Bindings for the C++ "; // v0::Value serialization methods. m.def("serialize_tensor_value", WithWrappedProtos( [](const tensorflow::Tensor& tensor) -> absl::StatusOr<v0::Value> { v0::Value value_pb; TFF_TRY(SerializeTensorValue(tensor, &value_pb)); return value_pb; })); m.def("deserialize_tensor_value", WithWrappedProtos(&DeserializeTensorValue)); // Provide an `OwnedValueId` class to handle return values from the // `Executor` interface. // // Note: no `init<>()` method defined, this object is only constructor from // Executor instances. py::class_<OwnedValueId>(m, "OwnedValueId") .def_property_readonly("ref", &OwnedValueId::ref) .def("__str__", [](const OwnedValueId& self) { return absl::StrCat(self.ref()); }) .def("__repr__", [](const OwnedValueId& self) { return absl::StrCat("<OwnedValueId: ", self.ref(), ">"); }); // We provide ComposingChild as an opaque object so that they can be returned // from pybind functions. py::class_<ComposingChild>(m, "ComposingChild") .def("__repr__", [](const ComposingChild& self) { return absl::StrCat( "<ComposingChild with num clients: ", self.num_clients(), ">"); }); // Provide the `Executor` interface. // // A `dispose` method is purposely not exposed. Though `Executor::Dispose` // exists in C++, Python should call `Dispose` via the `OwnedValueId` // destructor during garbage collection. // // Note: no `init<>()` method defined, must be constructed useing the create_* // methods defined below. py::class_<Executor, // PyExecutor trampoline goes here when ready std::shared_ptr<Executor>>(m, "Executor") .def("create_value", WithWrappedProtos(&Executor::CreateValue), py::arg("value_pb"), py::return_value_policy::move, py::call_guard<py::gil_scoped_release>()) .def("create_struct", &Executor::CreateStruct, py::return_value_policy::move, py::call_guard<py::gil_scoped_release>()) .def("create_selection", &Executor::CreateSelection, py::return_value_policy::move, py::call_guard<py::gil_scoped_release>()) .def("create_call", &Executor::CreateCall, py::arg("function"), // Allow `argument` to be `None`. py::arg("argument").none(true), py::return_value_policy::move, py::call_guard<py::gil_scoped_release>()) .def("materialize", WithWrappedProtos([](Executor& e, const ValueId& value_id) -> absl::StatusOr<v0::Value> { // Construct a new `v0::Value` to write to and return it to Python. v0::Value value_pb; absl::Status result = e.Materialize(value_id, &value_pb); if (!result.ok()) { return result; } return value_pb; }), py::call_guard<py::gil_scoped_release>()); // Executor construction methods. m.def("create_tensorflow_executor", &CreateTensorFlowExecutor, py::arg("max_concurrent_computation_calls") = py::none(), "Creates a TensorFlowExecutor."); m.def("create_reference_resolving_executor", &CreateReferenceResolvingExecutor, "Creates a ReferenceResolvingExecutor", py::arg("inner_executor")); m.def("create_federating_executor", &CreateFederatingExecutor, py::arg("inner_executor"), py::arg("cardinalities"), "Creates a FederatingExecutor."); m.def("create_composing_child", &ComposingChild::Make, py::arg("executor"), py::arg("cardinalities"), "Creates a ComposingExecutor."); m.def("create_composing_executor", &CreateComposingExecutor, py::arg("server"), py::arg("children"), "Creates a ComposingExecutor."); m.def("create_remote_executor", py::overload_cast<std::shared_ptr<grpc::ChannelInterface>, const CardinalityMap&>(&CreateRemoteExecutor), py::arg("channel"), py::arg("cardinalities"), "Creates a RemoteExecutor."); py::class_<grpc::ChannelInterface, std::shared_ptr<grpc::ChannelInterface>>( m, "GRPCChannelInterface"); m.def( "create_insecure_grpc_channel", [](const std::string& target) -> std::shared_ptr<grpc::ChannelInterface> { auto channel_options = grpc::ChannelArguments(); channel_options.SetMaxSendMessageSize( std::numeric_limits<int32_t>::max()); channel_options.SetMaxReceiveMessageSize( std::numeric_limits<int32_t>::max()); return grpc::CreateCustomChannel( target, grpc::InsecureChannelCredentials(), channel_options); }, pybind11::return_value_policy::take_ownership); } } // namespace } // namespace tensorflow_federated namespace pybind11 { namespace detail { template <> struct type_caster<tensorflow::Tensor> { public: // Macro to create `value` variable which is used in `load` to store the // result of the conversion. PYBIND11_TYPE_CASTER(tensorflow::Tensor, _("Tensor")); // Pybind11 caster for PyArray (Python) -> tensorflow::Tensor (C++). bool load(handle src, bool) { tensorflow::Safe_TF_TensorPtr tf_tensor_ptr; tensorflow::Status status = tensorflow::NdarrayToTensor(/*ctx=*/nullptr, src.ptr(), &tf_tensor_ptr); if (!status.ok()) { LOG(ERROR) << status; return false; } status = TF_TensorToTensor(tf_tensor_ptr.get(), &value); if (!status.ok()) { LOG(ERROR) << status; return false; } return !PyErr_Occurred(); } // Convert tensorflow::Tensor (C++) back to a PyArray (Python). static handle cast(const tensorflow::Tensor tensor, return_value_policy, handle) { PyObject* result = nullptr; tensorflow::Status status = tensorflow::TensorToNdarray(tensor, &result); if (!status.ok()) { PyErr_SetString(PyExc_ValueError, "Failed to create np.ndarray"); return nullptr; } return result; } }; } // namespace detail } // namespace pybind11
Use the namespace pybind11_protobuf::WithWrappedProtos rather than the alias py::google::...
Use the namespace pybind11_protobuf::WithWrappedProtos rather than the alias py::google::... PiperOrigin-RevId: 441279387
C++
apache-2.0
tensorflow/federated,tensorflow/federated,tensorflow/federated
4c863ba22d8686ae5d58ee13d0a527517437137b
src/Simulator.cpp
src/Simulator.cpp
/* * Universe * * Copyright 2015 Lubosz Sarnecki <[email protected]> * */ #include <stdio.h> #include <string> #include <iostream> #include "Simulator.h" #include "Renderer.h" #include "util.h" #include <GL/glx.h> using std::string; static std::string deviceTypeToString(int type) { switch (type) { case CL_DEVICE_TYPE_DEFAULT: return "CL_DEVICE_TYPE_DEFAULT"; case CL_DEVICE_TYPE_GPU: return "CL_DEVICE_TYPE_GPU"; case CL_DEVICE_TYPE_CPU: return "CL_DEVICE_TYPE_CPU"; default: return std::to_string(type); } } Simulator::Simulator() { std::vector<cl::Platform> platforms; cl::Platform currentPlatform; err = cl::Platform::get(&platforms); if (err != CL_SUCCESS) { printf("Error getting platforms: %s\n", oclErrorString(err)); exit(0); } printf("Available Platforms (%ld):\n", platforms.size()); for (auto platform : platforms) { string platformName; std::vector<cl::Device> devices; platform.getInfo(CL_PLATFORM_NAME, &platformName); try { platform.getDevices(CL_DEVICE_TYPE_ALL, &devices); } catch (cl::Error er) { printf("ERROR: Could not get Devices for Platform '%s'. %s(%s)\n", platformName.c_str(), er.what(), oclErrorString(er.err())); continue; } printf("=== %s (%ld Devices) ===\n", platformName.c_str(), devices.size()); for (auto device : devices) { string type = deviceTypeToString(device.getInfo<CL_DEVICE_TYPE>()); string deviceName = device.getInfo<CL_DEVICE_NAME>(); printf("%s: %s\n", type.c_str(), deviceName.c_str()); //if (deviceName.compare("Intel(R) Core(TM) i7-4550U CPU @ 1.50GHz") == 0) { //if (deviceName.compare("Intel(R) HD Graphics Haswell Ultrabook GT3 Mobile") == 0) { currentPlatform = platform; currentDevice = device; //} } } cl_context_properties props[] = { CL_GL_CONTEXT_KHR, reinterpret_cast<cl_context_properties>(glXGetCurrentContext()), CL_GLX_DISPLAY_KHR, reinterpret_cast<cl_context_properties>(glXGetCurrentDisplay()), CL_CONTEXT_PLATFORM, reinterpret_cast<cl_context_properties>((currentPlatform)()), 0 }; // cl_context cxGPUContext = // clCreateContext(props, 1, &cdDevices[uiDeviceUsed], NULL, NULL, &err); try { context = cl::Context(CL_DEVICE_TYPE_GPU, props); } catch (cl::Error er) { printf("ERROR: Could not create CL context. %s(%s) %d\n", er.what(), oclErrorString(er.err()), er.err()); } // create the command queue we will use to execute OpenCL commands try { queue = cl::CommandQueue(context, currentDevice, 0, &err); } catch (cl::Error er) { printf("ERROR: %s(%d)\n", er.what(), er.err()); } gravities = (float *)malloc(particleCount*sizeof(float)); dt = 1000.0f; } Simulator::~Simulator() {} void Simulator::loadProgram(std::string kernel_source) { // Program Setup int pl = kernel_source.size(); try { cl::Program::Sources source( 1, std::make_pair(kernel_source.c_str(), pl)); program = cl::Program(context, source); } catch (cl::Error er) { printf("ERROR: %s(%s)\n", er.what(), oclErrorString(er.err())); } std::vector<cl::Device> devices; devices.push_back(currentDevice); try { // err = program.build(devices, // "-cl-nv-verbose -cl-nv-maxrregcount=100"); err = program.build(devices); } catch (cl::Error er) { printf("program.build: %s\n", oclErrorString(er.err())); exit(0); } std::cout << "Build Status: " << program.getBuildInfo<CL_PROGRAM_BUILD_STATUS>(devices[0]) << std::endl << "Build Options:\t" << program.getBuildInfo<CL_PROGRAM_BUILD_OPTIONS>(devices[0]) << std::endl << "Build Log:\t " << program.getBuildInfo<CL_PROGRAM_BUILD_LOG>(devices[0]) << std::endl; } void Simulator::loadData(std::vector<Vec4> pos, std::vector<Vec4> vel, std::vector<Vec4> col, std::vector<float> mass) { // store the number of particles and the size in bytes of our arrays particleCount = pos.size(); array_size = particleCount * sizeof(Vec4); // create VBOs (defined in util.cpp) positionVBO = Renderer::createVBO( &pos[0], array_size, GL_ARRAY_BUFFER, GL_DYNAMIC_DRAW); colorVBO = Renderer::createVBO( &col[0], array_size, GL_ARRAY_BUFFER, GL_DYNAMIC_DRAW); massVBO = Renderer::createVBO( mass.data(), particleCount * sizeof(GLfloat), GL_ARRAY_BUFFER, GL_DYNAMIC_DRAW); // make sure OpenGL is finished before we proceed glFinish(); printf("gl interop!\n"); // create OpenCL buffer from GL VBO cl_vbos.push_back(cl::BufferGL( context, CL_MEM_READ_WRITE, positionVBO, &err)); cl_vbos.push_back(cl::BufferGL( context, CL_MEM_READ_WRITE, colorVBO, &err)); cl_vbos.push_back(cl::BufferGL( context, CL_MEM_READ_WRITE, massVBO, &err)); // create the OpenCL only arrays velocityBuffer = cl::Buffer(context, CL_MEM_WRITE_ONLY, array_size, NULL, &err); initialPositionBuffer = cl::Buffer(context, CL_MEM_WRITE_ONLY, array_size, NULL, &err); initivalVelocityBuffer = cl::Buffer(context, CL_MEM_WRITE_ONLY, array_size, NULL, &err); //gravityBuffer = // cl::Buffer(context, CL_MEM_WRITE_ONLY, particleCount * sizeof(float), NULL, &err); printf("Pushing data to the GPU\n"); // push our CPU arrays to the GPU // data is tightly packed in std::vector // starting with the adress of the first element err = queue.enqueueWriteBuffer( velocityBuffer, CL_TRUE, 0, array_size, &vel[0], NULL, &event); err = queue.enqueueWriteBuffer( initialPositionBuffer, CL_TRUE, 0, array_size, &pos[0], NULL, &event); err = queue.enqueueWriteBuffer( initivalVelocityBuffer, CL_TRUE, 0, array_size, &vel[0], NULL, &event); queue.finish(); } void Simulator::initKernel() { try { kernel = cl::Kernel(program, "vortex", &err); } catch (cl::Error er) { printf("ERROR: %s(%s)\n", er.what(), oclErrorString(er.err())); } try { err = kernel.setArg(0, cl_vbos[0]); err = kernel.setArg(1, cl_vbos[1]); err = kernel.setArg(2, cl_vbos[2]); err = kernel.setArg(3, velocityBuffer); err = kernel.setArg(4, initialPositionBuffer); err = kernel.setArg(5, initivalVelocityBuffer); //err = kernel.setArg(6, gravityBuffer); } catch (cl::Error er) { printf("ERROR: %s(%s)\n", er.what(), oclErrorString(er.err())); } // Wait for the command queue to finish these commands before proceeding queue.finish(); } void Simulator::runKernel() { // this will update our system by calculating new velocity // and updating the positions of our particles // Make sure OpenGL is done using our VBOs glFinish(); // map OpenGL buffer object for writing from OpenCL // this passes in the vector of VBO buffer objects (position and color) err = queue.enqueueAcquireGLObjects(&cl_vbos, NULL, &event); // pass in the timestep kernel.setArg(6, dt); // execute the kernel err = queue.enqueueNDRangeKernel( kernel, cl::NullRange, cl::NDRange(particleCount), cl::NullRange, NULL, &event); // printf("clEnqueueNDRangeKernel: %s\n", oclErrorString(err)); queue.finish(); /* queue.enqueueReadBuffer(gravityBuffer,false,0,particleCount*sizeof(float),gravities,NULL,NULL); for (int i=0; i < particleCount; i++) { std::cout << "gravities[" << i << "] = " << gravities[i] << "\n"; } */ // Release the VBOs so OpenGL can play with them err = queue.enqueueReleaseGLObjects(&cl_vbos, NULL, &event); queue.finish(); } const char* Simulator::oclErrorString(cl_int error) { static const char* errorString[] = { "CL_SUCCESS", "CL_DEVICE_NOT_FOUND", "CL_DEVICE_NOT_AVAILABLE", "CL_COMPILER_NOT_AVAILABLE", "CL_MEM_OBJECT_ALLOCATION_FAILURE", "CL_OUT_OF_RESOURCES", "CL_OUT_OF_HOST_MEMORY", "CL_PROFILING_INFO_NOT_AVAILABLE", "CL_MEM_COPY_OVERLAP", "CL_IMAGE_FORMAT_MISMATCH", "CL_IMAGE_FORMAT_NOT_SUPPORTED", "CL_BUILD_PROGRAM_FAILURE", "CL_MAP_FAILURE", "CL_MISALIGNED_SUB_BUFFER_OFFSET", "CL_EXEC_STATUS_ERROR_FOR_EVENTS_IN_WAIT_LIST", "CL_COMPILE_PROGRAM_FAILURE", "CL_LINKER_NOT_AVAILABLE", "CL_LINK_PROGRAM_FAILURE", "CL_DEVICE_PARTITION_FAILED", "CL_KERNEL_ARG_INFO_NOT_AVAILABLE", "", "", "", "", "", "", "", "", "", "", "CL_INVALID_VALUE", "CL_INVALID_DEVICE_TYPE", "CL_INVALID_PLATFORM", "CL_INVALID_DEVICE", "CL_INVALID_CONTEXT", "CL_INVALID_QUEUE_PROPERTIES", "CL_INVALID_COMMAND_QUEUE", "CL_INVALID_HOST_PTR", "CL_INVALID_MEM_OBJECT", "CL_INVALID_IMAGE_FORMAT_DESCRIPTOR", "CL_INVALID_IMAGE_SIZE", "CL_INVALID_SAMPLER", "CL_INVALID_BINARY", "CL_INVALID_BUILD_OPTIONS", "CL_INVALID_PROGRAM", "CL_INVALID_PROGRAM_EXECUTABLE", "CL_INVALID_KERNEL_NAME", "CL_INVALID_KERNEL_DEFINITION", "CL_INVALID_KERNEL", "CL_INVALID_ARG_INDEX", "CL_INVALID_ARG_VALUE", "CL_INVALID_ARG_SIZE", "CL_INVALID_KERNEL_ARGS", "CL_INVALID_WORK_DIMENSION", "CL_INVALID_WORK_GROUP_SIZE", "CL_INVALID_WORK_ITEM_SIZE", "CL_INVALID_GLOBAL_OFFSET", "CL_INVALID_EVENT_WAIT_LIST", "CL_INVALID_EVENT", "CL_INVALID_OPERATION", "CL_INVALID_GL_OBJECT", "CL_INVALID_BUFFER_SIZE", "CL_INVALID_MIP_LEVEL", "CL_INVALID_GLOBAL_WORK_SIZE", "CL_INVALID_PROPERTY", "CL_INVALID_IMAGE_DESCRIPTOR", "CL_INVALID_COMPILER_OPTIONS", "CL_INVALID_LINKER_OPTIONS", "CL_INVALID_DEVICE_PARTITION_COUNT" }; const int errorCount = sizeof(errorString) / sizeof(errorString[0]); const int index = -error; return (index >= 0 && index < errorCount) ? errorString[index] : ""; }
/* * Universe * * Copyright 2015 Lubosz Sarnecki <[email protected]> * */ #include <stdio.h> #include <string> #include <iostream> #include "Simulator.h" #include "Renderer.h" #include "util.h" #include <GL/glx.h> using std::string; static std::string deviceTypeToString(int type) { switch (type) { case CL_DEVICE_TYPE_DEFAULT: return "CL_DEVICE_TYPE_DEFAULT"; case CL_DEVICE_TYPE_GPU: return "CL_DEVICE_TYPE_GPU"; case CL_DEVICE_TYPE_CPU: return "CL_DEVICE_TYPE_CPU"; default: return std::to_string(type); } } Simulator::Simulator() { std::vector<cl::Platform> platforms; cl::Platform currentPlatform; err = cl::Platform::get(&platforms); if (err != CL_SUCCESS) { printf("Error getting platforms: %s\n", oclErrorString(err)); exit(0); } printf("Available Platforms (%ld):\n", platforms.size()); for (auto platform : platforms) { string platformName; std::vector<cl::Device> devices; platform.getInfo(CL_PLATFORM_NAME, &platformName); try { platform.getDevices(CL_DEVICE_TYPE_ALL, &devices); } catch (cl::Error er) { printf("ERROR: Could not get Devices for Platform '%s'. %s(%s)\n", platformName.c_str(), er.what(), oclErrorString(er.err())); continue; } printf("=== %s (%ld Devices) ===\n", platformName.c_str(), devices.size()); for (auto device : devices) { string type = deviceTypeToString(device.getInfo<CL_DEVICE_TYPE>()); string deviceName = device.getInfo<CL_DEVICE_NAME>(); printf("%s: %s\n", type.c_str(), deviceName.c_str()); //if (deviceName.compare("Intel(R) Core(TM) i7-4550U CPU @ 1.50GHz") == 0) { //if (deviceName.compare("Intel(R) HD Graphics Haswell Ultrabook GT3 Mobile") == 0) { currentPlatform = platform; currentDevice = device; //} } } cl_context_properties props[] = { CL_GL_CONTEXT_KHR, reinterpret_cast<cl_context_properties>(glXGetCurrentContext()), CL_GLX_DISPLAY_KHR, reinterpret_cast<cl_context_properties>(glXGetCurrentDisplay()), CL_CONTEXT_PLATFORM, reinterpret_cast<cl_context_properties>((currentPlatform)()), 0 }; // cl_context cxGPUContext = // clCreateContext(props, 1, &cdDevices[uiDeviceUsed], NULL, NULL, &err); try { context = cl::Context(CL_DEVICE_TYPE_GPU, props); } catch (cl::Error er) { printf("ERROR: Could not create CL context. %s(%s) %d\n", er.what(), oclErrorString(er.err()), er.err()); } // create the command queue we will use to execute OpenCL commands try { queue = cl::CommandQueue(context, currentDevice, 0, &err); } catch (cl::Error er) { printf("ERROR: %s(%d)\n", er.what(), er.err()); } // gravities = (float *)malloc(particleCount*sizeof(float)); dt = 1000.0f; } Simulator::~Simulator() {} void Simulator::loadProgram(std::string kernel_source) { // Program Setup int pl = kernel_source.size(); try { cl::Program::Sources source( 1, std::make_pair(kernel_source.c_str(), pl)); program = cl::Program(context, source); } catch (cl::Error er) { printf("ERROR: %s(%s)\n", er.what(), oclErrorString(er.err())); } std::vector<cl::Device> devices; devices.push_back(currentDevice); try { // err = program.build(devices, // "-cl-nv-verbose -cl-nv-maxrregcount=100"); err = program.build(devices); } catch (cl::Error er) { printf("program.build: %s\n", oclErrorString(er.err())); exit(0); } std::cout << "Build Status: " << program.getBuildInfo<CL_PROGRAM_BUILD_STATUS>(devices[0]) << std::endl << "Build Options:\t" << program.getBuildInfo<CL_PROGRAM_BUILD_OPTIONS>(devices[0]) << std::endl << "Build Log:\t " << program.getBuildInfo<CL_PROGRAM_BUILD_LOG>(devices[0]) << std::endl; } void Simulator::loadData(std::vector<Vec4> pos, std::vector<Vec4> vel, std::vector<Vec4> col, std::vector<float> mass) { // store the number of particles and the size in bytes of our arrays particleCount = pos.size(); array_size = particleCount * sizeof(Vec4); // create VBOs (defined in util.cpp) positionVBO = Renderer::createVBO( &pos[0], array_size, GL_ARRAY_BUFFER, GL_DYNAMIC_DRAW); colorVBO = Renderer::createVBO( &col[0], array_size, GL_ARRAY_BUFFER, GL_DYNAMIC_DRAW); massVBO = Renderer::createVBO( mass.data(), particleCount * sizeof(GLfloat), GL_ARRAY_BUFFER, GL_DYNAMIC_DRAW); // make sure OpenGL is finished before we proceed glFinish(); printf("gl interop!\n"); // create OpenCL buffer from GL VBO cl_vbos.push_back(cl::BufferGL( context, CL_MEM_READ_WRITE, positionVBO, &err)); cl_vbos.push_back(cl::BufferGL( context, CL_MEM_READ_WRITE, colorVBO, &err)); cl_vbos.push_back(cl::BufferGL( context, CL_MEM_READ_WRITE, massVBO, &err)); // create the OpenCL only arrays velocityBuffer = cl::Buffer(context, CL_MEM_WRITE_ONLY, array_size, NULL, &err); initialPositionBuffer = cl::Buffer(context, CL_MEM_WRITE_ONLY, array_size, NULL, &err); initivalVelocityBuffer = cl::Buffer(context, CL_MEM_WRITE_ONLY, array_size, NULL, &err); //gravityBuffer = // cl::Buffer(context, CL_MEM_WRITE_ONLY, particleCount * sizeof(float), NULL, &err); printf("Pushing data to the GPU\n"); // push our CPU arrays to the GPU // data is tightly packed in std::vector // starting with the adress of the first element err = queue.enqueueWriteBuffer( velocityBuffer, CL_TRUE, 0, array_size, &vel[0], NULL, &event); err = queue.enqueueWriteBuffer( initialPositionBuffer, CL_TRUE, 0, array_size, &pos[0], NULL, &event); err = queue.enqueueWriteBuffer( initivalVelocityBuffer, CL_TRUE, 0, array_size, &vel[0], NULL, &event); queue.finish(); } void Simulator::initKernel() { try { kernel = cl::Kernel(program, "vortex", &err); } catch (cl::Error er) { printf("ERROR: %s(%s)\n", er.what(), oclErrorString(er.err())); } try { err = kernel.setArg(0, cl_vbos[0]); err = kernel.setArg(1, cl_vbos[1]); err = kernel.setArg(2, cl_vbos[2]); err = kernel.setArg(3, velocityBuffer); err = kernel.setArg(4, initialPositionBuffer); err = kernel.setArg(5, initivalVelocityBuffer); //err = kernel.setArg(6, gravityBuffer); } catch (cl::Error er) { printf("ERROR: %s(%s)\n", er.what(), oclErrorString(er.err())); } // Wait for the command queue to finish these commands before proceeding queue.finish(); } void Simulator::runKernel() { // this will update our system by calculating new velocity // and updating the positions of our particles // Make sure OpenGL is done using our VBOs glFinish(); // map OpenGL buffer object for writing from OpenCL // this passes in the vector of VBO buffer objects (position and color) err = queue.enqueueAcquireGLObjects(&cl_vbos, NULL, &event); // pass in the timestep kernel.setArg(6, dt); // execute the kernel err = queue.enqueueNDRangeKernel( kernel, cl::NullRange, cl::NDRange(particleCount), cl::NullRange, NULL, &event); // printf("clEnqueueNDRangeKernel: %s\n", oclErrorString(err)); queue.finish(); /* queue.enqueueReadBuffer(gravityBuffer,false,0,particleCount*sizeof(float),gravities,NULL,NULL); for (int i=0; i < particleCount; i++) { std::cout << "gravities[" << i << "] = " << gravities[i] << "\n"; } */ // Release the VBOs so OpenGL can play with them err = queue.enqueueReleaseGLObjects(&cl_vbos, NULL, &event); queue.finish(); } const char* Simulator::oclErrorString(cl_int error) { static const char* errorString[] = { "CL_SUCCESS", "CL_DEVICE_NOT_FOUND", "CL_DEVICE_NOT_AVAILABLE", "CL_COMPILER_NOT_AVAILABLE", "CL_MEM_OBJECT_ALLOCATION_FAILURE", "CL_OUT_OF_RESOURCES", "CL_OUT_OF_HOST_MEMORY", "CL_PROFILING_INFO_NOT_AVAILABLE", "CL_MEM_COPY_OVERLAP", "CL_IMAGE_FORMAT_MISMATCH", "CL_IMAGE_FORMAT_NOT_SUPPORTED", "CL_BUILD_PROGRAM_FAILURE", "CL_MAP_FAILURE", "CL_MISALIGNED_SUB_BUFFER_OFFSET", "CL_EXEC_STATUS_ERROR_FOR_EVENTS_IN_WAIT_LIST", "CL_COMPILE_PROGRAM_FAILURE", "CL_LINKER_NOT_AVAILABLE", "CL_LINK_PROGRAM_FAILURE", "CL_DEVICE_PARTITION_FAILED", "CL_KERNEL_ARG_INFO_NOT_AVAILABLE", "", "", "", "", "", "", "", "", "", "", "CL_INVALID_VALUE", "CL_INVALID_DEVICE_TYPE", "CL_INVALID_PLATFORM", "CL_INVALID_DEVICE", "CL_INVALID_CONTEXT", "CL_INVALID_QUEUE_PROPERTIES", "CL_INVALID_COMMAND_QUEUE", "CL_INVALID_HOST_PTR", "CL_INVALID_MEM_OBJECT", "CL_INVALID_IMAGE_FORMAT_DESCRIPTOR", "CL_INVALID_IMAGE_SIZE", "CL_INVALID_SAMPLER", "CL_INVALID_BINARY", "CL_INVALID_BUILD_OPTIONS", "CL_INVALID_PROGRAM", "CL_INVALID_PROGRAM_EXECUTABLE", "CL_INVALID_KERNEL_NAME", "CL_INVALID_KERNEL_DEFINITION", "CL_INVALID_KERNEL", "CL_INVALID_ARG_INDEX", "CL_INVALID_ARG_VALUE", "CL_INVALID_ARG_SIZE", "CL_INVALID_KERNEL_ARGS", "CL_INVALID_WORK_DIMENSION", "CL_INVALID_WORK_GROUP_SIZE", "CL_INVALID_WORK_ITEM_SIZE", "CL_INVALID_GLOBAL_OFFSET", "CL_INVALID_EVENT_WAIT_LIST", "CL_INVALID_EVENT", "CL_INVALID_OPERATION", "CL_INVALID_GL_OBJECT", "CL_INVALID_BUFFER_SIZE", "CL_INVALID_MIP_LEVEL", "CL_INVALID_GLOBAL_WORK_SIZE", "CL_INVALID_PROPERTY", "CL_INVALID_IMAGE_DESCRIPTOR", "CL_INVALID_COMPILER_OPTIONS", "CL_INVALID_LINKER_OPTIONS", "CL_INVALID_DEVICE_PARTITION_COUNT" }; const int errorCount = sizeof(errorString) / sizeof(errorString[0]); const int index = -error; return (index >= 0 && index < errorCount) ? errorString[index] : ""; }
fix warning, do not initialize debug buffer.
Simulator: fix warning, do not initialize debug buffer.
C++
mit
lubosz/universe,lubosz/universe,lubosz/universe,lubosz/universe
2b1700d8a17ecf9a8c20aaa934a53618dac604a9
source/extensions/filters/http/dynamo/dynamo_request_parser.cc
source/extensions/filters/http/dynamo/dynamo_request_parser.cc
#include "extensions/filters/http/dynamo/dynamo_request_parser.h" #include <cmath> #include <cstdint> #include <string> #include <vector> #include "common/common/utility.h" #include "absl/strings/match.h" namespace Envoy { namespace Extensions { namespace HttpFilters { namespace Dynamo { /** * Basic json request/response format: * http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Appendix.CurrentAPI.html */ const Http::LowerCaseString RequestParser::X_AMZ_TARGET("X-AMZ-TARGET"); // clang-format off const std::vector<std::string> RequestParser::SINGLE_TABLE_OPERATIONS{ "CreateTable", "DeleteItem", "DeleteTable", "DescribeTable", "GetItem", "PutItem", "Query", "Scan", "UpdateItem", "UpdateTable"}; const std::vector<std::string> RequestParser::SUPPORTED_ERROR_TYPES{ // 4xx "AccessDeniedException", "ConditionalCheckFailedException", "IdempotentParameterMismatchException", "IncompleteSignatureException", "ItemCollectionSizeLimitExceededException", "LimitExceededException", "MissingAuthenticationTokenException", "ProvisionedThroughputExceededException", "ResourceInUseException", "ResourceNotFoundException", "ThrottlingException", "TransactionCanceledException", "TransactionInProgressException", "UnrecognizedClientException", "ValidationException"}; // clang-format on const std::vector<std::string> RequestParser::BATCH_OPERATIONS{"BatchGetItem", "BatchWriteItem"}; const std::vector<std::string> RequestParser::TRANSACT_OPERATIONS{"TransactGetItems", "TransactWriteItems"}; const std::vector<std::string> RequestParser::TRANSACT_ITEM_OPERATIONS{"ConditionCheck", "Delete", "Get", "Put", "Update"}; std::string RequestParser::parseOperation(const Http::HeaderMap& header_map) { std::string operation; const Http::HeaderEntry* x_amz_target = header_map.get(X_AMZ_TARGET); if (x_amz_target) { // Normally x-amz-target contains Version.Operation, e.g., DynamoDB_20160101.GetItem auto version_and_operation = StringUtil::splitToken(x_amz_target->value().getStringView(), "."); if (version_and_operation.size() == 2) { operation = std::string{version_and_operation[1]}; } } return operation; } RequestParser::TableDescriptor RequestParser::parseTable(const std::string& operation, const Json::Object& json_data) { TableDescriptor table{"", true}; // Simple operations on a single table, have "TableName" explicitly specified. if (find(SINGLE_TABLE_OPERATIONS.begin(), SINGLE_TABLE_OPERATIONS.end(), operation) != SINGLE_TABLE_OPERATIONS.end()) { table.table_name = json_data.getString("TableName", ""); } else if (find(BATCH_OPERATIONS.begin(), BATCH_OPERATIONS.end(), operation) != BATCH_OPERATIONS.end()) { Json::ObjectSharedPtr tables = json_data.getObject("RequestItems", true); tables->iterate([&table](const std::string& key, const Json::Object&) { if (table.table_name.empty()) { table.table_name = key; } else { if (table.table_name != key) { table.table_name = ""; table.is_single_table = false; return false; } } return true; }); } else if (find(TRANSACT_OPERATIONS.begin(), TRANSACT_OPERATIONS.end(), operation) != TRANSACT_OPERATIONS.end()) { std::vector<Json::ObjectSharedPtr> transact_items = json_data.getObjectArray("TransactItems", true); for (const Json::ObjectSharedPtr& transact_item : transact_items) { const auto next_table_name = getTableNameFromTransactItem(*transact_item); if (!next_table_name.has_value()) { // if an operation is missing a table name, we want to throw the normal set of errors table.table_name = ""; table.is_single_table = true; break; } if (table.table_name.empty()) { table.table_name = next_table_name.value(); } else if (table.table_name != next_table_name.value()) { table.table_name = ""; table.is_single_table = false; break; } } } return table; } absl::optional<std::string> RequestParser::getTableNameFromTransactItem(const Json::Object& transact_item) { for (const std::string& operation : TRANSACT_ITEM_OPERATIONS) { Json::ObjectSharedPtr item = transact_item.getObject(operation, true); std::string table_name = item->getString("TableName", ""); if (!table_name.empty()) { return absl::make_optional(table_name); } } return absl::nullopt; } std::vector<std::string> RequestParser::parseBatchUnProcessedKeys(const Json::Object& json_data) { std::vector<std::string> unprocessed_tables; Json::ObjectSharedPtr tables = json_data.getObject("UnprocessedKeys", true); tables->iterate([&unprocessed_tables](const std::string& key, const Json::Object&) { unprocessed_tables.emplace_back(key); return true; }); return unprocessed_tables; } std::string RequestParser::parseErrorType(const Json::Object& json_data) { std::string error_type = json_data.getString("__type", ""); if (error_type.empty()) { return ""; } for (const std::string& supported_error_type : SUPPORTED_ERROR_TYPES) { if (absl::EndsWith(error_type, supported_error_type)) { return supported_error_type; } } return ""; } bool RequestParser::isBatchOperation(const std::string& operation) { return find(BATCH_OPERATIONS.begin(), BATCH_OPERATIONS.end(), operation) != BATCH_OPERATIONS.end(); } std::vector<RequestParser::PartitionDescriptor> RequestParser::parsePartitions(const Json::Object& json_data) { std::vector<RequestParser::PartitionDescriptor> partition_descriptors; Json::ObjectSharedPtr partitions = json_data.getObject("ConsumedCapacity", true)->getObject("Partitions", true); partitions->iterate([&partition_descriptors, &partitions](const std::string& key, const Json::Object&) { // For a given partition id, the amount of capacity used is returned in the body as a double. // A stat will be created to track the capacity consumed for the operation, table and partition. // Stats counter only increments by whole numbers, capacity is round up to the nearest integer // to account for this. uint64_t capacity_integer = static_cast<uint64_t>(std::ceil(partitions->getDouble(key, 0.0))); partition_descriptors.emplace_back(key, capacity_integer); return true; }); return partition_descriptors; } void RequestParser::forEachStatString(const StringFn& fn) { for (const std::string& str : SINGLE_TABLE_OPERATIONS) { fn(str); } for (const std::string& str : SUPPORTED_ERROR_TYPES) { fn(str); } for (const std::string& str : BATCH_OPERATIONS) { fn(str); } for (const std::string& str : TRANSACT_OPERATIONS) { fn(str); } for (const std::string& str : TRANSACT_ITEM_OPERATIONS) { fn(str); } } } // namespace Dynamo } // namespace HttpFilters } // namespace Extensions } // namespace Envoy
#include "extensions/filters/http/dynamo/dynamo_request_parser.h" #include <cmath> #include <cstdint> #include <string> #include <vector> #include "common/common/utility.h" #include "absl/strings/match.h" namespace Envoy { namespace Extensions { namespace HttpFilters { namespace Dynamo { /** * Basic json request/response format: * https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_Operations_Amazon_DynamoDB.html */ const Http::LowerCaseString RequestParser::X_AMZ_TARGET("X-AMZ-TARGET"); // clang-format off const std::vector<std::string> RequestParser::SINGLE_TABLE_OPERATIONS{ "CreateTable", "DeleteItem", "DeleteTable", "DescribeTable", "GetItem", "PutItem", "Query", "Scan", "UpdateItem", "UpdateTable"}; const std::vector<std::string> RequestParser::SUPPORTED_ERROR_TYPES{ // 4xx "AccessDeniedException", "ConditionalCheckFailedException", "IdempotentParameterMismatchException", "IncompleteSignatureException", "ItemCollectionSizeLimitExceededException", "LimitExceededException", "MissingAuthenticationTokenException", "ProvisionedThroughputExceededException", "ResourceInUseException", "ResourceNotFoundException", "ThrottlingException", "TransactionCanceledException", "TransactionInProgressException", "UnrecognizedClientException", "ValidationException", // Errors not listed in the error handling section of DynamoDB developer guide, but observed in runtime "InvalidSignatureException", // https://github.com/aws/aws-sdk-go/issues/2598#issuecomment-526398896 }; // clang-format on const std::vector<std::string> RequestParser::BATCH_OPERATIONS{"BatchGetItem", "BatchWriteItem"}; const std::vector<std::string> RequestParser::TRANSACT_OPERATIONS{"TransactGetItems", "TransactWriteItems"}; const std::vector<std::string> RequestParser::TRANSACT_ITEM_OPERATIONS{"ConditionCheck", "Delete", "Get", "Put", "Update"}; std::string RequestParser::parseOperation(const Http::HeaderMap& header_map) { std::string operation; const Http::HeaderEntry* x_amz_target = header_map.get(X_AMZ_TARGET); if (x_amz_target) { // Normally x-amz-target contains Version.Operation, e.g., DynamoDB_20160101.GetItem auto version_and_operation = StringUtil::splitToken(x_amz_target->value().getStringView(), "."); if (version_and_operation.size() == 2) { operation = std::string{version_and_operation[1]}; } } return operation; } RequestParser::TableDescriptor RequestParser::parseTable(const std::string& operation, const Json::Object& json_data) { TableDescriptor table{"", true}; // Simple operations on a single table, have "TableName" explicitly specified. if (find(SINGLE_TABLE_OPERATIONS.begin(), SINGLE_TABLE_OPERATIONS.end(), operation) != SINGLE_TABLE_OPERATIONS.end()) { table.table_name = json_data.getString("TableName", ""); } else if (find(BATCH_OPERATIONS.begin(), BATCH_OPERATIONS.end(), operation) != BATCH_OPERATIONS.end()) { Json::ObjectSharedPtr tables = json_data.getObject("RequestItems", true); tables->iterate([&table](const std::string& key, const Json::Object&) { if (table.table_name.empty()) { table.table_name = key; } else { if (table.table_name != key) { table.table_name = ""; table.is_single_table = false; return false; } } return true; }); } else if (find(TRANSACT_OPERATIONS.begin(), TRANSACT_OPERATIONS.end(), operation) != TRANSACT_OPERATIONS.end()) { std::vector<Json::ObjectSharedPtr> transact_items = json_data.getObjectArray("TransactItems", true); for (const Json::ObjectSharedPtr& transact_item : transact_items) { const auto next_table_name = getTableNameFromTransactItem(*transact_item); if (!next_table_name.has_value()) { // if an operation is missing a table name, we want to throw the normal set of errors table.table_name = ""; table.is_single_table = true; break; } if (table.table_name.empty()) { table.table_name = next_table_name.value(); } else if (table.table_name != next_table_name.value()) { table.table_name = ""; table.is_single_table = false; break; } } } return table; } absl::optional<std::string> RequestParser::getTableNameFromTransactItem(const Json::Object& transact_item) { for (const std::string& operation : TRANSACT_ITEM_OPERATIONS) { Json::ObjectSharedPtr item = transact_item.getObject(operation, true); std::string table_name = item->getString("TableName", ""); if (!table_name.empty()) { return absl::make_optional(table_name); } } return absl::nullopt; } std::vector<std::string> RequestParser::parseBatchUnProcessedKeys(const Json::Object& json_data) { std::vector<std::string> unprocessed_tables; Json::ObjectSharedPtr tables = json_data.getObject("UnprocessedKeys", true); tables->iterate([&unprocessed_tables](const std::string& key, const Json::Object&) { unprocessed_tables.emplace_back(key); return true; }); return unprocessed_tables; } std::string RequestParser::parseErrorType(const Json::Object& json_data) { std::string error_type = json_data.getString("__type", ""); if (error_type.empty()) { return ""; } for (const std::string& supported_error_type : SUPPORTED_ERROR_TYPES) { if (absl::EndsWith(error_type, supported_error_type)) { return supported_error_type; } } return ""; } bool RequestParser::isBatchOperation(const std::string& operation) { return find(BATCH_OPERATIONS.begin(), BATCH_OPERATIONS.end(), operation) != BATCH_OPERATIONS.end(); } std::vector<RequestParser::PartitionDescriptor> RequestParser::parsePartitions(const Json::Object& json_data) { std::vector<RequestParser::PartitionDescriptor> partition_descriptors; Json::ObjectSharedPtr partitions = json_data.getObject("ConsumedCapacity", true)->getObject("Partitions", true); partitions->iterate([&partition_descriptors, &partitions](const std::string& key, const Json::Object&) { // For a given partition id, the amount of capacity used is returned in the body as a double. // A stat will be created to track the capacity consumed for the operation, table and partition. // Stats counter only increments by whole numbers, capacity is round up to the nearest integer // to account for this. uint64_t capacity_integer = static_cast<uint64_t>(std::ceil(partitions->getDouble(key, 0.0))); partition_descriptors.emplace_back(key, capacity_integer); return true; }); return partition_descriptors; } void RequestParser::forEachStatString(const StringFn& fn) { for (const std::string& str : SINGLE_TABLE_OPERATIONS) { fn(str); } for (const std::string& str : SUPPORTED_ERROR_TYPES) { fn(str); } for (const std::string& str : BATCH_OPERATIONS) { fn(str); } for (const std::string& str : TRANSACT_OPERATIONS) { fn(str); } for (const std::string& str : TRANSACT_ITEM_OPERATIONS) { fn(str); } } } // namespace Dynamo } // namespace HttpFilters } // namespace Extensions } // namespace Envoy
Add InvalidSignatureException to supported error types (#12509)
dynamo: Add InvalidSignatureException to supported error types (#12509) Signed-off-by: Bob Wang <[email protected]>
C++
apache-2.0
lizan/envoy,envoyproxy/envoy-wasm,lyft/envoy,lyft/envoy,lyft/envoy,envoyproxy/envoy,envoyproxy/envoy-wasm,envoyproxy/envoy-wasm,envoyproxy/envoy,envoyproxy/envoy-wasm,envoyproxy/envoy,lizan/envoy,envoyproxy/envoy,lyft/envoy,envoyproxy/envoy-wasm,envoyproxy/envoy,envoyproxy/envoy,envoyproxy/envoy-wasm,envoyproxy/envoy,envoyproxy/envoy,lizan/envoy,lizan/envoy,envoyproxy/envoy,envoyproxy/envoy,lyft/envoy,envoyproxy/envoy-wasm,envoyproxy/envoy,lizan/envoy,lyft/envoy,lizan/envoy,envoyproxy/envoy
4bb439af8962a8abafe80c65a5777af028e9672e
src/SlicePool.hxx
src/SlicePool.hxx
/* * Copyright 2007-2017 Content Management AG * All rights reserved. * * author: Max Kellermann <[email protected]> * * 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. * * 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 * FOUNDATION 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. */ /* * The "slice" memory allocator. It is an allocator for large numbers * of small fixed-size objects. */ #ifndef BENG_PROXY_SLICE_POOL_HXX #define BENG_PROXY_SLICE_POOL_HXX #include "SliceAllocation.hxx" #include "util/Compiler.h" #include <boost/intrusive/list.hpp> #include <assert.h> #include <stddef.h> struct AllocatorStats; class SlicePool; class SliceArea { public: static constexpr auto link_mode = boost::intrusive::normal_link; typedef boost::intrusive::link_mode<link_mode> LinkMode; typedef boost::intrusive::list_member_hook<LinkMode> SiblingsHook; SiblingsHook siblings; private: unsigned allocated_count = 0; unsigned free_head = 0; struct Slot { unsigned next; static constexpr unsigned ALLOCATED = -1; static constexpr unsigned END_OF_LIST = -2; #ifndef NDEBUG static constexpr unsigned MARK = -3; #endif constexpr bool IsAllocated() const noexcept { return next == ALLOCATED; } }; Slot slices[1]; SliceArea(SlicePool &pool) noexcept; ~SliceArea() noexcept { assert(allocated_count == 0); } public: static SliceArea *New(SlicePool &pool) noexcept; void Delete(SlicePool &pool) noexcept; static constexpr size_t GetHeaderSize(unsigned slices_per_area) noexcept { return sizeof(SliceArea) + sizeof(Slot) * (slices_per_area - 1); } void ForkCow(const SlicePool &pool, bool inherit) noexcept; bool IsEmpty() const noexcept { return allocated_count == 0; } bool IsFull(const SlicePool &pool) const noexcept; size_t GetNettoSize(size_t slice_size) const noexcept { return allocated_count * slice_size; } gcc_pure void *GetPage(const SlicePool &pool, unsigned page) noexcept; gcc_pure void *GetSlice(const SlicePool &pool, unsigned slice) noexcept; /** * Calculates the allocation slot index from an allocated pointer. * This is used to locate the #Slot for a pointer passed to a * public function. */ gcc_pure unsigned IndexOf(const SlicePool &pool, const void *_p) noexcept; /** * Find the first free slot index, starting at the specified position. */ gcc_pure unsigned FindFree(const SlicePool &pool, unsigned start) const noexcept; /** * Find the first allocated slot index, starting at the specified * position. */ gcc_pure unsigned FindAllocated(const SlicePool &pool, unsigned start) const noexcept; /** * Punch a hole in the memory map in the specified slot index range. * This means notifying the kernel that we will no longer need the * contents, which allows the kernel to drop the allocated pages and * reuse it for other processes. */ void PunchSliceRange(SlicePool &pool, unsigned start, unsigned end) noexcept; void Compress(SlicePool &pool) noexcept; void *Alloc(SlicePool &pool) noexcept; void Free(SlicePool &pool, void *p) noexcept; struct Disposer { SlicePool &pool; void operator()(SliceArea *area) noexcept { area->Delete(pool); } }; }; class SlicePool { friend class SliceArea; size_t slice_size; /** * Number of slices that fit on one MMU page (4 kB). */ unsigned slices_per_page; unsigned pages_per_slice; unsigned pages_per_area; unsigned slices_per_area; /** * Number of pages for the area header. */ unsigned header_pages; size_t area_size; typedef boost::intrusive::list<SliceArea, boost::intrusive::member_hook<SliceArea, SliceArea::SiblingsHook, &SliceArea::siblings>, boost::intrusive::constant_time_size<false>> AreaList; AreaList areas; /** * A list of #SliceArea instances which are empty. They are kept * in a separate list to reduce fragmentation: allocate first from * areas which are not empty. */ AreaList empty_areas; /** * A list of #SliceArea instances which are full. They are kept * in a separate list to speed up allocation, to avoid iterating * over full areas. */ AreaList full_areas; bool fork_cow = true; public: SlicePool(size_t _slice_size, unsigned _slices_per_area) noexcept; ~SlicePool() noexcept; size_t GetSliceSize() const noexcept { return slice_size; } /** * Controls whether forked child processes inherit the allocator. * This is enabled by default. */ void ForkCow(bool inherit) noexcept; void AddStats(AllocatorStats &stats, const AreaList &list) const noexcept; gcc_pure AllocatorStats GetStats() const noexcept; void Compress() noexcept; gcc_pure SliceArea *FindNonFullArea() noexcept; SliceArea &MakeNonFullArea() noexcept; SliceAllocation Alloc() noexcept; void Free(SliceArea &area, void *p) noexcept; }; #endif
/* * Copyright 2007-2017 Content Management AG * All rights reserved. * * author: Max Kellermann <[email protected]> * * 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. * * 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 * FOUNDATION 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. */ /* * The "slice" memory allocator. It is an allocator for large numbers * of small fixed-size objects. */ #ifndef BENG_PROXY_SLICE_POOL_HXX #define BENG_PROXY_SLICE_POOL_HXX #include "SliceAllocation.hxx" #include "util/Compiler.h" #include <boost/intrusive/list.hpp> #include <assert.h> #include <stddef.h> struct AllocatorStats; class SlicePool; class SliceArea : public boost::intrusive::list_base_hook<boost::intrusive::link_mode<boost::intrusive::normal_link>> { unsigned allocated_count = 0; unsigned free_head = 0; struct Slot { unsigned next; static constexpr unsigned ALLOCATED = -1; static constexpr unsigned END_OF_LIST = -2; #ifndef NDEBUG static constexpr unsigned MARK = -3; #endif constexpr bool IsAllocated() const noexcept { return next == ALLOCATED; } }; Slot slices[1]; SliceArea(SlicePool &pool) noexcept; ~SliceArea() noexcept { assert(allocated_count == 0); } public: static SliceArea *New(SlicePool &pool) noexcept; void Delete(SlicePool &pool) noexcept; static constexpr size_t GetHeaderSize(unsigned slices_per_area) noexcept { return sizeof(SliceArea) + sizeof(Slot) * (slices_per_area - 1); } void ForkCow(const SlicePool &pool, bool inherit) noexcept; bool IsEmpty() const noexcept { return allocated_count == 0; } bool IsFull(const SlicePool &pool) const noexcept; size_t GetNettoSize(size_t slice_size) const noexcept { return allocated_count * slice_size; } gcc_pure void *GetPage(const SlicePool &pool, unsigned page) noexcept; gcc_pure void *GetSlice(const SlicePool &pool, unsigned slice) noexcept; /** * Calculates the allocation slot index from an allocated pointer. * This is used to locate the #Slot for a pointer passed to a * public function. */ gcc_pure unsigned IndexOf(const SlicePool &pool, const void *_p) noexcept; /** * Find the first free slot index, starting at the specified position. */ gcc_pure unsigned FindFree(const SlicePool &pool, unsigned start) const noexcept; /** * Find the first allocated slot index, starting at the specified * position. */ gcc_pure unsigned FindAllocated(const SlicePool &pool, unsigned start) const noexcept; /** * Punch a hole in the memory map in the specified slot index range. * This means notifying the kernel that we will no longer need the * contents, which allows the kernel to drop the allocated pages and * reuse it for other processes. */ void PunchSliceRange(SlicePool &pool, unsigned start, unsigned end) noexcept; void Compress(SlicePool &pool) noexcept; void *Alloc(SlicePool &pool) noexcept; void Free(SlicePool &pool, void *p) noexcept; struct Disposer { SlicePool &pool; void operator()(SliceArea *area) noexcept { area->Delete(pool); } }; }; class SlicePool { friend class SliceArea; size_t slice_size; /** * Number of slices that fit on one MMU page (4 kB). */ unsigned slices_per_page; unsigned pages_per_slice; unsigned pages_per_area; unsigned slices_per_area; /** * Number of pages for the area header. */ unsigned header_pages; size_t area_size; typedef boost::intrusive::list<SliceArea, boost::intrusive::base_hook<boost::intrusive::list_base_hook<boost::intrusive::link_mode<boost::intrusive::normal_link>>>, boost::intrusive::constant_time_size<false>> AreaList; AreaList areas; /** * A list of #SliceArea instances which are empty. They are kept * in a separate list to reduce fragmentation: allocate first from * areas which are not empty. */ AreaList empty_areas; /** * A list of #SliceArea instances which are full. They are kept * in a separate list to speed up allocation, to avoid iterating * over full areas. */ AreaList full_areas; bool fork_cow = true; public: SlicePool(size_t _slice_size, unsigned _slices_per_area) noexcept; ~SlicePool() noexcept; size_t GetSliceSize() const noexcept { return slice_size; } /** * Controls whether forked child processes inherit the allocator. * This is enabled by default. */ void ForkCow(bool inherit) noexcept; void AddStats(AllocatorStats &stats, const AreaList &list) const noexcept; gcc_pure AllocatorStats GetStats() const noexcept; void Compress() noexcept; gcc_pure SliceArea *FindNonFullArea() noexcept; SliceArea &MakeNonFullArea() noexcept; SliceAllocation Alloc() noexcept; void Free(SliceArea &area, void *p) noexcept; }; #endif
use list_base_hook instead of list_member_hook
SlicePool: use list_base_hook instead of list_member_hook Easier to use and allows forward declaration.
C++
bsd-2-clause
CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy
674b65d0d0bb23ffa92100f5f5f20b23d58042f7
source/thewizardplusplus/wizard_parser/parser/match_parser.cpp
source/thewizardplusplus/wizard_parser/parser/match_parser.cpp
#include "match_parser.hpp" #include "ast_node.hpp" #include <memory> namespace thewizardplusplus::wizard_parser::parser { match_parser::match_parser(const match_type& type, const std::string& sample): type{type}, sample{sample} {} parsing_result match_parser::parse(const lexer::token_span& tokens) const { if (tokens.empty()) { return {}; } const auto matched_value = type == match_type::by_type ? tokens[0].type : tokens[0].value; return matched_value == sample ? parsing_result{ ast_node{tokens[0].type, tokens[0].value, {}, lexer::get_offset(tokens)}, tokens.subspan(1) } : parsing_result{{}, tokens}; } namespace operators { rule_parser::pointer operator""_t(const char* const sample, std::size_t) { return std::make_shared<match_parser>(match_type::by_type, sample); } rule_parser::pointer operator""_v(const char* const sample, std::size_t) { return std::make_shared<match_parser>(match_type::by_value, sample); } } }
#include "match_parser.hpp" #include "ast_node.hpp" #include <memory> namespace thewizardplusplus::wizard_parser::parser { match_parser::match_parser(const match_type& type, const std::string& sample): type{type}, sample{sample} {} parsing_result match_parser::parse(const lexer::token_span& tokens) const { if (tokens.empty()) { return {{}, {}}; } const auto token = tokens[0]; const auto match = type == match_type::by_type ? token.type : token.value; return match == sample ? parsing_result{ ast_node{token.type, token.value, {}, lexer::get_offset(tokens)}, tokens.subspan(1) } : parsing_result{{}, tokens}; } namespace operators { rule_parser::pointer operator""_t(const char* const sample, std::size_t) { return std::make_shared<match_parser>(match_type::by_type, sample); } rule_parser::pointer operator""_v(const char* const sample, std::size_t) { return std::make_shared<match_parser>(match_type::by_value, sample); } } }
Refactor the `parser::match_parser::parse()` method
Refactor the `parser::match_parser::parse()` method
C++
mit
thewizardplusplus/wizard-parser,thewizardplusplus/wizard-parser
d86866ecdd07a403a39bfa022c1e578fe74a92c2
common/eeprom_io.hpp
common/eeprom_io.hpp
#pragma once //=====================================================================// /*! @file @brief EEPROM ドライバー @author 平松邦仁 ([email protected]) */ //=====================================================================// #include <cstdint> #include "common/i2c_io.hpp" #include "common/time.h" namespace device { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief EEPROM テンプレートクラス @n PORT ポート指定クラス: @n class port { @n public: @n void scl_dir(bool val) const { } @n void scl_out(bool val) const { } @n bool scl_inp() const { return 0; } @n void sda_dir(bool val) const { } @n void sda_out(bool val) const { } @n bool sda_inp() const { return 0; } @n }; @param[in] PORT ポート定義クラス */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// template <class PORT> class eeprom_io { static const uint8_t EEPROM_ADR_ = 0x50; i2c_io<PORT>& i2c_io_; uint8_t ds_; bool exp_; uint8_t pagen_; uint8_t i2c_adr_(bool exta = 0) const { return EEPROM_ADR_ | ds_ | (static_cast<uint8_t>(exta) << 2); } public: //-----------------------------------------------------------------// /*! @brief コンストラクター @param[in] i2c i2c_io クラスを参照で渡す */ //-----------------------------------------------------------------// eeprom_io(i2c_io<PORT>& i2c) : i2c_io_(i2c), ds_(0), exp_(false), pagen_(1) { } //-----------------------------------------------------------------// /*! @brief 開始 @param[in] ds デバイス選択ビット @param[in] exp 「true」の場合、2バイトアドレス @param[in] pagen ページサイズ */ //-----------------------------------------------------------------// void start(uint8_t ds, bool exp, uint8_t pagen) { ds_ = ds & 7; exp_ = exp; pagen_ = pagen; } //-----------------------------------------------------------------// /*! @brief 書き込み同期 @param[in] adr 読み込みテストアドレス @param[in] delay 待ち時間(10us単位) @return デバイスエラーなら「false」 */ //-----------------------------------------------------------------// bool sync_write(uint32_t adr = 0, uint16_t delay = 600) const { bool ok = false; for(uint16_t i = 0; i < delay; ++i) { utils::delay::micro_second(10); uint8_t tmp[1]; if(read(adr, tmp, 1)) { ok = true; break; } } return ok; } //-----------------------------------------------------------------// /*! @brief EEPROM 読み出し @param[in] adr 読み出しアドレス @param[out] dst 先 @param[in] len 長さ @return 成功なら「true」 */ //-----------------------------------------------------------------// bool read(uint32_t adr, uint8_t* dst, uint16_t len) const { if(exp_) { uint8_t tmp[2]; tmp[0] = (adr >> 8) & 255; tmp[1] = adr & 255; if(!i2c_io_.send(i2c_adr_((adr >> 16) & 1), tmp, 2)) { return false; } if(!i2c_io_.recv(i2c_adr_((adr >> 16) & 1), dst, len)) { return false; } } else { uint8_t tmp[1]; tmp[0] = adr & 255; if(!i2c_io_.send(i2c_adr_(), tmp, 1)) { return false; } if(!i2c_io_.recv(i2c_adr_(), dst, len)) { return false; } } return true; } //-----------------------------------------------------------------// /*! @brief EEPROM 書き込み @param[in] adr 書き込みアドレス @param[out] src 元 @param[in] len 長さ @return 成功なら「true」 */ //-----------------------------------------------------------------// bool write(uint32_t adr, const uint8_t* src, uint16_t len) const { const uint8_t* end = src + len; while(src < end) { uint16_t l = pagen_ - (reinterpret_cast<uint16_t>(src) & (pagen_ - 1)); if(exp_) { if(!i2c_io_.send(i2c_adr_((adr >> 16) & 1), adr >> 8, adr & 255, src, l)) { return false; } } else { if(!i2c_io_.send(i2c_adr_((adr >> 16) & 1), adr & 255, src, l)) { return false; } } src += l; adr += l; if(src < end) { // 書き込み終了を待つポーリング if(!sync_write(adr)) { return false; } } } return true; } }; }
#pragma once //=====================================================================// /*! @file @brief EEPROM ドライバー @author 平松邦仁 ([email protected]) */ //=====================================================================// #include <cstdint> #include "common/i2c_io.hpp" #include "common/time.h" namespace device { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief EEPROM テンプレートクラス @n PORT ポート指定クラス: @n class port { @n public: @n void scl_dir(bool val) const { } @n void scl_out(bool val) const { } @n bool scl_inp() const { return 0; } @n void sda_dir(bool val) const { } @n void sda_out(bool val) const { } @n bool sda_inp() const { return 0; } @n }; @param[in] PORT ポート定義クラス */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// template <class PORT> class eeprom_io { static const uint8_t EEPROM_ADR_ = 0x50; i2c_io<PORT>& i2c_io_; uint8_t ds_; bool exp_; bool ad_mix_; uint8_t pagen_; uint8_t i2c_adr_(uint32_t adr) const { uint8_t a = EEPROM_ADR_ | ds_; if(ad_mix_) { if(adr >> 16) a |= 4; } return a; } public: //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief 256 バイトまでの EEPROM の ID (0 to 7) */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// enum class M256B { ID0, ID1, ID2, ID3, ID4, ID5, ID6, ID7, }; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief 64K バイトまでの EEPROM の ID (0 to 7) */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// enum class M64KB { ID0, ID1, ID2, ID3, ID4, ID5, ID6, ID7, }; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief 128K バイトまでの EEPROM の ID (0 to 3) */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// enum class M128KB { ID0, ID1, ID2, ID3, }; //-----------------------------------------------------------------// /*! @brief コンストラクター @param[in] i2c i2c_io クラスを参照で渡す */ //-----------------------------------------------------------------// eeprom_io(i2c_io<PORT>& i2c) : i2c_io_(i2c), ds_(0), exp_(false), ad_mix_(false), pagen_(1) { } //-----------------------------------------------------------------// /*! @brief 256 バイトまでの EEPROM を開始 @param[in] type デバイスのタイプとID @param[in] pagen ページサイズ(書き込み一時バッファのサイズ) */ //-----------------------------------------------------------------// void start(M256B type_id, uint8_t pagen) { ds_ = static_cast<uint8_t>(type_id); exp_ = false; ad_mix_ = false; pagen_ = pagen; } //-----------------------------------------------------------------// /*! @brief 64K バイトまでの EEPROM を開始 @param[in] type デバイスのタイプとID @param[in] pagen ページサイズ(書き込み一時バッファのサイズ) */ //-----------------------------------------------------------------// void start(M64KB type_id, uint8_t pagen) { ds_ = static_cast<uint8_t>(type_id); exp_ = true; ad_mix_ = false; pagen_ = pagen; } //-----------------------------------------------------------------// /*! @brief 128K バイトまでの EEPROM を開始 @param[in] type デバイスのタイプとID @param[in] pagen ページサイズ(書き込み一時バッファのサイズ) */ //-----------------------------------------------------------------// void start(M128KB type_id, uint8_t pagen) { ds_ = static_cast<uint8_t>(type_id); exp_ = true; ad_mix_ = true; pagen_ = pagen; } //-----------------------------------------------------------------// /*! @brief 書き込み同期 @param[in] adr 読み込みテストアドレス @param[in] delay 待ち時間(10us単位) @return デバイスエラーなら「false」 */ //-----------------------------------------------------------------// bool sync_write(uint32_t adr = 0, uint16_t delay = 600) const { bool ok = false; for(uint16_t i = 0; i < delay; ++i) { utils::delay::micro_second(10); uint8_t tmp[1]; if(read(adr, tmp, 1)) { ok = true; break; } } return ok; } //-----------------------------------------------------------------// /*! @brief EEPROM 読み出し @param[in] adr 読み出しアドレス @param[out] dst 先 @param[in] len 長さ @return 成功なら「true」 */ //-----------------------------------------------------------------// bool read(uint32_t adr, uint8_t* dst, uint16_t len) const { if(exp_) { uint8_t tmp[2]; tmp[0] = (adr >> 8) & 255; tmp[1] = adr & 255; if(!i2c_io_.send(i2c_adr_(adr), tmp, 2)) { return false; } if(!i2c_io_.recv(i2c_adr_(adr), dst, len)) { return false; } } else { uint8_t tmp[1]; tmp[0] = adr & 255; if(!i2c_io_.send(i2c_adr_(adr), tmp, 1)) { return false; } if(!i2c_io_.recv(i2c_adr_(adr), dst, len)) { return false; } } return true; } //-----------------------------------------------------------------// /*! @brief EEPROM 書き込み @param[in] adr 書き込みアドレス @param[out] src 元 @param[in] len 長さ @return 成功なら「true」 */ //-----------------------------------------------------------------// bool write(uint32_t adr, const uint8_t* src, uint16_t len) const { const uint8_t* end = src + len; while(src < end) { uint16_t l = pagen_ - (reinterpret_cast<uint16_t>(src) & (pagen_ - 1)); if(exp_) { if(!i2c_io_.send(i2c_adr_(adr), adr >> 8, adr & 255, src, l)) { return false; } } else { if(!i2c_io_.send(i2c_adr_(adr), adr & 255, src, l)) { return false; } } src += l; adr += l; if(src < end) { // 書き込み終了を待つポーリング if(!sync_write(adr)) { return false; } } } return true; } }; }
update eeprom type
update eeprom type
C++
bsd-3-clause
hirakuni45/R8C,hirakuni45/R8C,hirakuni45/R8C
13cb85f154454da887ac6bc3b6b3594a41d30e7c
samples/learn_depth_segmentation/learn_depth_segmentation.cpp
samples/learn_depth_segmentation/learn_depth_segmentation.cpp
#include <iostream> #include <boost/filesystem.hpp> #include "elm/core/core.h" #include "elm/core/debug_utils.h" #include "elm/core/layerconfig.h" #include "elm/core/inputname.h" #include "elm/io/readnyudepthv2labeled.h" #include "elm/layers/layerfactory.h" #include "elm/layers/mlp.h" using namespace std; namespace bfs=boost::filesystem; using namespace cv; using namespace elm; int main() { cout<<elm::GetVersion()<<endl; return 0; }
#include <iostream> #include <boost/filesystem.hpp> #include <opencv2/highgui/highgui.hpp> #include "elm/core/core.h" #include "elm/core/cv/mat_utils.h" #include "elm/core/debug_utils.h" #include "elm/core/layerconfig.h" #include "elm/core/inputname.h" #include "elm/io/readnyudepthv2labeled.h" #include "elm/layers/layerfactory.h" #include "elm/layers/mlp.h" using namespace std; namespace bfs=boost::filesystem; using namespace cv; using namespace elm; int main() { cout<<elm::GetVersion()<<endl; bfs::path p("/media/win/Users/woodstock/dev/data/nyu_depth_v2_labeled.mat"); ReadNYUDepthV2Labeled reader; int nb_items = reader.ReadHeader(p.string()); ELM_COUT_VAR(nb_items); for(int i=0; i<10; i++) { ELM_COUT_VAR(i); cv::Mat bgr, labels, depth; reader.Next(bgr, depth, labels); cv::imshow("image", bgr); cv::imshow("depth", elm::ConvertTo8U(depth)); cv::imshow("labels", elm::ConvertTo8U(labels)); cv::waitKey(0); } return 0; }
load nyu depth v2 data
load nyu depth v2 data
C++
bsd-3-clause
kashefy/elm,kashefy/elm,kashefy/elm,kashefy/elm
72a34d835900c03c84918f5bebb0ec91915b7619
src/plugins/clangcodemodel/test/clangcompletioncontextanalyzertest.cpp
src/plugins/clangcodemodel/test/clangcompletioncontextanalyzertest.cpp
/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms and ** conditions see http://www.qt.io/terms-conditions. For further information ** use the contact form at http://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, The Qt Company gives you certain additional ** rights. These rights are described in The Qt Company LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "clangcompletioncontextanalyzertest.h" #include <clangcodemodel/clangcompletioncontextanalyzer.h> #include <texteditor/codeassist/assistinterface.h> #include <utils/qtcassert.h> #include <QDebug> #include <QTest> #include <QTextDocument> using namespace CPlusPlus; using namespace ClangCodeModel; using namespace ClangCodeModel::Internal; using namespace ClangCodeModel::Internal::Tests; Q_DECLARE_METATYPE(ClangCodeModel::Internal::ClangCompletionContextAnalyzer::CompletionAction) namespace QTest { template<> char *toString(const ClangCompletionContextAnalyzer::CompletionAction &action) { using CCA = ClangCompletionContextAnalyzer; switch (action) { case CCA::PassThroughToLibClang: return qstrdup("PassThroughToLibClang"); case CCA::PassThroughToLibClangAfterLeftParen: return qstrdup("PassThroughToLibClangAfterLeftParen"); case CCA::CompleteDoxygenKeyword: return qstrdup("CompleteDoxygenKeyword"); case CCA::CompleteIncludePath: return qstrdup("CompleteIncludePath"); case CCA::CompletePreprocessorDirective: return qstrdup("CompletePreprocessorDirective"); case CCA::CompleteSignal: return qstrdup("CompleteSignal"); case CCA::CompleteSlot: return qstrdup("CompleteSlot"); } return qstrdup("Unexpected Value"); } } // namespace QTest namespace { typedef QByteArray _; class DummyAssistInterface : public TextEditor::AssistInterface { public: DummyAssistInterface(const QByteArray &text, int position) : AssistInterface(new QTextDocument(QString::fromUtf8(text)), position, QLatin1String("<testdocument>"), TextEditor::ActivationCharacter) {} ~DummyAssistInterface() { delete textDocument(); } }; class TestDocument { public: TestDocument(const QByteArray &theSource) : source(theSource) , position(theSource.lastIndexOf('@')) // Use 'lastIndexOf' due to doxygen: "//! @keyword" { QTC_CHECK(position != -1); source.remove(position, 1); } QByteArray source; int position; }; bool isAPassThroughToLibClangAction(ClangCompletionContextAnalyzer::CompletionAction action) { return action == ClangCompletionContextAnalyzer::PassThroughToLibClang || action == ClangCompletionContextAnalyzer::PassThroughToLibClangAfterLeftParen; } ClangCompletionContextAnalyzer runAnalyzer(const TestDocument &testDocument) { DummyAssistInterface assistInterface(testDocument.source, testDocument.position); ClangCompletionContextAnalyzer analyzer(&assistInterface, LanguageFeatures::defaultFeatures()); analyzer.analyze(); return analyzer; } } // anonymous namespace void ClangCompletionContextAnalyzerTest::testPassThroughToClangAndSignalSlotRecognition_data() { QTest::addColumn<QByteArray>("givenSource"); QTest::addColumn<ClangCompletionContextAnalyzer::CompletionAction>("expectedCompletionAction"); QTest::addColumn<int>("expectedDiffBetweenCursorAndCalculatedClangPosition"); QTest::addColumn<int>("expectedDiffBetweenCursorAndCalculatedProposalPosition"); using CCA = ClangCompletionContextAnalyzer; QTest::newRow("members - dot 1") << _("o.mem@") << CCA::PassThroughToLibClang << -3 << -3; QTest::newRow("members - dot 2") << _("o. mem@") << CCA::PassThroughToLibClang << -4 << -3; QTest::newRow("members - dot 3") << _("o.@mem") << CCA::PassThroughToLibClang << 0 << 0; QTest::newRow("members - dot 4") << _("o. @ mem") << CCA::PassThroughToLibClang << -1 << 0; QTest::newRow("members - arrow 1") << _("o->mem@") << CCA::PassThroughToLibClang << -3 << -3; QTest::newRow("members - arrow 2") << _("o-> mem@") << CCA::PassThroughToLibClang << -4 << -3; QTest::newRow("members - arrow 3") << _("o->@mem") << CCA::PassThroughToLibClang << 0 << 0; QTest::newRow("members - arrow 4") << _("o-> @ mem") << CCA::PassThroughToLibClang << -1 << 0; QTest::newRow("call 1") << _("f(@") << CCA::PassThroughToLibClangAfterLeftParen << -2 << 0; QTest::newRow("call 2") << _("f(1,@") << CCA::PassThroughToLibClangAfterLeftParen << -4 << -2; QTest::newRow("call 3") << _("f(1, @") << CCA::PassThroughToLibClang << -1 << 0; QTest::newRow("qt4 signals 1") << _("SIGNAL(@") << CCA::CompleteSignal << 0 << 0; QTest::newRow("qt4 signals 2") << _("SIGNAL(foo@") << CCA::CompleteSignal << -3 << -3; QTest::newRow("qt4 slots 1") << _("SLOT(@") << CCA::CompleteSlot << 0 << 0; QTest::newRow("qt4 slots 2") << _("SLOT(foo@") << CCA::CompleteSlot << -3 << -3; } void ClangCompletionContextAnalyzerTest::testPassThroughToClangAndSignalSlotRecognition() { QFETCH(QByteArray, givenSource); QFETCH(ClangCompletionContextAnalyzer::CompletionAction, expectedCompletionAction); QFETCH(int, expectedDiffBetweenCursorAndCalculatedClangPosition); QFETCH(int, expectedDiffBetweenCursorAndCalculatedProposalPosition); const TestDocument testDocument(givenSource); ClangCompletionContextAnalyzer analyzer = runAnalyzer(testDocument); QCOMPARE(analyzer.completionAction(), expectedCompletionAction); QCOMPARE(analyzer.positionForClang() - testDocument.position, expectedDiffBetweenCursorAndCalculatedClangPosition); QCOMPARE(analyzer.positionForProposal() - testDocument.position, expectedDiffBetweenCursorAndCalculatedProposalPosition); } void ClangCompletionContextAnalyzerTest::testSpecialCompletionRecognition_data() { QTest::addColumn<QByteArray>("givenSource"); QTest::addColumn<ClangCompletionContextAnalyzer::CompletionAction>("expectedCompletionAction"); QTest::addColumn<int>("expectedDiffBetweenCursorAndCalculatedProposalPosition"); using CCA = ClangCompletionContextAnalyzer; QTest::newRow("doxygen keywords 1") << _("//! \\@") << CCA::CompleteDoxygenKeyword << 0; QTest::newRow("doxygen keywords 3") << _("//! @@") << CCA::CompleteDoxygenKeyword << 0; QTest::newRow("doxygen keywords 2") << _("//! \\par@") << CCA::CompleteDoxygenKeyword << -3; QTest::newRow("pp directives 1") << _("#@") << CCA::CompletePreprocessorDirective << 0; QTest::newRow("pp directives 2") << _("#if@") << CCA::CompletePreprocessorDirective << -2; QTest::newRow("pp include path 1") << _("#include \"foo@\"") << CCA::CompleteIncludePath << -3; QTest::newRow("pp include path 2") << _("#include <foo@>") << CCA::CompleteIncludePath << -3; QTest::newRow("pp include path 3") << _("#include <foo/@>") << CCA::CompleteIncludePath << 0; } void ClangCompletionContextAnalyzerTest::testSpecialCompletionRecognition() { QFETCH(QByteArray, givenSource); QFETCH(ClangCompletionContextAnalyzer::CompletionAction, expectedCompletionAction); QFETCH(int, expectedDiffBetweenCursorAndCalculatedProposalPosition); const TestDocument testDocument(givenSource); ClangCompletionContextAnalyzer analyzer = runAnalyzer(testDocument); QCOMPARE(analyzer.completionAction(), expectedCompletionAction); QCOMPARE(analyzer.positionForClang(), -1); QCOMPARE(analyzer.positionForProposal() - testDocument.position, expectedDiffBetweenCursorAndCalculatedProposalPosition); } void ClangCompletionContextAnalyzerTest::testAvoidSpecialCompletionRecognition_data() { QTest::addColumn<QByteArray>("givenSource"); QTest::newRow("no special completion for literals 1") << _("\"@"); QTest::newRow("no special completion for literals 2") << _(" \"@"); QTest::newRow("no special completion for literals 3") << _("\"text\"@"); QTest::newRow("no special completion for literals 4") << _("\"hello cruel@ world\""); QTest::newRow("no special completion for literals 5") << _("'@'"); QTest::newRow("no special completion for literals 6") << _("'a@'"); QTest::newRow("no special completion for comma operator") << _("a = b,@\""); QTest::newRow("no special completion for doxygen marker not in doxygen comment 1") << _("@@"); QTest::newRow("no special completion for doxygen marker not in doxygen comment 2") << _("\\@"); QTest::newRow("no special completion in comments 1") << _("// text@"); QTest::newRow("no special completion in comments 2") << _("/* text@ */"); QTest::newRow("no special completion for slash") << _("5 /@"); QTest::newRow("no special completion for '(' 1") << _("(@"); QTest::newRow("no special completion for '(' 2") << _("((@"); QTest::newRow("no special completion for '(' 3") << _("*(@"); } void ClangCompletionContextAnalyzerTest::testAvoidSpecialCompletionRecognition() { QFETCH(QByteArray, givenSource); const TestDocument testDocument(givenSource); ClangCompletionContextAnalyzer analyzer = runAnalyzer(testDocument); QVERIFY(isAPassThroughToLibClangAction(analyzer.completionAction())); }
/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms and ** conditions see http://www.qt.io/terms-conditions. For further information ** use the contact form at http://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, The Qt Company gives you certain additional ** rights. These rights are described in The Qt Company LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "clangcompletioncontextanalyzertest.h" #include <clangcodemodel/clangcompletioncontextanalyzer.h> #include <texteditor/codeassist/assistinterface.h> #include <utils/qtcassert.h> #include <QDebug> #include <QTest> #include <QTextDocument> using namespace CPlusPlus; using namespace ClangCodeModel; using namespace ClangCodeModel::Internal; using namespace ClangCodeModel::Internal::Tests; Q_DECLARE_METATYPE(ClangCodeModel::Internal::ClangCompletionContextAnalyzer::CompletionAction) QT_BEGIN_NAMESPACE namespace QTest { template<> char *toString(const ClangCompletionContextAnalyzer::CompletionAction &action) { using CCA = ClangCompletionContextAnalyzer; switch (action) { case CCA::PassThroughToLibClang: return qstrdup("PassThroughToLibClang"); case CCA::PassThroughToLibClangAfterLeftParen: return qstrdup("PassThroughToLibClangAfterLeftParen"); case CCA::CompleteDoxygenKeyword: return qstrdup("CompleteDoxygenKeyword"); case CCA::CompleteIncludePath: return qstrdup("CompleteIncludePath"); case CCA::CompletePreprocessorDirective: return qstrdup("CompletePreprocessorDirective"); case CCA::CompleteSignal: return qstrdup("CompleteSignal"); case CCA::CompleteSlot: return qstrdup("CompleteSlot"); } return qstrdup("Unexpected Value"); } } // namespace QTest QT_END_NAMESPACE namespace { typedef QByteArray _; class DummyAssistInterface : public TextEditor::AssistInterface { public: DummyAssistInterface(const QByteArray &text, int position) : AssistInterface(new QTextDocument(QString::fromUtf8(text)), position, QLatin1String("<testdocument>"), TextEditor::ActivationCharacter) {} ~DummyAssistInterface() { delete textDocument(); } }; class TestDocument { public: TestDocument(const QByteArray &theSource) : source(theSource) , position(theSource.lastIndexOf('@')) // Use 'lastIndexOf' due to doxygen: "//! @keyword" { QTC_CHECK(position != -1); source.remove(position, 1); } QByteArray source; int position; }; bool isAPassThroughToLibClangAction(ClangCompletionContextAnalyzer::CompletionAction action) { return action == ClangCompletionContextAnalyzer::PassThroughToLibClang || action == ClangCompletionContextAnalyzer::PassThroughToLibClangAfterLeftParen; } ClangCompletionContextAnalyzer runAnalyzer(const TestDocument &testDocument) { DummyAssistInterface assistInterface(testDocument.source, testDocument.position); ClangCompletionContextAnalyzer analyzer(&assistInterface, LanguageFeatures::defaultFeatures()); analyzer.analyze(); return analyzer; } } // anonymous namespace void ClangCompletionContextAnalyzerTest::testPassThroughToClangAndSignalSlotRecognition_data() { QTest::addColumn<QByteArray>("givenSource"); QTest::addColumn<ClangCompletionContextAnalyzer::CompletionAction>("expectedCompletionAction"); QTest::addColumn<int>("expectedDiffBetweenCursorAndCalculatedClangPosition"); QTest::addColumn<int>("expectedDiffBetweenCursorAndCalculatedProposalPosition"); using CCA = ClangCompletionContextAnalyzer; QTest::newRow("members - dot 1") << _("o.mem@") << CCA::PassThroughToLibClang << -3 << -3; QTest::newRow("members - dot 2") << _("o. mem@") << CCA::PassThroughToLibClang << -4 << -3; QTest::newRow("members - dot 3") << _("o.@mem") << CCA::PassThroughToLibClang << 0 << 0; QTest::newRow("members - dot 4") << _("o. @ mem") << CCA::PassThroughToLibClang << -1 << 0; QTest::newRow("members - arrow 1") << _("o->mem@") << CCA::PassThroughToLibClang << -3 << -3; QTest::newRow("members - arrow 2") << _("o-> mem@") << CCA::PassThroughToLibClang << -4 << -3; QTest::newRow("members - arrow 3") << _("o->@mem") << CCA::PassThroughToLibClang << 0 << 0; QTest::newRow("members - arrow 4") << _("o-> @ mem") << CCA::PassThroughToLibClang << -1 << 0; QTest::newRow("call 1") << _("f(@") << CCA::PassThroughToLibClangAfterLeftParen << -2 << 0; QTest::newRow("call 2") << _("f(1,@") << CCA::PassThroughToLibClangAfterLeftParen << -4 << -2; QTest::newRow("call 3") << _("f(1, @") << CCA::PassThroughToLibClang << -1 << 0; QTest::newRow("qt4 signals 1") << _("SIGNAL(@") << CCA::CompleteSignal << 0 << 0; QTest::newRow("qt4 signals 2") << _("SIGNAL(foo@") << CCA::CompleteSignal << -3 << -3; QTest::newRow("qt4 slots 1") << _("SLOT(@") << CCA::CompleteSlot << 0 << 0; QTest::newRow("qt4 slots 2") << _("SLOT(foo@") << CCA::CompleteSlot << -3 << -3; } void ClangCompletionContextAnalyzerTest::testPassThroughToClangAndSignalSlotRecognition() { QFETCH(QByteArray, givenSource); QFETCH(ClangCompletionContextAnalyzer::CompletionAction, expectedCompletionAction); QFETCH(int, expectedDiffBetweenCursorAndCalculatedClangPosition); QFETCH(int, expectedDiffBetweenCursorAndCalculatedProposalPosition); const TestDocument testDocument(givenSource); ClangCompletionContextAnalyzer analyzer = runAnalyzer(testDocument); QCOMPARE(analyzer.completionAction(), expectedCompletionAction); QCOMPARE(analyzer.positionForClang() - testDocument.position, expectedDiffBetweenCursorAndCalculatedClangPosition); QCOMPARE(analyzer.positionForProposal() - testDocument.position, expectedDiffBetweenCursorAndCalculatedProposalPosition); } void ClangCompletionContextAnalyzerTest::testSpecialCompletionRecognition_data() { QTest::addColumn<QByteArray>("givenSource"); QTest::addColumn<ClangCompletionContextAnalyzer::CompletionAction>("expectedCompletionAction"); QTest::addColumn<int>("expectedDiffBetweenCursorAndCalculatedProposalPosition"); using CCA = ClangCompletionContextAnalyzer; QTest::newRow("doxygen keywords 1") << _("//! \\@") << CCA::CompleteDoxygenKeyword << 0; QTest::newRow("doxygen keywords 3") << _("//! @@") << CCA::CompleteDoxygenKeyword << 0; QTest::newRow("doxygen keywords 2") << _("//! \\par@") << CCA::CompleteDoxygenKeyword << -3; QTest::newRow("pp directives 1") << _("#@") << CCA::CompletePreprocessorDirective << 0; QTest::newRow("pp directives 2") << _("#if@") << CCA::CompletePreprocessorDirective << -2; QTest::newRow("pp include path 1") << _("#include \"foo@\"") << CCA::CompleteIncludePath << -3; QTest::newRow("pp include path 2") << _("#include <foo@>") << CCA::CompleteIncludePath << -3; QTest::newRow("pp include path 3") << _("#include <foo/@>") << CCA::CompleteIncludePath << 0; } void ClangCompletionContextAnalyzerTest::testSpecialCompletionRecognition() { QFETCH(QByteArray, givenSource); QFETCH(ClangCompletionContextAnalyzer::CompletionAction, expectedCompletionAction); QFETCH(int, expectedDiffBetweenCursorAndCalculatedProposalPosition); const TestDocument testDocument(givenSource); ClangCompletionContextAnalyzer analyzer = runAnalyzer(testDocument); QCOMPARE(analyzer.completionAction(), expectedCompletionAction); QCOMPARE(analyzer.positionForClang(), -1); QCOMPARE(analyzer.positionForProposal() - testDocument.position, expectedDiffBetweenCursorAndCalculatedProposalPosition); } void ClangCompletionContextAnalyzerTest::testAvoidSpecialCompletionRecognition_data() { QTest::addColumn<QByteArray>("givenSource"); QTest::newRow("no special completion for literals 1") << _("\"@"); QTest::newRow("no special completion for literals 2") << _(" \"@"); QTest::newRow("no special completion for literals 3") << _("\"text\"@"); QTest::newRow("no special completion for literals 4") << _("\"hello cruel@ world\""); QTest::newRow("no special completion for literals 5") << _("'@'"); QTest::newRow("no special completion for literals 6") << _("'a@'"); QTest::newRow("no special completion for comma operator") << _("a = b,@\""); QTest::newRow("no special completion for doxygen marker not in doxygen comment 1") << _("@@"); QTest::newRow("no special completion for doxygen marker not in doxygen comment 2") << _("\\@"); QTest::newRow("no special completion in comments 1") << _("// text@"); QTest::newRow("no special completion in comments 2") << _("/* text@ */"); QTest::newRow("no special completion for slash") << _("5 /@"); QTest::newRow("no special completion for '(' 1") << _("(@"); QTest::newRow("no special completion for '(' 2") << _("((@"); QTest::newRow("no special completion for '(' 3") << _("*(@"); } void ClangCompletionContextAnalyzerTest::testAvoidSpecialCompletionRecognition() { QFETCH(QByteArray, givenSource); const TestDocument testDocument(givenSource); ClangCompletionContextAnalyzer analyzer = runAnalyzer(testDocument); QVERIFY(isAPassThroughToLibClangAction(analyzer.completionAction())); }
Fix build with namespaced Qt.
ClangCodeModel: Fix build with namespaced Qt. Change-Id: I8a8e92e9bbd441bac1b305248034f31e7a2ad5d7 Reviewed-by: hjk <[email protected]> Reviewed-by: Christian Stenger <[email protected]>
C++
lgpl-2.1
xianian/qt-creator,xianian/qt-creator,martyone/sailfish-qtcreator,martyone/sailfish-qtcreator,xianian/qt-creator,martyone/sailfish-qtcreator,xianian/qt-creator,martyone/sailfish-qtcreator,martyone/sailfish-qtcreator,xianian/qt-creator,xianian/qt-creator,martyone/sailfish-qtcreator,xianian/qt-creator,martyone/sailfish-qtcreator,xianian/qt-creator,martyone/sailfish-qtcreator,martyone/sailfish-qtcreator,xianian/qt-creator
d6a94b0dc002966753225cc1eeca13cf173f9c83
src/plugins/qmldesigner/components/importmanager/importmanagerview.cpp
src/plugins/qmldesigner/components/importmanager/importmanagerview.cpp
/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** 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. ** ****************************************************************************/ #include "importmanagerview.h" #include "importswidget.h" namespace QmlDesigner { ImportManagerView::ImportManagerView(QObject *parent) : AbstractView(parent), m_importsWidget(0) { } ImportManagerView::~ImportManagerView() { } bool ImportManagerView::hasWidget() const { return true; } WidgetInfo ImportManagerView::widgetInfo() { if (m_importsWidget == 0) { m_importsWidget = new ImportsWidget; connect(m_importsWidget, SIGNAL(removeImport(Import)), this, SLOT(removeImport(Import))); connect(m_importsWidget, SIGNAL(addImport(Import)), this, SLOT(addImport(Import))); if (model()) m_importsWidget->setImports(model()->imports()); } return createWidgetInfo(m_importsWidget, 0, "ImportManager", WidgetInfo::LeftPane, 1); } void ImportManagerView::modelAttached(Model *model) { AbstractView::modelAttached(model); if (m_importsWidget) { m_importsWidget->setImports(model->imports()); m_importsWidget->setPossibleImports(model->possibleImports()); m_importsWidget->setUsedImports(model->usedImports()); } } void ImportManagerView::modelAboutToBeDetached(Model *model) { if (m_importsWidget) { m_importsWidget->removeImports(); m_importsWidget->removePossibleImports(); m_importsWidget->removeUsedImports(); } AbstractView::modelAboutToBeDetached(model); } void ImportManagerView::nodeCreated(const ModelNode &createdNode) { if (m_importsWidget) m_importsWidget->setUsedImports(model()->usedImports()); } void ImportManagerView::nodeAboutToBeRemoved(const ModelNode &removedNode) { if (m_importsWidget) m_importsWidget->setUsedImports(model()->usedImports()); } void ImportManagerView::nodeRemoved(const ModelNode &/*removedNode*/, const NodeAbstractProperty &/*parentProperty*/, AbstractView::PropertyChangeFlags /*propertyChange*/) { } void ImportManagerView::nodeAboutToBeReparented(const ModelNode &/*node*/, const NodeAbstractProperty &/*newPropertyParent*/, const NodeAbstractProperty &/*oldPropertyParent*/, AbstractView::PropertyChangeFlags /*propertyChange*/) { } void ImportManagerView::nodeReparented(const ModelNode &/*node*/, const NodeAbstractProperty &/*newPropertyParent*/, const NodeAbstractProperty &/*oldPropertyParent*/, AbstractView::PropertyChangeFlags /*propertyChange*/) { } void ImportManagerView::nodeIdChanged(const ModelNode &/*node*/, const QString &/*newId*/, const QString &/*oldId*/) { } void ImportManagerView::propertiesAboutToBeRemoved(const QList<AbstractProperty> &/*propertyList*/) { } void ImportManagerView::propertiesRemoved(const QList<AbstractProperty> &/*propertyList*/) { } void ImportManagerView::variantPropertiesChanged(const QList<VariantProperty> &/*propertyList*/, AbstractView::PropertyChangeFlags /*propertyChange*/) { } void ImportManagerView::bindingPropertiesChanged(const QList<BindingProperty> &/*propertyList*/, AbstractView::PropertyChangeFlags /*propertyChange*/) { } void ImportManagerView::signalHandlerPropertiesChanged(const QVector<SignalHandlerProperty> &/*propertyList*/, AbstractView::PropertyChangeFlags /*propertyChange*/) { } void ImportManagerView::rootNodeTypeChanged(const QString &/*type*/, int /*majorVersion*/, int /*minorVersion*/) { } void ImportManagerView::instancePropertyChange(const QList<QPair<ModelNode, PropertyName> > &/*propertyList*/) { } void ImportManagerView::instancesCompleted(const QVector<ModelNode> &/*completedNodeList*/) { } void ImportManagerView::instanceInformationsChange(const QMultiHash<ModelNode, InformationName> &/*informationChangeHash*/) { } void ImportManagerView::instancesRenderImageChanged(const QVector<ModelNode> &/*nodeList*/) { } void ImportManagerView::instancesPreviewImageChanged(const QVector<ModelNode> &/*nodeList*/) { } void ImportManagerView::instancesChildrenChanged(const QVector<ModelNode> &/*nodeList*/) { } void ImportManagerView::instancesToken(const QString &/*tokenName*/, int /*tokenNumber*/, const QVector<ModelNode> &/*nodeVector*/) { } void ImportManagerView::nodeSourceChanged(const ModelNode &/*modelNode*/, const QString &/*newNodeSource*/) { } void ImportManagerView::rewriterBeginTransaction() { } void ImportManagerView::rewriterEndTransaction() { } void ImportManagerView::currentStateChanged(const ModelNode &/*node*/) { } void ImportManagerView::selectedNodesChanged(const QList<ModelNode> &/*selectedNodeList*/, const QList<ModelNode> &/*lastSelectedNodeList*/) { } void ImportManagerView::fileUrlChanged(const QUrl &/*oldUrl*/, const QUrl &/*newUrl*/) { } void ImportManagerView::nodeOrderChanged(const NodeListProperty &/*listProperty*/, const ModelNode &/*movedNode*/, int /*oldIndex*/) { } void ImportManagerView::importsChanged(const QList<Import> &addedImports, const QList<Import> &removedImports) { if (m_importsWidget) { m_importsWidget->setImports(model()->imports()); m_importsWidget->setPossibleImports(model()->possibleImports()); m_importsWidget->setUsedImports(model()->usedImports()); } } void ImportManagerView::auxiliaryDataChanged(const ModelNode &/*node*/, const PropertyName &/*name*/, const QVariant &/*data*/) { } void ImportManagerView::customNotification(const AbstractView */*view*/, const QString &/*identifier*/, const QList<ModelNode> &/*nodeList*/, const QList<QVariant> &/*data*/) { } void ImportManagerView::scriptFunctionsChanged(const ModelNode &/*node*/, const QStringList &/*scriptFunctionList*/) { } void ImportManagerView::removeImport(const Import &import) { if (model()) model()->changeImports(QList<Import>(), QList<Import>() << import); } void ImportManagerView::addImport(const Import &import) { if (model()) model()->changeImports(QList<Import>() << import, QList<Import>()); } } // namespace QmlDesigner
/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** 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. ** ****************************************************************************/ #include "importmanagerview.h" #include "importswidget.h" namespace QmlDesigner { ImportManagerView::ImportManagerView(QObject *parent) : AbstractView(parent), m_importsWidget(0) { } ImportManagerView::~ImportManagerView() { } bool ImportManagerView::hasWidget() const { return true; } WidgetInfo ImportManagerView::widgetInfo() { if (m_importsWidget == 0) { m_importsWidget = new ImportsWidget; connect(m_importsWidget, SIGNAL(removeImport(Import)), this, SLOT(removeImport(Import))); connect(m_importsWidget, SIGNAL(addImport(Import)), this, SLOT(addImport(Import))); if (model()) m_importsWidget->setImports(model()->imports()); } return createWidgetInfo(m_importsWidget, 0, "ImportManager", WidgetInfo::LeftPane, 1); } void ImportManagerView::modelAttached(Model *model) { AbstractView::modelAttached(model); if (m_importsWidget) { m_importsWidget->setImports(model->imports()); m_importsWidget->setPossibleImports(model->possibleImports()); m_importsWidget->setUsedImports(model->usedImports()); } } void ImportManagerView::modelAboutToBeDetached(Model *model) { if (m_importsWidget) { m_importsWidget->removeImports(); m_importsWidget->removePossibleImports(); m_importsWidget->removeUsedImports(); } AbstractView::modelAboutToBeDetached(model); } void ImportManagerView::nodeCreated(const ModelNode &/*createdNode*/) { if (m_importsWidget) m_importsWidget->setUsedImports(model()->usedImports()); } void ImportManagerView::nodeAboutToBeRemoved(const ModelNode &/*removedNode*/) { if (m_importsWidget) m_importsWidget->setUsedImports(model()->usedImports()); } void ImportManagerView::nodeRemoved(const ModelNode &/*removedNode*/, const NodeAbstractProperty &/*parentProperty*/, AbstractView::PropertyChangeFlags /*propertyChange*/) { } void ImportManagerView::nodeAboutToBeReparented(const ModelNode &/*node*/, const NodeAbstractProperty &/*newPropertyParent*/, const NodeAbstractProperty &/*oldPropertyParent*/, AbstractView::PropertyChangeFlags /*propertyChange*/) { } void ImportManagerView::nodeReparented(const ModelNode &/*node*/, const NodeAbstractProperty &/*newPropertyParent*/, const NodeAbstractProperty &/*oldPropertyParent*/, AbstractView::PropertyChangeFlags /*propertyChange*/) { } void ImportManagerView::nodeIdChanged(const ModelNode &/*node*/, const QString &/*newId*/, const QString &/*oldId*/) { } void ImportManagerView::propertiesAboutToBeRemoved(const QList<AbstractProperty> &/*propertyList*/) { } void ImportManagerView::propertiesRemoved(const QList<AbstractProperty> &/*propertyList*/) { } void ImportManagerView::variantPropertiesChanged(const QList<VariantProperty> &/*propertyList*/, AbstractView::PropertyChangeFlags /*propertyChange*/) { } void ImportManagerView::bindingPropertiesChanged(const QList<BindingProperty> &/*propertyList*/, AbstractView::PropertyChangeFlags /*propertyChange*/) { } void ImportManagerView::signalHandlerPropertiesChanged(const QVector<SignalHandlerProperty> &/*propertyList*/, AbstractView::PropertyChangeFlags /*propertyChange*/) { } void ImportManagerView::rootNodeTypeChanged(const QString &/*type*/, int /*majorVersion*/, int /*minorVersion*/) { } void ImportManagerView::instancePropertyChange(const QList<QPair<ModelNode, PropertyName> > &/*propertyList*/) { } void ImportManagerView::instancesCompleted(const QVector<ModelNode> &/*completedNodeList*/) { } void ImportManagerView::instanceInformationsChange(const QMultiHash<ModelNode, InformationName> &/*informationChangeHash*/) { } void ImportManagerView::instancesRenderImageChanged(const QVector<ModelNode> &/*nodeList*/) { } void ImportManagerView::instancesPreviewImageChanged(const QVector<ModelNode> &/*nodeList*/) { } void ImportManagerView::instancesChildrenChanged(const QVector<ModelNode> &/*nodeList*/) { } void ImportManagerView::instancesToken(const QString &/*tokenName*/, int /*tokenNumber*/, const QVector<ModelNode> &/*nodeVector*/) { } void ImportManagerView::nodeSourceChanged(const ModelNode &/*modelNode*/, const QString &/*newNodeSource*/) { } void ImportManagerView::rewriterBeginTransaction() { } void ImportManagerView::rewriterEndTransaction() { } void ImportManagerView::currentStateChanged(const ModelNode &/*node*/) { } void ImportManagerView::selectedNodesChanged(const QList<ModelNode> &/*selectedNodeList*/, const QList<ModelNode> &/*lastSelectedNodeList*/) { } void ImportManagerView::fileUrlChanged(const QUrl &/*oldUrl*/, const QUrl &/*newUrl*/) { } void ImportManagerView::nodeOrderChanged(const NodeListProperty &/*listProperty*/, const ModelNode &/*movedNode*/, int /*oldIndex*/) { } void ImportManagerView::importsChanged(const QList<Import> &/*addedImports*/, const QList<Import> &/*removedImports*/) { if (m_importsWidget) { m_importsWidget->setImports(model()->imports()); m_importsWidget->setPossibleImports(model()->possibleImports()); m_importsWidget->setUsedImports(model()->usedImports()); } } void ImportManagerView::auxiliaryDataChanged(const ModelNode &/*node*/, const PropertyName &/*name*/, const QVariant &/*data*/) { } void ImportManagerView::customNotification(const AbstractView */*view*/, const QString &/*identifier*/, const QList<ModelNode> &/*nodeList*/, const QList<QVariant> &/*data*/) { } void ImportManagerView::scriptFunctionsChanged(const ModelNode &/*node*/, const QStringList &/*scriptFunctionList*/) { } void ImportManagerView::removeImport(const Import &import) { if (model()) model()->changeImports(QList<Import>(), QList<Import>() << import); } void ImportManagerView::addImport(const Import &import) { if (model()) model()->changeImports(QList<Import>() << import, QList<Import>()); } } // namespace QmlDesigner
Fix warning in ImportManager
QmlDesigner: Fix warning in ImportManager Change-Id: I3c392ad333b9a7720495073fb8549996c6f1842d Reviewed-by: Marco Bubke <[email protected]>
C++
lgpl-2.1
martyone/sailfish-qtcreator,AltarBeastiful/qt-creator,amyvmiwei/qt-creator,AltarBeastiful/qt-creator,omniacreator/qtcreator,farseerri/git_code,amyvmiwei/qt-creator,danimo/qt-creator,omniacreator/qtcreator,xianian/qt-creator,martyone/sailfish-qtcreator,martyone/sailfish-qtcreator,farseerri/git_code,maui-packages/qt-creator,maui-packages/qt-creator,darksylinc/qt-creator,danimo/qt-creator,danimo/qt-creator,darksylinc/qt-creator,Distrotech/qtcreator,AltarBeastiful/qt-creator,kuba1/qtcreator,Distrotech/qtcreator,omniacreator/qtcreator,farseerri/git_code,martyone/sailfish-qtcreator,maui-packages/qt-creator,amyvmiwei/qt-creator,omniacreator/qtcreator,xianian/qt-creator,AltarBeastiful/qt-creator,xianian/qt-creator,maui-packages/qt-creator,colede/qtcreator,richardmg/qtcreator,AltarBeastiful/qt-creator,xianian/qt-creator,darksylinc/qt-creator,Distrotech/qtcreator,farseerri/git_code,martyone/sailfish-qtcreator,danimo/qt-creator,richardmg/qtcreator,Distrotech/qtcreator,richardmg/qtcreator,kuba1/qtcreator,darksylinc/qt-creator,martyone/sailfish-qtcreator,danimo/qt-creator,xianian/qt-creator,martyone/sailfish-qtcreator,richardmg/qtcreator,danimo/qt-creator,kuba1/qtcreator,amyvmiwei/qt-creator,maui-packages/qt-creator,farseerri/git_code,darksylinc/qt-creator,amyvmiwei/qt-creator,colede/qtcreator,martyone/sailfish-qtcreator,colede/qtcreator,danimo/qt-creator,xianian/qt-creator,AltarBeastiful/qt-creator,kuba1/qtcreator,kuba1/qtcreator,farseerri/git_code,Distrotech/qtcreator,darksylinc/qt-creator,kuba1/qtcreator,farseerri/git_code,danimo/qt-creator,xianian/qt-creator,Distrotech/qtcreator,Distrotech/qtcreator,danimo/qt-creator,AltarBeastiful/qt-creator,colede/qtcreator,amyvmiwei/qt-creator,martyone/sailfish-qtcreator,kuba1/qtcreator,richardmg/qtcreator,xianian/qt-creator,darksylinc/qt-creator,farseerri/git_code,colede/qtcreator,maui-packages/qt-creator,richardmg/qtcreator,omniacreator/qtcreator,omniacreator/qtcreator,colede/qtcreator,colede/qtcreator,maui-packages/qt-creator,amyvmiwei/qt-creator,kuba1/qtcreator,omniacreator/qtcreator,richardmg/qtcreator,darksylinc/qt-creator,AltarBeastiful/qt-creator,kuba1/qtcreator,xianian/qt-creator,amyvmiwei/qt-creator
9a8f5383d5fe5570331711966b8a7c5f2b83fa65
src/plugins/qmldesigner/designercore/model/rewriteactioncompressor.cpp
src/plugins/qmldesigner/designercore/model/rewriteactioncompressor.cpp
/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** 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. ** ****************************************************************************/ #include "rewriteactioncompressor.h" #include <QSet> #include "modelnode.h" #include "nodelistproperty.h" #include "qmltextgenerator.h" using namespace QmlDesigner; using namespace QmlDesigner::Internal; static bool nodeOrParentInSet(const ModelNode &node, const QSet<ModelNode> &nodeSet) { ModelNode n = node; while (n.isValid()) { if (nodeSet.contains(n)) return true; if (!n.hasParentProperty()) return false; n = n.parentProperty().parentModelNode(); } return false; } void RewriteActionCompressor::operator()(QList<RewriteAction *> &actions) const { compressImports(actions); compressRereparentActions(actions); compressReparentIntoSamePropertyActions(actions); compressPropertyActions(actions); compressAddEditRemoveNodeActions(actions); compressAddEditActions(actions); compressAddReparentActions(actions); } void RewriteActionCompressor::compressImports(QList<RewriteAction *> &actions) const { QList<RewriteAction *> actionsToRemove; QHash<Import, RewriteAction *> addedImports; QHash<Import, RewriteAction *> removedImports; QMutableListIterator<RewriteAction *> iter(actions); iter.toBack(); while (iter.hasPrevious()) { RewriteAction *action = iter.previous(); if (RemoveImportRewriteAction *removeImportAction = action->asRemoveImportRewriteAction()) { const Import import = removeImportAction->import(); if (removedImports.contains(import)) { actionsToRemove.append(action); } else if (RewriteAction *addImportAction = addedImports.value(import, 0)) { actionsToRemove.append(action); actionsToRemove.append(addImportAction); addedImports.remove(import); delete addImportAction; } else { removedImports.insert(import, action); } } else if (AddImportRewriteAction *addImportAction = action->asAddImportRewriteAction()) { const Import import = addImportAction->import(); if (RewriteAction *duplicateAction = addedImports.value(import, 0)) { actionsToRemove.append(duplicateAction); addedImports.remove(import); delete duplicateAction; addedImports.insert(import, action); } else if (RewriteAction *removeAction = removedImports.value(import, 0)) { actionsToRemove.append(action); actionsToRemove.append(removeAction); removedImports.remove(import); delete removeAction; } else { addedImports.insert(import, action); } } } foreach (RewriteAction *action, actionsToRemove) { actions.removeOne(action); delete action; } } void RewriteActionCompressor::compressRereparentActions(QList<RewriteAction *> &actions) const { QList<RewriteAction *> actionsToRemove; QHash<ModelNode, ReparentNodeRewriteAction *> reparentedNodes; QMutableListIterator<RewriteAction*> iter(actions); iter.toBack(); while (iter.hasPrevious()) { RewriteAction *action = iter.previous(); if (ReparentNodeRewriteAction *reparentAction = action->asReparentNodeRewriteAction()) { const ModelNode reparentedNode = reparentAction->reparentedNode(); if (ReparentNodeRewriteAction *otherAction = reparentedNodes.value(reparentedNode, 0)) { otherAction->setOldParentProperty(reparentAction->oldParentProperty()); actionsToRemove.append(action); } else { reparentedNodes.insert(reparentedNode, reparentAction); } } } foreach (RewriteAction *action, actionsToRemove) { actions.removeOne(action); delete action; } } void RewriteActionCompressor::compressReparentIntoSamePropertyActions(QList<RewriteAction *> &actions) const { QList<RewriteAction *> actionsToRemove; QMutableListIterator<RewriteAction *> iter(actions); iter.toBack(); while (iter.hasPrevious()) { RewriteAction *action = iter.previous(); if (ReparentNodeRewriteAction *reparentAction = action->asReparentNodeRewriteAction()) { if (reparentAction->targetProperty() == reparentAction->oldParentProperty()) actionsToRemove.append(action); } } foreach (RewriteAction *action, actionsToRemove) { actions.removeOne(action); delete action; } } void RewriteActionCompressor::compressAddEditRemoveNodeActions(QList<RewriteAction *> &actions) const { QList<RewriteAction *> actionsToRemove; QHash<ModelNode, RewriteAction *> removedNodes; QMutableListIterator<RewriteAction*> iter(actions); iter.toBack(); while (iter.hasPrevious()) { RewriteAction *action = iter.previous(); if (RemoveNodeRewriteAction *removeNodeAction = action->asRemoveNodeRewriteAction()) { const ModelNode modelNode = removeNodeAction->node(); if (removedNodes.contains(modelNode)) actionsToRemove.append(action); else removedNodes.insert(modelNode, action); } else if (action->asAddPropertyRewriteAction() || action->asChangePropertyRewriteAction()) { AbstractProperty property; ModelNode containedModelNode; if (action->asAddPropertyRewriteAction()) { property = action->asAddPropertyRewriteAction()->property(); containedModelNode = action->asAddPropertyRewriteAction()->containedModelNode(); } else { property = action->asChangePropertyRewriteAction()->property(); containedModelNode = action->asChangePropertyRewriteAction()->containedModelNode(); } if (removedNodes.contains(property.parentModelNode())) { actionsToRemove.append(action); } else if (RewriteAction *removeAction = removedNodes.value(containedModelNode, 0)) { actionsToRemove.append(action); actionsToRemove.append(removeAction); } } else if (RemovePropertyRewriteAction *removePropertyAction = action->asRemovePropertyRewriteAction()) { const AbstractProperty property = removePropertyAction->property(); if (removedNodes.contains(property.parentModelNode())) actionsToRemove.append(action); } else if (ChangeIdRewriteAction *changeIdAction = action->asChangeIdRewriteAction()) { if (removedNodes.contains(changeIdAction->node())) actionsToRemove.append(action); } else if (ChangeTypeRewriteAction *changeTypeAction = action->asChangeTypeRewriteAction()) { if (removedNodes.contains(changeTypeAction->node())) actionsToRemove.append(action); } else if (ReparentNodeRewriteAction *reparentAction = action->asReparentNodeRewriteAction()) { if (removedNodes.contains(reparentAction->reparentedNode())) actionsToRemove.append(action); } } foreach (RewriteAction *action, actionsToRemove) { actions.removeOne(action); delete action; } } void RewriteActionCompressor::compressPropertyActions(QList<RewriteAction *> &actions) const { QList<RewriteAction *> actionsToRemove; QHash<AbstractProperty, RewriteAction *> removedProperties; QHash<AbstractProperty, ChangePropertyRewriteAction *> changedProperties; QHash<AbstractProperty, AddPropertyRewriteAction *> addedProperties; QMutableListIterator<RewriteAction*> iter(actions); iter.toBack(); while (iter.hasPrevious()) { RewriteAction *action = iter.previous(); if (RemovePropertyRewriteAction *removeAction = action->asRemovePropertyRewriteAction()) { const AbstractProperty property = removeAction->property(); if (AddPropertyRewriteAction *addAction = addedProperties.value(property, 0)) { Q_UNUSED(addAction); } else { removedProperties.insert(property, action); } } else if (ChangePropertyRewriteAction *changeAction = action->asChangePropertyRewriteAction()) { const AbstractProperty property = changeAction->property(); if (removedProperties.contains(property)) { actionsToRemove.append(action); } else if (changedProperties.contains(property)) { if (!property.isValid() || !property.isDefaultProperty()) actionsToRemove.append(action); } else { changedProperties.insert(property, changeAction); } } else if (AddPropertyRewriteAction *addAction = action->asAddPropertyRewriteAction()) { const AbstractProperty property = addAction->property(); if (RewriteAction *removeAction = removedProperties.value(property, 0)) { actionsToRemove.append(action); actionsToRemove.append(removeAction); removedProperties.remove(property); } else { if (changedProperties.contains(property)) changedProperties.remove(property); addedProperties.insert(property, addAction); } } } foreach (RewriteAction *action, actionsToRemove){ actions.removeOne(action); delete action; } } void RewriteActionCompressor::compressAddEditActions(QList<RewriteAction *> &actions) const { QList<RewriteAction *> actionsToRemove; QSet<ModelNode> addedNodes; QSet<RewriteAction *> dirtyActions; QMutableListIterator<RewriteAction*> iter(actions); while (iter.hasNext()) { RewriteAction *action = iter.next(); if (action->asAddPropertyRewriteAction() || action->asChangePropertyRewriteAction()) { AbstractProperty property; ModelNode containedNode; if (AddPropertyRewriteAction *addAction = action->asAddPropertyRewriteAction()) { property = addAction->property(); containedNode = addAction->containedModelNode(); } else if (ChangePropertyRewriteAction *changeAction = action->asChangePropertyRewriteAction()) { property = changeAction->property(); containedNode = changeAction->containedModelNode(); } if (property.isValid() && addedNodes.contains(property.parentModelNode())) { actionsToRemove.append(action); continue; } if (!containedNode.isValid()) continue; if (nodeOrParentInSet(containedNode, addedNodes)) { actionsToRemove.append(action); } else { addedNodes.insert(containedNode); dirtyActions.insert(action); } } else if (ChangeIdRewriteAction *changeIdAction = action->asChangeIdRewriteAction()) { if (nodeOrParentInSet(changeIdAction->node(), addedNodes)) actionsToRemove.append(action); } else if (ChangeTypeRewriteAction *changeTypeAction = action->asChangeTypeRewriteAction()) { if (nodeOrParentInSet(changeTypeAction->node(), addedNodes)) actionsToRemove.append(action); } } foreach (RewriteAction *action, actionsToRemove){ actions.removeOne(action); delete action; } QmlTextGenerator gen(m_propertyOrder); foreach (RewriteAction *action, dirtyActions) { RewriteAction *newAction = 0; if (AddPropertyRewriteAction *addAction = action->asAddPropertyRewriteAction()) { newAction = new AddPropertyRewriteAction(addAction->property(), gen(addAction->containedModelNode()), addAction->propertyType(), addAction->containedModelNode()); } else if (ChangePropertyRewriteAction *changeAction = action->asChangePropertyRewriteAction()) { newAction = new ChangePropertyRewriteAction(changeAction->property(), gen(changeAction->containedModelNode()), changeAction->propertyType(), changeAction->containedModelNode()); } const int idx = actions.indexOf(action); if (newAction && idx >= 0) actions[idx] = newAction; else delete newAction; } } void RewriteActionCompressor::compressAddReparentActions(QList<RewriteAction *> &actions) const { QList<RewriteAction *> actionsToRemove; QMap<ModelNode, RewriteAction*> addedNodes; QMutableListIterator<RewriteAction*> iter(actions); while (iter.hasNext()) { RewriteAction *action = iter.next(); if (action->asAddPropertyRewriteAction() || action->asChangePropertyRewriteAction()) { ModelNode containedNode; if (AddPropertyRewriteAction *addAction = action->asAddPropertyRewriteAction()) containedNode = addAction->containedModelNode(); else if (ChangePropertyRewriteAction *changeAction = action->asChangePropertyRewriteAction()) containedNode = changeAction->containedModelNode(); if (!containedNode.isValid()) continue; addedNodes.insert(containedNode, action); } else if (ReparentNodeRewriteAction *reparentAction = action->asReparentNodeRewriteAction()) { if (addedNodes.contains(reparentAction->reparentedNode())) { RewriteAction *previousAction = addedNodes[reparentAction->reparentedNode()]; actionsToRemove.append(previousAction); RewriteAction *replacementAction = 0; if (AddPropertyRewriteAction *addAction = previousAction->asAddPropertyRewriteAction()) { replacementAction = new AddPropertyRewriteAction(reparentAction->targetProperty(), addAction->valueText(), reparentAction->propertyType(), addAction->containedModelNode()); } else if (ChangePropertyRewriteAction *changeAction = previousAction->asChangePropertyRewriteAction()) { replacementAction = new AddPropertyRewriteAction(reparentAction->targetProperty(), changeAction->valueText(), reparentAction->propertyType(), changeAction->containedModelNode()); } iter.setValue(replacementAction); delete action; } } } foreach (RewriteAction *action, actionsToRemove){ actions.removeOne(action); delete action; } }
/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** 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. ** ****************************************************************************/ #include "rewriteactioncompressor.h" #include <QSet> #include "modelnode.h" #include "nodelistproperty.h" #include "qmltextgenerator.h" using namespace QmlDesigner; using namespace QmlDesigner::Internal; static bool nodeOrParentInSet(const ModelNode &modelNode, const QSet<ModelNode> &nodeSet) { ModelNode currentModelnode = modelNode; while (currentModelnode.isValid()) { if (nodeSet.contains(currentModelnode)) return true; if (!currentModelnode.hasParentProperty()) return false; currentModelnode = currentModelnode.parentProperty().parentModelNode(); } return false; } void RewriteActionCompressor::operator()(QList<RewriteAction *> &actions) const { compressImports(actions); compressRereparentActions(actions); compressReparentIntoSamePropertyActions(actions); compressPropertyActions(actions); compressAddEditRemoveNodeActions(actions); compressAddEditActions(actions); compressAddReparentActions(actions); } void RewriteActionCompressor::compressImports(QList<RewriteAction *> &actions) const { QList<RewriteAction *> actionsToRemove; QHash<Import, RewriteAction *> addedImports; QHash<Import, RewriteAction *> removedImports; QMutableListIterator<RewriteAction *> iter(actions); iter.toBack(); while (iter.hasPrevious()) { RewriteAction *action = iter.previous(); if (RemoveImportRewriteAction *removeImportAction = action->asRemoveImportRewriteAction()) { const Import import = removeImportAction->import(); if (removedImports.contains(import)) { actionsToRemove.append(action); } else if (RewriteAction *addImportAction = addedImports.value(import, 0)) { actionsToRemove.append(action); actionsToRemove.append(addImportAction); addedImports.remove(import); delete addImportAction; } else { removedImports.insert(import, action); } } else if (AddImportRewriteAction *addImportAction = action->asAddImportRewriteAction()) { const Import import = addImportAction->import(); if (RewriteAction *duplicateAction = addedImports.value(import, 0)) { actionsToRemove.append(duplicateAction); addedImports.remove(import); delete duplicateAction; addedImports.insert(import, action); } else if (RewriteAction *removeAction = removedImports.value(import, 0)) { actionsToRemove.append(action); actionsToRemove.append(removeAction); removedImports.remove(import); delete removeAction; } else { addedImports.insert(import, action); } } } foreach (RewriteAction *action, actionsToRemove) { actions.removeOne(action); delete action; } } void RewriteActionCompressor::compressRereparentActions(QList<RewriteAction *> &actions) const { QList<RewriteAction *> actionsToRemove; QHash<ModelNode, ReparentNodeRewriteAction *> reparentedNodes; QMutableListIterator<RewriteAction*> iter(actions); iter.toBack(); while (iter.hasPrevious()) { RewriteAction *action = iter.previous(); if (ReparentNodeRewriteAction *reparentAction = action->asReparentNodeRewriteAction()) { const ModelNode reparentedNode = reparentAction->reparentedNode(); if (ReparentNodeRewriteAction *otherAction = reparentedNodes.value(reparentedNode, 0)) { otherAction->setOldParentProperty(reparentAction->oldParentProperty()); actionsToRemove.append(action); } else { reparentedNodes.insert(reparentedNode, reparentAction); } } } foreach (RewriteAction *action, actionsToRemove) { actions.removeOne(action); delete action; } } void RewriteActionCompressor::compressReparentIntoSamePropertyActions(QList<RewriteAction *> &actions) const { QList<RewriteAction *> actionsToRemove; QMutableListIterator<RewriteAction *> iter(actions); iter.toBack(); while (iter.hasPrevious()) { RewriteAction *action = iter.previous(); if (ReparentNodeRewriteAction *reparentAction = action->asReparentNodeRewriteAction()) { if (reparentAction->targetProperty() == reparentAction->oldParentProperty()) actionsToRemove.append(action); } } foreach (RewriteAction *action, actionsToRemove) { actions.removeOne(action); delete action; } } void RewriteActionCompressor::compressAddEditRemoveNodeActions(QList<RewriteAction *> &actions) const { QList<RewriteAction *> actionsToRemove; QHash<ModelNode, RewriteAction *> removedNodes; QMutableListIterator<RewriteAction*> iter(actions); iter.toBack(); while (iter.hasPrevious()) { RewriteAction *action = iter.previous(); if (RemoveNodeRewriteAction *removeNodeAction = action->asRemoveNodeRewriteAction()) { const ModelNode modelNode = removeNodeAction->node(); if (removedNodes.contains(modelNode)) actionsToRemove.append(action); else removedNodes.insert(modelNode, action); } else if (action->asAddPropertyRewriteAction() || action->asChangePropertyRewriteAction()) { AbstractProperty property; ModelNode containedModelNode; if (action->asAddPropertyRewriteAction()) { property = action->asAddPropertyRewriteAction()->property(); containedModelNode = action->asAddPropertyRewriteAction()->containedModelNode(); } else { property = action->asChangePropertyRewriteAction()->property(); containedModelNode = action->asChangePropertyRewriteAction()->containedModelNode(); } if (removedNodes.contains(property.parentModelNode())) { actionsToRemove.append(action); } else if (RewriteAction *removeAction = removedNodes.value(containedModelNode, 0)) { actionsToRemove.append(action); actionsToRemove.append(removeAction); } } else if (RemovePropertyRewriteAction *removePropertyAction = action->asRemovePropertyRewriteAction()) { const AbstractProperty property = removePropertyAction->property(); if (removedNodes.contains(property.parentModelNode())) actionsToRemove.append(action); } else if (ChangeIdRewriteAction *changeIdAction = action->asChangeIdRewriteAction()) { if (removedNodes.contains(changeIdAction->node())) actionsToRemove.append(action); } else if (ChangeTypeRewriteAction *changeTypeAction = action->asChangeTypeRewriteAction()) { if (removedNodes.contains(changeTypeAction->node())) actionsToRemove.append(action); } else if (ReparentNodeRewriteAction *reparentAction = action->asReparentNodeRewriteAction()) { if (removedNodes.contains(reparentAction->reparentedNode())) actionsToRemove.append(action); } } foreach (RewriteAction *action, actionsToRemove) { actions.removeOne(action); delete action; } } void RewriteActionCompressor::compressPropertyActions(QList<RewriteAction *> &actions) const { QList<RewriteAction *> actionsToRemove; QHash<AbstractProperty, RewriteAction *> removedProperties; QHash<AbstractProperty, ChangePropertyRewriteAction *> changedProperties; QHash<AbstractProperty, AddPropertyRewriteAction *> addedProperties; QMutableListIterator<RewriteAction*> iter(actions); iter.toBack(); while (iter.hasPrevious()) { RewriteAction *action = iter.previous(); if (RemovePropertyRewriteAction *removeAction = action->asRemovePropertyRewriteAction()) { const AbstractProperty property = removeAction->property(); if (AddPropertyRewriteAction *addAction = addedProperties.value(property, 0)) { Q_UNUSED(addAction); } else { removedProperties.insert(property, action); } } else if (ChangePropertyRewriteAction *changeAction = action->asChangePropertyRewriteAction()) { const AbstractProperty property = changeAction->property(); if (removedProperties.contains(property)) { actionsToRemove.append(action); } else if (changedProperties.contains(property)) { if (!property.isValid() || !property.isDefaultProperty()) actionsToRemove.append(action); } else { changedProperties.insert(property, changeAction); } } else if (AddPropertyRewriteAction *addAction = action->asAddPropertyRewriteAction()) { const AbstractProperty property = addAction->property(); if (RewriteAction *removeAction = removedProperties.value(property, 0)) { actionsToRemove.append(action); actionsToRemove.append(removeAction); removedProperties.remove(property); } else { if (changedProperties.contains(property)) changedProperties.remove(property); addedProperties.insert(property, addAction); } } } foreach (RewriteAction *action, actionsToRemove){ actions.removeOne(action); delete action; } } void RewriteActionCompressor::compressAddEditActions(QList<RewriteAction *> &actions) const { QList<RewriteAction *> actionsToRemove; QSet<ModelNode> addedNodes; QSet<RewriteAction *> dirtyActions; QMutableListIterator<RewriteAction*> iter(actions); while (iter.hasNext()) { RewriteAction *action = iter.next(); if (action->asAddPropertyRewriteAction() || action->asChangePropertyRewriteAction()) { AbstractProperty property; ModelNode containedNode; if (AddPropertyRewriteAction *addAction = action->asAddPropertyRewriteAction()) { property = addAction->property(); containedNode = addAction->containedModelNode(); } else if (ChangePropertyRewriteAction *changeAction = action->asChangePropertyRewriteAction()) { property = changeAction->property(); containedNode = changeAction->containedModelNode(); } if (property.isValid() && addedNodes.contains(property.parentModelNode())) { actionsToRemove.append(action); continue; } if (!containedNode.isValid()) continue; if (nodeOrParentInSet(containedNode, addedNodes)) { actionsToRemove.append(action); } else { addedNodes.insert(containedNode); dirtyActions.insert(action); } } else if (ChangeIdRewriteAction *changeIdAction = action->asChangeIdRewriteAction()) { if (nodeOrParentInSet(changeIdAction->node(), addedNodes)) actionsToRemove.append(action); } else if (ChangeTypeRewriteAction *changeTypeAction = action->asChangeTypeRewriteAction()) { if (nodeOrParentInSet(changeTypeAction->node(), addedNodes)) actionsToRemove.append(action); } } foreach (RewriteAction *action, actionsToRemove){ actions.removeOne(action); delete action; } QmlTextGenerator gen(m_propertyOrder); foreach (RewriteAction *action, dirtyActions) { RewriteAction *newAction = 0; if (AddPropertyRewriteAction *addAction = action->asAddPropertyRewriteAction()) { newAction = new AddPropertyRewriteAction(addAction->property(), gen(addAction->containedModelNode()), addAction->propertyType(), addAction->containedModelNode()); } else if (ChangePropertyRewriteAction *changeAction = action->asChangePropertyRewriteAction()) { newAction = new ChangePropertyRewriteAction(changeAction->property(), gen(changeAction->containedModelNode()), changeAction->propertyType(), changeAction->containedModelNode()); } const int idx = actions.indexOf(action); if (newAction && idx >= 0) actions[idx] = newAction; else delete newAction; } } void RewriteActionCompressor::compressAddReparentActions(QList<RewriteAction *> &actions) const { QList<RewriteAction *> actionsToRemove; QMap<ModelNode, RewriteAction*> addedNodes; QMutableListIterator<RewriteAction*> iter(actions); while (iter.hasNext()) { RewriteAction *action = iter.next(); if (action->asAddPropertyRewriteAction() || action->asChangePropertyRewriteAction()) { ModelNode containedNode; if (AddPropertyRewriteAction *addAction = action->asAddPropertyRewriteAction()) containedNode = addAction->containedModelNode(); else if (ChangePropertyRewriteAction *changeAction = action->asChangePropertyRewriteAction()) containedNode = changeAction->containedModelNode(); if (!containedNode.isValid()) continue; addedNodes.insert(containedNode, action); } else if (ReparentNodeRewriteAction *reparentAction = action->asReparentNodeRewriteAction()) { if (addedNodes.contains(reparentAction->reparentedNode())) { RewriteAction *previousAction = addedNodes[reparentAction->reparentedNode()]; actionsToRemove.append(previousAction); RewriteAction *replacementAction = 0; if (AddPropertyRewriteAction *addAction = previousAction->asAddPropertyRewriteAction()) { replacementAction = new AddPropertyRewriteAction(reparentAction->targetProperty(), addAction->valueText(), reparentAction->propertyType(), addAction->containedModelNode()); } else if (ChangePropertyRewriteAction *changeAction = previousAction->asChangePropertyRewriteAction()) { replacementAction = new AddPropertyRewriteAction(reparentAction->targetProperty(), changeAction->valueText(), reparentAction->propertyType(), changeAction->containedModelNode()); } iter.setValue(replacementAction); delete action; } } } foreach (RewriteAction *action, actionsToRemove){ actions.removeOne(action); delete action; } }
Improve short name
QmlDesigner: Improve short name Change-Id: I773964fac0b4981a9d33bc047b8e5e9599c2a3b0 Reviewed-by: Tim Jenssen <[email protected]>
C++
lgpl-2.1
danimo/qt-creator,amyvmiwei/qt-creator,martyone/sailfish-qtcreator,darksylinc/qt-creator,AltarBeastiful/qt-creator,danimo/qt-creator,colede/qtcreator,maui-packages/qt-creator,xianian/qt-creator,omniacreator/qtcreator,darksylinc/qt-creator,darksylinc/qt-creator,amyvmiwei/qt-creator,maui-packages/qt-creator,amyvmiwei/qt-creator,richardmg/qtcreator,farseerri/git_code,maui-packages/qt-creator,danimo/qt-creator,amyvmiwei/qt-creator,maui-packages/qt-creator,omniacreator/qtcreator,danimo/qt-creator,farseerri/git_code,Distrotech/qtcreator,omniacreator/qtcreator,colede/qtcreator,kuba1/qtcreator,Distrotech/qtcreator,amyvmiwei/qt-creator,Distrotech/qtcreator,kuba1/qtcreator,kuba1/qtcreator,omniacreator/qtcreator,richardmg/qtcreator,omniacreator/qtcreator,darksylinc/qt-creator,farseerri/git_code,omniacreator/qtcreator,darksylinc/qt-creator,farseerri/git_code,AltarBeastiful/qt-creator,kuba1/qtcreator,darksylinc/qt-creator,martyone/sailfish-qtcreator,kuba1/qtcreator,colede/qtcreator,colede/qtcreator,kuba1/qtcreator,xianian/qt-creator,AltarBeastiful/qt-creator,maui-packages/qt-creator,richardmg/qtcreator,maui-packages/qt-creator,Distrotech/qtcreator,darksylinc/qt-creator,AltarBeastiful/qt-creator,kuba1/qtcreator,danimo/qt-creator,Distrotech/qtcreator,AltarBeastiful/qt-creator,xianian/qt-creator,richardmg/qtcreator,richardmg/qtcreator,xianian/qt-creator,martyone/sailfish-qtcreator,martyone/sailfish-qtcreator,colede/qtcreator,colede/qtcreator,amyvmiwei/qt-creator,danimo/qt-creator,farseerri/git_code,Distrotech/qtcreator,martyone/sailfish-qtcreator,Distrotech/qtcreator,farseerri/git_code,martyone/sailfish-qtcreator,kuba1/qtcreator,xianian/qt-creator,AltarBeastiful/qt-creator,xianian/qt-creator,farseerri/git_code,danimo/qt-creator,darksylinc/qt-creator,amyvmiwei/qt-creator,xianian/qt-creator,colede/qtcreator,kuba1/qtcreator,maui-packages/qt-creator,martyone/sailfish-qtcreator,xianian/qt-creator,danimo/qt-creator,danimo/qt-creator,xianian/qt-creator,richardmg/qtcreator,AltarBeastiful/qt-creator,farseerri/git_code,AltarBeastiful/qt-creator,omniacreator/qtcreator,martyone/sailfish-qtcreator,richardmg/qtcreator,amyvmiwei/qt-creator,martyone/sailfish-qtcreator
8b10fd58311857f49af0b5d2fbfb298626a9fdeb
platform/shared/common/PosixThreadImpl.cpp
platform/shared/common/PosixThreadImpl.cpp
/*------------------------------------------------------------------------ * (The MIT License) * * Copyright (c) 2008-2011 Rhomobile, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * http://rhomobile.com *------------------------------------------------------------------------*/ #include "common/PosixThreadImpl.h" extern "C" { void* rho_nativethread_start(); void rho_nativethread_end(void*); } namespace rho { namespace common { IMPLEMENT_LOGCLASS(CPosixThreadImpl, "RhoThread"); CPosixThreadImpl::CPosixThreadImpl() :m_stop_wait(false) { #if defined(OS_ANDROID) // Android has no pthread_condattr_xxx API pthread_cond_init(&m_condSync, NULL); #else pthread_condattr_t sync_details; pthread_condattr_init(&sync_details); pthread_cond_init(&m_condSync, &sync_details); pthread_condattr_destroy(&sync_details); #endif } CPosixThreadImpl::~CPosixThreadImpl() { pthread_cond_destroy(&m_condSync); } void *runProc(void *pv) { IRhoRunnable *p = static_cast<IRhoRunnable *>(pv); void *pData = rho_nativethread_start(); p->runObject(); rho_nativethread_end(pData); return 0; } void CPosixThreadImpl::start(IRhoRunnable *pRunnable, IRhoRunnable::EPriority ePriority) { pthread_attr_t attr; int return_val = pthread_attr_init(&attr); //return_val = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); RHO_ASSERT(!return_val); if ( ePriority != IRhoRunnable::epNormal) { sched_param param; return_val = pthread_attr_getschedparam (&attr, &param); param.sched_priority = ePriority == IRhoRunnable::epLow ? 20 : 100; //TODO: sched_priority return_val = pthread_attr_setschedparam (&attr, &param); } #ifdef __SYMBIAN32__ size_t stacksize = 80000; pthread_attr_setstacksize(&attr, stacksize); #endif int thread_error = pthread_create(&m_thread, &attr, &runProc, pRunnable); return_val = pthread_attr_destroy(&attr); RHO_ASSERT(!return_val); RHO_ASSERT(thread_error==0); } void CPosixThreadImpl::stop(unsigned int nTimeoutToKillMs) { stopWait(); //TODO: wait for nTimeoutToKill and kill thread void* status; pthread_join(m_thread,&status); } int CPosixThreadImpl::wait(unsigned int nTimeoutMs) { struct timeval tp; struct timespec ts; unsigned long long max; bool timed_wait = (int)nTimeoutMs >= 0; unsigned int nTimeout = nTimeoutMs/1000; if (timed_wait) { gettimeofday(&tp, NULL); /* Convert from timeval to timespec */ ts.tv_sec = tp.tv_sec; ts.tv_nsec = tp.tv_usec * 1000 + ((unsigned long long)(nTimeoutMs - nTimeout*1000))*1000000; ts.tv_sec += nTimeout; max = ((unsigned long long)tp.tv_sec + nTimeout)*1000000 + tp.tv_usec; } common::CMutexLock oLock(m_mxSync); int nRet = 0; while (!m_stop_wait) { if (timed_wait) { gettimeofday(&tp, NULL); unsigned long long now = ((unsigned long long)tp.tv_sec)*1000000 + tp.tv_usec; if (now > max) break; nRet = pthread_cond_timedwait(&m_condSync, m_mxSync.getNativeMutex(), &ts) == ETIMEDOUT ? 1 : 0; } else pthread_cond_wait(&m_condSync, m_mxSync.getNativeMutex()); } m_stop_wait = false; return nRet; } void CPosixThreadImpl::sleep(unsigned int nTimeoutMs) { ::usleep(1000*nTimeoutMs); } void CPosixThreadImpl::stopWait() { #if defined(OS_MACOSX) || defined(OS_IPHONE) m_stop_wait = true; common::CMutexLock oLock(m_mxSync); #else common::CMutexLock oLock(m_mxSync); m_stop_wait = true; #endif pthread_cond_broadcast(&m_condSync); } } // namespace common } // namespace rho
/*------------------------------------------------------------------------ * (The MIT License) * * Copyright (c) 2008-2011 Rhomobile, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * http://rhomobile.com *------------------------------------------------------------------------*/ #include "common/PosixThreadImpl.h" extern "C" { void* rho_nativethread_start(); void rho_nativethread_end(void*); } namespace rho { namespace common { IMPLEMENT_LOGCLASS(CPosixThreadImpl, "RhoThread"); CPosixThreadImpl::CPosixThreadImpl() :m_stop_wait(false) { #if defined(OS_ANDROID) // Android has no pthread_condattr_xxx API pthread_cond_init(&m_condSync, NULL); #else pthread_condattr_t sync_details; pthread_condattr_init(&sync_details); pthread_cond_init(&m_condSync, &sync_details); pthread_condattr_destroy(&sync_details); #endif } CPosixThreadImpl::~CPosixThreadImpl() { pthread_cond_destroy(&m_condSync); } void *runProc(void *pv) { IRhoRunnable *p = static_cast<IRhoRunnable *>(pv); void *pData = rho_nativethread_start(); p->runObject(); rho_nativethread_end(pData); return 0; } void CPosixThreadImpl::start(IRhoRunnable *pRunnable, IRhoRunnable::EPriority ePriority) { pthread_attr_t attr; int return_val = pthread_attr_init(&attr); //return_val = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); RHO_ASSERT(!return_val); if ( ePriority != IRhoRunnable::epNormal) { sched_param param; return_val = pthread_attr_getschedparam (&attr, &param); param.sched_priority = ePriority == IRhoRunnable::epLow ? 20 : 100; //TODO: sched_priority return_val = pthread_attr_setschedparam (&attr, &param); } #ifdef __SYMBIAN32__ size_t stacksize = 80000; pthread_attr_setstacksize(&attr, stacksize); #endif int thread_error = pthread_create(&m_thread, &attr, &runProc, pRunnable); return_val = pthread_attr_destroy(&attr); RHO_ASSERT(!return_val); RHO_ASSERT(thread_error==0); } void CPosixThreadImpl::stop(unsigned int nTimeoutToKillMs) { stopWait(); //TODO: wait for nTimeoutToKill and kill thread void* status; pthread_join(m_thread,&status); } int CPosixThreadImpl::wait(unsigned int nTimeoutMs) { struct timeval tp; struct timespec ts; unsigned long long max; bool timed_wait = (int)nTimeoutMs >= 0; unsigned int nTimeout = nTimeoutMs/1000; if (timed_wait) { gettimeofday(&tp, NULL); unsigned long long nanosecs = tp.tv_usec * 1000 + ((unsigned long long)nTimeoutMs)*((unsigned long long)1000000); unsigned long long nanosec_sec = nanosecs / ((unsigned long long)1000000000); nanosecs = nanosecs - (nanosec_sec * ((unsigned long long)1000000000)); /* Convert from timeval to timespec */ ts.tv_sec = tp.tv_sec + nanosec_sec; ts.tv_nsec = nanosecs;//tp.tv_usec * 1000 + ((unsigned long long)(nTimeoutMs - nTimeout*1000))*1000000; //ts.tv_sec += nTimeout; max = ((unsigned long long)tp.tv_sec)*1000000 + tp.tv_usec + ((unsigned long long)nTimeoutMs)*((unsigned long long)1000); } common::CMutexLock oLock(m_mxSync); int nRet = 0; while (!m_stop_wait) { if (timed_wait) { gettimeofday(&tp, NULL); unsigned long long now = ((unsigned long long)tp.tv_sec)*1000000 + tp.tv_usec; if (now > max) break; nRet = pthread_cond_timedwait(&m_condSync, m_mxSync.getNativeMutex(), &ts) == ETIMEDOUT ? 1 : 0; } else pthread_cond_wait(&m_condSync, m_mxSync.getNativeMutex()); } m_stop_wait = false; return nRet; } void CPosixThreadImpl::sleep(unsigned int nTimeoutMs) { ::usleep(1000*nTimeoutMs); } void CPosixThreadImpl::stopWait() { #if defined(OS_MACOSX) || defined(OS_IPHONE) m_stop_wait = true; common::CMutexLock oLock(m_mxSync); #else common::CMutexLock oLock(m_mxSync); m_stop_wait = true; #endif pthread_cond_broadcast(&m_condSync); } } // namespace common } // namespace rho
fix wait time calculation in PosixThread
fix wait time calculation in PosixThread
C++
mit
rhomobile/rhodes,watusi/rhodes,rhomobile/rhodes,tauplatform/tau,rhomobile/rhodes,watusi/rhodes,rhomobile/rhodes,rhomobile/rhodes,rhomobile/rhodes,watusi/rhodes,watusi/rhodes,watusi/rhodes,watusi/rhodes,tauplatform/tau,rhomobile/rhodes,tauplatform/tau,tauplatform/tau,rhomobile/rhodes,tauplatform/tau,tauplatform/tau,rhomobile/rhodes,watusi/rhodes,watusi/rhodes,watusi/rhodes,tauplatform/tau,tauplatform/tau,rhomobile/rhodes,tauplatform/tau,watusi/rhodes,tauplatform/tau
dc407aa2a9c458af049a4c6c473247c16129736d
server/SesNotSvc/BroadcastTcpServer.cpp
server/SesNotSvc/BroadcastTcpServer.cpp
#include "BroadcastTcpServer.h" #include <winsock2.h> #include <ws2tcpip.h> #include <string> #include <vector> #include <list> #include <process.h> // _beginthreadex #pragma comment(lib, "ws2_32.lib") const static int DeletedObject = 0; std::string getLastWsaError(const char *msg); class TcpServerSocket { public: TcpServerSocket(); ~TcpServerSocket(); bool bind(unsigned short port); bool listen(int backlog); SOCKET accept(struct sockaddr* addr, int* addrlen); void close(); private: SOCKET serverSocket; std::string message; void recordMessage(const char*); }; class TcpClientSubscriber { public: TcpClientSubscriber(); ~TcpClientSubscriber(); int broadcast(const char* message); void addSubscriber(SOCKET socket); void acceptAsync(TcpServerSocket* tss); void stopAcceptAsync() { this->continueAccept = false; } bool hasSubscriber(); static unsigned __stdcall asyncAcceptThreadFunction(void* Param) { TcpClientSubscriber* self = (TcpClientSubscriber*)Param; ::ResetEvent(self->threadStopEvent); // nonsignaled while (self->continueAccept) { SOCKADDR_IN clientaddr; int addrlen = sizeof(clientaddr); if (self->tss == DeletedObject) { return 0; } SOCKET client_sock = self->tss->accept((SOCKADDR *)&clientaddr, &addrlen); if (client_sock != INVALID_SOCKET) { if (self->continueAccept) { self->addSubscriber(client_sock); } } } ::SetEvent(self->threadStopEvent); // signaled return 0; } private: CRITICAL_SECTION criticalSection; TcpServerSocket * tss; std::list<SOCKET> subscribers; volatile bool continueAccept; // use volatile for multi-thread check HANDLE threadStopEvent; void disconnectSubscribers(); void stopServer(); }; BroadcastTcpServer::BroadcastTcpServer() : tss(DeletedObject), subscriber(DeletedObject) { // ʱȭ WSADATA wsa; this->winsockInitialized = (::WSAStartup(MAKEWORD(2, 2), &wsa) == 0); this->tss = new TcpServerSocket(); this->subscriber = new TcpClientSubscriber(); } BroadcastTcpServer::~BroadcastTcpServer() { close(); if (this->winsockInitialized) { // ::WSACleanup(); this->winsockInitialized = false; } } void BroadcastTcpServer::listen(unsigned short port) { // bind if (this->tss->bind(port)) { // listen if (this->tss->listen(SOMAXCONN)) { this->subscriber->acceptAsync(this->tss); } } } int BroadcastTcpServer::broadcast(const char * message) { return subscriber->broadcast(message); } void BroadcastTcpServer::close() { if (this->subscriber != 0) { delete this->subscriber; this->subscriber = DeletedObject; } if (this->tss != 0) { delete this->tss; this->tss = DeletedObject; } } bool BroadcastTcpServer::hasSubscriber() { return subscriber->hasSubscriber(); } // TcpServerSocket implementation TcpServerSocket::TcpServerSocket() : serverSocket(INVALID_SOCKET) { this->serverSocket = ::socket(AF_INET, SOCK_STREAM, 0); } TcpServerSocket::~TcpServerSocket() { close(); } bool TcpServerSocket::bind(unsigned short port) { SOCKADDR_IN serveraddr; ZeroMemory(&serveraddr, sizeof(serveraddr)); serveraddr.sin_family = AF_INET; serveraddr.sin_port = htons(port); serveraddr.sin_addr.s_addr = htonl(INADDR_ANY); int retval = ::bind(serverSocket, (SOCKADDR *)&serveraddr, sizeof(serveraddr)); if (retval == SOCKET_ERROR) { this->recordMessage("bind()"); return false; } return true; } bool TcpServerSocket::listen(int backlog) { int retval = ::listen(serverSocket, backlog); if (retval == SOCKET_ERROR) { this->recordMessage("listen()"); return false; } return true; } SOCKET TcpServerSocket::accept(sockaddr * addr, int * addrlen) { return ::accept(this->serverSocket, addr, addrlen); } void TcpServerSocket::close() { if (this->serverSocket != INVALID_SOCKET) { ::closesocket(this->serverSocket); this->serverSocket = INVALID_SOCKET; } } void TcpServerSocket::recordMessage(const char *headerMessage) { this->message.assign(getLastWsaError(headerMessage)); } // Լ ޼ ȹ std::string getLastWsaError(const char *msg) { LPVOID lpMsgBuf; FormatMessageA( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, WSAGetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&lpMsgBuf, 0, NULL); std::string message((LPSTR)lpMsgBuf); LocalFree(lpMsgBuf); return message; } TcpClientSubscriber::TcpClientSubscriber() : threadStopEvent(INVALID_HANDLE_VALUE), tss(DeletedObject) { ::InitializeCriticalSection(&criticalSection); threadStopEvent = ::CreateEvent( NULL, // default security attributes TRUE, // manual-reset event TRUE, // initial state is signaled NULL); } TcpClientSubscriber::~TcpClientSubscriber() { stopAcceptAsync(); stopServer(); disconnectSubscribers(); ::WaitForSingleObject(this->threadStopEvent, INFINITE); ::CloseHandle(this->threadStopEvent); ::DeleteCriticalSection(&criticalSection); } int TcpClientSubscriber::broadcast(const char * message) { const int CannotSend = 0; using namespace std; int succeedCount = 0; ::EnterCriticalSection(&criticalSection); list<SOCKET>::iterator pos = this->subscribers.begin(); while (pos != this->subscribers.end()) { SOCKET s = *pos; int retval = ::send(s, message, (int)strlen(message), 0); if (retval == SOCKET_ERROR || retval == CannotSend) { ::shutdown(s, SD_SEND); ::closesocket(s); this->subscribers.erase(pos++); } else { succeedCount++; pos++; } } ::LeaveCriticalSection(&criticalSection); return succeedCount; } void TcpClientSubscriber::addSubscriber(SOCKET socket) { ::EnterCriticalSection(&criticalSection); this->subscribers.push_back(socket); ::LeaveCriticalSection(&criticalSection); } void TcpClientSubscriber::acceptAsync(TcpServerSocket * tss) { const int BeginThreadExFailed = 0; this->tss = tss; this->continueAccept = true; unsigned int threadID; HANDLE hThread = (HANDLE)::_beginthreadex(NULL, 0, asyncAcceptThreadFunction, (LPVOID)this, 0, &threadID); if (hThread != BeginThreadExFailed) { ::CloseHandle(hThread); } } bool TcpClientSubscriber::hasSubscriber() { ::EnterCriticalSection(&criticalSection); bool has = !(this->subscribers.empty()); ::LeaveCriticalSection(&criticalSection); return has; } void TcpClientSubscriber::disconnectSubscribers() { using namespace std; ::EnterCriticalSection(&criticalSection); list<SOCKET>::iterator pos = this->subscribers.begin(); while (pos != this->subscribers.end()) { SOCKET s = *pos; ::closesocket(s); this->subscribers.erase(pos++); } ::LeaveCriticalSection(&criticalSection); } void TcpClientSubscriber::stopServer() { if (tss != DeletedObject) { tss->close(); } }
#include "BroadcastTcpServer.h" #include <winsock2.h> #include <ws2tcpip.h> #include <string> #include <vector> #include <list> #include <process.h> // _beginthreadex #pragma comment(lib, "ws2_32.lib") const static int DeletedObject = 0; std::string getLastWsaError(const char *msg); class TcpServerSocket { public: TcpServerSocket() : serverSocket(INVALID_SOCKET) { this->serverSocket = ::socket(AF_INET, SOCK_STREAM, 0); } ~TcpServerSocket() { close(); } bool bind(unsigned short port) { SOCKADDR_IN serveraddr; ZeroMemory(&serveraddr, sizeof(serveraddr)); serveraddr.sin_family = AF_INET; serveraddr.sin_port = htons(port); serveraddr.sin_addr.s_addr = htonl(INADDR_ANY); int retval = ::bind(serverSocket, (SOCKADDR *)&serveraddr, sizeof(serveraddr)); if (retval == SOCKET_ERROR) { this->recordMessage("bind()"); return false; } return true; } bool listen(int backlog) { int retval = ::listen(serverSocket, backlog); if (retval == SOCKET_ERROR) { this->recordMessage("listen()"); return false; } return true; } SOCKET accept(sockaddr * addr, int * addrlen) { return ::accept(this->serverSocket, addr, addrlen); } void close() { if (this->serverSocket != INVALID_SOCKET) { ::closesocket(this->serverSocket); this->serverSocket = INVALID_SOCKET; } } private: SOCKET serverSocket; std::string message; void recordMessage(const char *headerMessage) { this->message.assign(getLastWsaError(headerMessage)); } }; class TcpClientSubscriber { public: TcpClientSubscriber() : threadStopEvent(INVALID_HANDLE_VALUE), tss(DeletedObject) { ::InitializeCriticalSection(&criticalSection); threadStopEvent = ::CreateEvent( NULL, // default security attributes TRUE, // manual-reset event TRUE, // initial state is signaled NULL); } ~TcpClientSubscriber() { stopAcceptAsync(); stopServer(); disconnectSubscribers(); ::WaitForSingleObject(this->threadStopEvent, INFINITE); ::CloseHandle(this->threadStopEvent); ::DeleteCriticalSection(&criticalSection); } int broadcast(const char * message) { const int CannotSend = 0; using namespace std; int succeedCount = 0; ::EnterCriticalSection(&criticalSection); list<SOCKET>::iterator pos = this->subscribers.begin(); while (pos != this->subscribers.end()) { SOCKET s = *pos; int retval = ::send(s, message, (int)strlen(message), 0); if (retval == SOCKET_ERROR || retval == CannotSend) { ::shutdown(s, SD_SEND); ::closesocket(s); this->subscribers.erase(pos++); } else { succeedCount++; pos++; } } ::LeaveCriticalSection(&criticalSection); return succeedCount; } void addSubscriber(SOCKET socket) { ::EnterCriticalSection(&criticalSection); this->subscribers.push_back(socket); ::LeaveCriticalSection(&criticalSection); } void acceptAsync(TcpServerSocket * tss) { const int BeginThreadExFailed = 0; this->tss = tss; this->continueAccept = true; unsigned int threadID; HANDLE hThread = (HANDLE)::_beginthreadex(NULL, 0, asyncAcceptThreadFunction, (LPVOID)this, 0, &threadID); if (hThread != BeginThreadExFailed) { ::CloseHandle(hThread); } } void stopAcceptAsync() { this->continueAccept = false; } bool hasSubscriber() { ::EnterCriticalSection(&criticalSection); bool has = !(this->subscribers.empty()); ::LeaveCriticalSection(&criticalSection); return has; } static unsigned __stdcall asyncAcceptThreadFunction(void* Param) { TcpClientSubscriber* self = (TcpClientSubscriber*)Param; ::ResetEvent(self->threadStopEvent); // nonsignaled while (self->continueAccept) { SOCKADDR_IN clientaddr; int addrlen = sizeof(clientaddr); if (self->tss == DeletedObject) { return 0; } SOCKET client_sock = self->tss->accept((SOCKADDR *)&clientaddr, &addrlen); if (client_sock != INVALID_SOCKET) { if (self->continueAccept) { self->addSubscriber(client_sock); } } } ::SetEvent(self->threadStopEvent); // signaled return 0; } private: CRITICAL_SECTION criticalSection; TcpServerSocket * tss; std::list<SOCKET> subscribers; volatile bool continueAccept; // use volatile for multi-thread check HANDLE threadStopEvent; void disconnectSubscribers() { using namespace std; ::EnterCriticalSection(&criticalSection); list<SOCKET>::iterator pos = this->subscribers.begin(); while (pos != this->subscribers.end()) { SOCKET s = *pos; ::closesocket(s); this->subscribers.erase(pos++); } ::LeaveCriticalSection(&criticalSection); } void stopServer() { if (tss != DeletedObject) { tss->close(); } } }; BroadcastTcpServer::BroadcastTcpServer() : tss(DeletedObject), subscriber(DeletedObject) { // ʱȭ WSADATA wsa; this->winsockInitialized = (::WSAStartup(MAKEWORD(2, 2), &wsa) == 0); this->tss = new TcpServerSocket(); this->subscriber = new TcpClientSubscriber(); } BroadcastTcpServer::~BroadcastTcpServer() { close(); if (this->winsockInitialized) { // ::WSACleanup(); this->winsockInitialized = false; } } void BroadcastTcpServer::listen(unsigned short port) { // bind if (this->tss->bind(port)) { // listen if (this->tss->listen(SOMAXCONN)) { this->subscriber->acceptAsync(this->tss); } } } int BroadcastTcpServer::broadcast(const char * message) { return subscriber->broadcast(message); } void BroadcastTcpServer::close() { if (this->subscriber != 0) { delete this->subscriber; this->subscriber = DeletedObject; } if (this->tss != 0) { delete this->tss; this->tss = DeletedObject; } } bool BroadcastTcpServer::hasSubscriber() { return subscriber->hasSubscriber(); } // Լ ޼ ȹ std::string getLastWsaError(const char *msg) { LPVOID lpMsgBuf; FormatMessageA( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, WSAGetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&lpMsgBuf, 0, NULL); std::string message((LPSTR)lpMsgBuf); LocalFree(lpMsgBuf); return message; }
combine the implement of classes
[SE-0005] combine the implement of classes
C++
mit
namhokim/windows-session-notification,namhokim/windows-session-notification
7268a4b87ffc963be544301c1d8daf9bd77e5ba9
Plugins/org.mitk.gui.qt.application/src/QmitkFileSaveAction.cpp
Plugins/org.mitk.gui.qt.application/src/QmitkFileSaveAction.cpp
/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkFileSaveAction.h" #include "internal/org_mitk_gui_qt_application_Activator.h" #include <mitkWorkbenchUtil.h> #include <mitkDataNodeSelection.h> #include <berryISelectionService.h> #include <berryINullSelectionListener.h> #include <QmitkIOUtil.h> #include <QFileDialog> #include <QMessageBox> class QmitkFileSaveActionPrivate { private: void HandleSelectionChanged(berry::IWorkbenchPart::Pointer /*part*/, berry::ISelection::ConstPointer selection) { this->setEnabled(selection); } berry::ISelectionListener::Pointer m_SelectionListener; public: QmitkFileSaveActionPrivate() : m_SelectionListener(new berry::NullSelectionChangedAdapter<QmitkFileSaveActionPrivate>( this, &QmitkFileSaveActionPrivate::HandleSelectionChanged)) { } ~QmitkFileSaveActionPrivate() { m_Window.Lock()->GetSelectionService()->RemoveSelectionListener(m_SelectionListener); } void init ( berry::IWorkbenchWindow::Pointer window, QmitkFileSaveAction* action ) { m_Window = window; m_Action = action; action->setParent(static_cast<QWidget*>(m_Window.Lock()->GetShell()->GetControl())); action->setText("&Save..."); action->setToolTip("Save data objects (images, surfaces,...)"); berry::ISelectionService* selectionService = m_Window.Lock()->GetSelectionService(); setEnabled(selectionService->GetSelection()); selectionService->AddSelectionListener(m_SelectionListener); QObject::connect(action, SIGNAL(triggered(bool)), action, SLOT(Run())); } berry::IPreferences::Pointer GetPreferences() const { berry::IPreferencesService::Pointer prefService = mitk::PluginActivator::GetInstance()->GetPreferencesService(); if (prefService.IsNotNull()) { return prefService->GetSystemPreferences()->Node("/General"); } return berry::IPreferences::Pointer(0); } QString getLastFileSavePath() const { berry::IPreferences::Pointer prefs = GetPreferences(); if(prefs.IsNotNull()) { return QString::fromStdString(prefs->Get("LastFileSavePath", "")); } return QString(); } void setLastFileSavePath(const QString& path) const { berry::IPreferences::Pointer prefs = GetPreferences(); if(prefs.IsNotNull()) { prefs->Put("LastFileSavePath", path.toStdString()); prefs->Flush(); } } void setEnabled(berry::ISelection::ConstPointer selection) { mitk::DataNodeSelection::ConstPointer nodeSelection = selection.Cast<const mitk::DataNodeSelection>(); if (nodeSelection.IsNotNull() && !selection->IsEmpty()) { bool enable = false; std::list<mitk::DataNode::Pointer> dataNodes = nodeSelection->GetSelectedDataNodes(); for (std::list<mitk::DataNode::Pointer>::const_iterator nodeIter = dataNodes.begin(), nodeIterEnd = dataNodes.end(); nodeIter != nodeIterEnd; ++nodeIter) { if ((*nodeIter)->GetData() != NULL) { qDebug() << "Got non-empty data-node: " << (*nodeIter)->GetData()->GetNameOfClass(); enable = true; break; } } m_Action->setEnabled(enable); } else { m_Action->setEnabled(false); } } berry::IWorkbenchWindow::WeakPtr m_Window; QAction* m_Action; }; QmitkFileSaveAction::QmitkFileSaveAction(berry::IWorkbenchWindow::Pointer window) : QAction(0), d(new QmitkFileSaveActionPrivate) { d->init(window, this); } QmitkFileSaveAction::QmitkFileSaveAction(const QIcon & icon, berry::IWorkbenchWindow::Pointer window) : QAction(0), d(new QmitkFileSaveActionPrivate) { d->init(window, this); this->setIcon(icon); } QmitkFileSaveAction::~QmitkFileSaveAction() { } void QmitkFileSaveAction::Run() { // Get the list of selected base data objects mitk::DataNodeSelection::ConstPointer selection = d->m_Window.Lock()->GetSelectionService()->GetSelection().Cast<const mitk::DataNodeSelection>(); if (selection.IsNull() || selection->IsEmpty()) { MITK_ERROR << "Assertion failed: data node selection is NULL or empty"; return; } std::list<mitk::DataNode::Pointer> dataNodes = selection->GetSelectedDataNodes(); std::vector<const mitk::BaseData*> data; QStringList names; for (std::list<mitk::DataNode::Pointer>::const_iterator nodeIter = dataNodes.begin(), nodeIterEnd = dataNodes.end(); nodeIter != nodeIterEnd; ++nodeIter) { data.push_back((*nodeIter)->GetData()); std::string name; (*nodeIter)->GetStringProperty("name", name); names.push_back(QString::fromStdString(name)); } try { QStringList fileNames = QmitkIOUtil::Save(data, names, d->getLastFileSavePath(), d->m_Action->parentWidget()); if (!fileNames.empty()) { d->setLastFileSavePath(QFileInfo(fileNames.back()).absolutePath()); } } catch (const mitk::Exception& e) { MITK_INFO << e; return; } }
/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkFileSaveAction.h" #include "internal/org_mitk_gui_qt_application_Activator.h" #include <mitkWorkbenchUtil.h> #include <mitkDataNodeSelection.h> #include <berryISelectionService.h> #include <berryINullSelectionListener.h> #include <QmitkIOUtil.h> #include <QFileDialog> #include <QMessageBox> class QmitkFileSaveActionPrivate { private: void HandleSelectionChanged(berry::IWorkbenchPart::Pointer /*part*/, berry::ISelection::ConstPointer selection) { this->setEnabled(selection); } berry::ISelectionListener::Pointer m_SelectionListener; public: QmitkFileSaveActionPrivate() : m_SelectionListener(new berry::NullSelectionChangedAdapter<QmitkFileSaveActionPrivate>( this, &QmitkFileSaveActionPrivate::HandleSelectionChanged)) { } ~QmitkFileSaveActionPrivate() { if (!m_Window.Expired()) { m_Window.Lock()->GetSelectionService()->RemoveSelectionListener(m_SelectionListener); } } void init ( berry::IWorkbenchWindow::Pointer window, QmitkFileSaveAction* action ) { m_Window = window; m_Action = action; action->setParent(static_cast<QWidget*>(m_Window.Lock()->GetShell()->GetControl())); action->setText("&Save..."); action->setToolTip("Save data objects (images, surfaces,...)"); berry::ISelectionService* selectionService = m_Window.Lock()->GetSelectionService(); setEnabled(selectionService->GetSelection()); selectionService->AddSelectionListener(m_SelectionListener); QObject::connect(action, SIGNAL(triggered(bool)), action, SLOT(Run())); } berry::IPreferences::Pointer GetPreferences() const { berry::IPreferencesService::Pointer prefService = mitk::PluginActivator::GetInstance()->GetPreferencesService(); if (prefService.IsNotNull()) { return prefService->GetSystemPreferences()->Node("/General"); } return berry::IPreferences::Pointer(0); } QString getLastFileSavePath() const { berry::IPreferences::Pointer prefs = GetPreferences(); if(prefs.IsNotNull()) { return QString::fromStdString(prefs->Get("LastFileSavePath", "")); } return QString(); } void setLastFileSavePath(const QString& path) const { berry::IPreferences::Pointer prefs = GetPreferences(); if(prefs.IsNotNull()) { prefs->Put("LastFileSavePath", path.toStdString()); prefs->Flush(); } } void setEnabled(berry::ISelection::ConstPointer selection) { mitk::DataNodeSelection::ConstPointer nodeSelection = selection.Cast<const mitk::DataNodeSelection>(); if (nodeSelection.IsNotNull() && !selection->IsEmpty()) { bool enable = false; std::list<mitk::DataNode::Pointer> dataNodes = nodeSelection->GetSelectedDataNodes(); for (std::list<mitk::DataNode::Pointer>::const_iterator nodeIter = dataNodes.begin(), nodeIterEnd = dataNodes.end(); nodeIter != nodeIterEnd; ++nodeIter) { if ((*nodeIter)->GetData() != NULL) { qDebug() << "Got non-empty data-node: " << (*nodeIter)->GetData()->GetNameOfClass(); enable = true; break; } } m_Action->setEnabled(enable); } else { m_Action->setEnabled(false); } } berry::IWorkbenchWindow::WeakPtr m_Window; QAction* m_Action; }; QmitkFileSaveAction::QmitkFileSaveAction(berry::IWorkbenchWindow::Pointer window) : QAction(0), d(new QmitkFileSaveActionPrivate) { d->init(window, this); } QmitkFileSaveAction::QmitkFileSaveAction(const QIcon & icon, berry::IWorkbenchWindow::Pointer window) : QAction(0), d(new QmitkFileSaveActionPrivate) { d->init(window, this); this->setIcon(icon); } QmitkFileSaveAction::~QmitkFileSaveAction() { } void QmitkFileSaveAction::Run() { // Get the list of selected base data objects mitk::DataNodeSelection::ConstPointer selection = d->m_Window.Lock()->GetSelectionService()->GetSelection().Cast<const mitk::DataNodeSelection>(); if (selection.IsNull() || selection->IsEmpty()) { MITK_ERROR << "Assertion failed: data node selection is NULL or empty"; return; } std::list<mitk::DataNode::Pointer> dataNodes = selection->GetSelectedDataNodes(); std::vector<const mitk::BaseData*> data; QStringList names; for (std::list<mitk::DataNode::Pointer>::const_iterator nodeIter = dataNodes.begin(), nodeIterEnd = dataNodes.end(); nodeIter != nodeIterEnd; ++nodeIter) { data.push_back((*nodeIter)->GetData()); std::string name; (*nodeIter)->GetStringProperty("name", name); names.push_back(QString::fromStdString(name)); } try { QStringList fileNames = QmitkIOUtil::Save(data, names, d->getLastFileSavePath(), d->m_Action->parentWidget()); if (!fileNames.empty()) { d->setLastFileSavePath(QFileInfo(fileNames.back()).absolutePath()); } } catch (const mitk::Exception& e) { MITK_INFO << e; return; } }
Check if workbench window still exists.
Check if workbench window still exists.
C++
bsd-3-clause
NifTK/MITK,RabadanLab/MITKats,fmilano/mitk,iwegner/MITK,iwegner/MITK,NifTK/MITK,fmilano/mitk,iwegner/MITK,danielknorr/MITK,MITK/MITK,MITK/MITK,fmilano/mitk,NifTK/MITK,danielknorr/MITK,iwegner/MITK,danielknorr/MITK,RabadanLab/MITKats,iwegner/MITK,fmilano/mitk,danielknorr/MITK,danielknorr/MITK,NifTK/MITK,RabadanLab/MITKats,fmilano/mitk,MITK/MITK,danielknorr/MITK,RabadanLab/MITKats,fmilano/mitk,iwegner/MITK,MITK/MITK,fmilano/mitk,MITK/MITK,NifTK/MITK,NifTK/MITK,RabadanLab/MITKats,RabadanLab/MITKats,danielknorr/MITK,MITK/MITK
795be496fe855ebe09413995f6ecb891d03a6bf0
modules/webbrowser/src/properties/propertycefsynchronizer.cpp
modules/webbrowser/src/properties/propertycefsynchronizer.cpp
/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2018-2019 Inviwo Foundation * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *********************************************************************************/ #include <modules/webbrowser/properties/propertycefsynchronizer.h> #include <modules/webbrowser/webbrowsermodule.h> #include <inviwo/core/util/stringconversion.h> #include <warn/push> #include <warn/ignore/all> #include "include/cef_parser.h" #include <warn/pop> namespace inviwo { PropertyCefSynchronizer::PropertyCefSynchronizer(const PropertyWidgetCEFFactory* htmlWidgetFactory) : htmlWidgetFactory_(htmlWidgetFactory){ }; void PropertyCefSynchronizer::OnLoadEnd(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, int /*httpStatusCode*/) { // synchronize all properties // Ok to send javascript commands when frame loaded for (auto& widget : widgets_) { widget->setFrame(frame); } } bool PropertyCefSynchronizer::OnQuery(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, int64 query_id, const CefString& request, bool persistent, CefRefPtr<Callback> callback) { const std::string& requestStr = request; // Assume format "id":"htmlId" auto j = json::parse(requestStr); try { auto command = j.at("command").get<std::string>(); auto propCommand = std::string("property"); if (command == "subscribe") { auto network = InviwoApplication::getPtr()->getProcessorNetwork(); auto p = j.at("path").get<std::string>(); auto path = splitString(p, '.'); auto prop = network->getProperty(path); if (prop) { auto onChange = j.at("onChange").get<std::string>(); auto widget = std::find_if( std::begin(widgets_), std::end(widgets_), [onChange, prop](const auto& widget) { return prop == widget->getProperty() && onChange == widget->getOnChange(); }); if (widget == widgets_.end()) { auto propertyObserver = j.at("propertyObserver").get<std::string>(); startSynchronize(prop, onChange, propertyObserver); widget = --(widgets_.end()); (*widget)->setFrame(frame); } } else { callback->Failure(0, "Could not find property: " + p); } } else if (!command.compare(0, propCommand.size(), propCommand)) { auto network = InviwoApplication::getPtr()->getProcessorNetwork(); auto propertyPath = j.at("path").get<std::string>(); auto path = splitString(propertyPath, '.'); auto prop = network->getProperty(path); if (!prop) { throw Exception("Could not find property " + propertyPath); } // Use synchronized widget if it exists // to avoid recursive loop when setting the property auto widget = std::find_if(std::begin(widgets_), std::end(widgets_), [prop](const auto& widget) { return prop == widget->getProperty(); }); if (widget != widgets_.end()) { return (*widget)->onQuery(browser, frame, query_id, request, persistent, callback); } else { auto w = htmlWidgetFactory_->create(prop->getClassIdentifier(), prop); if (!w) { throw Exception("No HTML property widget for " + prop->getClassIdentifier()); } return w->onQuery(browser, frame, query_id, request, persistent, callback); } } } catch (json::exception& ex) { LogError(ex.what()); callback->Failure(0, ex.what()); } return false; } void PropertyCefSynchronizer::onWillRemoveProperty(Property* property, size_t) { stopSynchronize(property); } void PropertyCefSynchronizer::startSynchronize(Property* property, std::string onChange, std::string propertyObserverCallback) { auto widget = htmlWidgetFactory_->create(property->getClassIdentifier(), property); if (!widget) { throw Exception("No HTML property widget for " + property->getClassIdentifier()); } widget->setOnChange(onChange); widget->setPropertyObserverCallback(propertyObserverCallback); // auto widget = std::make_unique<OrdinalPropertyWidgetCEF<T>>(property, // browser_->GetMainFrame(), htmlId); widgets_.emplace_back(std::move(widget)); if (auto owner = property->getOwner()) { owner->addObserver(this); } } void PropertyCefSynchronizer::stopSynchronize(Property* property) { util::erase_remove_if(widgets_, [property](auto& widget) { return property == widget->getProperty(); }); } } // namespace inviwo
/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2018-2019 Inviwo Foundation * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *********************************************************************************/ #include <modules/webbrowser/properties/propertycefsynchronizer.h> #include <modules/webbrowser/webbrowsermodule.h> #include <inviwo/core/util/stringconversion.h> #include <warn/push> #include <warn/ignore/all> #include "include/cef_parser.h" #include <warn/pop> namespace inviwo { PropertyCefSynchronizer::PropertyCefSynchronizer(const PropertyWidgetCEFFactory* htmlWidgetFactory) : htmlWidgetFactory_(htmlWidgetFactory){ }; void PropertyCefSynchronizer::OnLoadEnd(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, int /*httpStatusCode*/) { // synchronize all properties // Ok to send javascript commands when frame loaded for (auto& widget : widgets_) { widget->setFrame(frame); } } bool PropertyCefSynchronizer::OnQuery(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, int64 query_id, const CefString& request, bool persistent, CefRefPtr<Callback> callback) { const std::string& requestStr = request; // Assume format "id":"htmlId" auto j = json::parse(requestStr); try { auto command = j.at("command").get<std::string>(); auto propCommand = std::string("property"); if (command == "subscribe") { auto network = InviwoApplication::getPtr()->getProcessorNetwork(); auto p = j.at("path").get<std::string>(); auto path = splitString(p, '.'); auto prop = network->getProperty(path); if (prop) { auto onChange = j.at("onChange").get<std::string>(); auto widget = std::find_if( std::begin(widgets_), std::end(widgets_), [onChange, prop](const auto& widget) { return prop == widget->getProperty() && onChange == widget->getOnChange(); }); if (widget == widgets_.end()) { auto propertyObserver = j.at("propertyObserver").get<std::string>(); startSynchronize(prop, onChange, propertyObserver); widget = --(widgets_.end()); (*widget)->setFrame(frame); } } else { callback->Failure(0, "Could not find property: " + p); } } else if (!command.compare(0, propCommand.size(), propCommand)) { auto network = InviwoApplication::getPtr()->getProcessorNetwork(); auto propertyPath = j.at("path").get<std::string>(); auto path = splitString(propertyPath, '.'); auto prop = network->getProperty(path); if (!prop) { throw Exception("Could not find property " + propertyPath); } // Use synchronized widget if it exists // to avoid recursive loop when setting the property auto widget = std::find_if(std::begin(widgets_), std::end(widgets_), [prop](const auto& widget) { return prop == widget->getProperty(); }); if (widget != widgets_.end()) { return (*widget)->onQuery(browser, frame, query_id, request, persistent, callback); } else { auto w = htmlWidgetFactory_->create(prop->getClassIdentifier(), prop); if (!w) { throw Exception("No HTML property widget for " + prop->getClassIdentifier()); } return w->onQuery(browser, frame, query_id, request, persistent, callback); } } } catch (json::exception& ex) { LogError(ex.what()); callback->Failure(0, ex.what()); } catch (inviwo::Exception& ex) { util::log(ex.getContext(), ex.getMessage(), LogLevel::Error); callback->Failure(0, ex.what()); } catch (std::exception& ex) { LogError(ex.what()); callback->Failure(0, ex.what()); } return false; } void PropertyCefSynchronizer::onWillRemoveProperty(Property* property, size_t) { stopSynchronize(property); } void PropertyCefSynchronizer::startSynchronize(Property* property, std::string onChange, std::string propertyObserverCallback) { auto widget = htmlWidgetFactory_->create(property->getClassIdentifier(), property); if (!widget) { throw Exception("No HTML property widget for " + property->getClassIdentifier()); } widget->setOnChange(onChange); widget->setPropertyObserverCallback(propertyObserverCallback); // auto widget = std::make_unique<OrdinalPropertyWidgetCEF<T>>(property, // browser_->GetMainFrame(), htmlId); widgets_.emplace_back(std::move(widget)); if (auto owner = property->getOwner()) { owner->addObserver(this); } } void PropertyCefSynchronizer::stopSynchronize(Property* property) { util::erase_remove_if(widgets_, [property](auto& widget) { return property == widget->getProperty(); }); } } // namespace inviwo
Handle inviwo and std exception, not on json exception to prevent broken state (see #584)
WebBrowser: Handle inviwo and std exception, not on json exception to prevent broken state (see #584)
C++
bsd-2-clause
inviwo/inviwo,inviwo/inviwo,inviwo/inviwo,inviwo/inviwo,inviwo/inviwo,inviwo/inviwo
42f436f6d8e0abc1788f6d2ab0dfcb5ad09d84b1
remoting/host/setup/me2me_native_messaging_host_main.cc
remoting/host/setup/me2me_native_messaging_host_main.cc
// Copyright 2013 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 "remoting/host/setup/me2me_native_messaging_host_main.h" #include "base/at_exit.h" #include "base/command_line.h" #include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "base/strings/string_number_conversions.h" #include "net/url_request/url_fetcher.h" #include "remoting/base/breakpad.h" #include "remoting/host/host_exit_codes.h" #include "remoting/host/logging.h" #include "remoting/host/pairing_registry_delegate.h" #include "remoting/host/setup/me2me_native_messaging_host.h" #include "remoting/host/usage_stats_consent.h" #if defined(OS_MACOSX) #include "base/mac/scoped_nsautorelease_pool.h" #endif // defined(OS_MACOSX) #if defined(OS_WIN) #include "base/win/registry.h" #include "base/win/windows_version.h" #include "remoting/host/pairing_registry_delegate_win.h" #endif // defined(OS_WIN) using remoting::protocol::PairingRegistry; namespace { const char kParentWindowSwitchName[] = "parent-window"; } // namespace namespace remoting { #if defined(OS_WIN) bool IsProcessElevated() { // Conceptually, all processes running on a pre-VISTA version of Windows can // be considered "elevated". if (base::win::GetVersion() < base::win::VERSION_VISTA) return true; HANDLE process_token; OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &process_token); base::win::ScopedHandle scoped_process_token(process_token); // Unlike TOKEN_ELEVATION_TYPE which returns TokenElevationTypeDefault when // UAC is turned off, TOKEN_ELEVATION will tell you the process is elevated. DWORD size; TOKEN_ELEVATION elevation; GetTokenInformation(process_token, TokenElevation, &elevation, sizeof(elevation), &size); return elevation.TokenIsElevated != 0; } #endif // defined(OS_WIN) int StartMe2MeNativeMessagingHost() { #if defined(OS_MACOSX) // Needed so we don't leak objects when threads are created. base::mac::ScopedNSAutoreleasePool pool; #endif // defined(OS_MACOSX) #if defined(REMOTING_ENABLE_BREAKPAD) // Initialize Breakpad as early as possible. On Mac the command-line needs to // be initialized first, so that the preference for crash-reporting can be // looked up in the config file. if (IsUsageStatsAllowed()) { InitializeCrashReporting(); } #endif // defined(REMOTING_ENABLE_BREAKPAD) // Mac OS X requires that the main thread be a UI message loop in order to // receive distributed notifications from the System Preferences pane. An // IO thread is needed for the pairing registry and URL context getter. base::Thread io_thread("io_thread"); io_thread.StartWithOptions( base::Thread::Options(base::MessageLoop::TYPE_IO, 0)); base::MessageLoopForUI message_loop; base::RunLoop run_loop; scoped_refptr<DaemonController> daemon_controller = DaemonController::Create(); // Pass handle of the native view to the controller so that the UAC prompts // are focused properly. const CommandLine* command_line = CommandLine::ForCurrentProcess(); int64 native_view_handle = 0; if (command_line->HasSwitch(kParentWindowSwitchName)) { std::string native_view = command_line->GetSwitchValueASCII(kParentWindowSwitchName); if (base::StringToInt64(native_view, &native_view_handle)) { daemon_controller->SetWindow(reinterpret_cast<void*>(native_view_handle)); } else { LOG(WARNING) << "Invalid parameter value --" << kParentWindowSwitchName << "=" << native_view; } } base::File read_file; base::File write_file; bool needs_elevation = false; #if defined(OS_WIN) needs_elevation = !IsProcessElevated(); if (command_line->HasSwitch(kElevatingSwitchName)) { DCHECK(!needs_elevation); // The "elevate" switch is always accompanied by the "input" and "output" // switches whose values name named pipes that should be used in place of // stdin and stdout. DCHECK(command_line->HasSwitch(kInputSwitchName)); DCHECK(command_line->HasSwitch(kOutputSwitchName)); // presubmit: allow wstring std::wstring input_pipe_name = command_line->GetSwitchValueNative(kInputSwitchName); // presubmit: allow wstring std::wstring output_pipe_name = command_line->GetSwitchValueNative(kOutputSwitchName); // A NULL SECURITY_ATTRIBUTES signifies that the handle can't be inherited read_file = base::File(CreateFile( input_pipe_name.c_str(), GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL)); if (!read_file.IsValid()) { LOG_GETLASTERROR(ERROR) << "CreateFile failed on '" << input_pipe_name << "'"; return kInitializationFailed; } write_file = base::File(CreateFile( output_pipe_name.c_str(), GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL)); if (!write_file.IsValid()) { LOG_GETLASTERROR(ERROR) << "CreateFile failed on '" << output_pipe_name << "'"; return kInitializationFailed; } } else { // GetStdHandle() returns pseudo-handles for stdin and stdout even if // the hosting executable specifies "Windows" subsystem. However the // returned handles are invalid in that case unless standard input and // output are redirected to a pipe or file. read_file = base::File(GetStdHandle(STD_INPUT_HANDLE)); write_file = base::File(GetStdHandle(STD_OUTPUT_HANDLE)); // After the native messaging channel starts the native messaging reader // will keep doing blocking read operations on the input named pipe. // If any other thread tries to perform any operation on STDIN, it will also // block because the input named pipe is synchronous (non-overlapped). // It is pretty common for a DLL to query the device info (GetFileType) of // the STD* handles at startup. So any LoadLibrary request can potentially // be blocked. To prevent that from happening we close STDIN and STDOUT // handles as soon as we retrieve the corresponding file handles. SetStdHandle(STD_INPUT_HANDLE, NULL); SetStdHandle(STD_OUTPUT_HANDLE, NULL); } #elif defined(OS_POSIX) // The files will be automatically closed. read_file = base::File(STDIN_FILENO); write_file = base::File(STDOUT_FILENO); #else #error Not implemented. #endif // OAuth client (for credential requests). scoped_refptr<net::URLRequestContextGetter> url_request_context_getter( new URLRequestContextGetter(io_thread.message_loop_proxy())); scoped_ptr<OAuthClient> oauth_client( new OAuthClient(url_request_context_getter)); net::URLFetcher::SetIgnoreCertificateRequests(true); // Create the pairing registry. scoped_refptr<PairingRegistry> pairing_registry; #if defined(OS_WIN) base::win::RegKey root; LONG result = root.Open(HKEY_LOCAL_MACHINE, kPairingRegistryKeyName, KEY_READ); if (result != ERROR_SUCCESS) { SetLastError(result); PLOG(ERROR) << "Failed to open HKLM\\" << kPairingRegistryKeyName; return kInitializationFailed; } base::win::RegKey unprivileged; result = unprivileged.Open(root.Handle(), kPairingRegistrySecretsKeyName, needs_elevation ? KEY_READ : KEY_READ | KEY_WRITE); if (result != ERROR_SUCCESS) { SetLastError(result); PLOG(ERROR) << "Failed to open HKLM\\" << kPairingRegistrySecretsKeyName << "\\" << kPairingRegistrySecretsKeyName; return kInitializationFailed; } // Only try to open the privileged key if the current process is elevated. base::win::RegKey privileged; if (!needs_elevation) { result = privileged.Open(root.Handle(), kPairingRegistryClientsKeyName, KEY_READ | KEY_WRITE); if (result != ERROR_SUCCESS) { SetLastError(result); PLOG(ERROR) << "Failed to open HKLM\\" << kPairingRegistryKeyName << "\\" << kPairingRegistryClientsKeyName; return kInitializationFailed; } } // Initialize the pairing registry delegate and set the root keys. scoped_ptr<PairingRegistryDelegateWin> delegate( new PairingRegistryDelegateWin()); if (!delegate->SetRootKeys(privileged.Take(), unprivileged.Take())) return kInitializationFailed; pairing_registry = new PairingRegistry( io_thread.message_loop_proxy(), delegate.PassAs<PairingRegistry::Delegate>()); #else // defined(OS_WIN) pairing_registry = CreatePairingRegistry(io_thread.message_loop_proxy()); #endif // !defined(OS_WIN) // Set up the native messaging channel. scoped_ptr<NativeMessagingChannel> channel( new NativeMessagingChannel(read_file.Pass(), write_file.Pass())); // Create the native messaging host. scoped_ptr<Me2MeNativeMessagingHost> host( new Me2MeNativeMessagingHost( needs_elevation, static_cast<intptr_t>(native_view_handle), channel.Pass(), daemon_controller, pairing_registry, oauth_client.Pass())); host->Start(run_loop.QuitClosure()); // Run the loop until channel is alive. run_loop.Run(); return kSuccessExitCode; } int Me2MeNativeMessagingHostMain(int argc, char** argv) { // This object instance is required by Chrome code (such as MessageLoop). base::AtExitManager exit_manager; CommandLine::Init(argc, argv); remoting::InitHostLogging(); return StartMe2MeNativeMessagingHost(); } } // namespace remoting
// Copyright 2013 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 "remoting/host/setup/me2me_native_messaging_host_main.h" #include "base/at_exit.h" #include "base/command_line.h" #include "base/i18n/icu_util.h" #include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "base/strings/string_number_conversions.h" #include "net/url_request/url_fetcher.h" #include "remoting/base/breakpad.h" #include "remoting/host/host_exit_codes.h" #include "remoting/host/logging.h" #include "remoting/host/pairing_registry_delegate.h" #include "remoting/host/setup/me2me_native_messaging_host.h" #include "remoting/host/usage_stats_consent.h" #if defined(OS_MACOSX) #include "base/mac/scoped_nsautorelease_pool.h" #endif // defined(OS_MACOSX) #if defined(OS_WIN) #include "base/win/registry.h" #include "base/win/windows_version.h" #include "remoting/host/pairing_registry_delegate_win.h" #endif // defined(OS_WIN) using remoting::protocol::PairingRegistry; namespace { const char kParentWindowSwitchName[] = "parent-window"; } // namespace namespace remoting { #if defined(OS_WIN) bool IsProcessElevated() { // Conceptually, all processes running on a pre-VISTA version of Windows can // be considered "elevated". if (base::win::GetVersion() < base::win::VERSION_VISTA) return true; HANDLE process_token; OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &process_token); base::win::ScopedHandle scoped_process_token(process_token); // Unlike TOKEN_ELEVATION_TYPE which returns TokenElevationTypeDefault when // UAC is turned off, TOKEN_ELEVATION will tell you the process is elevated. DWORD size; TOKEN_ELEVATION elevation; GetTokenInformation(process_token, TokenElevation, &elevation, sizeof(elevation), &size); return elevation.TokenIsElevated != 0; } #endif // defined(OS_WIN) int StartMe2MeNativeMessagingHost() { #if defined(OS_MACOSX) // Needed so we don't leak objects when threads are created. base::mac::ScopedNSAutoreleasePool pool; #endif // defined(OS_MACOSX) // Required to find the ICU data file, used by some file_util routines. base::i18n::InitializeICU(); #if defined(REMOTING_ENABLE_BREAKPAD) // Initialize Breakpad as early as possible. On Mac the command-line needs to // be initialized first, so that the preference for crash-reporting can be // looked up in the config file. if (IsUsageStatsAllowed()) { InitializeCrashReporting(); } #endif // defined(REMOTING_ENABLE_BREAKPAD) // Mac OS X requires that the main thread be a UI message loop in order to // receive distributed notifications from the System Preferences pane. An // IO thread is needed for the pairing registry and URL context getter. base::Thread io_thread("io_thread"); io_thread.StartWithOptions( base::Thread::Options(base::MessageLoop::TYPE_IO, 0)); base::MessageLoopForUI message_loop; base::RunLoop run_loop; scoped_refptr<DaemonController> daemon_controller = DaemonController::Create(); // Pass handle of the native view to the controller so that the UAC prompts // are focused properly. const CommandLine* command_line = CommandLine::ForCurrentProcess(); int64 native_view_handle = 0; if (command_line->HasSwitch(kParentWindowSwitchName)) { std::string native_view = command_line->GetSwitchValueASCII(kParentWindowSwitchName); if (base::StringToInt64(native_view, &native_view_handle)) { daemon_controller->SetWindow(reinterpret_cast<void*>(native_view_handle)); } else { LOG(WARNING) << "Invalid parameter value --" << kParentWindowSwitchName << "=" << native_view; } } base::File read_file; base::File write_file; bool needs_elevation = false; #if defined(OS_WIN) needs_elevation = !IsProcessElevated(); if (command_line->HasSwitch(kElevatingSwitchName)) { DCHECK(!needs_elevation); // The "elevate" switch is always accompanied by the "input" and "output" // switches whose values name named pipes that should be used in place of // stdin and stdout. DCHECK(command_line->HasSwitch(kInputSwitchName)); DCHECK(command_line->HasSwitch(kOutputSwitchName)); // presubmit: allow wstring std::wstring input_pipe_name = command_line->GetSwitchValueNative(kInputSwitchName); // presubmit: allow wstring std::wstring output_pipe_name = command_line->GetSwitchValueNative(kOutputSwitchName); // A NULL SECURITY_ATTRIBUTES signifies that the handle can't be inherited read_file = base::File(CreateFile( input_pipe_name.c_str(), GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL)); if (!read_file.IsValid()) { LOG_GETLASTERROR(ERROR) << "CreateFile failed on '" << input_pipe_name << "'"; return kInitializationFailed; } write_file = base::File(CreateFile( output_pipe_name.c_str(), GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL)); if (!write_file.IsValid()) { LOG_GETLASTERROR(ERROR) << "CreateFile failed on '" << output_pipe_name << "'"; return kInitializationFailed; } } else { // GetStdHandle() returns pseudo-handles for stdin and stdout even if // the hosting executable specifies "Windows" subsystem. However the // returned handles are invalid in that case unless standard input and // output are redirected to a pipe or file. read_file = base::File(GetStdHandle(STD_INPUT_HANDLE)); write_file = base::File(GetStdHandle(STD_OUTPUT_HANDLE)); // After the native messaging channel starts the native messaging reader // will keep doing blocking read operations on the input named pipe. // If any other thread tries to perform any operation on STDIN, it will also // block because the input named pipe is synchronous (non-overlapped). // It is pretty common for a DLL to query the device info (GetFileType) of // the STD* handles at startup. So any LoadLibrary request can potentially // be blocked. To prevent that from happening we close STDIN and STDOUT // handles as soon as we retrieve the corresponding file handles. SetStdHandle(STD_INPUT_HANDLE, NULL); SetStdHandle(STD_OUTPUT_HANDLE, NULL); } #elif defined(OS_POSIX) // The files will be automatically closed. read_file = base::File(STDIN_FILENO); write_file = base::File(STDOUT_FILENO); #else #error Not implemented. #endif // OAuth client (for credential requests). scoped_refptr<net::URLRequestContextGetter> url_request_context_getter( new URLRequestContextGetter(io_thread.message_loop_proxy())); scoped_ptr<OAuthClient> oauth_client( new OAuthClient(url_request_context_getter)); net::URLFetcher::SetIgnoreCertificateRequests(true); // Create the pairing registry. scoped_refptr<PairingRegistry> pairing_registry; #if defined(OS_WIN) base::win::RegKey root; LONG result = root.Open(HKEY_LOCAL_MACHINE, kPairingRegistryKeyName, KEY_READ); if (result != ERROR_SUCCESS) { SetLastError(result); PLOG(ERROR) << "Failed to open HKLM\\" << kPairingRegistryKeyName; return kInitializationFailed; } base::win::RegKey unprivileged; result = unprivileged.Open(root.Handle(), kPairingRegistrySecretsKeyName, needs_elevation ? KEY_READ : KEY_READ | KEY_WRITE); if (result != ERROR_SUCCESS) { SetLastError(result); PLOG(ERROR) << "Failed to open HKLM\\" << kPairingRegistrySecretsKeyName << "\\" << kPairingRegistrySecretsKeyName; return kInitializationFailed; } // Only try to open the privileged key if the current process is elevated. base::win::RegKey privileged; if (!needs_elevation) { result = privileged.Open(root.Handle(), kPairingRegistryClientsKeyName, KEY_READ | KEY_WRITE); if (result != ERROR_SUCCESS) { SetLastError(result); PLOG(ERROR) << "Failed to open HKLM\\" << kPairingRegistryKeyName << "\\" << kPairingRegistryClientsKeyName; return kInitializationFailed; } } // Initialize the pairing registry delegate and set the root keys. scoped_ptr<PairingRegistryDelegateWin> delegate( new PairingRegistryDelegateWin()); if (!delegate->SetRootKeys(privileged.Take(), unprivileged.Take())) return kInitializationFailed; pairing_registry = new PairingRegistry( io_thread.message_loop_proxy(), delegate.PassAs<PairingRegistry::Delegate>()); #else // defined(OS_WIN) pairing_registry = CreatePairingRegistry(io_thread.message_loop_proxy()); #endif // !defined(OS_WIN) // Set up the native messaging channel. scoped_ptr<NativeMessagingChannel> channel( new NativeMessagingChannel(read_file.Pass(), write_file.Pass())); // Create the native messaging host. scoped_ptr<Me2MeNativeMessagingHost> host( new Me2MeNativeMessagingHost( needs_elevation, static_cast<intptr_t>(native_view_handle), channel.Pass(), daemon_controller, pairing_registry, oauth_client.Pass())); host->Start(run_loop.QuitClosure()); // Run the loop until channel is alive. run_loop.Run(); return kSuccessExitCode; } int Me2MeNativeMessagingHostMain(int argc, char** argv) { // This object instance is required by Chrome code (such as MessageLoop). base::AtExitManager exit_manager; CommandLine::Init(argc, argv); remoting::InitHostLogging(); return StartMe2MeNativeMessagingHost(); } } // namespace remoting
Initialize ICU on remoting_native_messaging_host
Initialize ICU on remoting_native_messaging_host BUG=371432 [email protected] Review URL: https://codereview.chromium.org/274933002 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@269413 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
krieger-od/nwjs_chromium.src,axinging/chromium-crosswalk,littlstar/chromium.src,Just-D/chromium-1,mohamed--abdel-maksoud/chromium.src,ltilve/chromium,jaruba/chromium.src,jaruba/chromium.src,markYoungH/chromium.src,TheTypoMaster/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,dednal/chromium.src,PeterWangIntel/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,fujunwei/chromium-crosswalk,ltilve/chromium,M4sse/chromium.src,Fireblend/chromium-crosswalk,M4sse/chromium.src,littlstar/chromium.src,hgl888/chromium-crosswalk-efl,krieger-od/nwjs_chromium.src,M4sse/chromium.src,ltilve/chromium,markYoungH/chromium.src,hgl888/chromium-crosswalk,jaruba/chromium.src,M4sse/chromium.src,hgl888/chromium-crosswalk-efl,fujunwei/chromium-crosswalk,fujunwei/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,ondra-novak/chromium.src,krieger-od/nwjs_chromium.src,fujunwei/chromium-crosswalk,dednal/chromium.src,dednal/chromium.src,crosswalk-project/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,Fireblend/chromium-crosswalk,bright-sparks/chromium-spacewalk,dushu1203/chromium.src,PeterWangIntel/chromium-crosswalk,Jonekee/chromium.src,dednal/chromium.src,markYoungH/chromium.src,M4sse/chromium.src,axinging/chromium-crosswalk,markYoungH/chromium.src,Jonekee/chromium.src,Pluto-tv/chromium-crosswalk,bright-sparks/chromium-spacewalk,hgl888/chromium-crosswalk,ondra-novak/chromium.src,axinging/chromium-crosswalk,axinging/chromium-crosswalk,hgl888/chromium-crosswalk-efl,TheTypoMaster/chromium-crosswalk,krieger-od/nwjs_chromium.src,Jonekee/chromium.src,dednal/chromium.src,Chilledheart/chromium,markYoungH/chromium.src,ondra-novak/chromium.src,Fireblend/chromium-crosswalk,ltilve/chromium,crosswalk-project/chromium-crosswalk-efl,ltilve/chromium,littlstar/chromium.src,hgl888/chromium-crosswalk,axinging/chromium-crosswalk,axinging/chromium-crosswalk,krieger-od/nwjs_chromium.src,Fireblend/chromium-crosswalk,markYoungH/chromium.src,jaruba/chromium.src,hgl888/chromium-crosswalk-efl,PeterWangIntel/chromium-crosswalk,ltilve/chromium,bright-sparks/chromium-spacewalk,bright-sparks/chromium-spacewalk,Jonekee/chromium.src,hgl888/chromium-crosswalk,ondra-novak/chromium.src,jaruba/chromium.src,mohamed--abdel-maksoud/chromium.src,dednal/chromium.src,Just-D/chromium-1,Just-D/chromium-1,krieger-od/nwjs_chromium.src,TheTypoMaster/chromium-crosswalk,ltilve/chromium,axinging/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,hgl888/chromium-crosswalk-efl,chuan9/chromium-crosswalk,Jonekee/chromium.src,crosswalk-project/chromium-crosswalk-efl,markYoungH/chromium.src,littlstar/chromium.src,dushu1203/chromium.src,Pluto-tv/chromium-crosswalk,chuan9/chromium-crosswalk,littlstar/chromium.src,hgl888/chromium-crosswalk-efl,ltilve/chromium,dednal/chromium.src,Jonekee/chromium.src,hgl888/chromium-crosswalk,ondra-novak/chromium.src,Chilledheart/chromium,hgl888/chromium-crosswalk,Just-D/chromium-1,fujunwei/chromium-crosswalk,M4sse/chromium.src,jaruba/chromium.src,Pluto-tv/chromium-crosswalk,M4sse/chromium.src,markYoungH/chromium.src,Jonekee/chromium.src,hgl888/chromium-crosswalk-efl,Chilledheart/chromium,Jonekee/chromium.src,axinging/chromium-crosswalk,Just-D/chromium-1,ondra-novak/chromium.src,littlstar/chromium.src,chuan9/chromium-crosswalk,dednal/chromium.src,jaruba/chromium.src,TheTypoMaster/chromium-crosswalk,dushu1203/chromium.src,Fireblend/chromium-crosswalk,bright-sparks/chromium-spacewalk,PeterWangIntel/chromium-crosswalk,markYoungH/chromium.src,dednal/chromium.src,Fireblend/chromium-crosswalk,chuan9/chromium-crosswalk,bright-sparks/chromium-spacewalk,hgl888/chromium-crosswalk,krieger-od/nwjs_chromium.src,Pluto-tv/chromium-crosswalk,jaruba/chromium.src,TheTypoMaster/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,fujunwei/chromium-crosswalk,dednal/chromium.src,mohamed--abdel-maksoud/chromium.src,TheTypoMaster/chromium-crosswalk,Chilledheart/chromium,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk-efl,dushu1203/chromium.src,chuan9/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,crosswalk-project/chromium-crosswalk-efl,dushu1203/chromium.src,mohamed--abdel-maksoud/chromium.src,Just-D/chromium-1,bright-sparks/chromium-spacewalk,ondra-novak/chromium.src,chuan9/chromium-crosswalk,fujunwei/chromium-crosswalk,littlstar/chromium.src,mohamed--abdel-maksoud/chromium.src,Chilledheart/chromium,Just-D/chromium-1,TheTypoMaster/chromium-crosswalk,ltilve/chromium,jaruba/chromium.src,Pluto-tv/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,markYoungH/chromium.src,Chilledheart/chromium,crosswalk-project/chromium-crosswalk-efl,Jonekee/chromium.src,dushu1203/chromium.src,dushu1203/chromium.src,Chilledheart/chromium,ondra-novak/chromium.src,M4sse/chromium.src,Just-D/chromium-1,axinging/chromium-crosswalk,krieger-od/nwjs_chromium.src,chuan9/chromium-crosswalk,Fireblend/chromium-crosswalk,ondra-novak/chromium.src,PeterWangIntel/chromium-crosswalk,jaruba/chromium.src,dednal/chromium.src,M4sse/chromium.src,Jonekee/chromium.src,mohamed--abdel-maksoud/chromium.src,Jonekee/chromium.src,hgl888/chromium-crosswalk,hgl888/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,fujunwei/chromium-crosswalk,Fireblend/chromium-crosswalk,M4sse/chromium.src,PeterWangIntel/chromium-crosswalk,axinging/chromium-crosswalk,bright-sparks/chromium-spacewalk,dushu1203/chromium.src,Just-D/chromium-1,Fireblend/chromium-crosswalk,dushu1203/chromium.src,Chilledheart/chromium,Pluto-tv/chromium-crosswalk,Pluto-tv/chromium-crosswalk,krieger-od/nwjs_chromium.src,axinging/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,M4sse/chromium.src,hgl888/chromium-crosswalk-efl,Chilledheart/chromium,dushu1203/chromium.src,chuan9/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,hgl888/chromium-crosswalk-efl,krieger-od/nwjs_chromium.src,krieger-od/nwjs_chromium.src,littlstar/chromium.src,fujunwei/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,chuan9/chromium-crosswalk,bright-sparks/chromium-spacewalk,Pluto-tv/chromium-crosswalk,jaruba/chromium.src,crosswalk-project/chromium-crosswalk-efl,markYoungH/chromium.src,dushu1203/chromium.src
e5168811a25484521268024d09f5a1d89046d8f8
dune/stuff/grid/periodicview.hh
dune/stuff/grid/periodicview.hh
// This file is part of the dune-stuff project: // https://github.com/wwu-numerik/dune-stuff/ // Copyright holders: Rene Milk, Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) // // Contributors: Tobias Leibner #ifndef DUNE_STUFF_GRID_PERIODICVIEW_HH #define DUNE_STUFF_GRID_PERIODICVIEW_HH #include <bitset> #include <map> #include <utility> #include <vector> #include <dune/grid/common/gridview.hh> #include <dune/stuff/aliases.hh> #include <dune/stuff/common/exceptions.hh> #include <dune/stuff/common/memory.hh> #include <dune/stuff/common/float_cmp.hh> #include <dune/stuff/common/ranges.hh> #include <dune/stuff/grid/search.hh> #include <dune/stuff/grid/information.hh> namespace Dune { namespace Stuff { namespace Grid { namespace internal { template< class RealGridViewImp > class PeriodicIntersection : public RealGridViewImp::Intersection { typedef RealGridViewImp RealGridViewType; typedef PeriodicIntersection< RealGridViewType > ThisType; typedef typename RealGridViewType::Intersection BaseType; public: typedef typename BaseType::LocalGeometry LocalGeometry; typedef typename BaseType::Geometry::GlobalCoordinate GlobalCoordinate; typedef typename BaseType::EntityPointer EntityPointer; typedef typename RealGridViewType::IntersectionIterator RealIntersectionIteratorType; static const size_t dimDomain = RealGridViewType::dimension; //! \brief Constructor from real intersection PeriodicIntersection(const BaseType& real_intersection, const RealGridViewType& real_grid_view, const std::pair< bool, EntityPointer >& periodic_pair) : BaseType(real_intersection) , periodic_(periodic_pair.first) , outside_(periodic_pair.second) , real_grid_view_(new DSC::ConstStorageProvider< RealGridViewType >(real_grid_view)) {} // methods that differ from BaseType bool neighbor() const { if (periodic_) return true; else return BaseType::neighbor(); } bool boundary() const { if (periodic_) return false; else return BaseType::boundary(); } bool periodic() const { return periodic_; } EntityPointer outside() const { if (periodic_) return outside_; else return BaseType::outside(); } LocalGeometry geometryInOutside() const { if (periodic_) { const RealIntersectionIteratorType outside_intersection_it = find_intersection_in_outside(); return outside_intersection_it->geometryInInside(); } else { return BaseType::geometryInOutside(); } } //geometryInOutSide int indexInOutside() const { if (periodic_) { const RealIntersectionIteratorType outside_intersection_it = find_intersection_in_outside(); return outside_intersection_it->indexInInside(); } else { return BaseType::indexInOutside(); } } private: // tries to find intersection in outside (works only if periodic_ == true) RealIntersectionIteratorType find_intersection_in_outside() const { const GlobalCoordinate coords = this->geometry().center(); RealIntersectionIteratorType outside_i_it = real_grid_view_->access().ibegin(*outside()); const RealIntersectionIteratorType outside_i_it_end = real_grid_view_->access().iend(*outside()); // walk over outside intersections and find an intersection on the boundary that differs only in one coordinate for ( ; outside_i_it != outside_i_it_end; ++outside_i_it) { const BaseType& curr_outside_intersection = *outside_i_it; if (curr_outside_intersection.boundary()) { const GlobalCoordinate curr_outside_intersection_coords = curr_outside_intersection.geometry().center(); size_t coord_difference_count = 0; for (size_t ii = 0; ii < dimDomain; ++ii) { if (Dune::Stuff::Common::FloatCmp::ne(curr_outside_intersection_coords[ii], coords[ii])) { ++coord_difference_count; } } if (coord_difference_count == size_t(1)) { return outside_i_it; } } } DUNE_THROW(Dune::InvalidStateException, "Could not find outside intersection!"); return real_grid_view_->access().ibegin(*outside()); } protected: bool periodic_; EntityPointer outside_; std::unique_ptr< DSC::ConstStorageProvider< RealGridViewType > > real_grid_view_; }; // ... class PeriodicIntersection ... template< class RealGridViewImp > class PeriodicIntersectionIterator : public RealGridViewImp::IntersectionIterator { typedef RealGridViewImp RealGridViewType; typedef PeriodicIntersectionIterator< RealGridViewType > ThisType; typedef typename RealGridViewType::IntersectionIterator BaseType; public: typedef typename BaseType::Intersection RealIntersectionType; typedef int IntersectionIndexType; typedef typename RealIntersectionType::EntityPointer EntityPointerType; typedef PeriodicIntersection< RealGridViewType > Intersection; typedef typename RealGridViewType::template Codim< 0 >::Entity EntityType; static const size_t dimDomain = RealGridViewType::dimension; /** Copy Constructor from real intersection iterator*/ PeriodicIntersectionIterator(BaseType real_intersection_iterator, const RealGridViewType& real_grid_view, const EntityType& entity, const std::map< IntersectionIndexType, std::pair< bool, EntityPointerType > >& intersection_map) : BaseType(real_intersection_iterator) , real_grid_view_(real_grid_view) , entity_(entity) , has_boundary_intersections_(entity_.hasBoundaryIntersections()) , intersection_map_(intersection_map) , current_intersection_(create_current_intersection_safely()) {} // methods that differ from BaseType const Intersection& operator*() const { current_intersection_ = create_current_intersection(); return *current_intersection_; } const Intersection* operator->() const { current_intersection_ = create_current_intersection(); return &(*current_intersection_); } ThisType& operator++() { BaseType::operator++(); return *this; } private: std::unique_ptr< Intersection > create_current_intersection() const { return DSC::make_unique< Intersection >(BaseType::operator*(), real_grid_view_, has_boundary_intersections_ ? intersection_map_.at((BaseType::operator*()).indexInInside()) : std::make_pair(bool(false), EntityPointerType(entity_))); } std::unique_ptr< Intersection > create_current_intersection_safely() const { const bool is_iend = (*this == real_grid_view_.iend(entity_)); const RealIntersectionType& real_intersection = is_iend ? *real_grid_view_.ibegin(entity_) : BaseType::operator*(); return DSC::make_unique< Intersection >(real_intersection, real_grid_view_, has_boundary_intersections_ ? intersection_map_.at(real_intersection.indexInInside()) : std::make_pair(bool(false), EntityPointerType(entity_))); } const RealGridViewType& real_grid_view_; const EntityType& entity_; const bool has_boundary_intersections_; const std::map< IntersectionIndexType, std::pair< bool, EntityPointerType > >& intersection_map_; mutable std::unique_ptr< Intersection > current_intersection_; }; // ... class PeriodicIntersectionIterator ... // forward template< class RealGridViewImp > class PeriodicGridViewImp; template< class RealGridViewImp > class PeriodicGridViewTraits { public: typedef RealGridViewImp RealGridViewType; // use types from RealGridViewType... typedef PeriodicGridViewImp< RealGridViewType > GridViewImp; typedef typename RealGridViewType::Grid Grid; typedef typename RealGridViewType::IndexSet IndexSet; typedef typename RealGridViewType::CollectiveCommunication CollectiveCommunication; typedef typename RealGridViewType::Traits RealGridViewTraits; template< int cd > struct Codim { typedef typename RealGridViewTraits::template Codim< cd >::Iterator Iterator; typedef typename RealGridViewTraits::template Codim< cd >::EntityPointer EntityPointer; typedef typename RealGridViewTraits::template Codim< cd >::Entity Entity; typedef typename RealGridViewTraits::template Codim< cd >::Geometry Geometry; typedef typename RealGridViewTraits::template Codim< cd >::LocalGeometry LocalGeometry; template< PartitionIteratorType pit > struct Partition { typedef typename RealGridViewTraits::template Codim< cd >::template Partition< pit >::Iterator Iterator; }; }; // ... struct Codim ... enum { conforming = RealGridViewTraits::conforming }; enum { dimension = Grid::dimension }; enum { dimensionworld = Grid::dimensionworld }; typedef typename Grid::ctype ctype; // ...except for the Intersection and IntersectionIterator typedef PeriodicIntersection< RealGridViewType > Intersection; typedef PeriodicIntersectionIterator< RealGridViewType > IntersectionIterator; }; // ... class PeriodicGridViewTraits ... template< class RealGridViewImp > class PeriodicGridViewImp : public RealGridViewImp { typedef RealGridViewImp BaseType; typedef PeriodicGridViewImp< BaseType > ThisType; typedef PeriodicGridViewTraits< BaseType > Traits; public: typedef typename BaseType::Grid Grid; typedef typename BaseType::IndexSet IndexSet; typedef PeriodicIntersectionIterator< BaseType > IntersectionIterator; typedef typename IntersectionIterator::RealIntersectionType RealIntersectionType; typedef typename BaseType::IndexSet::IndexType EntityIndexType; typedef int IntersectionIndexType; typedef typename RealIntersectionType::GlobalCoordinate CoordinateType; typedef PeriodicIntersection< BaseType > Intersection; typedef typename Grid::template Codim< 0 >::EntityPointer EntityPointerType; static const size_t dimDomain = BaseType::dimension; template< int cd > struct Codim : public Traits::template Codim< cd > {}; /** Constructor from real grid view */ PeriodicGridViewImp(const BaseType& real_grid_view, const std::bitset< dimDomain > periodic_directions) : BaseType(real_grid_view) , periodic_directions_(periodic_directions) { EntityInlevelSearch< BaseType > entity_search(*this); CoordinateType periodic_neighbor_coords; std::map< IntersectionIndexType, std::pair< bool, EntityPointerType > > intersection_neighbor_map; for (const auto& entity : DSC::entityRange(*this)) { if (entity.hasBoundaryIntersections()) { intersection_neighbor_map.clear(); const auto i_it_end = BaseType::iend(entity); for (auto i_it = BaseType::ibegin(entity); i_it != i_it_end; ++i_it) { const RealIntersectionType& intersection = *i_it; const IntersectionIndexType index_in_inside = intersection.indexInInside(); bool is_periodic = false; if (intersection.boundary()) { periodic_neighbor_coords = intersection.geometry().center(); size_t num_boundary_coords = 0; for (std::size_t ii = 0; ii < dimDomain; ++ii) { if (periodic_directions_[ii]) { if (Dune::Stuff::Common::FloatCmp::eq(periodic_neighbor_coords[ii], 0.0)) { is_periodic = true; periodic_neighbor_coords[ii] = 1.0 - 1.0/100.0*entity.geometry().center()[ii]; ++num_boundary_coords; } else if (Dune::Stuff::Common::FloatCmp::eq(periodic_neighbor_coords[ii], 1.0)) { is_periodic = true; periodic_neighbor_coords[ii] = 1.0/100.0*(1.0 - entity.geometry().center()[ii]); ++num_boundary_coords; } } } assert(num_boundary_coords = 1); if (is_periodic) { const auto outside_ptr_ptrs = entity_search(std::vector< CoordinateType >(1, periodic_neighbor_coords)); const auto& outside_ptr_ptr = outside_ptr_ptrs.at(0); const auto& outside_entity = *outside_ptr_ptr; intersection_neighbor_map.insert(std::make_pair(index_in_inside, std::make_pair(is_periodic, EntityPointerType(outside_entity)))); } else { intersection_neighbor_map.insert(std::make_pair(index_in_inside, std::make_pair(is_periodic, EntityPointerType(entity)))); } } else { intersection_neighbor_map.insert(std::make_pair(index_in_inside, std::make_pair(bool(false), EntityPointerType(entity)))); } } entity_to_intersection_map_map_.insert(std::make_pair(this->indexSet().index(entity), intersection_neighbor_map)); } } } IntersectionIterator ibegin(const typename Codim< 0 >::Entity& entity) const { if (entity.hasBoundaryIntersections()) return IntersectionIterator(BaseType::ibegin(entity), *this, entity, entity_to_intersection_map_map_.at(this->indexSet().index(entity))); else return IntersectionIterator(BaseType::ibegin(entity), *this, entity, std::map< IntersectionIndexType, std::pair< bool, EntityPointerType > >()); } IntersectionIterator iend(const typename Codim< 0 >::Entity& entity) const { if (entity.hasBoundaryIntersections()) return IntersectionIterator(BaseType::iend(entity), *this, entity, entity_to_intersection_map_map_.at(this->indexSet().index(entity))); else return IntersectionIterator(BaseType::iend(entity), *this, entity, std::map< IntersectionIndexType, std::pair< bool, EntityPointerType > >()); } private: std::map< EntityIndexType, std::map< IntersectionIndexType, std::pair< bool, EntityPointerType > > > entity_to_intersection_map_map_; const std::bitset< dimDomain > periodic_directions_; }; // ... class PeriodicGridViewImp ... } // namespace internal template< class RealGridViewImp > class PeriodicGridView : Dune::Stuff::Common::ConstStorageProvider< internal::PeriodicGridViewImp< RealGridViewImp > > , public Dune::GridView< internal::PeriodicGridViewTraits< RealGridViewImp > > { typedef RealGridViewImp RealGridViewType; typedef typename Dune::GridView < internal::PeriodicGridViewTraits< RealGridViewType > > BaseType; typedef typename Dune::Stuff::Common::ConstStorageProvider< internal::PeriodicGridViewImp< RealGridViewImp > > ConstStorProv; public: static const size_t dimension = RealGridViewType::dimension; PeriodicGridView(const RealGridViewType& real_grid_view, const std::bitset< dimension > periodic_directions = std::bitset< dimension >().set()) : ConstStorProv(new internal::PeriodicGridViewImp< RealGridViewType >(real_grid_view, periodic_directions)) , BaseType(ConstStorProv::access()) {} PeriodicGridView(const PeriodicGridView& other) : ConstStorProv(other.access()) , BaseType(ConstStorProv::access()) {} }; // class PeriodicGridView } // namespace Grid } // namespace Stuff } // namespace Dune #endif //DUNE_STUFF_GRID_PERIODICVIEW_HH
// This file is part of the dune-stuff project: // https://github.com/wwu-numerik/dune-stuff/ // Copyright holders: Rene Milk, Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) // // Contributors: Tobias Leibner #ifndef DUNE_STUFF_GRID_PERIODICVIEW_HH #define DUNE_STUFF_GRID_PERIODICVIEW_HH #include <bitset> #include <map> #include <utility> #include <vector> #include <dune/grid/common/gridview.hh> #include <dune/stuff/aliases.hh> #include <dune/stuff/common/exceptions.hh> #include <dune/stuff/common/memory.hh> #include <dune/stuff/common/float_cmp.hh> #include <dune/stuff/common/ranges.hh> #include <dune/stuff/grid/search.hh> #include <dune/stuff/grid/information.hh> namespace Dune { namespace Stuff { namespace Grid { namespace internal { /** \brief Intersection for PeriodicGridView * * PeriodicIntersection is derived from the Intersection of the underlying GridView. On the inside of the grid or if * periodic_ is false, the PeriodicIntersection will behave exactly like its BaseType. If periodic_ is true, the * PeriodicIntersection will return boundary() == false even if it actually is on the boundary. In this case, outside(), * geometryInOutside() and indexInOutside() are well-defined and give the information from the periodically adjacent * entity. To be able to differentiate between PeriodicIntersections on the boundary and PeriodicIntersections inside * the grid, the method 'bool periodic()' has been added. * * \see PeriodicGridView */ template< class RealGridViewImp > class PeriodicIntersection : public RealGridViewImp::Intersection { typedef RealGridViewImp RealGridViewType; typedef PeriodicIntersection< RealGridViewType > ThisType; typedef typename RealGridViewType::Intersection BaseType; public: typedef typename BaseType::LocalGeometry LocalGeometry; typedef typename BaseType::Geometry::GlobalCoordinate GlobalCoordinate; typedef typename BaseType::EntityPointer EntityPointer; typedef typename RealGridViewType::IntersectionIterator RealIntersectionIteratorType; static const size_t dimDomain = RealGridViewType::dimension; //! \brief Constructor from real intersection PeriodicIntersection(const BaseType& real_intersection, const RealGridViewType& real_grid_view, const std::pair< bool, EntityPointer >& periodic_pair) : BaseType(real_intersection) , periodic_(periodic_pair.first) , outside_(periodic_pair.second) , real_grid_view_(new DSC::ConstStorageProvider< RealGridViewType >(real_grid_view)) {} // methods that differ from BaseType bool neighbor() const { if (periodic_) return true; else return BaseType::neighbor(); } bool boundary() const { if (periodic_) return false; else return BaseType::boundary(); } bool periodic() const { return periodic_; } EntityPointer outside() const { if (periodic_) return outside_; else return BaseType::outside(); } LocalGeometry geometryInOutside() const { if (periodic_) { const RealIntersectionIteratorType outside_intersection_it = find_intersection_in_outside(); return outside_intersection_it->geometryInInside(); } else { return BaseType::geometryInOutside(); } } //geometryInOutSide int indexInOutside() const { if (periodic_) { const RealIntersectionIteratorType outside_intersection_it = find_intersection_in_outside(); return outside_intersection_it->indexInInside(); } else { return BaseType::indexInOutside(); } } private: // tries to find intersection in outside (works only if periodic_ == true) RealIntersectionIteratorType find_intersection_in_outside() const { const GlobalCoordinate coords = this->geometry().center(); RealIntersectionIteratorType outside_i_it = real_grid_view_->access().ibegin(*outside()); const RealIntersectionIteratorType outside_i_it_end = real_grid_view_->access().iend(*outside()); // walk over outside intersections and find an intersection on the boundary that differs only in one coordinate for ( ; outside_i_it != outside_i_it_end; ++outside_i_it) { const BaseType& curr_outside_intersection = *outside_i_it; if (curr_outside_intersection.boundary()) { const GlobalCoordinate curr_outside_intersection_coords = curr_outside_intersection.geometry().center(); size_t coord_difference_count = 0; for (size_t ii = 0; ii < dimDomain; ++ii) { if (Dune::Stuff::Common::FloatCmp::ne(curr_outside_intersection_coords[ii], coords[ii])) { ++coord_difference_count; } } if (coord_difference_count == size_t(1)) { return outside_i_it; } } } DUNE_THROW(Dune::InvalidStateException, "Could not find outside intersection!"); return real_grid_view_->access().ibegin(*outside()); } protected: bool periodic_; EntityPointer outside_; std::unique_ptr< DSC::ConstStorageProvider< RealGridViewType > > real_grid_view_; }; // ... class PeriodicIntersection ... /** \brief IntersectionIterator for PeriodicGridView * * PeriodicIntersectionIterator is derived from the IntersectionIterator of the underlying GridView and behaves exactly * like the underlying IntersectionIterator except that it returns a PeriodicIntersection in its operator* and * operator-> methods. * * \see PeriodicGridView */ template< class RealGridViewImp > class PeriodicIntersectionIterator : public RealGridViewImp::IntersectionIterator { typedef RealGridViewImp RealGridViewType; typedef PeriodicIntersectionIterator< RealGridViewType > ThisType; typedef typename RealGridViewType::IntersectionIterator BaseType; public: typedef typename BaseType::Intersection RealIntersectionType; typedef int IntersectionIndexType; typedef typename RealIntersectionType::EntityPointer EntityPointerType; typedef PeriodicIntersection< RealGridViewType > Intersection; typedef typename RealGridViewType::template Codim< 0 >::Entity EntityType; static const size_t dimDomain = RealGridViewType::dimension; PeriodicIntersectionIterator(BaseType real_intersection_iterator, const RealGridViewType& real_grid_view, const EntityType& entity, const std::map< IntersectionIndexType, std::pair< bool, EntityPointerType > >& intersection_map) : BaseType(real_intersection_iterator) , real_grid_view_(real_grid_view) , entity_(entity) , has_boundary_intersections_(entity_.hasBoundaryIntersections()) , intersection_map_(intersection_map) , current_intersection_(create_current_intersection_safely()) {} // methods that differ from BaseType const Intersection& operator*() const { current_intersection_ = create_current_intersection(); return *current_intersection_; } const Intersection* operator->() const { current_intersection_ = create_current_intersection(); return &(*current_intersection_); } ThisType& operator++() { BaseType::operator++(); return *this; } private: std::unique_ptr< Intersection > create_current_intersection() const { return DSC::make_unique< Intersection >(BaseType::operator*(), real_grid_view_, has_boundary_intersections_ ? intersection_map_.at((BaseType::operator*()).indexInInside()) : std::make_pair(bool(false), EntityPointerType(entity_))); } std::unique_ptr< Intersection > create_current_intersection_safely() const { const bool is_iend = (*this == real_grid_view_.iend(entity_)); const RealIntersectionType& real_intersection = is_iend ? *real_grid_view_.ibegin(entity_) : BaseType::operator*(); return DSC::make_unique< Intersection >(real_intersection, real_grid_view_, has_boundary_intersections_ ? intersection_map_.at(real_intersection.indexInInside()) : std::make_pair(bool(false), EntityPointerType(entity_))); } const RealGridViewType& real_grid_view_; const EntityType& entity_; const bool has_boundary_intersections_; const std::map< IntersectionIndexType, std::pair< bool, EntityPointerType > >& intersection_map_; mutable std::unique_ptr< Intersection > current_intersection_; }; // ... class PeriodicIntersectionIterator ... // forward template< class RealGridViewImp > class PeriodicGridViewImp; //! Traits for PeriodicGridView template< class RealGridViewImp > class PeriodicGridViewTraits { public: typedef RealGridViewImp RealGridViewType; // use types from RealGridViewType... typedef PeriodicGridViewImp< RealGridViewType > GridViewImp; typedef typename RealGridViewType::Grid Grid; typedef typename RealGridViewType::IndexSet IndexSet; typedef typename RealGridViewType::CollectiveCommunication CollectiveCommunication; typedef typename RealGridViewType::Traits RealGridViewTraits; template< int cd > struct Codim { typedef typename RealGridViewTraits::template Codim< cd >::Iterator Iterator; typedef typename RealGridViewTraits::template Codim< cd >::EntityPointer EntityPointer; typedef typename RealGridViewTraits::template Codim< cd >::Entity Entity; typedef typename RealGridViewTraits::template Codim< cd >::Geometry Geometry; typedef typename RealGridViewTraits::template Codim< cd >::LocalGeometry LocalGeometry; template< PartitionIteratorType pit > struct Partition { typedef typename RealGridViewTraits::template Codim< cd >::template Partition< pit >::Iterator Iterator; }; }; // ... struct Codim ... enum { conforming = RealGridViewTraits::conforming }; enum { dimension = Grid::dimension }; enum { dimensionworld = Grid::dimensionworld }; typedef typename Grid::ctype ctype; // ...except for the Intersection and IntersectionIterator typedef PeriodicIntersection< RealGridViewType > Intersection; typedef PeriodicIntersectionIterator< RealGridViewType > IntersectionIterator; }; // ... class PeriodicGridViewTraits ... /** \brief Actual Implementation of PeriodicGridView * \see PeriodicGridView */ template< class RealGridViewImp > class PeriodicGridViewImp : public RealGridViewImp { typedef RealGridViewImp BaseType; typedef PeriodicGridViewImp< BaseType > ThisType; typedef PeriodicGridViewTraits< BaseType > Traits; public: typedef typename BaseType::Grid Grid; typedef typename BaseType::IndexSet IndexSet; typedef PeriodicIntersectionIterator< BaseType > IntersectionIterator; typedef typename IntersectionIterator::RealIntersectionType RealIntersectionType; typedef typename BaseType::IndexSet::IndexType EntityIndexType; typedef int IntersectionIndexType; typedef typename RealIntersectionType::GlobalCoordinate CoordinateType; typedef PeriodicIntersection< BaseType > Intersection; typedef typename Grid::template Codim< 0 >::EntityPointer EntityPointerType; static const size_t dimDomain = BaseType::dimension; template< int cd > struct Codim : public Traits::template Codim< cd > {}; PeriodicGridViewImp(const BaseType& real_grid_view, const std::bitset< dimDomain > periodic_directions) : BaseType(real_grid_view) , periodic_directions_(periodic_directions) { EntityInlevelSearch< BaseType > entity_search(*this); CoordinateType periodic_neighbor_coords; std::map< IntersectionIndexType, std::pair< bool, EntityPointerType > > intersection_neighbor_map; for (const auto& entity : DSC::entityRange(*this)) { if (entity.hasBoundaryIntersections()) { intersection_neighbor_map.clear(); const auto i_it_end = BaseType::iend(entity); for (auto i_it = BaseType::ibegin(entity); i_it != i_it_end; ++i_it) { const RealIntersectionType& intersection = *i_it; const IntersectionIndexType index_in_inside = intersection.indexInInside(); bool is_periodic = false; if (intersection.boundary()) { periodic_neighbor_coords = intersection.geometry().center(); size_t num_boundary_coords = 0; for (std::size_t ii = 0; ii < dimDomain; ++ii) { if (periodic_directions_[ii]) { if (Dune::Stuff::Common::FloatCmp::eq(periodic_neighbor_coords[ii], 0.0)) { is_periodic = true; periodic_neighbor_coords[ii] = 1.0 - 1.0/100.0*entity.geometry().center()[ii]; ++num_boundary_coords; } else if (Dune::Stuff::Common::FloatCmp::eq(periodic_neighbor_coords[ii], 1.0)) { is_periodic = true; periodic_neighbor_coords[ii] = 1.0/100.0*(1.0 - entity.geometry().center()[ii]); ++num_boundary_coords; } } } assert(num_boundary_coords = 1); if (is_periodic) { const auto outside_ptr_ptrs = entity_search(std::vector< CoordinateType >(1, periodic_neighbor_coords)); const auto& outside_ptr_ptr = outside_ptr_ptrs.at(0); const auto& outside_entity = *outside_ptr_ptr; intersection_neighbor_map.insert(std::make_pair(index_in_inside, std::make_pair(is_periodic, EntityPointerType(outside_entity)))); } else { intersection_neighbor_map.insert(std::make_pair(index_in_inside, std::make_pair(is_periodic, EntityPointerType(entity)))); } } else { intersection_neighbor_map.insert(std::make_pair(index_in_inside, std::make_pair(bool(false), EntityPointerType(entity)))); } } entity_to_intersection_map_map_.insert(std::make_pair(this->indexSet().index(entity), intersection_neighbor_map)); } } } IntersectionIterator ibegin(const typename Codim< 0 >::Entity& entity) const { if (entity.hasBoundaryIntersections()) return IntersectionIterator(BaseType::ibegin(entity), *this, entity, entity_to_intersection_map_map_.at(this->indexSet().index(entity))); else return IntersectionIterator(BaseType::ibegin(entity), *this, entity, std::map< IntersectionIndexType, std::pair< bool, EntityPointerType > >()); } IntersectionIterator iend(const typename Codim< 0 >::Entity& entity) const { if (entity.hasBoundaryIntersections()) return IntersectionIterator(BaseType::iend(entity), *this, entity, entity_to_intersection_map_map_.at(this->indexSet().index(entity))); else return IntersectionIterator(BaseType::iend(entity), *this, entity, std::map< IntersectionIndexType, std::pair< bool, EntityPointerType > >()); } private: std::map< EntityIndexType, std::map< IntersectionIndexType, std::pair< bool, EntityPointerType > > > entity_to_intersection_map_map_; const std::bitset< dimDomain > periodic_directions_; }; // ... class PeriodicGridViewImp ... } // namespace internal /** \brief GridView that takes an arbitrary Dune::GridView and adds periodic boundaries * * PeriodicGridView is templated by and derived from an arbitrary Dune::GridView. All methods are forwarded to the * underlying GridView except for the ibegin and iend methods. These methods return a PeriodicIntersectionIterator * which again behaves like the underlying IntersectionIterator except that it returns a PeriodicIntersection in its * operator*. The PeriodicIntersection again behaves like an Intersection of the underlying GridView, but may return * boundary() == false and an outside() entity even if it is on the boundary. The outside() entity is the entity * adjacent to the intersection if it is identified with the intersection on the other side of the grid. * In the constructor, PeriodicGridViewImp will build a map mapping boundary entity indices to a map mapping local * intersection indices to a std::pair containing the information whether this intersection shall be periodic and the * outside entity. This may take quite long as finding the outside entity requires a grid walk for each periodic * intersection. * By default, all coordinate directions will be made periodic. By supplying a std::bitset< dimension > you can decide * for each direction whether it should be periodic (1 means periodic, 0 means 'behave like underlying GridView in that * direction'). \note - Currently, PeriodicGridView will only work with GridViews on the unit hypercube - Only cube and regular simplex grids have been tested so far. Other grids may not work properly. This is due to the heuristics for finding the periodic neighbor entity: Given an intersection on the boundary that shall be periodic, the coordinates intersection.geometry().center() are moved to the other side of the grid and then supplied to Dune::Stuff::Grid::EntityInLevelSearch. As the coordinates are on the boundary of the wanted entity, this search will fail for some grids. Thus, the coordinates are moved a little to the inside of the grid before searching for the entity. The moved coordinates will be inside the wanted entity for cube and usual simplex grids but this is not guaranteed for arbitrary grids. */ template< class RealGridViewImp > class PeriodicGridView : Dune::Stuff::Common::ConstStorageProvider< internal::PeriodicGridViewImp< RealGridViewImp > > , public Dune::GridView< internal::PeriodicGridViewTraits< RealGridViewImp > > { typedef RealGridViewImp RealGridViewType; typedef typename Dune::GridView < internal::PeriodicGridViewTraits< RealGridViewType > > BaseType; typedef typename Dune::Stuff::Common::ConstStorageProvider< internal::PeriodicGridViewImp< RealGridViewImp > > ConstStorProv; public: static const size_t dimension = RealGridViewType::dimension; PeriodicGridView(const RealGridViewType& real_grid_view, const std::bitset< dimension > periodic_directions = std::bitset< dimension >().set()) : ConstStorProv(new internal::PeriodicGridViewImp< RealGridViewType >(real_grid_view, periodic_directions)) , BaseType(ConstStorProv::access()) {} PeriodicGridView(const PeriodicGridView& other) : ConstStorProv(other.access()) , BaseType(ConstStorProv::access()) {} }; // class PeriodicGridView } // namespace Grid } // namespace Stuff } // namespace Dune #endif //DUNE_STUFF_GRID_PERIODICVIEW_HH
add some documentation
[grid.periodicview] add some documentation
C++
bsd-2-clause
renemilk/DUNE-Stuff,renemilk/DUNE-Stuff,renemilk/DUNE-Stuff
18edcc8b2d1226f509717612b846b5fb62904482
Source/GenericGraphEditor/Private/GenericGraphAssetEditor/SEdNode_GenericGraphNode.cpp
Source/GenericGraphEditor/Private/GenericGraphAssetEditor/SEdNode_GenericGraphNode.cpp
#include "SEdNode_GenericGraphNode.h" #include "GenericGraphEditorPCH.h" #include "Colors_GenericGraph.h" #include "SLevelOfDetailBranchNode.h" #include "Widgets/Text/SInlineEditableTextBlock.h" #include "SCommentBubble.h" #include "SlateOptMacros.h" #include "SGraphPin.h" #include "GraphEditorSettings.h" #include "EdNode_GenericGraphNode.h" #include "GenericGraphDragConnection.h" #define LOCTEXT_NAMESPACE "EdNode_GenericGraph" ////////////////////////////////////////////////////////////////////////// class SGenericGraphPin : public SGraphPin { public: SLATE_BEGIN_ARGS(SGenericGraphPin) {} SLATE_END_ARGS() void Construct(const FArguments& InArgs, UEdGraphPin* InPin) { this->SetCursor(EMouseCursor::Default); bShowLabel = true; GraphPinObj = InPin; check(GraphPinObj != nullptr); const UEdGraphSchema* Schema = GraphPinObj->GetSchema(); check(Schema); SBorder::Construct(SBorder::FArguments() .BorderImage(this, &SGenericGraphPin::GetPinBorder) .BorderBackgroundColor(this, &SGenericGraphPin::GetPinColor) .OnMouseButtonDown(this, &SGenericGraphPin::OnPinMouseDown) .Cursor(this, &SGenericGraphPin::GetPinCursor) .Padding(FMargin(5.0f)) ); } protected: virtual FSlateColor GetPinColor() const override { return GenericGraphColors::Pin::Default; } virtual TSharedRef<SWidget> GetDefaultValueWidget() override { return SNew(STextBlock); } const FSlateBrush* GetPinBorder() const { return FEditorStyle::GetBrush(TEXT("Graph.StateNode.Body")); } virtual TSharedRef<FDragDropOperation> SpawnPinDragEvent(const TSharedRef<class SGraphPanel>& InGraphPanel, const TArray< TSharedRef<SGraphPin> >& InStartingPins) override { FGenericGraphDragConnection::FDraggedPinTable PinHandles; PinHandles.Reserve(InStartingPins.Num()); // since the graph can be refreshed and pins can be reconstructed/replaced // behind the scenes, the DragDropOperation holds onto FGraphPinHandles // instead of direct widgets/graph-pins for (const TSharedRef<SGraphPin>& PinWidget : InStartingPins) { PinHandles.Add(PinWidget->GetPinObj()); } return FGenericGraphDragConnection::New(InGraphPanel, PinHandles); } }; ////////////////////////////////////////////////////////////////////////// void SEdNode_GenericGraphNode::Construct(const FArguments& InArgs, UEdNode_GenericGraphNode* InNode) { GraphNode = InNode; UpdateGraphNode(); InNode->SEdNode = this; } BEGIN_SLATE_FUNCTION_BUILD_OPTIMIZATION void SEdNode_GenericGraphNode::UpdateGraphNode() { const FMargin NodePadding = FMargin(5); const FMargin NamePadding = FMargin(2); InputPins.Empty(); OutputPins.Empty(); // Reset variables that are going to be exposed, in case we are refreshing an already setup node. RightNodeBox.Reset(); LeftNodeBox.Reset(); const FSlateBrush *NodeTypeIcon = GetNameIcon(); FLinearColor TitleShadowColor(0.6f, 0.6f, 0.6f); TSharedPtr<SErrorText> ErrorText; TSharedPtr<SVerticalBox> NodeBody; TSharedPtr<SNodeTitle> NodeTitle = SNew(SNodeTitle, GraphNode); this->ContentScale.Bind(this, &SGraphNode::GetContentScale); this->GetOrAddSlot(ENodeZone::Center) .HAlign(HAlign_Fill) .VAlign(VAlign_Center) [ SNew(SBorder) .BorderImage(FEditorStyle::GetBrush("Graph.StateNode.Body")) .Padding(0.0f) .BorderBackgroundColor(this, &SEdNode_GenericGraphNode::GetBorderBackgroundColor) [ SNew(SOverlay) // Pins and node details + SOverlay::Slot() .HAlign(HAlign_Fill) .VAlign(VAlign_Fill) [ SNew(SVerticalBox) // INPUT PIN AREA + SVerticalBox::Slot() .AutoHeight() [ SNew(SBox) .MinDesiredHeight(NodePadding.Top) [ SAssignNew(LeftNodeBox, SVerticalBox) ] ] // STATE NAME AREA + SVerticalBox::Slot() .Padding(NamePadding) [ SNew(SVerticalBox) + SVerticalBox::Slot() .AutoHeight() [ SNew(SBorder) .BorderImage(FEditorStyle::GetBrush("Graph.StateNode.ColorSpill")) .BorderBackgroundColor(TitleShadowColor) .HAlign(HAlign_Center) .VAlign(VAlign_Center) .Visibility(EVisibility::SelfHitTestInvisible) .Padding(6.0f) [ SAssignNew(NodeBody, SVerticalBox) // Title + SVerticalBox::Slot() .AutoHeight() [ SNew(SHorizontalBox) // Error message + SHorizontalBox::Slot() .AutoWidth() [ SAssignNew(ErrorText, SErrorText) .BackgroundColor(this, &SEdNode_GenericGraphNode::GetErrorColor) .ToolTipText(this, &SEdNode_GenericGraphNode::GetErrorMsgToolTip) ] // Icon +SHorizontalBox::Slot() .AutoWidth() .VAlign(VAlign_Center) [ SNew(SImage) .Image(NodeTypeIcon) ] // Node Title + SHorizontalBox::Slot() .Padding(FMargin(4.0f, 0.0f, 4.0f, 0.0f)) [ SNew(SVerticalBox) + SVerticalBox::Slot() .AutoHeight() [ SAssignNew(InlineEditableText, SInlineEditableTextBlock) .Style(FEditorStyle::Get(), "Graph.StateNode.NodeTitleInlineEditableText") .Text(NodeTitle.Get(), &SNodeTitle::GetHeadTitle) .OnVerifyTextChanged(this, &SEdNode_GenericGraphNode::OnVerifyNameTextChanged) .OnTextCommitted(this, &SEdNode_GenericGraphNode::OnNameTextCommited) .IsReadOnly(this, &SEdNode_GenericGraphNode::IsNameReadOnly) .IsSelected(this, &SEdNode_GenericGraphNode::IsSelectedExclusively) ] + SVerticalBox::Slot() .AutoHeight() [ NodeTitle.ToSharedRef() ] ] ] ] ] ] // OUTPUT PIN AREA + SVerticalBox::Slot() .AutoHeight() [ SNew(SBox) .MinDesiredHeight(NodePadding.Top) [ SAssignNew(RightNodeBox, SVerticalBox) ] ] ] ] ]; // Create comment bubble TSharedPtr<SCommentBubble> CommentBubble; const FSlateColor CommentColor = GetDefault<UGraphEditorSettings>()->DefaultCommentNodeTitleColor; SAssignNew(CommentBubble, SCommentBubble) .GraphNode(GraphNode) .Text(this, &SGraphNode::GetNodeComment) .OnTextCommitted(this, &SGraphNode::OnCommentTextCommitted) .ColorAndOpacity(CommentColor) .AllowPinning(true) .EnableTitleBarBubble(true) .EnableBubbleCtrls(true) .GraphLOD(this, &SGraphNode::GetCurrentLOD) .IsGraphNodeHovered(this, &SGraphNode::IsHovered); GetOrAddSlot(ENodeZone::TopCenter) .SlotOffset(TAttribute<FVector2D>(CommentBubble.Get(), &SCommentBubble::GetOffset)) .SlotSize(TAttribute<FVector2D>(CommentBubble.Get(), &SCommentBubble::GetSize)) .AllowScaling(TAttribute<bool>(CommentBubble.Get(), &SCommentBubble::IsScalingAllowed)) .VAlign(VAlign_Top) [ CommentBubble.ToSharedRef() ]; ErrorReporting = ErrorText; ErrorReporting->SetError(ErrorMsg); CreatePinWidgets(); } void SEdNode_GenericGraphNode::CreatePinWidgets() { UEdNode_GenericGraphNode* StateNode = CastChecked<UEdNode_GenericGraphNode>(GraphNode); for (int32 PinIdx = 0; PinIdx < StateNode->Pins.Num(); PinIdx++) { UEdGraphPin* MyPin = StateNode->Pins[PinIdx]; if (!MyPin->bHidden) { TSharedPtr<SGraphPin> NewPin = SNew(SGenericGraphPin, MyPin); AddPin(NewPin.ToSharedRef()); } } } void SEdNode_GenericGraphNode::AddPin(const TSharedRef<SGraphPin>& PinToAdd) { PinToAdd->SetOwner(SharedThis(this)); const UEdGraphPin* PinObj = PinToAdd->GetPinObj(); const bool bAdvancedParameter = PinObj && PinObj->bAdvancedView; if (bAdvancedParameter) { PinToAdd->SetVisibility( TAttribute<EVisibility>(PinToAdd, &SGraphPin::IsPinVisibleAsAdvanced) ); } TSharedPtr<SVerticalBox> PinBox; if (PinToAdd->GetDirection() == EEdGraphPinDirection::EGPD_Input) { PinBox = LeftNodeBox; InputPins.Add(PinToAdd); } else // Direction == EEdGraphPinDirection::EGPD_Output { PinBox = RightNodeBox; OutputPins.Add(PinToAdd); } PinBox->AddSlot() .HAlign(HAlign_Fill) .VAlign(VAlign_Fill) .FillHeight(1.0f) //.Padding(6.0f, 0.0f) [ PinToAdd ]; } bool SEdNode_GenericGraphNode::IsNameReadOnly() const { UEdNode_GenericGraphNode* EdNode_Node = Cast<UEdNode_GenericGraphNode>(GraphNode); check(EdNode_Node != nullptr); UGenericGraph* GenericGraph = EdNode_Node->GenericGraphNode->Graph; check(GenericGraph != nullptr); return !GenericGraph->bCanRenameNode || SGraphNode::IsNameReadOnly(); } END_SLATE_FUNCTION_BUILD_OPTIMIZATION void SEdNode_GenericGraphNode::OnNameTextCommited(const FText& InText, ETextCommit::Type CommitInfo) { SGraphNode::OnNameTextCommited(InText, CommitInfo); UEdNode_GenericGraphNode* MyNode = CastChecked<UEdNode_GenericGraphNode>(GraphNode); if (MyNode != nullptr && MyNode->GenericGraphNode != nullptr) { const FScopedTransaction Transaction(LOCTEXT("GenericGraphEditorRenameNode", "Generic Graph Editor: Rename Node")); MyNode->Modify(); MyNode->GenericGraphNode->Modify(); MyNode->GenericGraphNode->SetNodeTitle(InText); UpdateGraphNode(); } } FSlateColor SEdNode_GenericGraphNode::GetBorderBackgroundColor() const { UEdNode_GenericGraphNode* MyNode = CastChecked<UEdNode_GenericGraphNode>(GraphNode); return MyNode ? MyNode->GetBackgroundColor() : GenericGraphColors::NodeBorder::HighlightAbortRange0; } FSlateColor SEdNode_GenericGraphNode::GetBackgroundColor() const { return GenericGraphColors::NodeBody::Default; } EVisibility SEdNode_GenericGraphNode::GetDragOverMarkerVisibility() const { return EVisibility::Visible; } const FSlateBrush* SEdNode_GenericGraphNode::GetNameIcon() const { return FEditorStyle::GetBrush(TEXT("BTEditor.Graph.BTNode.Icon")); } #undef LOCTEXT_NAMESPACE
#include "SEdNode_GenericGraphNode.h" #include "GenericGraphEditorPCH.h" #include "Colors_GenericGraph.h" #include "SLevelOfDetailBranchNode.h" #include "Widgets/Text/SInlineEditableTextBlock.h" #include "SCommentBubble.h" #include "SlateOptMacros.h" #include "SGraphPin.h" #include "GraphEditorSettings.h" #include "EdNode_GenericGraphNode.h" #include "GenericGraphDragConnection.h" #define LOCTEXT_NAMESPACE "EdNode_GenericGraph" ////////////////////////////////////////////////////////////////////////// class SGenericGraphPin : public SGraphPin { public: SLATE_BEGIN_ARGS(SGenericGraphPin) {} SLATE_END_ARGS() void Construct(const FArguments& InArgs, UEdGraphPin* InPin) { this->SetCursor(EMouseCursor::Default); bShowLabel = true; GraphPinObj = InPin; check(GraphPinObj != nullptr); const UEdGraphSchema* Schema = GraphPinObj->GetSchema(); check(Schema); SBorder::Construct(SBorder::FArguments() .BorderImage(this, &SGenericGraphPin::GetPinBorder) .BorderBackgroundColor(this, &SGenericGraphPin::GetPinColor) .OnMouseButtonDown(this, &SGenericGraphPin::OnPinMouseDown) .Cursor(this, &SGenericGraphPin::GetPinCursor) .Padding(FMargin(5.0f)) ); } protected: virtual FSlateColor GetPinColor() const override { return GenericGraphColors::Pin::Default; } virtual TSharedRef<SWidget> GetDefaultValueWidget() override { return SNew(STextBlock); } const FSlateBrush* GetPinBorder() const { return FEditorStyle::GetBrush(TEXT("Graph.StateNode.Body")); } virtual TSharedRef<FDragDropOperation> SpawnPinDragEvent(const TSharedRef<class SGraphPanel>& InGraphPanel, const TArray< TSharedRef<SGraphPin> >& InStartingPins) override { FGenericGraphDragConnection::FDraggedPinTable PinHandles; PinHandles.Reserve(InStartingPins.Num()); // since the graph can be refreshed and pins can be reconstructed/replaced // behind the scenes, the DragDropOperation holds onto FGraphPinHandles // instead of direct widgets/graph-pins for (const TSharedRef<SGraphPin>& PinWidget : InStartingPins) { PinHandles.Add(PinWidget->GetPinObj()); } return FGenericGraphDragConnection::New(InGraphPanel, PinHandles); } }; ////////////////////////////////////////////////////////////////////////// void SEdNode_GenericGraphNode::Construct(const FArguments& InArgs, UEdNode_GenericGraphNode* InNode) { GraphNode = InNode; UpdateGraphNode(); InNode->SEdNode = this; } BEGIN_SLATE_FUNCTION_BUILD_OPTIMIZATION void SEdNode_GenericGraphNode::UpdateGraphNode() { const FMargin NodePadding = FMargin(5); const FMargin NamePadding = FMargin(2); InputPins.Empty(); OutputPins.Empty(); // Reset variables that are going to be exposed, in case we are refreshing an already setup node. RightNodeBox.Reset(); LeftNodeBox.Reset(); const FSlateBrush *NodeTypeIcon = GetNameIcon(); FLinearColor TitleShadowColor(0.6f, 0.6f, 0.6f); TSharedPtr<SErrorText> ErrorText; TSharedPtr<SVerticalBox> NodeBody; TSharedPtr<SNodeTitle> NodeTitle = SNew(SNodeTitle, GraphNode); this->ContentScale.Bind(this, &SGraphNode::GetContentScale); this->GetOrAddSlot(ENodeZone::Center) .HAlign(HAlign_Fill) .VAlign(VAlign_Center) [ SNew(SBorder) .BorderImage(FEditorStyle::GetBrush("Graph.StateNode.Body")) .Padding(0.0f) .BorderBackgroundColor(this, &SEdNode_GenericGraphNode::GetBorderBackgroundColor) [ SNew(SOverlay) // Input Pin Area + SOverlay::Slot() .HAlign(HAlign_Fill) .VAlign(VAlign_Fill) [ SAssignNew(LeftNodeBox, SVerticalBox) ] // Output Pin Area + SOverlay::Slot() .HAlign(HAlign_Fill) .VAlign(VAlign_Fill) [ SAssignNew(RightNodeBox, SVerticalBox) ] + SOverlay::Slot() .HAlign(HAlign_Center) .VAlign(VAlign_Center) .Padding(8.0f) [ SNew(SBorder) .BorderImage(FEditorStyle::GetBrush("Graph.StateNode.ColorSpill")) .BorderBackgroundColor(TitleShadowColor) .HAlign(HAlign_Center) .VAlign(VAlign_Center) .Visibility(EVisibility::SelfHitTestInvisible) .Padding(6.0f) [ SAssignNew(NodeBody, SVerticalBox) // Title + SVerticalBox::Slot() .AutoHeight() [ SNew(SHorizontalBox) // Error message + SHorizontalBox::Slot() .AutoWidth() [ SAssignNew(ErrorText, SErrorText) .BackgroundColor(this, &SEdNode_GenericGraphNode::GetErrorColor) .ToolTipText(this, &SEdNode_GenericGraphNode::GetErrorMsgToolTip) ] // Icon +SHorizontalBox::Slot() .AutoWidth() .VAlign(VAlign_Center) [ SNew(SImage) .Image(NodeTypeIcon) ] // Node Title + SHorizontalBox::Slot() .Padding(FMargin(4.0f, 0.0f, 4.0f, 0.0f)) [ SNew(SVerticalBox) + SVerticalBox::Slot() .AutoHeight() [ SAssignNew(InlineEditableText, SInlineEditableTextBlock) .Style(FEditorStyle::Get(), "Graph.StateNode.NodeTitleInlineEditableText") .Text(NodeTitle.Get(), &SNodeTitle::GetHeadTitle) .OnVerifyTextChanged(this, &SEdNode_GenericGraphNode::OnVerifyNameTextChanged) .OnTextCommitted(this, &SEdNode_GenericGraphNode::OnNameTextCommited) .IsReadOnly(this, &SEdNode_GenericGraphNode::IsNameReadOnly) .IsSelected(this, &SEdNode_GenericGraphNode::IsSelectedExclusively) ] + SVerticalBox::Slot() .AutoHeight() [ NodeTitle.ToSharedRef() ] ] ] ] ] ] ]; // Create comment bubble TSharedPtr<SCommentBubble> CommentBubble; const FSlateColor CommentColor = GetDefault<UGraphEditorSettings>()->DefaultCommentNodeTitleColor; SAssignNew(CommentBubble, SCommentBubble) .GraphNode(GraphNode) .Text(this, &SGraphNode::GetNodeComment) .OnTextCommitted(this, &SGraphNode::OnCommentTextCommitted) .ColorAndOpacity(CommentColor) .AllowPinning(true) .EnableTitleBarBubble(true) .EnableBubbleCtrls(true) .GraphLOD(this, &SGraphNode::GetCurrentLOD) .IsGraphNodeHovered(this, &SGraphNode::IsHovered); GetOrAddSlot(ENodeZone::TopCenter) .SlotOffset(TAttribute<FVector2D>(CommentBubble.Get(), &SCommentBubble::GetOffset)) .SlotSize(TAttribute<FVector2D>(CommentBubble.Get(), &SCommentBubble::GetSize)) .AllowScaling(TAttribute<bool>(CommentBubble.Get(), &SCommentBubble::IsScalingAllowed)) .VAlign(VAlign_Top) [ CommentBubble.ToSharedRef() ]; ErrorReporting = ErrorText; ErrorReporting->SetError(ErrorMsg); CreatePinWidgets(); } void SEdNode_GenericGraphNode::CreatePinWidgets() { UEdNode_GenericGraphNode* StateNode = CastChecked<UEdNode_GenericGraphNode>(GraphNode); for (int32 PinIdx = 0; PinIdx < StateNode->Pins.Num(); PinIdx++) { UEdGraphPin* MyPin = StateNode->Pins[PinIdx]; if (!MyPin->bHidden) { TSharedPtr<SGraphPin> NewPin = SNew(SGenericGraphPin, MyPin); AddPin(NewPin.ToSharedRef()); } } } void SEdNode_GenericGraphNode::AddPin(const TSharedRef<SGraphPin>& PinToAdd) { PinToAdd->SetOwner(SharedThis(this)); const UEdGraphPin* PinObj = PinToAdd->GetPinObj(); const bool bAdvancedParameter = PinObj && PinObj->bAdvancedView; if (bAdvancedParameter) { PinToAdd->SetVisibility( TAttribute<EVisibility>(PinToAdd, &SGraphPin::IsPinVisibleAsAdvanced) ); } TSharedPtr<SVerticalBox> PinBox; if (PinToAdd->GetDirection() == EEdGraphPinDirection::EGPD_Input) { PinBox = LeftNodeBox; InputPins.Add(PinToAdd); } else // Direction == EEdGraphPinDirection::EGPD_Output { PinBox = RightNodeBox; OutputPins.Add(PinToAdd); } if (PinBox) { PinBox->AddSlot() .HAlign(HAlign_Fill) .VAlign(VAlign_Fill) .FillHeight(1.0f) //.Padding(6.0f, 0.0f) [ PinToAdd ]; } } bool SEdNode_GenericGraphNode::IsNameReadOnly() const { UEdNode_GenericGraphNode* EdNode_Node = Cast<UEdNode_GenericGraphNode>(GraphNode); check(EdNode_Node != nullptr); UGenericGraph* GenericGraph = EdNode_Node->GenericGraphNode->Graph; check(GenericGraph != nullptr); return !GenericGraph->bCanRenameNode || SGraphNode::IsNameReadOnly(); } END_SLATE_FUNCTION_BUILD_OPTIMIZATION void SEdNode_GenericGraphNode::OnNameTextCommited(const FText& InText, ETextCommit::Type CommitInfo) { SGraphNode::OnNameTextCommited(InText, CommitInfo); UEdNode_GenericGraphNode* MyNode = CastChecked<UEdNode_GenericGraphNode>(GraphNode); if (MyNode != nullptr && MyNode->GenericGraphNode != nullptr) { const FScopedTransaction Transaction(LOCTEXT("GenericGraphEditorRenameNode", "Generic Graph Editor: Rename Node")); MyNode->Modify(); MyNode->GenericGraphNode->Modify(); MyNode->GenericGraphNode->SetNodeTitle(InText); UpdateGraphNode(); } } FSlateColor SEdNode_GenericGraphNode::GetBorderBackgroundColor() const { UEdNode_GenericGraphNode* MyNode = CastChecked<UEdNode_GenericGraphNode>(GraphNode); return MyNode ? MyNode->GetBackgroundColor() : GenericGraphColors::NodeBorder::HighlightAbortRange0; } FSlateColor SEdNode_GenericGraphNode::GetBackgroundColor() const { return GenericGraphColors::NodeBody::Default; } EVisibility SEdNode_GenericGraphNode::GetDragOverMarkerVisibility() const { return EVisibility::Visible; } const FSlateBrush* SEdNode_GenericGraphNode::GetNameIcon() const { return FEditorStyle::GetBrush(TEXT("BTEditor.Graph.BTNode.Icon")); } #undef LOCTEXT_NAMESPACE
Make pins less visible
Make pins less visible
C++
mit
jinyuliao/GenericGraph,jinyuliao/GenericGraph,jinyuliao/GenericGraph
3868c9779124d9f8b377a1103a6cd4b31be37021
HLT/BASE/AliHLTTrackGeometry.cxx
HLT/BASE/AliHLTTrackGeometry.cxx
// $Id$ //************************************************************************** //* This file is property of and copyright by the ALICE HLT Project * //* ALICE Experiment at CERN, All rights reserved. * //* * //* Primary Authors: Matthias Richter <[email protected]> * //* for The ALICE HLT Project. * //* * //* Permission to use, copy, modify and distribute this software and its * //* documentation strictly for non-commercial purposes is hereby granted * //* without fee, provided that the above copyright notice appears in all * //* copies and that both the copyright notice and this permission notice * //* appear in the supporting documentation. The authors make no claims * //* about the suitability of this software for any purpose. It is * //* provided "as is" without express or implied warranty. * //************************************************************************** /// @file AliHLTTrackGeometry.cxx /// @author Matthias Richter /// @date 2011-05-20 /// @brief Desciption of a track by a sequence of track points /// #include "AliHLTTrackGeometry.h" #include "AliHLTSpacePointContainer.h" #include "TObjArray.h" #include "TMarker.h" #include "TMath.h" #include <memory> #include <iostream> #include <algorithm> /** ROOT macro for the implementation of ROOT specific class methods */ ClassImp(AliHLTTrackGeometry) AliHLTTrackGeometry::AliHLTTrackGeometry() : TObject(), AliHLTLogging() , fTrackPoints() , fTrackId(-1) { /// standard constructor } AliHLTTrackGeometry::AliHLTTrackGeometry(const AliHLTTrackGeometry& src) : TObject(src), AliHLTLogging() , fTrackPoints(src.fTrackPoints) , fTrackId(src.fTrackId) { /// copy constructor } AliHLTTrackGeometry& AliHLTTrackGeometry::operator=(const AliHLTTrackGeometry& src) { /// assignment operator if (this!=&src) { fTrackPoints.assign(src.fTrackPoints.begin(), src.fTrackPoints.end()); fTrackId=src.fTrackId; } return *this; } AliHLTTrackGeometry::~AliHLTTrackGeometry() { /// destructor } int AliHLTTrackGeometry::AddTrackPoint(const AliHLTTrackPoint& point) { /// add a track point to the list vector<AliHLTTrackPoint>::const_iterator element = find(fTrackPoints.begin(), fTrackPoints.end(), point); if (element==fTrackPoints.end()) { fTrackPoints.push_back(point); } else { HLTError("track point of id %08x already existing", point.GetId()); return -EEXIST; } return 0; } void AliHLTTrackGeometry::Clear(Option_t * /*option*/) { // internal cleanup } void AliHLTTrackGeometry::Print(Option_t *option) const { // print info Print(cout, option); } void AliHLTTrackGeometry::Print(ostream& out, Option_t */*option*/) const { // print to stream out << "AliHLTTrackGeometry::Print" << endl; } void AliHLTTrackGeometry::Draw(Option_t *option) { /// Inherited from TObject, draw the track float scale=250; float center[2]={0.5,0.5}; int markerColor=1; int markerSize=1; TString strOption(option); std::auto_ptr<TObjArray> tokens(strOption.Tokenize(" ")); if (!tokens.get()) return; for (int i=0; i<tokens->GetEntriesFast(); i++) { if (!tokens->At(i)) continue; const char* key=""; TString arg=tokens->At(i)->GetName(); key="scale="; if (arg.BeginsWith(key)) { arg.ReplaceAll(key, ""); scale=arg.Atof(); continue; } key="centerx="; if (arg.BeginsWith(key)) { arg.ReplaceAll(key, ""); center[0]=arg.Atof(); continue; } key="centery="; if (arg.BeginsWith(key)) { arg.ReplaceAll(key, ""); center[1]=arg.Atof(); continue; } key="markercolor="; if (arg.BeginsWith(key)) { arg.ReplaceAll(key, ""); markerColor=arg.Atoi(); continue; } key="markersize="; if (arg.BeginsWith(key)) { arg.ReplaceAll(key, ""); markerSize=arg.Atoi(); continue; } } bool bFirstPoint=true; float firstalpha=0.0; for (vector<AliHLTTrackPoint>::const_iterator point=fTrackPoints.begin(); point!=fTrackPoints.end(); point++) { float alpha=GetPlaneAlpha(point->GetId()); float r=GetPlaneR(point->GetId()); float cosa=TMath::Cos(alpha); float sina=TMath::Sin(alpha); float x = r*sina + point->GetU()*cosa; float y =-r*cosa + point->GetU()*sina; int color=markerColor; if (bFirstPoint) { bFirstPoint=false; TMarker* m=new TMarker(x/(2*scale)+center[0], y/(2*scale)+center[1], 29); m->SetMarkerSize(2); m->SetMarkerColor(2); m->Draw("same"); firstalpha=alpha; } else { color+=9*TMath::Abs(alpha-firstalpha)/TMath::Pi(); } TMarker* m=new TMarker(x/(2*scale)+center[0], y/(2*scale)+center[1], point->GetV()>0?2:5); m->SetMarkerColor(color); m->SetMarkerSize(markerSize); m->Draw("same"); } } int AliHLTTrackGeometry::SetAssociatedSpacePoint(UInt_t planeId, UInt_t spacepointId, int status) { /// set the spacepoint associated with a track point vector<AliHLTTrackPoint>::iterator element = find(fTrackPoints.begin(), fTrackPoints.end(), planeId); if (element==fTrackPoints.end()) return -ENOENT; element->SetAssociatedSpacePoint(spacepointId, status); return 0; } int AliHLTTrackGeometry::GetAssociatedSpacePoint(UInt_t planeId, UInt_t& spacepointId) const { /// get the spacepoint associated with a track point /// return status flag if found, -ENOENT if no associated spacepoint found vector<AliHLTTrackPoint>::const_iterator element = find(fTrackPoints.begin(), fTrackPoints.end(), planeId); if (element==fTrackPoints.end()) return -ENOENT; if (!element->HaveAssociatedSpacePoint()) return -ENODATA; return element->GetAssociatedSpacePoint(spacepointId); } const AliHLTTrackGeometry::AliHLTTrackPoint* AliHLTTrackGeometry::GetTrackPoint(AliHLTUInt32_t id) const { /// get const pointer to track point vector<AliHLTTrackPoint>::const_iterator element = find(fTrackPoints.begin(), fTrackPoints.end(), id); if (element==fTrackPoints.end()) return NULL; return &(*element); } AliHLTTrackGeometry::AliHLTTrackPoint* AliHLTTrackGeometry::GetTrackPoint(AliHLTUInt32_t id) { /// get const pointer to track point vector<AliHLTTrackPoint>::iterator element = find(fTrackPoints.begin(), fTrackPoints.end(), id); if (element==fTrackPoints.end()) return NULL; return &(*element); } int AliHLTTrackGeometry::AssociateSpacePoints(AliHLTSpacePointContainer& points) { /// associate the track space points to the calculated track points vector<AliHLTUInt32_t> ids; points.GetClusterIDs(ids); if (ids.size()>0) return 0; int result=AssociateSpacePoints(&ids[0], ids.size(), points); if (result>0) { HLTInfo("associated %d space point(s) to track points", result); } return result; } int AliHLTTrackGeometry::AssociateSpacePoints(const AliHLTUInt32_t* trackpoints, AliHLTUInt32_t nofPoints, AliHLTSpacePointContainer& points) { /// associate the track space points to the calculated track points if (nofPoints==0) return 0; if (trackpoints==NULL) return -EINVAL; int count=0; for (int i=nofPoints-1; i>=0; i--) { if (!points.Check(trackpoints[i])) { HLTWarning("can not find point id %08x", trackpoints[i]); continue; } float xyz[3]={points.GetX(trackpoints[i]), points.GetY(trackpoints[i]), points.GetZ(trackpoints[i])}; AliHLTUInt32_t planeId=0; int result=FindMatchingTrackPoint(trackpoints[i], xyz, planeId); if (result<0) { HLTWarning("no associated track point found for space point id %08x x=%f y=%f z=%f", trackpoints[i], xyz[0], xyz[1], xyz[2]); continue; } else if (result==0) { HLTWarning("associated track point for space pointid %08x x=%f y=%f z=%f occupied", trackpoints[i], xyz[0], xyz[1], xyz[2]); continue; } SetAssociatedSpacePoint(planeId, trackpoints[i], 1); if (points.GetTrackID(trackpoints[i])<0 && GetTrackId()>=0) { points.SetTrackID(GetTrackId(), trackpoints[i]); HLTDebug("associating unused cluster %08x with track %d", trackpoints[i], GetTrackId()); } count++; } return count; } int AliHLTTrackGeometry::AssociateUnusedSpacePoints(AliHLTSpacePointContainer& points) { /// associate the track space points to the calculated track points int count=0; vector<AliHLTUInt32_t> ids; points.GetClusterIDs(ids); for (vector<AliHLTUInt32_t>::iterator id=ids.begin(); id!=ids.end(); id++) { float xyz[3]={points.GetX(*id), points.GetY(*id), points.GetZ(*id)}; AliHLTUInt32_t planeId=0; int result=FindMatchingTrackPoint(*id, xyz, planeId); if (result<0) { //HLTWarning("no associated track point found for space point id %08x x=%f y=%f z=%f", *id, xyz[0], xyz[1], xyz[2]); continue; } else if (result==0) { //HLTWarning("associated track point for space pointid %08x x=%f y=%f z=%f occupied", *id, xyz[0], xyz[1], xyz[2]); continue; } SetAssociatedSpacePoint(planeId, *id, 1); if (points.GetTrackID(*id)<0 && GetTrackId()>=0) { points.SetTrackID(GetTrackId(), *id); HLTDebug("associating unused cluster %08x with track %d", *id, GetTrackId()); } count++; } return count; } ostream& operator<<(ostream &out, const AliHLTTrackGeometry& p) { p.Print(out); return out; }
// $Id$ //************************************************************************** //* This file is property of and copyright by the ALICE HLT Project * //* ALICE Experiment at CERN, All rights reserved. * //* * //* Primary Authors: Matthias Richter <[email protected]> * //* for The ALICE HLT Project. * //* * //* Permission to use, copy, modify and distribute this software and its * //* documentation strictly for non-commercial purposes is hereby granted * //* without fee, provided that the above copyright notice appears in all * //* copies and that both the copyright notice and this permission notice * //* appear in the supporting documentation. The authors make no claims * //* about the suitability of this software for any purpose. It is * //* provided "as is" without express or implied warranty. * //************************************************************************** /// @file AliHLTTrackGeometry.cxx /// @author Matthias Richter /// @date 2011-05-20 /// @brief Desciption of a track by a sequence of track points /// #include "AliHLTTrackGeometry.h" #include "AliHLTSpacePointContainer.h" #include "TObjArray.h" #include "TMarker.h" #include "TMath.h" #include <memory> #include <iostream> #include <algorithm> /** ROOT macro for the implementation of ROOT specific class methods */ ClassImp(AliHLTTrackGeometry) AliHLTTrackGeometry::AliHLTTrackGeometry() : TObject(), AliHLTLogging() , fTrackPoints() , fTrackId(-1) { /// standard constructor } AliHLTTrackGeometry::AliHLTTrackGeometry(const AliHLTTrackGeometry& src) : TObject(src), AliHLTLogging() , fTrackPoints(src.fTrackPoints) , fTrackId(src.fTrackId) { /// copy constructor } AliHLTTrackGeometry& AliHLTTrackGeometry::operator=(const AliHLTTrackGeometry& src) { /// assignment operator if (this!=&src) { fTrackPoints.assign(src.fTrackPoints.begin(), src.fTrackPoints.end()); fTrackId=src.fTrackId; } return *this; } AliHLTTrackGeometry::~AliHLTTrackGeometry() { /// destructor } int AliHLTTrackGeometry::AddTrackPoint(const AliHLTTrackPoint& point) { /// add a track point to the list vector<AliHLTTrackPoint>::const_iterator element = find(fTrackPoints.begin(), fTrackPoints.end(), point); if (element==fTrackPoints.end()) { fTrackPoints.push_back(point); } else { HLTError("track point of id %08x already existing", point.GetId()); return -EEXIST; } return 0; } void AliHLTTrackGeometry::Clear(Option_t * /*option*/) { // internal cleanup } void AliHLTTrackGeometry::Print(Option_t *option) const { // print info Print(cout, option); } void AliHLTTrackGeometry::Print(ostream& out, Option_t */*option*/) const { // print to stream out << "AliHLTTrackGeometry::Print" << endl; } void AliHLTTrackGeometry::Draw(Option_t *option) { /// Inherited from TObject, draw the track float scale=250; float center[2]={0.5,0.5}; int markerColor=1; int markerSize=1; TString strOption(option); std::auto_ptr<TObjArray> tokens(strOption.Tokenize(" ")); if (!tokens.get()) return; for (int i=0; i<tokens->GetEntriesFast(); i++) { if (!tokens->At(i)) continue; const char* key=""; TString arg=tokens->At(i)->GetName(); key="scale="; if (arg.BeginsWith(key)) { arg.ReplaceAll(key, ""); scale=arg.Atof(); continue; } key="centerx="; if (arg.BeginsWith(key)) { arg.ReplaceAll(key, ""); center[0]=arg.Atof(); continue; } key="centery="; if (arg.BeginsWith(key)) { arg.ReplaceAll(key, ""); center[1]=arg.Atof(); continue; } key="markercolor="; if (arg.BeginsWith(key)) { arg.ReplaceAll(key, ""); markerColor=arg.Atoi(); continue; } key="markersize="; if (arg.BeginsWith(key)) { arg.ReplaceAll(key, ""); markerSize=arg.Atoi(); continue; } } bool bFirstPoint=true; float firstalpha=0.0; for (vector<AliHLTTrackPoint>::const_iterator point=fTrackPoints.begin(); point!=fTrackPoints.end(); point++) { float alpha=GetPlaneAlpha(point->GetId()); float r=GetPlaneR(point->GetId()); float cosa=TMath::Cos(alpha); float sina=TMath::Sin(alpha); float x = r*sina + point->GetU()*cosa; float y =-r*cosa + point->GetU()*sina; int color=markerColor; if (bFirstPoint) { bFirstPoint=false; TMarker* m=new TMarker(x/(2*scale)+center[0], y/(2*scale)+center[1], 29); m->SetMarkerSize(2); m->SetMarkerColor(2); m->Draw("same"); firstalpha=alpha; } else { color+=int(9*TMath::Abs(alpha-firstalpha)/TMath::Pi()); } TMarker* m=new TMarker(x/(2*scale)+center[0], y/(2*scale)+center[1], point->GetV()>0?2:5); m->SetMarkerColor(color); m->SetMarkerSize(markerSize); m->Draw("same"); } } int AliHLTTrackGeometry::SetAssociatedSpacePoint(UInt_t planeId, UInt_t spacepointId, int status) { /// set the spacepoint associated with a track point vector<AliHLTTrackPoint>::iterator element = find(fTrackPoints.begin(), fTrackPoints.end(), planeId); if (element==fTrackPoints.end()) return -ENOENT; element->SetAssociatedSpacePoint(spacepointId, status); return 0; } int AliHLTTrackGeometry::GetAssociatedSpacePoint(UInt_t planeId, UInt_t& spacepointId) const { /// get the spacepoint associated with a track point /// return status flag if found, -ENOENT if no associated spacepoint found vector<AliHLTTrackPoint>::const_iterator element = find(fTrackPoints.begin(), fTrackPoints.end(), planeId); if (element==fTrackPoints.end()) return -ENOENT; if (!element->HaveAssociatedSpacePoint()) return -ENODATA; return element->GetAssociatedSpacePoint(spacepointId); } const AliHLTTrackGeometry::AliHLTTrackPoint* AliHLTTrackGeometry::GetTrackPoint(AliHLTUInt32_t id) const { /// get const pointer to track point vector<AliHLTTrackPoint>::const_iterator element = find(fTrackPoints.begin(), fTrackPoints.end(), id); if (element==fTrackPoints.end()) return NULL; return &(*element); } AliHLTTrackGeometry::AliHLTTrackPoint* AliHLTTrackGeometry::GetTrackPoint(AliHLTUInt32_t id) { /// get const pointer to track point vector<AliHLTTrackPoint>::iterator element = find(fTrackPoints.begin(), fTrackPoints.end(), id); if (element==fTrackPoints.end()) return NULL; return &(*element); } int AliHLTTrackGeometry::AssociateSpacePoints(AliHLTSpacePointContainer& points) { /// associate the track space points to the calculated track points vector<AliHLTUInt32_t> ids; points.GetClusterIDs(ids); if (ids.size()>0) return 0; int result=AssociateSpacePoints(&ids[0], ids.size(), points); if (result>0) { HLTInfo("associated %d space point(s) to track points", result); } return result; } int AliHLTTrackGeometry::AssociateSpacePoints(const AliHLTUInt32_t* trackpoints, AliHLTUInt32_t nofPoints, AliHLTSpacePointContainer& points) { /// associate the track space points to the calculated track points if (nofPoints==0) return 0; if (trackpoints==NULL) return -EINVAL; int count=0; for (int i=nofPoints-1; i>=0; i--) { if (!points.Check(trackpoints[i])) { HLTWarning("can not find point id %08x", trackpoints[i]); continue; } float xyz[3]={points.GetX(trackpoints[i]), points.GetY(trackpoints[i]), points.GetZ(trackpoints[i])}; AliHLTUInt32_t planeId=0; int result=FindMatchingTrackPoint(trackpoints[i], xyz, planeId); if (result<0) { HLTWarning("no associated track point found for space point id %08x x=%f y=%f z=%f", trackpoints[i], xyz[0], xyz[1], xyz[2]); continue; } else if (result==0) { HLTWarning("associated track point for space pointid %08x x=%f y=%f z=%f occupied", trackpoints[i], xyz[0], xyz[1], xyz[2]); continue; } SetAssociatedSpacePoint(planeId, trackpoints[i], 1); if (points.GetTrackID(trackpoints[i])<0 && GetTrackId()>=0) { points.SetTrackID(GetTrackId(), trackpoints[i]); HLTDebug("associating unused cluster %08x with track %d", trackpoints[i], GetTrackId()); } count++; } return count; } int AliHLTTrackGeometry::AssociateUnusedSpacePoints(AliHLTSpacePointContainer& points) { /// associate the track space points to the calculated track points int count=0; vector<AliHLTUInt32_t> ids; points.GetClusterIDs(ids); for (vector<AliHLTUInt32_t>::iterator id=ids.begin(); id!=ids.end(); id++) { float xyz[3]={points.GetX(*id), points.GetY(*id), points.GetZ(*id)}; AliHLTUInt32_t planeId=0; int result=FindMatchingTrackPoint(*id, xyz, planeId); if (result<0) { //HLTWarning("no associated track point found for space point id %08x x=%f y=%f z=%f", *id, xyz[0], xyz[1], xyz[2]); continue; } else if (result==0) { //HLTWarning("associated track point for space pointid %08x x=%f y=%f z=%f occupied", *id, xyz[0], xyz[1], xyz[2]); continue; } SetAssociatedSpacePoint(planeId, *id, 1); if (points.GetTrackID(*id)<0 && GetTrackId()>=0) { points.SetTrackID(GetTrackId(), *id); HLTDebug("associating unused cluster %08x with track %d", *id, GetTrackId()); } count++; } return count; } ostream& operator<<(ostream &out, const AliHLTTrackGeometry& p) { p.Print(out); return out; }
use explicite cast from double to int
use explicite cast from double to int
C++
bsd-3-clause
sebaleh/AliRoot,miranov25/AliRoot,alisw/AliRoot,miranov25/AliRoot,miranov25/AliRoot,coppedis/AliRoot,ALICEHLT/AliRoot,ALICEHLT/AliRoot,ecalvovi/AliRoot,ecalvovi/AliRoot,ecalvovi/AliRoot,shahor02/AliRoot,alisw/AliRoot,coppedis/AliRoot,sebaleh/AliRoot,miranov25/AliRoot,alisw/AliRoot,mkrzewic/AliRoot,jgrosseo/AliRoot,mkrzewic/AliRoot,jgrosseo/AliRoot,alisw/AliRoot,ALICEHLT/AliRoot,miranov25/AliRoot,jgrosseo/AliRoot,coppedis/AliRoot,shahor02/AliRoot,alisw/AliRoot,jgrosseo/AliRoot,ecalvovi/AliRoot,ALICEHLT/AliRoot,miranov25/AliRoot,mkrzewic/AliRoot,coppedis/AliRoot,ALICEHLT/AliRoot,sebaleh/AliRoot,coppedis/AliRoot,ecalvovi/AliRoot,ecalvovi/AliRoot,mkrzewic/AliRoot,jgrosseo/AliRoot,sebaleh/AliRoot,miranov25/AliRoot,ALICEHLT/AliRoot,alisw/AliRoot,alisw/AliRoot,jgrosseo/AliRoot,jgrosseo/AliRoot,sebaleh/AliRoot,coppedis/AliRoot,shahor02/AliRoot,coppedis/AliRoot,ALICEHLT/AliRoot,shahor02/AliRoot,alisw/AliRoot,mkrzewic/AliRoot,coppedis/AliRoot,miranov25/AliRoot,ecalvovi/AliRoot,sebaleh/AliRoot,mkrzewic/AliRoot,mkrzewic/AliRoot,shahor02/AliRoot,shahor02/AliRoot,shahor02/AliRoot,sebaleh/AliRoot
81b04723fdfaaef658114c0247945e9fa175e041
xchainer/check_backward_test.cc
xchainer/check_backward_test.cc
#include "xchainer/gradient_check.h" #include <algorithm> #include <memory> #include <tuple> #include <unordered_map> #include <vector> #include <gtest/gtest-spi.h> #include <gtest/gtest.h> #include <gsl/gsl> #include "xchainer/array.h" #include "xchainer/check_backward.h" #include "xchainer/native_backend.h" #include "xchainer/op_node.h" #include "xchainer/shape.h" namespace xchainer { namespace { using Arrays = std::vector<Array>; using Fprop = std::function<std::vector<Array>(const std::vector<Array>&)>; Arrays IncorrectBackwardUnaryFunc(const Arrays& inputs) { const Array& in = inputs[0]; Array out = Array::EmptyLike(in); auto backward_function = [](const Array& gout, const std::vector<GraphId>&) { return gout * gout; }; internal::SetUpOpNodes("incorrect_unary", {in}, out, {backward_function}); VisitDtype(in.dtype(), [&](auto pt) { using T = typename decltype(pt)::type; int64_t total_size = in.GetTotalSize(); auto* ldata = static_cast<const T*>(in.data().get()); auto* odata = static_cast<T*>(out.data().get()); for (int64_t i = 0; i < total_size; i++) { odata[i] = ldata[i]; } }); return {out}; } Arrays IncorrectBackwardBinaryFunc(const Arrays& inputs) { const Array& lhs = inputs[0]; const Array& rhs = inputs[1]; CheckEqual(lhs.dtype(), rhs.dtype()); CheckEqual(lhs.shape(), rhs.shape()); Array out = Array::EmptyLike(lhs); auto lhs_backward_function = [other = rhs](const Array& gout, const std::vector<GraphId>& graph_ids_to_stop_gradient)->Array { return gout + other.AsConstant(graph_ids_to_stop_gradient); }; auto rhs_backward_function = lhs_backward_function; internal::SetUpOpNodes("incorrect_binary", {lhs, rhs}, out, {lhs_backward_function, rhs_backward_function}); VisitDtype(lhs.dtype(), [&](auto pt) { using T = typename decltype(pt)::type; int64_t total_size = lhs.GetTotalSize(); auto* ldata = static_cast<const T*>(lhs.data().get()); auto* rdata = static_cast<const T*>(rhs.data().get()); auto* odata = static_cast<T*>(out.data().get()); for (int64_t i = 0; i < total_size; i++) { odata[i] = ldata[i] * rdata[i]; } }); return {out}; } class CheckBackwardBaseTest : public ::testing::Test { protected: virtual void SetUp() { backend_ = std::make_unique<NativeBackend>(); device_scope_ = std::make_unique<DeviceScope>("cpu", backend_.get()); } virtual void TearDown() { device_scope_.reset(); backend_.reset(); } protected: template <typename T> Array MakeArray(const Shape& shape, const T* data) const { int64_t size = shape.GetTotalSize(); auto a = std::make_unique<T[]>(size); std::copy(data, data + size, a.get()); return Array::FromBuffer(shape, TypeToDtype<T>, std::move(a)); } void CheckBackwardBaseComputation(bool expect_correct, Fprop fprop, Arrays& inputs, const Arrays& grad_outputs, const Arrays& eps, double atol, double rtol, const GraphId& graph_id) { bool is_none_of_grad_required = std::none_of(inputs.begin(), inputs.end(), [graph_id](const Array& input) { return input.IsGradRequired(graph_id); }); if (expect_correct || is_none_of_grad_required) { // We cannot expect any failures in case none of the input std::vector<Array> require gradients CheckBackwardComputation(fprop, inputs, grad_outputs, eps, atol, rtol, graph_id); } else { // Catch the gtest failure expected to be generated by CheckBackwardComputation but without failing this test EXPECT_NONFATAL_FAILURE(CheckBackwardComputation(fprop, inputs, grad_outputs, eps, atol, rtol, graph_id), "Backward check failure"); } } private: std::unique_ptr<Backend> backend_; std::unique_ptr<DeviceScope> device_scope_; }; class CheckBackwardUnaryTest : public CheckBackwardBaseTest, public ::testing::WithParamInterface<bool> { protected: void SetUp() override { CheckBackwardBaseTest::SetUp(); requires_grad = GetParam(); } template <typename T> void CheckBackwardUnaryComputation(bool expect_correct, Fprop fprop, const Shape& shape, const T* input_data, const T* grad_output_data, const T* eps_data, double atol, double rtol, const GraphId& graph_id) { Arrays inputs{MakeArray(shape, input_data)}; if (requires_grad) { inputs[0].RequireGrad(graph_id); } Arrays grad_outputs{MakeArray(shape, grad_output_data)}; Arrays eps{MakeArray(shape, eps_data)}; CheckBackwardBaseComputation(expect_correct, fprop, inputs, grad_outputs, eps, atol, rtol, graph_id); } private: bool requires_grad; }; class CheckBackwardBinaryTest : public CheckBackwardBaseTest, public ::testing::WithParamInterface<std::tuple<bool, bool>> { protected: void SetUp() override { CheckBackwardBaseTest::SetUp(); requires_grads = {std::get<0>(GetParam()), std::get<1>(GetParam())}; } template <typename T> void CheckBackwardBinaryComputation(bool expect_correct, Fprop fprop, const Shape& shape, const T* input_data1, const T* input_data2, const T* grad_output_data, const T* eps_data1, const T* eps_data2, double atol, double rtol, const GraphId& graph_id) { Arrays inputs{MakeArray(shape, input_data1), MakeArray(shape, input_data2)}; if (requires_grads[0]) { inputs[0].RequireGrad(graph_id); } if (requires_grads[1]) { inputs[1].RequireGrad(graph_id); } Arrays grad_outputs{MakeArray(shape, grad_output_data)}; Arrays eps{MakeArray(shape, eps_data1), MakeArray(shape, eps_data2)}; CheckBackwardBaseComputation(expect_correct, fprop, inputs, grad_outputs, eps, atol, rtol, graph_id); } private: std::vector<bool> requires_grads; }; TEST_P(CheckBackwardUnaryTest, CorrectBackward) { float input_data[]{1.f, 2.f, 1.f}; float grad_output_data[]{0.f, -2.f, 1.f}; float eps_data[]{1e-3f, 1e-3f, 1e-3f}; Fprop fprop = [](const Arrays& inputs) -> Arrays { return {inputs[0] * inputs[0]}; }; CheckBackwardUnaryComputation(true, fprop, {1, 3}, input_data, grad_output_data, eps_data, 1e-5, 1e-4, "graph_1"); } TEST_P(CheckBackwardUnaryTest, IncorrectBackward) { float input_data[]{-2.f, 3.f, 1.f}; float grad_output_data[]{0.f, -2.f, 1.f}; float eps_data[]{1e-3f, 1e-3f, 1e-3f}; CheckBackwardUnaryComputation(false, &IncorrectBackwardUnaryFunc, {1, 3}, input_data, grad_output_data, eps_data, 1e-5, 1e-4, "graph_1"); } TEST_P(CheckBackwardBinaryTest, CorrectBackward) { float input_data1[]{1.f, 2.f, 1.f}; float input_data2[]{0.f, 1.f, 2.f}; float eps_data1[]{1e-3f, 1e-3f, 1e-3f}; float eps_data2[]{1e-3f, 1e-3f, 1e-3f}; float grad_output_data[]{1.f, -2.f, 3.f}; Fprop fprop = [](const Arrays& inputs) -> Arrays { return {inputs[0] * inputs[1]}; }; CheckBackwardBinaryComputation(true, fprop, {1, 3}, input_data1, input_data2, grad_output_data, eps_data1, eps_data2, 1e-5, 1e-4, "graph_1"); } TEST_P(CheckBackwardBinaryTest, IncorrectBackward) { float input_data1[]{1.f, -2.f, 1.f}; float input_data2[]{0.f, 1.4f, 2.f}; float eps_data1[]{1e-3f, 1e-3f, 1e-3f}; float eps_data2[]{1e-3f, 1e-3f, 1e-3f}; float grad_output_data[]{4.f, -2.f, 3.f}; CheckBackwardBinaryComputation(false, &IncorrectBackwardBinaryFunc, {1, 3}, input_data1, input_data2, grad_output_data, eps_data1, eps_data2, 1e-5, 1e-4, "graph_1"); } INSTANTIATE_TEST_CASE_P(ForEachSingleSetRequiresGrad, CheckBackwardUnaryTest, ::testing::Bool()); INSTANTIATE_TEST_CASE_P(ForEachCombinedSetRequiresGrad, CheckBackwardBinaryTest, ::testing::Combine(::testing::Bool(), ::testing::Bool())); } // namespace } // namespace xchainer
#include "xchainer/gradient_check.h" #include <algorithm> #include <memory> #include <tuple> #include <unordered_map> #include <vector> #include <gtest/gtest-spi.h> #include <gtest/gtest.h> #include <gsl/gsl> #include "xchainer/array.h" #include "xchainer/check_backward.h" #include "xchainer/native_backend.h" #include "xchainer/op_node.h" #include "xchainer/shape.h" namespace xchainer { namespace { using Arrays = std::vector<Array>; using Fprop = std::function<std::vector<Array>(const std::vector<Array>&)>; Arrays IncorrectBackwardUnaryFunc(const Arrays& inputs) { const Array& in = inputs[0]; Array out = Array::EmptyLike(in); auto backward_function = [](const Array& gout, const std::vector<GraphId>&) { return gout * gout; }; internal::SetUpOpNodes("incorrect_unary", {in}, out, {backward_function}); VisitDtype(in.dtype(), [&](auto pt) { using T = typename decltype(pt)::type; int64_t total_size = in.GetTotalSize(); auto* ldata = static_cast<const T*>(in.data().get()); auto* odata = static_cast<T*>(out.data().get()); for (int64_t i = 0; i < total_size; i++) { odata[i] = ldata[i]; } }); return {out}; } Arrays IncorrectBackwardBinaryFunc(const Arrays& inputs) { const Array& lhs = inputs[0]; const Array& rhs = inputs[1]; CheckEqual(lhs.dtype(), rhs.dtype()); CheckEqual(lhs.shape(), rhs.shape()); Array out = Array::EmptyLike(lhs); auto lhs_backward_function = [other = rhs](const Array& gout, const std::vector<GraphId>& graph_ids_to_stop_gradient)->Array { return gout + other.AsConstant(graph_ids_to_stop_gradient); }; auto rhs_backward_function = lhs_backward_function; internal::SetUpOpNodes("incorrect_binary", {lhs, rhs}, out, {lhs_backward_function, rhs_backward_function}); VisitDtype(lhs.dtype(), [&](auto pt) { using T = typename decltype(pt)::type; int64_t total_size = lhs.GetTotalSize(); auto* ldata = static_cast<const T*>(lhs.data().get()); auto* rdata = static_cast<const T*>(rhs.data().get()); auto* odata = static_cast<T*>(out.data().get()); for (int64_t i = 0; i < total_size; i++) { odata[i] = ldata[i] * rdata[i]; } }); return {out}; } class CheckBackwardBaseTest : public ::testing::Test { protected: virtual void SetUp() { backend_ = std::make_unique<NativeBackend>(); device_id_scope_ = std::make_unique<DeviceIdScope>(backend_.get()); } virtual void TearDown() { device_id_scope_.reset(); backend_.reset(); } protected: template <typename T> Array MakeArray(const Shape& shape, const T* data) const { int64_t size = shape.GetTotalSize(); auto a = std::make_unique<T[]>(size); std::copy(data, data + size, a.get()); return Array::FromBuffer(shape, TypeToDtype<T>, std::move(a)); } void CheckBackwardBaseComputation(bool expect_correct, Fprop fprop, Arrays& inputs, const Arrays& grad_outputs, const Arrays& eps, double atol, double rtol, const GraphId& graph_id) { bool is_none_of_grad_required = std::none_of(inputs.begin(), inputs.end(), [graph_id](const Array& input) { return input.IsGradRequired(graph_id); }); if (expect_correct || is_none_of_grad_required) { // We cannot expect any failures in case none of the input std::vector<Array> require gradients CheckBackwardComputation(fprop, inputs, grad_outputs, eps, atol, rtol, graph_id); } else { // Catch the gtest failure expected to be generated by CheckBackwardComputation but without failing this test EXPECT_NONFATAL_FAILURE(CheckBackwardComputation(fprop, inputs, grad_outputs, eps, atol, rtol, graph_id), "Backward check failure"); } } private: std::unique_ptr<Backend> backend_; std::unique_ptr<DeviceIdScope> device_id_scope_; }; class CheckBackwardUnaryTest : public CheckBackwardBaseTest, public ::testing::WithParamInterface<bool> { protected: void SetUp() override { CheckBackwardBaseTest::SetUp(); requires_grad = GetParam(); } template <typename T> void CheckBackwardUnaryComputation(bool expect_correct, Fprop fprop, const Shape& shape, const T* input_data, const T* grad_output_data, const T* eps_data, double atol, double rtol, const GraphId& graph_id) { Arrays inputs{MakeArray(shape, input_data)}; if (requires_grad) { inputs[0].RequireGrad(graph_id); } Arrays grad_outputs{MakeArray(shape, grad_output_data)}; Arrays eps{MakeArray(shape, eps_data)}; CheckBackwardBaseComputation(expect_correct, fprop, inputs, grad_outputs, eps, atol, rtol, graph_id); } private: bool requires_grad; }; class CheckBackwardBinaryTest : public CheckBackwardBaseTest, public ::testing::WithParamInterface<std::tuple<bool, bool>> { protected: void SetUp() override { CheckBackwardBaseTest::SetUp(); requires_grads = {std::get<0>(GetParam()), std::get<1>(GetParam())}; } template <typename T> void CheckBackwardBinaryComputation(bool expect_correct, Fprop fprop, const Shape& shape, const T* input_data1, const T* input_data2, const T* grad_output_data, const T* eps_data1, const T* eps_data2, double atol, double rtol, const GraphId& graph_id) { Arrays inputs{MakeArray(shape, input_data1), MakeArray(shape, input_data2)}; if (requires_grads[0]) { inputs[0].RequireGrad(graph_id); } if (requires_grads[1]) { inputs[1].RequireGrad(graph_id); } Arrays grad_outputs{MakeArray(shape, grad_output_data)}; Arrays eps{MakeArray(shape, eps_data1), MakeArray(shape, eps_data2)}; CheckBackwardBaseComputation(expect_correct, fprop, inputs, grad_outputs, eps, atol, rtol, graph_id); } private: std::vector<bool> requires_grads; }; TEST_P(CheckBackwardUnaryTest, CorrectBackward) { float input_data[]{1.f, 2.f, 1.f}; float grad_output_data[]{0.f, -2.f, 1.f}; float eps_data[]{1e-3f, 1e-3f, 1e-3f}; Fprop fprop = [](const Arrays& inputs) -> Arrays { return {inputs[0] * inputs[0]}; }; CheckBackwardUnaryComputation(true, fprop, {1, 3}, input_data, grad_output_data, eps_data, 1e-5, 1e-4, "graph_1"); } TEST_P(CheckBackwardUnaryTest, IncorrectBackward) { float input_data[]{-2.f, 3.f, 1.f}; float grad_output_data[]{0.f, -2.f, 1.f}; float eps_data[]{1e-3f, 1e-3f, 1e-3f}; CheckBackwardUnaryComputation(false, &IncorrectBackwardUnaryFunc, {1, 3}, input_data, grad_output_data, eps_data, 1e-5, 1e-4, "graph_1"); } TEST_P(CheckBackwardBinaryTest, CorrectBackward) { float input_data1[]{1.f, 2.f, 1.f}; float input_data2[]{0.f, 1.f, 2.f}; float eps_data1[]{1e-3f, 1e-3f, 1e-3f}; float eps_data2[]{1e-3f, 1e-3f, 1e-3f}; float grad_output_data[]{1.f, -2.f, 3.f}; Fprop fprop = [](const Arrays& inputs) -> Arrays { return {inputs[0] * inputs[1]}; }; CheckBackwardBinaryComputation(true, fprop, {1, 3}, input_data1, input_data2, grad_output_data, eps_data1, eps_data2, 1e-5, 1e-4, "graph_1"); } TEST_P(CheckBackwardBinaryTest, IncorrectBackward) { float input_data1[]{1.f, -2.f, 1.f}; float input_data2[]{0.f, 1.4f, 2.f}; float eps_data1[]{1e-3f, 1e-3f, 1e-3f}; float eps_data2[]{1e-3f, 1e-3f, 1e-3f}; float grad_output_data[]{4.f, -2.f, 3.f}; CheckBackwardBinaryComputation(false, &IncorrectBackwardBinaryFunc, {1, 3}, input_data1, input_data2, grad_output_data, eps_data1, eps_data2, 1e-5, 1e-4, "graph_1"); } INSTANTIATE_TEST_CASE_P(ForEachSingleSetRequiresGrad, CheckBackwardUnaryTest, ::testing::Bool()); INSTANTIATE_TEST_CASE_P(ForEachCombinedSetRequiresGrad, CheckBackwardBinaryTest, ::testing::Combine(::testing::Bool(), ::testing::Bool())); } // namespace } // namespace xchainer
Fix check_backward_test.cc to use new DeviceId
Fix check_backward_test.cc to use new DeviceId
C++
mit
jnishi/chainer,ktnyt/chainer,pfnet/chainer,niboshi/chainer,niboshi/chainer,hvy/chainer,okuta/chainer,chainer/chainer,jnishi/chainer,ktnyt/chainer,wkentaro/chainer,wkentaro/chainer,keisuke-umezawa/chainer,niboshi/chainer,okuta/chainer,keisuke-umezawa/chainer,wkentaro/chainer,jnishi/chainer,keisuke-umezawa/chainer,okuta/chainer,niboshi/chainer,ktnyt/chainer,chainer/chainer,hvy/chainer,keisuke-umezawa/chainer,tkerola/chainer,ktnyt/chainer,chainer/chainer,chainer/chainer,wkentaro/chainer,hvy/chainer,okuta/chainer,hvy/chainer,jnishi/chainer
b5d840e4dce2fdc0940a3f17fec89bf4ea938105
include/stack.hpp
include/stack.hpp
#include <iostream> using namespace std; template <typename T> class stack { public: stack(); stack(const stack<T> &copy); size_t count() const; void print()const; void push(T const &); void swap(); void swap(const stack&); T pop(); stack<T>& operator=(stack<T> const &); ~stack(); private: T * array_; size_t array_size_; size_t count_; }; template <typename T> stack<T>::stack() : count_(0), array_size_(0), array_{ nullptr } {} template<class T> stack<T>::~stack() { count_ = 0; array_size_ = 0; delete[] array_; } template <typename T> stack<T>::stack(const stack<T>& copy) { array_size_ = copy.array_size_; count_ = copy.count_; array_ = new T*[array_size_]; for (int i = 0; i < array_size_; i++) array_[array_size_] = copy.array_[array_size_]; } template<class T> size_t stack<T>::count() const { return count_; } template<typename T> void stack<T>::swap(const stack& x) { T * temp = new T[x.array_size_](); std::copy(x, x + x.count_, temp); array_ = temp; return temp; } template<typename T> void stack<T>::swap() { T* temp = new T[array_size_](); std::copy(array_, array_ + count_, temp); array_ = temp; } template <typename T> void stack<T>::push(T const &value) { if (array_size_ == 0) { array_size_ = 1; array_ = new T[array_size_]; } else if (array_size_ == count_) { array_size_ = array_size_ * 2; swap(); //T *s1 = new T[array_size_]; //for (int i = 0; i < count_; i++) //std::copy(int i = 0; i < count; i++) // s1[i] = array_[i]; //delete[] array_; //array_ = s1; } array_[count_] = value; count_++; } template <typename T> T stack<T>::pop() { if (count_ == 0) throw "Stack is empty" ; count_--; T x = array_[count_]; swap(); return x; } template <typename T> void stack<T>::print() const { for (int i = 0; i < array_size_; i++) cout << array_[i]; } template<typename T> stack<T>& stack<T>::operator=(stack<T> const & tmp) { delete[] array_; array_ = swap(tmp); array_size_ = tmp.array_size_; count_ = tmp.count_; }
#include <iostream> using namespace std; template <typename T> class stack { public: stack(); stack(const stack<T> &); size_t count() const; void print()const; void push(T const &); void swap(stack<T>&); T pop(); stack<T>& operator=(const stack<T> &); ~stack(); private: T * array_; size_t array_size_; size_t count_; }; template <typename T> stack<T>::stack() : count_(0), array_size_(0), array_{ nullptr } {} template<class T> stack<T>::~stack() { count_ = 0; array_size_ = 0; delete[] array_; } template <typename T> stack<T>::stack(const stack<T>& copy) { array_size_ = copy.array_size_; count_ = copy.count_; array_ = new T*[array_size_]; for (int i = 0; i < array_size_; i++) array_[array_size_] = copy.array_[array_size_]; } template<class T> size_t stack<T>::count() const { return count_; } template<typename T> void stack<T>::swap(const stack& x) { std::swap(x.array_size_, array_size_); std::swap(count_, x.count_); std::swap(x.array_, array_); } template <typename T> void stack<T>::push(T const &value) { if (array_size_ == 0) { array_size_ = 1; array_ = new T[array_size_]; } else if (array_size_ == count_) { array_size_ = array_size_ * 2; swap(); //T *s1 = new T[array_size_]; //for (int i = 0; i < count_; i++) //std::copy(int i = 0; i < count; i++) // s1[i] = array_[i]; //delete[] array_; //array_ = s1; } array_[count_] = value; count_++; } template <typename T> T stack<T>::pop() { if (count_ == 0) throw "Stack is empty" ; count_--; T x = array_[count_]; swap(); return x; } template <typename T> void stack<T>::print() const { for (int i = 0; i < array_size_; i++) cout << array_[i]; } template<typename T> stack<T>& stack<T>::operator=(const stack<T> & tmp) { if (this != &tmp) { delete[] array_; } if (array_size_ != 0) { array_size_ = tmp.array_size_; count_ = tmp.count_; array_=new T[count_]; std::copy(tmp.array_, tmp.array_ + tmp.count_, array_); } return *this; }
Update stack.hpp
Update stack.hpp
C++
mit
rtv22/stack
5c8ec1aaba65305e8a65e45ca5aa151440b0d697
include/stack.hpp
include/stack.hpp
#ifndef stack_cpp #define stack_cpp #pragma once #include <iostream> #include <memory> #include <thread> #include <mutex> class bitset { public: explicit bitset(size_t size) /*strong*/; bitset(bitset const & other) = delete; auto operator =(bitset const & other)->bitset & = delete; bitset(bitset && other) = delete; auto operator =(bitset && other)->bitset & = delete; auto set(size_t index) /*strong*/ -> void; auto reset(size_t index) /*strong*/ -> void; auto test(size_t index) /*strong*/ -> bool; auto size() const /*noexcept*/ -> size_t; auto counter() const /*noexcept*/ -> size_t; private: std::unique_ptr<bool[]> ptr_; size_t size_; size_t counter_; }; bitset::bitset(size_t size) : ptr_(std::make_unique<bool[]>(size)), size_(size), counter_(0) {} auto bitset::set(size_t index) -> void { if (index < size_) { ptr_[index] = true; ++counter_; } else throw("false_index"); } auto bitset::reset(size_t index) -> void { if (index < size_) { ptr_[index] = false; --counter_; } else throw("false_index"); } auto bitset::test(size_t index) -> bool { if (index < size_) { return !ptr_[index]; } else throw("false_index"); } auto bitset::size() const -> size_t { return size_; } auto bitset::counter() const -> size_t { return counter_; } template <typename T> class allocator { public: explicit allocator(std::size_t size = 0) /*strong*/; allocator(allocator const & other) /*strong*/; auto operator =(allocator const & other)->allocator & = delete; ~allocator(); auto resize() /*strong*/ -> void; auto construct(T * ptr, T const & value) /*strong*/ -> void; auto destroy(T * ptr) /*noexcept*/ -> void; auto get() /*noexcept*/ -> T *; auto get() const /*noexcept*/ -> T const *; auto count() const /*noexcept*/ -> size_t; auto full() const /*noexcept*/ -> bool; auto empty() const /*noexcept*/ -> bool; auto swap(allocator & other) /*noexcept*/ -> void; private: auto destroy(T * first, T * last) /*noexcept*/ -> void; T * ptr_; size_t size_; std::unique_ptr<bitset> map_; }; template <typename T> allocator<T>::allocator(size_t size) : ptr_((T*)(operator new(size*sizeof(T)))), size_(size), map_(std::make_unique<bitset>(size)) {}; template<typename T> allocator<T>::allocator(allocator const& other) : allocator<T>(other.size_) { for (size_t i = 0; i < size_; ++i) if (other.map_->test(i)) construct(ptr_ + i, other.ptr_[i]); } template<typename T> allocator<T>::~allocator() { destroy(ptr_, ptr_ + size_); operator delete(ptr_); } template<typename T> auto allocator<T>::resize() -> void { allocator<T> buff(size_ * 2 + (size_ == 0)); for (size_t i = 0; i < size_; ++i) construct(buff.ptr_ + i, ptr_[i]); this->swap(buff); } template<typename T> auto allocator<T>::construct(T * ptr, T const & value)->void { if (ptr >= ptr_&&ptr < ptr_ + size_&&map_->test(ptr - ptr_)) { new(ptr)T(value); map_->set(ptr - ptr_); } else throw("error"); } template<typename T> auto allocator<T>::destroy(T * ptr) -> void { if (ptr >= ptr_&&ptr <= ptr_ + this->size_) { if (!map_->test(ptr - ptr_)) { ptr->~T(); map_->reset(ptr - ptr_); } } else throw("error"); } template<typename T> auto allocator<T>::destroy(T * first, T * last) -> void { if (first >= ptr_&&last <= ptr_ + this->size_) for (; first != last; ++first) { destroy(&*first); } } template<typename T> auto allocator<T>::get()-> T* { return ptr_; } template<typename T> auto allocator<T>::get() const -> T const * { return ptr_; } template<typename T> auto allocator<T>::count() const -> size_t { return map_->counter(); } template<typename T> auto allocator<T>::full() const -> bool { return map_->counter() == size_; } template<typename T> auto allocator<T>::empty() const -> bool { return map_->counter() == 0; } template<typename T> auto allocator<T>::swap(allocator & other) -> void { std::swap(ptr_, other.ptr_); std::swap(map_, other.map_); std::swap(size_, other.size_); } template <typename T> class stack { public: explicit stack(size_t size = 0); stack(stack const & other); auto operator =(stack const & other) /*strong*/ -> stack &; auto empty() const /*noexcept*/ -> bool; auto count() const /*noexcept*/ -> size_t; auto push(T const & value) /*strong*/ -> void; auto pop() /*strong*/ -> void; auto top() /*strong*/ -> T &; auto top() const /*strong*/ -> T const &; private: allocator<T> allocator_; mutable std::mutex m; auto throw_is_empty() const -> void; }; template <typename T> size_t stack<T>::count() const { //std::lock_guard<std::mutex> locker(m); return allocator_.count(); } template <typename T> stack<T>::stack(size_t size) :allocator_(size), m() {} template <typename T> stack<T>::stack(stack const & other) : allocator_(0), m() { std::lock_guard<std::mutex> locker(other.m); allocator_.swap(allocator<T>(other.allocator_)); } template <typename T> void stack<T>::push(T const &item) { std::lock_guard<std::mutex> locker(m); if (allocator_.full()) allocator_.resize(); allocator_.construct(allocator_.get() + this->count(), item); } template<typename T> void stack<T>::pop() { std::lock_guard<std::mutex> locker(m); if (this->count() > 0) allocator_.destroy(allocator_.get() + (this->count() - 1)); else throw_is_empty(); } template<typename T> auto stack<T>::top() -> T & { std::lock_guard<std::mutex> locker(m); if (allocator_.count() == 0) { throw_is_empty(); } return (*(allocator_.get() + allocator_.count() - 1)); } template<typename T> auto stack<T>::top() const -> T const & { std::lock_guard<std::mutex> locker(m); if (allocator_.count() == 0) { throw_is_empty(); } return (*(allocator_.get() + allocator_.count() - 1)); } template<typename T> auto stack<T>::throw_is_empty() const -> void { throw("Stack is empty!"); } template<typename T> auto stack<T>::operator =(stack const & right)-> stack & { if (this != &right) { std::lock(m, right.m); std::lock_guard<std::mutex> locker1(m, std::adopt_lock); std::lock_guard<std::mutex> locker2(right.m, std::adopt_lock); allocator<T>(right.allocator_).swap(allocator_); } return *this; } #endif
#ifndef stack_cpp #define stack_cpp #pragma once #include <iostream> #include <memory> #include <thread> #include <mutex> class bitset { public: explicit bitset(size_t size) /*strong*/; bitset(bitset const & other) = delete; auto operator =(bitset const & other)->bitset & = delete; bitset(bitset && other) = delete; auto operator =(bitset && other)->bitset & = delete; auto set(size_t index) /*strong*/ -> void; auto reset(size_t index) /*strong*/ -> void; auto test(size_t index) /*strong*/ -> bool; auto size() const /*noexcept*/ -> size_t; auto counter() const /*noexcept*/ -> size_t; private: std::unique_ptr<bool[]> ptr_; size_t size_; size_t counter_; }; bitset::bitset(size_t size) : ptr_(std::make_unique<bool[]>(size)), size_(size), counter_(0) {} auto bitset::set(size_t index) -> void { if (index < size_) { ptr_[index] = true; ++counter_; } else throw("false_index"); } auto bitset::reset(size_t index) -> void { if (index < size_) { ptr_[index] = false; --counter_; } else throw("false_index"); } auto bitset::test(size_t index) -> bool { if (index < size_) { return !ptr_[index]; } else throw("false_index"); } auto bitset::size() const -> size_t { return size_; } auto bitset::counter() const -> size_t { return counter_; } template <typename T> class allocator { public: explicit allocator(std::size_t size = 0) /*strong*/; allocator(allocator const & other) /*strong*/; auto operator =(allocator const & other)->allocator & = delete; ~allocator(); auto resize() /*strong*/ -> void; auto construct(T * ptr, T const & value) /*strong*/ -> void; auto destroy(T * ptr) /*noexcept*/ -> void; auto get() /*noexcept*/ -> T *; auto get() const /*noexcept*/ -> T const *; auto count() const /*noexcept*/ -> size_t; auto full() const /*noexcept*/ -> bool; auto empty() const /*noexcept*/ -> bool; auto swap(allocator & other) /*noexcept*/ -> void; private: auto destroy(T * first, T * last) /*noexcept*/ -> void; T * ptr_; size_t size_; std::unique_ptr<bitset> map_; }; template <typename T> allocator<T>::allocator(size_t size) : ptr_((T*)(operator new(size*sizeof(T)))), size_(size), map_(std::make_unique<bitset>(size)) {}; template<typename T> allocator<T>::allocator(allocator const& other) : allocator<T>(other.size_) { for (size_t i = 0; i < size_; ++i) if (other.map_->test(i)) construct(ptr_ + i, other.ptr_[i]); } template<typename T> allocator<T>::~allocator() { destroy(ptr_, ptr_ + size_); operator delete(ptr_); } template<typename T> auto allocator<T>::resize() -> void { allocator<T> buff(size_ * 2 + (size_ == 0)); for (size_t i = 0; i < size_; ++i) construct(buff.ptr_ + i, ptr_[i]); this->swap(buff); } template<typename T> auto allocator<T>::construct(T * ptr, T const & value)->void { if (ptr >= ptr_&&ptr < ptr_ + size_&&map_->test(ptr - ptr_)) { new(ptr)T(value); map_->set(ptr - ptr_); } else throw("error"); } template<typename T> auto allocator<T>::destroy(T * ptr) -> void { if (ptr >= ptr_&&ptr <= ptr_ + this->size_) { if (!map_->test(ptr - ptr_)) { ptr->~T(); map_->reset(ptr - ptr_); } } else throw("error"); } template<typename T> auto allocator<T>::destroy(T * first, T * last) -> void { if (first >= ptr_&&last <= ptr_ + this->size_) for (; first != last; ++first) { destroy(&*first); } } template<typename T> auto allocator<T>::get()-> T* { return ptr_; } template<typename T> auto allocator<T>::get() const -> T const * { return ptr_; } template<typename T> auto allocator<T>::count() const -> size_t { return map_->counter(); } template<typename T> auto allocator<T>::full() const -> bool { return map_->counter() == size_; } template<typename T> auto allocator<T>::empty() const -> bool { return map_->counter() == 0; } template<typename T> auto allocator<T>::swap(allocator & other) -> void { std::swap(ptr_, other.ptr_); std::swap(map_, other.map_); std::swap(size_, other.size_); std::swap(count_, other.count_); } template <typename T> class stack { public: explicit stack(size_t size = 0); stack(stack const & other); auto operator =(stack const & other) /*strong*/ -> stack &; auto empty() const /*noexcept*/ -> bool; auto count() const /*noexcept*/ -> size_t; auto push(T const & value) /*strong*/ -> void; auto pop() /*strong*/ -> void; auto top() /*strong*/ -> T &; auto top() const /*strong*/ -> T const &; private: allocator<T> allocator_; mutable std::mutex m; auto throw_is_empty() const -> void; }; template <typename T> size_t stack<T>::count() const { //std::lock_guard<std::mutex> locker(m); return allocator_.count(); } template <typename T> stack<T>::stack(size_t size) :allocator_(size), m() {} template <typename T> stack<T>::stack(stack const & other) : allocator_(0), m() { std::lock_guard<std::mutex> locker(other.m); allocator_.swap(allocator<T>(other.allocator_)); } template <typename T> void stack<T>::push(T const &item) { std::lock_guard<std::mutex> locker(m); if (allocator_.full()) allocator_.resize(); allocator_.construct(allocator_.get() + this->count(), item); } template<typename T> void stack<T>::pop() { std::lock_guard<std::mutex> locker(m); if (this->count() > 0) allocator_.destroy(allocator_.get() + (this->count() - 1)); else throw_is_empty(); } template<typename T> auto stack<T>::top() -> T & { std::lock_guard<std::mutex> locker(m); if (allocator_.count() == 0) { throw_is_empty(); } return (*(allocator_.get() + allocator_.count() - 1)); } template<typename T> auto stack<T>::top() const -> T const & { std::lock_guard<std::mutex> locker(m); if (allocator_.count() == 0) { throw_is_empty(); } return (*(allocator_.get() + allocator_.count() - 1)); } template<typename T> auto stack<T>::throw_is_empty() const -> void { throw("Stack is empty!"); } template<typename T> auto stack<T>::operator =(stack const & right)-> stack & { if (this != &right) { std::lock(m, right.m); std::lock_guard<std::mutex> locker1(m, std::adopt_lock); std::lock_guard<std::mutex> locker2(right.m, std::adopt_lock); allocator<T>(right.allocator_).swap(allocator_); } return *this; } #endif
Update stack.hpp
Update stack.hpp
C++
mit
DANTEpolaris/stack
c3a902de78b484222e7d549efc020ccd250c6768
vcf2multialign/vcf2multialign/check_overlapping_non_nested_variants.cc
vcf2multialign/vcf2multialign/check_overlapping_non_nested_variants.cc
/* * Copyright (c) 2017 Tuukka Norri * This code is licensed under MIT license (see LICENSE for details). */ #include <boost/bimap.hpp> #include <boost/bimap/list_of.hpp> #include <boost/bimap/multiset_of.hpp> #include <boost/range/adaptor/reversed.hpp> #include <iostream> #include <vcf2multialign/check_overlapping_non_nested_variants.hh> namespace v2m = vcf2multialign; typedef boost::bimap < boost::bimaps::multiset_of <size_t>, boost::bimaps::multiset_of <size_t> > overlap_map; typedef boost::bimap < boost::bimaps::set_of <size_t>, // lineno boost::bimaps::list_of <size_t> // count > conflict_count_map; namespace { template <typename t_map> void check_overlap( t_map &bad_overlap_side, conflict_count_map &conflict_counts, v2m::variant_set &skipped_variants, size_t const var_lineno, v2m::error_logger &error_logger ) { auto const range(bad_overlap_side.equal_range(var_lineno)); if (! (bad_overlap_side.end() == range.first || range.first == range.second)) { if (error_logger.is_logging_errors()) { for (auto it(range.first); it != range.second; ++it) error_logger.log_conflicting_variants(var_lineno, it->second); } // Update conflict counts. for (auto it(range.first); it != range.second; ++it) { auto c_it(conflict_counts.left.find(it->second)); if (conflict_counts.left.end() == c_it) throw std::runtime_error("Unable to find conflict count for variant"); auto &val(c_it->second); --val; if (0 == val) conflict_counts.left.erase(c_it); // In case 0 == val, bad_overlaps need not be updated b.c. the entries have // already been erased as part of handling previous overlapping variants. } skipped_variants.insert(var_lineno); // May be done without checking b.c. skipped_variants is a set. bad_overlap_side.erase(range.first, range.second); } } } namespace vcf2multialign { size_t check_overlapping_non_nested_variants( vcf_reader &reader, variant_set /* out */ &skipped_variants, variant_set /* out */ &non_nested_variants, error_logger &error_logger ) { typedef boost::bimap < boost::bimaps::multiset_of <size_t>, boost::bimaps::multiset_of <size_t> > overlap_map; size_t last_position(0); std::multimap <size_t, size_t> end_positions; std::multimap <size_t, size_t, std::greater <size_t>> current_end_positions; // End positions for variants that have the same POS. conflict_count_map conflict_counts; overlap_map bad_overlaps; size_t i(0); size_t conflict_count(0); reader.reset(); reader.set_parsed_fields(vcf_field::REF); variant var(reader.sample_count()); while (reader.get_next_variant(var)) { // Verify that the positions are in increasing order. auto const pos(var.zero_based_pos()); if (! (last_position <= pos)) throw std::runtime_error("Positions not in increasing order"); auto const end(pos + var.ref().size()); auto const var_lineno(var.lineno()); if (last_position != pos) current_end_positions.clear(); // Check end position order. if (last_position == pos) { auto const it(current_end_positions.upper_bound(end)); if (current_end_positions.cend() != it) { non_nested_variants.emplace(var_lineno); non_nested_variants.emplace(it->second); } current_end_positions.emplace(end, var_lineno); } // Try to find an end position that is greater than var's position. auto it(end_positions.upper_bound(pos)); auto const end_it(end_positions.cend()); if (end_it == it) { end_positions.emplace(end, var_lineno); goto loop_end; } // Check that the found position is not within var's range. // If it is, continue checking succeeding positions. do { // Proper nesting. if (end <= it->first) break; ++conflict_count; std::cerr << "Variant on line " << var_lineno << " conflicts with line " << it->second << "." << std::endl; auto const res(bad_overlaps.insert(overlap_map::value_type(it->second, var_lineno))); if (false == res.second) throw std::runtime_error("Unable to insert"); ++conflict_counts.left[it->second]; ++conflict_counts.left[var_lineno]; ++it; } while (end_it != it); // Add the end position. end_positions.emplace(end, var_lineno); loop_end: last_position = pos; ++i; if (0 == i % 100000) std::cerr << "Handled " << i << " variants…" << std::endl; } // Remove conflicting variants starting from the one with the highest score. while (!conflict_counts.empty()) { conflict_counts.right.sort(); auto const it(conflict_counts.right.rbegin()); auto const count(it->first); auto const var_lineno(it->second); // Check if the candidate variant is still listed. check_overlap(bad_overlaps.left, conflict_counts, skipped_variants, var_lineno, error_logger); check_overlap(bad_overlaps.right, conflict_counts, skipped_variants, var_lineno, error_logger); conflict_counts.left.erase(var_lineno); } if (bad_overlaps.size() != 0) throw std::runtime_error("Unable to remove all conflicting variants"); return conflict_count; } }
/* * Copyright (c) 2017 Tuukka Norri * This code is licensed under MIT license (see LICENSE for details). */ #include <boost/bimap.hpp> #include <boost/bimap/list_of.hpp> #include <boost/bimap/multiset_of.hpp> #include <boost/range/adaptor/reversed.hpp> #include <iostream> #include <vcf2multialign/check_overlapping_non_nested_variants.hh> namespace v2m = vcf2multialign; typedef boost::bimap < boost::bimaps::multiset_of <size_t>, boost::bimaps::multiset_of <size_t> > overlap_map; typedef boost::bimap < boost::bimaps::set_of <size_t>, // lineno boost::bimaps::list_of <size_t> // count > conflict_count_map; namespace { struct var_info { size_t pos; size_t lineno; var_info(size_t const pos_, size_t const lineno_): pos(pos_), lineno(lineno_) { } }; template <typename t_map> void check_overlap( t_map &bad_overlap_side, conflict_count_map &conflict_counts, v2m::variant_set &skipped_variants, size_t const var_lineno, v2m::error_logger &error_logger ) { auto const range(bad_overlap_side.equal_range(var_lineno)); if (! (bad_overlap_side.end() == range.first || range.first == range.second)) { if (error_logger.is_logging_errors()) { for (auto it(range.first); it != range.second; ++it) error_logger.log_conflicting_variants(var_lineno, it->second); } // Update conflict counts. for (auto it(range.first); it != range.second; ++it) { auto c_it(conflict_counts.left.find(it->second)); if (conflict_counts.left.end() == c_it) throw std::runtime_error("Unable to find conflict count for variant"); auto &val(c_it->second); --val; if (0 == val) conflict_counts.left.erase(c_it); // In case 0 == val, bad_overlaps need not be updated b.c. the entries have // already been erased as part of handling previous overlapping variants. } skipped_variants.insert(var_lineno); // May be done without checking b.c. skipped_variants is a set. bad_overlap_side.erase(range.first, range.second); } } } namespace vcf2multialign { size_t check_overlapping_non_nested_variants( vcf_reader &reader, variant_set /* out */ &skipped_variants, variant_set /* out */ &non_nested_variants, error_logger &error_logger ) { typedef boost::bimap < boost::bimaps::multiset_of <size_t>, boost::bimaps::multiset_of <size_t> > overlap_map; size_t last_position(0); std::multimap <size_t, var_info> end_positions; // end -> pos & lineno std::multimap <size_t, size_t, std::greater <size_t>> current_end_positions; // End positions for variants that have the same POS. conflict_count_map conflict_counts; overlap_map bad_overlaps; size_t i(0); size_t conflict_count(0); reader.reset(); reader.set_parsed_fields(vcf_field::REF); variant var(reader.sample_count()); while (reader.get_next_variant(var)) { // Verify that the positions are in increasing order. auto const pos(var.zero_based_pos()); if (! (last_position <= pos)) throw std::runtime_error("Positions not in increasing order"); auto const end(pos + var.ref().size()); auto const var_lineno(var.lineno()); if (last_position != pos) current_end_positions.clear(); // Check end position order. if (last_position == pos) { auto const it(current_end_positions.upper_bound(end)); if (current_end_positions.cend() != it) { non_nested_variants.emplace(var_lineno); non_nested_variants.emplace(it->second); } current_end_positions.emplace(end, var_lineno); } // Try to find an end position that is greater than var's position. auto it(end_positions.upper_bound(pos)); auto const end_it(end_positions.cend()); if (end_it == it) { end_positions.emplace( std::piecewise_construct, std::forward_as_tuple(end), std::forward_as_tuple(pos, var_lineno) ); goto loop_end; } // Check that the found position is not within var's range. // If it is, continue checking succeeding positions. do { // Proper nesting. if (end <= it->first) break; // Check if the potentially conflicting variant is in fact inside this one. auto const other_lineno(it->second.lineno); auto const other_pos(it->second.pos); if (pos == other_pos) goto loop_end_2; ++conflict_count; std::cerr << "Variant on line " << var_lineno << " conflicts with line " << other_lineno << "." << std::endl; { auto const res(bad_overlaps.insert(overlap_map::value_type(other_lineno, var_lineno))); if (false == res.second) throw std::runtime_error("Unable to insert"); } ++conflict_counts.left[other_lineno]; ++conflict_counts.left[var_lineno]; loop_end_2: ++it; } while (end_it != it); // Add the end position. end_positions.emplace( std::piecewise_construct, std::forward_as_tuple(end), std::forward_as_tuple(pos, var_lineno) ); loop_end: last_position = pos; ++i; if (0 == i % 100000) std::cerr << "Handled " << i << " variants…" << std::endl; } // Remove conflicting variants starting from the one with the highest score. while (!conflict_counts.empty()) { conflict_counts.right.sort(); auto const it(conflict_counts.right.rbegin()); auto const count(it->first); auto const var_lineno(it->second); // Check if the candidate variant is still listed. check_overlap(bad_overlaps.left, conflict_counts, skipped_variants, var_lineno, error_logger); check_overlap(bad_overlaps.right, conflict_counts, skipped_variants, var_lineno, error_logger); conflict_counts.left.erase(var_lineno); } if (bad_overlaps.size() != 0) throw std::runtime_error("Unable to remove all conflicting variants"); return conflict_count; } }
Handle nested variants in case the longer REF is listed first
Handle nested variants in case the longer REF is listed first
C++
mit
tsnorri/vcf2multialign,tsnorri/vcf2multialign,tsnorri/vcf2multialign,tsnorri/vcf2multialign
9ef8bc31776e3f4f1b6b1b0706882da5c579b090
dtrans/test/win32/dnd/dndTest.cxx
dtrans/test/win32/dnd/dndTest.cxx
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_dtrans.hxx" #if defined _MSC_VER #pragma warning(push,1) #endif #include <windows.h> #include <comdef.h> #include <tchar.h> #include <atlbase.h> CComModule _Module; #include<atlcom.h> #include<atlimpl.cpp> #if defined _MSC_VER #pragma warning(pop) #endif #include <com/sun/star/uno/Reference.h> #include <com/sun/star/lang/XInitialization.hpp> #include <com/sun/star/datatransfer/dnd/XDropTarget.hpp> #include <com/sun/star/datatransfer/dnd/DNDConstants.hpp> #include <com/sun/star/lang/XInitialization.hpp> #include <com/sun/star/lang/XComponent.hpp> #include <rtl/process.h> #include <cppuhelper/servicefactory.hxx> #include "sourcelistener.hxx" #include "atlwindow.hxx" BEGIN_OBJECT_MAP(ObjectMap) END_OBJECT_MAP() using namespace com::sun::star::lang; using namespace com::sun::star::datatransfer; using namespace com::sun::star::uno; using namespace com::sun::star::datatransfer::dnd; using namespace com::sun::star::datatransfer::dnd::DNDConstants; using namespace rtl; // defined in atlwindow.hxx // #define WM_SOURCE_INIT WM_APP+100 // #define WM_SOURCE_STARTDRAG WM_APP+101 #define WM_CREATE_MTA_WND HRESULT doTest(); DWORD WINAPI MTAFunc( void* threadData); Reference< XMultiServiceFactory > MultiServiceFactory; //int APIENTRY WinMain(HINSTANCE hInstance, // HINSTANCE hPrevInstance, // LPSTR lpCmdLine, // int nCmdShow) //int _tmain( int argc, TCHAR *argv[ ], TCHAR *envp[ ] ) int main( int argc, char *argv[ ], char *envp[ ] ) { HRESULT hr; if( FAILED( hr=CoInitialize(NULL ))) { _tprintf(_T("CoInitialize failed \n")); return -1; } _Module.Init( ObjectMap, GetModuleHandle( NULL)); if( FAILED(hr=doTest())) { _com_error err( hr); const TCHAR * errMsg= err.ErrorMessage(); // MessageBox( NULL, errMsg, "Test failed", MB_ICONERROR); } _Module.Term(); CoUninitialize(); return 0; } HRESULT doTest() { MultiServiceFactory= createRegistryServiceFactory( OUString(L"types.rdb"), OUString( L"services.rdb") , sal_True); // create the MTA thread that is used to realize MTA calls to the services // We create the thread and wait until the thread has created its message queue HANDLE evt= CreateEvent(NULL, FALSE, FALSE, NULL); DWORD threadIdMTA=0; HANDLE hMTAThread= CreateThread( NULL, 0, MTAFunc, &evt, 0, &threadIdMTA); WaitForSingleObject( evt, INFINITE); CloseHandle(evt); HRESULT hr= S_OK; RECT pos1={0,0,300,200}; AWindow win(_T("DnD starting in Ole STA"), threadIdMTA, pos1); RECT pos2={ 0, 205, 300, 405}; AWindow win2( _T("DnD starting in MTA"), threadIdMTA, pos2, true); // win3 and win4 call initialize from an MTA but they are created in an STA RECT pos3={300,0,600,200}; AWindow win3(_T("DnD starting in OLE STA"), threadIdMTA, pos3, false, true); RECT pos4={ 300, 205, 600, 405}; AWindow win24( _T("DnD starting in Ole MTA"), threadIdMTA, pos4, true, true); MSG msg; while( GetMessage(&msg, (HWND)NULL, 0, 0) ) { TranslateMessage( &msg); DispatchMessage( &msg); } // Shut down the MTA thread PostThreadMessage( threadIdMTA, WM_QUIT, 0, 0); WaitForSingleObject(hMTAThread, INFINITE); CloseHandle(hMTAThread); return S_OK; } extern Reference<XMultiServiceFactory> MultiServiceFactory; DWORD WINAPI MTAFunc( void* threadData) { HRESULT hr= S_OK; hr= CoInitializeEx( NULL, COINIT_MULTITHREADED); ATLASSERT( FAILED(hr) ); MSG msg; // force the creation of a message queue PeekMessage(&msg, NULL, WM_USER, WM_USER, PM_NOREMOVE); SetEvent( *(HANDLE*)threadData ); RECT pos={0, 406, 300, 605}; AWindow win(_T("DnD, full MTA"), GetCurrentThreadId(), pos, false, true); // ThreadData data= *( ThreadData*)pParams; // SetEvent(data.evtThreadReady); while( GetMessage(&msg, (HWND)NULL, 0, 0) ) { switch( msg.message) { case WM_SOURCE_INIT: { InitializationData* pData= (InitializationData*)msg.wParam; Any any; any <<= (sal_uInt32) pData->hWnd; pData->xInit->initialize( Sequence<Any>( &any, 1)); CoTaskMemFree( pData); break; } case WM_SOURCE_STARTDRAG: { // wParam contains necessary data StartDragData* pData= (StartDragData*)msg.wParam; Sequence<DataFlavor> seq= pData->transferable->getTransferDataFlavors(); // have a look what flavours are supported for( int i=0; i<seq.getLength(); i++) { DataFlavor d= seq[i]; } pData->source->startDrag( DragGestureEvent(), ACTION_LINK|ACTION_MOVE|ACTION_COPY, 0, 0, pData->transferable, Reference<XDragSourceListener>( static_cast<XDragSourceListener*> ( new DragSourceListener()))); CoTaskMemFree( pData); break; } } // end switch TranslateMessage( &msg); DispatchMessage( &msg); } CoUninitialize(); return 0; } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_dtrans.hxx" #if defined _MSC_VER #pragma warning(push,1) #endif #include <windows.h> #include <comdef.h> #include <tchar.h> #include <atlbase.h> CComModule _Module; #include<atlcom.h> #include<atlimpl.cpp> #if defined _MSC_VER #pragma warning(pop) #endif #include <com/sun/star/uno/Reference.h> #include <com/sun/star/lang/XInitialization.hpp> #include <com/sun/star/datatransfer/dnd/XDropTarget.hpp> #include <com/sun/star/datatransfer/dnd/DNDConstants.hpp> #include <com/sun/star/lang/XInitialization.hpp> #include <com/sun/star/lang/XComponent.hpp> #include <rtl/process.h> #include <cppuhelper/servicefactory.hxx> #include "sourcelistener.hxx" #include "atlwindow.hxx" BEGIN_OBJECT_MAP(ObjectMap) END_OBJECT_MAP() using namespace com::sun::star::lang; using namespace com::sun::star::datatransfer; using namespace com::sun::star::uno; using namespace com::sun::star::datatransfer::dnd; using namespace com::sun::star::datatransfer::dnd::DNDConstants; using namespace rtl; #define WM_CREATE_MTA_WND HRESULT doTest(); DWORD WINAPI MTAFunc( void* threadData); Reference< XMultiServiceFactory > MultiServiceFactory; int main( int argc, char *argv[ ], char *envp[ ] ) { HRESULT hr; if( FAILED( hr=CoInitialize(NULL ))) { _tprintf(_T("CoInitialize failed \n")); return -1; } _Module.Init( ObjectMap, GetModuleHandle( NULL)); if( FAILED(hr=doTest())) { _com_error err( hr); } _Module.Term(); CoUninitialize(); return 0; } HRESULT doTest() { MultiServiceFactory= createRegistryServiceFactory( OUString(L"types.rdb"), OUString( L"services.rdb") , sal_True); // create the MTA thread that is used to realize MTA calls to the services // We create the thread and wait until the thread has created its message queue HANDLE evt= CreateEvent(NULL, FALSE, FALSE, NULL); DWORD threadIdMTA=0; HANDLE hMTAThread= CreateThread( NULL, 0, MTAFunc, &evt, 0, &threadIdMTA); WaitForSingleObject( evt, INFINITE); CloseHandle(evt); HRESULT hr= S_OK; RECT pos1={0,0,300,200}; AWindow win(_T("DnD starting in Ole STA"), threadIdMTA, pos1); RECT pos2={ 0, 205, 300, 405}; AWindow win2( _T("DnD starting in MTA"), threadIdMTA, pos2, true); // win3 and win4 call initialize from an MTA but they are created in an STA RECT pos3={300,0,600,200}; AWindow win3(_T("DnD starting in OLE STA"), threadIdMTA, pos3, false, true); RECT pos4={ 300, 205, 600, 405}; AWindow win24( _T("DnD starting in Ole MTA"), threadIdMTA, pos4, true, true); MSG msg; while( GetMessage(&msg, (HWND)NULL, 0, 0) ) { TranslateMessage( &msg); DispatchMessage( &msg); } // Shut down the MTA thread PostThreadMessage( threadIdMTA, WM_QUIT, 0, 0); WaitForSingleObject(hMTAThread, INFINITE); CloseHandle(hMTAThread); return S_OK; } extern Reference<XMultiServiceFactory> MultiServiceFactory; DWORD WINAPI MTAFunc( void* threadData) { HRESULT hr= S_OK; hr= CoInitializeEx( NULL, COINIT_MULTITHREADED); ATLASSERT( FAILED(hr) ); MSG msg; // force the creation of a message queue PeekMessage(&msg, NULL, WM_USER, WM_USER, PM_NOREMOVE); SetEvent( *(HANDLE*)threadData ); RECT pos={0, 406, 300, 605}; AWindow win(_T("DnD, full MTA"), GetCurrentThreadId(), pos, false, true); while( GetMessage(&msg, (HWND)NULL, 0, 0) ) { switch( msg.message) { case WM_SOURCE_INIT: { InitializationData* pData= (InitializationData*)msg.wParam; Any any; any <<= (sal_uInt32) pData->hWnd; pData->xInit->initialize( Sequence<Any>( &any, 1)); CoTaskMemFree( pData); break; } case WM_SOURCE_STARTDRAG: { // wParam contains necessary data StartDragData* pData= (StartDragData*)msg.wParam; Sequence<DataFlavor> seq= pData->transferable->getTransferDataFlavors(); // have a look what flavours are supported for( int i=0; i<seq.getLength(); i++) { DataFlavor d= seq[i]; } pData->source->startDrag( DragGestureEvent(), ACTION_LINK|ACTION_MOVE|ACTION_COPY, 0, 0, pData->transferable, Reference<XDragSourceListener>( static_cast<XDragSourceListener*> ( new DragSourceListener()))); CoTaskMemFree( pData); break; } } // end switch TranslateMessage( &msg); DispatchMessage( &msg); } CoUninitialize(); return 0; } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */
Remove unused variable errMsg and dead code.
Remove unused variable errMsg and dead code.
C++
mpl-2.0
JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core
e9693bed4dac41fb1ae8bffa4221e0ba1f9218de
frameworks/runtime-src/Framework/utils/MWAssetManager.cpp
frameworks/runtime-src/Framework/utils/MWAssetManager.cpp
#include "MWAssetManager.h" #include "../json/MWJsonStructure.h" #include "../platform/MWIOUtils.h" #include "../net/http/MWHttpDownloader.h" #include "../lua/MWLuaUtils.h" #include "cocos2d.h" #include <vector> // files and directorys #define AM_VERSION_FILE "version.json" #define AM_CONFIG_FILE "config.json" #define AM_BUNDLE_MD5_FILE "bundle_md5.json" #define AM_LOCAL_VERSION_FILE "local_version.json" #define AM_LOCAL_MD5_FILE "local_md5.json" #define AM_ASSET_DIR "Asset" #define AM_BUNDLE_MD5_DIR "BundleMd5" #define AM_SCRIPT_DIR "src" // version description file keys #define AM_VERSION_STR_KEY "version_str" #define AM_CPP_VERSION_KEY "cpp_version" #define AM_UPDATE_URL_KEY "cpp_update_url" #define AM_FILE_COUNT_KEY "file_count" #define AM_FILE_INFO_KEY "file_info" // file id to identify what kinds of file is downloading or downloaded. #define AM_VERSION_FILE_ID "am.version.id" #define AM_CONFIG_FILE_ID "am.config.id" #define AM_BUNDLE_MD5_FILE_ID "am.bundle.md5.id" using namespace std; using namespace cocos2d; MW_FRAMEWORK_BEGIN MWAssetManager::MWAssetManager() : _isDevelopMode(false) , _bundleVersion() , _programVersion(0) , _serverUrl() , _assetRoot() , _delegate(nullptr) , _downloader(nullptr) , _downloadFileList() , _fileSizeMap() , _readyToUpdate(false) , _localVersion() , _newVersion() , _programUpdateUrl() { _downloader = new MWHttpDownloader(); _downloader->setDelegate(this); } MWAssetManager::~MWAssetManager() { CC_SAFE_DELETE(_downloader); CC_SAFE_DELETE(_delegate); } void MWAssetManager::checkVersion() { this->_loadLocalVersion(); this->_configSearchPath(); this->_downloadVersionFile(); } void MWAssetManager::beginUpdate() { if (!_readyToUpdate) { CCLOG("Unable to update, did you call the checkVersion first?"); return; } this->_downloadNextAssetFile(); } void MWAssetManager::setAssetUpdateDelegate(mwframework::IAssetUpdateDelegate *delegate) { CC_SAFE_DELETE(_delegate); _delegate = delegate; } void MWAssetManager::_loadLocalVersion() { if (!MWIOUtils::getInstance()->directoryExists(this->_fullLocalAssetPath())) { MWIOUtils::getInstance()->createDirectory(this->_fullLocalAssetPath()); } string assetDir = this->_fullLocalAssetPath(); string localVersionPath = MWIOUtils::getInstance()->splicePath(assetDir, AM_LOCAL_VERSION_FILE); if (!MWIOUtils::getInstance()->fileExists(localVersionPath)) { _localVersion = _bundleVersion; } else { MWJsonObject *localVersionJson = MWJsonObject::createWithFile(localVersionPath); if (!localVersionJson || !localVersionJson->hasKey(AM_VERSION_STR_KEY) || !localVersionJson->hasKey(AM_CPP_VERSION_KEY)) { // local version file is damaged. delete it. MWIOUtils::getInstance()->removeFile(localVersionPath); _localVersion = _bundleVersion; } else { // check whether cpp version is the latest int cppVersion = (int) localVersionJson->getNumber(AM_CPP_VERSION_KEY); if (cppVersion < _programVersion) { // remove all updated data. MWIOUtils::getInstance->removeDirectory(this->_fullLocalAssetPath()); _localVersion = _bundleVersion; } else { _localVersion = localVersionJson->getString(AM_VERSION_STR_KEY); } } } } void MWAssetManager::_downloadVersionFile() { string url = this->_fullServerAssetPath(AM_VERSION_FILE); string savePath = this->_fullLocalAssetPath(AM_VERSION_FILE); _downloader->beginDownloading(url, savePath, __String::create(AM_VERSION_FILE_ID)); } void MWAssetManager::_processAfterDownloadVersionFile() { string versionFilePath = this->_fullLocalAssetPath(AM_VERSION_FILE); auto versionJson = MWJsonObject::createWithFile(versionFilePath); if (!versionJson) { this->_delegateUpdateError(EAssetUpdateErrorType::VERSION_CHECK_ERROR, "Failed to parse version file."); return; } if (!versionJson->hasKey(AM_VERSION_STR_KEY) || !versionJson->hasKey(AM_UPDATE_URL_KEY)) { this->_delegateUpdateError(EAssetUpdateErrorType::VERSION_CHECK_ERROR, "Invalid version file."); return; } _newVersion = versionJson->getString(AM_VERSION_STR_KEY); _programUpdateUrl = versionJson->getString(AM_UPDATE_URL_KEY); if (_localVersion == _newVersion) { string localMd5Path = this->_fullLocalAssetPath(AM_LOCAL_MD5_FILE); if (MWIOUtils::getInstance()->fileExists(localMd5Path)) { this->_saveVersion(); this->_delegateVersionCheckCompleted(true, 0, false, ""); } else { // download related md5 file string url = this->_fullServerAssetPath(string(AM_BUNDLE_MD5_DIR) + "/" + _newVersion + "/" + AM_BUNDLE_MD5_FILE); _downloader->beginDownloading(url, localMd5Path, __String::create(AM_BUNDLE_MD5_FILE_ID)); } } else { this->_downloadAssetConfigFile(); } } void MWAssetManager::_downloadAssetConfigFile() { string url = this->_fullServerAssetPath(AM_CONFIG_FILE); string savePath = this->_fullLocalAssetPath(AM_CONFIG_FILE); _downloader->beginDownloading(url, savePath, __String::create(AM_CONFIG_FILE_ID)); } void MWAssetManager::_processAfterDownloadAssetConfigFile() { string configFilePath = this->_fullLocalAssetPath(AM_CONFIG_FILE); auto configJson = MWJsonObject::createWithFile(configFilePath); if (!configJson) { this->_delegateUpdateError(EAssetUpdateErrorType::VERSION_CHECK_ERROR, "Failed to parse config file."); return; } if (!configJson->hasKey(AM_FILE_COUNT_KEY) || !configJson->hasKey(AM_FILE_INFO_KEY)) { this->_delegateUpdateError(EAssetUpdateErrorType::VERSION_CHECK_ERROR, "Invalid config file."); return; } MWJsonObject *fileInfoJson = configJson->getJsonObject(AM_FILE_INFO_KEY); if (!fileInfoJson) { this->_delegateUpdateError(EAssetUpdateErrorType::VERSION_CHECK_ERROR, "Invalid config file."); return; } _fileSizeMap.clear(); auto allKeys = fileInfoJson->allKeys(); for (const auto &key : allKeys) { _fileSizeMap[key] = (long) fileInfoJson->getNumber(key); } this->_downloadBundleMd5File(); } void MWAssetManager::_downloadBundleMd5File() { string url = this->_fullServerAssetPath(string(AM_BUNDLE_MD5_DIR) + "/" + _newVersion + "/" + AM_BUNDLE_MD5_FILE); string savePath = this->_fullLocalAssetPath(AM_BUNDLE_MD5_FILE); _downloader->beginDownloading(url, savePath, __String::create(AM_BUNDLE_MD5_FILE_ID)); } void MWAssetManager::_processAfterDownloadBundleMd5File() { this->_mergeBundleMd5File(); _readyToUpdate = true; this->_delegateVersionCheckCompleted(false, (int) _downloadFileList.size(), !_programUpdateUrl.empty(), _programUpdateUrl); } void MWAssetManager::_mergeBundleMd5File() { // retreive new bundle md5 file. string bundleMd5Path = this->_fullLocalAssetPath(AM_BUNDLE_MD5_FILE); MWJsonObject *bundleMd5Json = MWJsonObject::createWithFile(bundleMd5Path); if (!bundleMd5Json) { this->_delegateUpdateError(EAssetUpdateErrorType::VERSION_CHECK_ERROR, "Failed to parse bundle md5 file."); return; } // retreive local bundle md5 file. string localMd5Path = this->_fullLocalAssetPath(AM_LOCAL_MD5_FILE); MWJsonObject *localMd5Map = MWJsonObject::create(); if (MWIOUtils::getInstance()->fileExists(localMd5Path)) { MWJsonObject *localMd5Json = MWJsonObject::createWithFile(localMd5Path); if (!localMd5Json) { // invalid local md5 file, delete it. MWIOUtils::getInstance()->removeFile(localMd5Path); this->_delegateUpdateError(EAssetUpdateErrorType::VERSION_CHECK_ERROR, "Failed to parse local md5 file."); return; } else { localMd5Map = localMd5Json; } } // remove unneccessary resources. auto allKeys = localMd5Map->allKeys(); for (const auto &key : allKeys) { if (!bundleMd5Json->hasKey(key)) { MWIOUtils::getInstance()->removeFile(this->_fullLocalAssetPath(key)); } } MWIOUtils::getInstance()->copyFile(bundleMd5Path, localMd5Path); // save download file list _downloadFileList = queue<string>(); allKeys = bundleMd5Json->allKeys(); for (const auto &key : allKeys) { if (!localMd5Map->hasKey(key) || strcmp(localMd5Map->getString(key), bundleMd5Json->getString(key)) != 0) { _downloadFileList.push(key); } } } void MWAssetManager::_downloadNextAssetFile() { // todo. continue with the progress of last accident which cause the failure of the update. if (!_downloadFileList.empty()) { string rpath = _downloadFileList.front(); string downloadPath = this->_fullServerAssetPath(string(AM_ASSET_DIR) + "/" + rpath); string savePath = this->_fullLocalAssetPath(string(AM_ASSET_DIR) + "/" + rpath); _downloader->beginDownloading(downloadPath, savePath, __String::create(rpath), true); } else { if (this->_saveVersion()) { this->_delegateVersionUpdated(); } } } bool MWAssetManager::_saveVersion() { if (!MWIOUtils::getInstance()->copyFile(this->_fullLocalAssetPath(AM_VERSION_FILE), this->_fullLocalAssetPath(AM_LOCAL_VERSION_FILE))) { this->_delegateUpdateError(EAssetUpdateErrorType::IO_ERROR, "Failed to save local version."); return; } _localVersion = _newVersion; } string MWAssetManager::_fullLocalAssetPath(const std::string &path) { return MWIOUtils::getInstance()->splicePath(_assetRoot, path); } string MWAssetManager::_fullServerAssetPath(const std::string &path) { return MWIOUtils::getInstance()->splicePath(_serverUrl, path); } void MWAssetManager::_configSearchPath() { vector<string> searchPaths = FileUtils::getInstance()->getSearchPaths(); string assetPath = this->_fullLocalAssetPath(AM_ASSET_DIR); // check whether the asset resource path is already set. bool didSet = false; for (const auto &path : searchPaths) { if (path == assetPath) { didSet = true; break; } } // set if non-exist. if (!didSet) { // the asset path must occupy the highest priority. searchPaths.insert(searchPaths.cbegin(), assetPath); FileUtils::getInstance()->setSearchPaths(searchPaths); // set search order, the asset resource path should be the prepreerence. FileUtils::getInstance()->addSearchResolutionsOrder(assetPath, true); // add lua script package path. #if MW_ENABLE_SCRIPT_BINDING vector<string> packages; packages.push_back(MWIOUtils::getInstance()->splicePath(this->_fullLocalAssetPath(AM_ASSET_DIR), AM_SCRIPT_DIR)); MWLuaUtils::getInstance()->addPackagePaths(packages); // CCLOG("%s", MWLuaUtils::getInstance()->getPackagePath().c_str()); #endif } } void MWAssetManager::_delegateVersionCheckCompleted(bool latest, int fileCount, bool needUpdateProgram, const std::string &programUpdateUrl) { if (_delegate) { _delegate->onVersionCheckCompleted(latest, fileCount, needUpdateProgram, programUpdateUrl); } } void MWAssetManager::_delegateVersionUpdated() { if (_delegate) { _delegate->onVersionUpdated(); } } void MWAssetManager::_delegateAssetFileDownloaded(const std::string &relativePath) { if (_delegate) { _delegate->onAssetFileDownloaded(relativePath); } } void MWAssetManager::_delegateAssetFileDownloading(const std::string &relativePath, double downloaded, double totalToDownload) { if (_delegate) { _delegate->onAssetFileDownloading(relativePath, downloaded, totalToDownload); } } void MWAssetManager::_delegateUpdateError(mwframework::EAssetUpdateErrorType errorType, const std::string &errorMsg) { if (_delegate) { _delegate->onUpdateError(errorType, errorMsg); } } void MWAssetManager::onDownloadStarted(mwframework::MWHttpDownloader *downloader, cocos2d::Ref *userdata) { MW_UNUSED_PARAM(downloader); string fileId = static_cast<__String *>(userdata)->getCString(); if (fileId == string(AM_VERSION_FILE_ID)) { CCLOG("开始下载版本文件..."); } else if (fileId == string(AM_CONFIG_FILE_ID)) { CCLOG("开始下载Asset配置文件..."); } else if (fileId == string(AM_BUNDLE_MD5_FILE_ID)) { CCLOG("开始下载Bundle Md5文件..."); } else { CCLOG("开始下载%s", static_cast<__String *>(userdata)->getCString()); } } void MWAssetManager::onDownloading(mwframework::MWHttpDownloader *downloader, float progress, cocos2d::Ref *userdata) { MW_UNUSED_PARAM(downloader); string fileId = static_cast<__String *>(userdata)->getCString(); if (fileId != string(AM_VERSION_FILE_ID) && fileId != string(AM_CONFIG_FILE_ID) && fileId != string(AM_BUNDLE_MD5_FILE_ID)) { long totalSize = _fileSizeMap[fileId]; this->_delegateAssetFileDownloading(fileId, (double) progress * totalSize, (double) totalSize); } } void MWAssetManager::onDownloadCompleted(mwframework::MWHttpDownloader *downloader, cocos2d::Ref *userdata) { MW_UNUSED_PARAM(downloader); string fileId = static_cast<__String *>(userdata)->getCString(); if (fileId == string(AM_VERSION_FILE_ID)) { this->_processAfterDownloadVersionFile(); } else if (fileId == string(AM_CONFIG_FILE_ID)) { this->_processAfterDownloadAssetConfigFile(); } else if (fileId == string(AM_BUNDLE_MD5_FILE_ID)) { if (_localVersion == _newVersion) { this->_saveVersion(); this->_delegateVersionCheckCompleted(true, 0, false, ""); } else { this->_processAfterDownloadBundleMd5File(); } } else { this->_delegateAssetFileDownloaded(fileId); _downloadFileList.pop(); this->_downloadNextAssetFile(); } } void MWAssetManager::onDownloadFailed(mwframework::MWHttpDownloader *downloader, const std::string &errorMsg, cocos2d::Ref *userdata) { MW_UNUSED_PARAM(downloader); CCLOG("下载错误: %s", errorMsg.c_str()); if (_downloader->retry(userdata)) { CCLOG("重试下载..."); return; } this->_delegateUpdateError(EAssetUpdateErrorType::NETWORK_ERROR, errorMsg); } MW_FRAMEWORK_END
#include "MWAssetManager.h" #include "../json/MWJsonStructure.h" #include "../platform/MWIOUtils.h" #include "../net/http/MWHttpDownloader.h" #include "../lua/MWLuaUtils.h" #include "cocos2d.h" #include <vector> // files and directorys #define AM_VERSION_FILE "version.json" #define AM_CONFIG_FILE "config.json" #define AM_BUNDLE_MD5_FILE "bundle_md5.json" #define AM_LOCAL_VERSION_FILE "local_version.json" #define AM_LOCAL_MD5_FILE "local_md5.json" #define AM_ASSET_DIR "Asset" #define AM_BUNDLE_MD5_DIR "BundleMd5" #define AM_SCRIPT_DIR "src" // version description file keys #define AM_VERSION_STR_KEY "version_str" #define AM_CPP_VERSION_KEY "cpp_version" #define AM_UPDATE_URL_KEY "cpp_update_url" #define AM_FILE_COUNT_KEY "file_count" #define AM_FILE_INFO_KEY "file_info" // file id to identify what kinds of file is downloading or downloaded. #define AM_VERSION_FILE_ID "am.version.id" #define AM_CONFIG_FILE_ID "am.config.id" #define AM_BUNDLE_MD5_FILE_ID "am.bundle.md5.id" using namespace std; using namespace cocos2d; MW_FRAMEWORK_BEGIN MWAssetManager::MWAssetManager() : _isDevelopMode(false) , _bundleVersion() , _programVersion(0) , _serverUrl() , _assetRoot() , _delegate(nullptr) , _downloader(nullptr) , _downloadFileList() , _fileSizeMap() , _readyToUpdate(false) , _localVersion() , _newVersion() , _programUpdateUrl() { _downloader = new MWHttpDownloader(); _downloader->setDelegate(this); } MWAssetManager::~MWAssetManager() { CC_SAFE_DELETE(_downloader); CC_SAFE_DELETE(_delegate); } void MWAssetManager::checkVersion() { this->_loadLocalVersion(); this->_configSearchPath(); this->_downloadVersionFile(); } void MWAssetManager::beginUpdate() { if (!_readyToUpdate) { CCLOG("Unable to update, did you call the checkVersion first?"); return; } this->_downloadNextAssetFile(); } void MWAssetManager::setAssetUpdateDelegate(mwframework::IAssetUpdateDelegate *delegate) { CC_SAFE_DELETE(_delegate); _delegate = delegate; } void MWAssetManager::_loadLocalVersion() { if (!MWIOUtils::getInstance()->directoryExists(this->_fullLocalAssetPath())) { MWIOUtils::getInstance()->createDirectory(this->_fullLocalAssetPath()); } string assetDir = this->_fullLocalAssetPath(); string localVersionPath = MWIOUtils::getInstance()->splicePath(assetDir, AM_LOCAL_VERSION_FILE); if (!MWIOUtils::getInstance()->fileExists(localVersionPath)) { _localVersion = _bundleVersion; } else { MWJsonObject *localVersionJson = MWJsonObject::createWithFile(localVersionPath); if (!localVersionJson || !localVersionJson->hasKey(AM_VERSION_STR_KEY) || !localVersionJson->hasKey(AM_CPP_VERSION_KEY)) { // local version file is damaged. delete it. MWIOUtils::getInstance()->removeFile(localVersionPath); _localVersion = _bundleVersion; } else { // check whether cpp version is the latest int cppVersion = (int) localVersionJson->getNumber(AM_CPP_VERSION_KEY); if (cppVersion < _programVersion) { // remove all updated data. MWIOUtils::getInstance->removeDirectory(this->_fullLocalAssetPath()); _localVersion = _bundleVersion; } else { _localVersion = localVersionJson->getString(AM_VERSION_STR_KEY); } } } } void MWAssetManager::_downloadVersionFile() { string url = this->_fullServerAssetPath(AM_VERSION_FILE); string savePath = this->_fullLocalAssetPath(AM_VERSION_FILE); _downloader->beginDownloading(url, savePath, __String::create(AM_VERSION_FILE_ID)); } void MWAssetManager::_processAfterDownloadVersionFile() { string versionFilePath = this->_fullLocalAssetPath(AM_VERSION_FILE); auto versionJson = MWJsonObject::createWithFile(versionFilePath); if (!versionJson) { this->_delegateUpdateError(EAssetUpdateErrorType::VERSION_CHECK_ERROR, "Failed to parse version file."); return; } if (!versionJson->hasKey(AM_VERSION_STR_KEY) || !versionJson->hasKey(AM_UPDATE_URL_KEY)) { this->_delegateUpdateError(EAssetUpdateErrorType::VERSION_CHECK_ERROR, "Invalid version file."); return; } _newVersion = versionJson->getString(AM_VERSION_STR_KEY); _programUpdateUrl = versionJson->getString(AM_UPDATE_URL_KEY); if (_localVersion == _newVersion) { string localMd5Path = this->_fullLocalAssetPath(AM_LOCAL_MD5_FILE); if (MWIOUtils::getInstance()->fileExists(localMd5Path)) { this->_saveVersion(); this->_delegateVersionCheckCompleted(true, 0, false, ""); } else { // download related md5 file string url = this->_fullServerAssetPath(string(AM_BUNDLE_MD5_DIR) + "/" + _newVersion + "/" + AM_BUNDLE_MD5_FILE); _downloader->beginDownloading(url, localMd5Path, __String::create(AM_BUNDLE_MD5_FILE_ID)); } } else { this->_downloadAssetConfigFile(); } } void MWAssetManager::_downloadAssetConfigFile() { string url = this->_fullServerAssetPath(AM_CONFIG_FILE); string savePath = this->_fullLocalAssetPath(AM_CONFIG_FILE); _downloader->beginDownloading(url, savePath, __String::create(AM_CONFIG_FILE_ID)); } void MWAssetManager::_processAfterDownloadAssetConfigFile() { string configFilePath = this->_fullLocalAssetPath(AM_CONFIG_FILE); auto configJson = MWJsonObject::createWithFile(configFilePath); if (!configJson) { this->_delegateUpdateError(EAssetUpdateErrorType::VERSION_CHECK_ERROR, "Failed to parse config file."); return; } if (!configJson->hasKey(AM_FILE_COUNT_KEY) || !configJson->hasKey(AM_FILE_INFO_KEY)) { this->_delegateUpdateError(EAssetUpdateErrorType::VERSION_CHECK_ERROR, "Invalid config file."); return; } MWJsonObject *fileInfoJson = configJson->getJsonObject(AM_FILE_INFO_KEY); if (!fileInfoJson) { this->_delegateUpdateError(EAssetUpdateErrorType::VERSION_CHECK_ERROR, "Invalid config file."); return; } _fileSizeMap.clear(); auto allKeys = fileInfoJson->allKeys(); for (const auto &key : allKeys) { _fileSizeMap[key] = (long) fileInfoJson->getNumber(key); } this->_downloadBundleMd5File(); } void MWAssetManager::_downloadBundleMd5File() { string url = this->_fullServerAssetPath(string(AM_BUNDLE_MD5_DIR) + "/" + _newVersion + "/" + AM_BUNDLE_MD5_FILE); string savePath = this->_fullLocalAssetPath(AM_BUNDLE_MD5_FILE); _downloader->beginDownloading(url, savePath, __String::create(AM_BUNDLE_MD5_FILE_ID)); } void MWAssetManager::_processAfterDownloadBundleMd5File() { this->_mergeBundleMd5File(); _readyToUpdate = true; this->_delegateVersionCheckCompleted(false, (int) _downloadFileList.size(), !_programUpdateUrl.empty(), _programUpdateUrl); } void MWAssetManager::_mergeBundleMd5File() { // retreive new bundle md5 file. string bundleMd5Path = this->_fullLocalAssetPath(AM_BUNDLE_MD5_FILE); MWJsonObject *bundleMd5Json = MWJsonObject::createWithFile(bundleMd5Path); if (!bundleMd5Json) { this->_delegateUpdateError(EAssetUpdateErrorType::VERSION_CHECK_ERROR, "Failed to parse bundle md5 file."); return; } // retreive local bundle md5 file. string localMd5Path = this->_fullLocalAssetPath(AM_LOCAL_MD5_FILE); MWJsonObject *localMd5Map = MWJsonObject::create(); if (MWIOUtils::getInstance()->fileExists(localMd5Path)) { MWJsonObject *localMd5Json = MWJsonObject::createWithFile(localMd5Path); if (!localMd5Json) { // invalid local md5 file, delete it. MWIOUtils::getInstance()->removeFile(localMd5Path); this->_delegateUpdateError(EAssetUpdateErrorType::VERSION_CHECK_ERROR, "Failed to parse local md5 file."); return; } else { localMd5Map = localMd5Json; } } // remove unneccessary resources. auto allKeys = localMd5Map->allKeys(); for (const auto &key : allKeys) { if (!bundleMd5Json->hasKey(key)) { MWIOUtils::getInstance()->removeFile(this->_fullLocalAssetPath(key)); } } MWIOUtils::getInstance()->copyFile(bundleMd5Path, localMd5Path); // save download file list _downloadFileList = queue<string>(); allKeys = bundleMd5Json->allKeys(); for (const auto &key : allKeys) { if (!localMd5Map->hasKey(key) || strcmp(localMd5Map->getString(key), bundleMd5Json->getString(key)) != 0) { _downloadFileList.push(key); } } } void MWAssetManager::_downloadNextAssetFile() { // todo. continue with the progress of last accident which cause the failure of the update. if (!_downloadFileList.empty()) { string rpath = _downloadFileList.front(); string downloadPath = this->_fullServerAssetPath(string(AM_ASSET_DIR) + "/" + rpath); string savePath = this->_fullLocalAssetPath(string(AM_ASSET_DIR) + "/" + rpath); _downloader->beginDownloading(downloadPath, savePath, __String::create(rpath), true); } else { if (this->_saveVersion()) { this->_delegateVersionUpdated(); } } } bool MWAssetManager::_saveVersion() { if (!MWIOUtils::getInstance()->copyFile(this->_fullLocalAssetPath(AM_VERSION_FILE), this->_fullLocalAssetPath(AM_LOCAL_VERSION_FILE))) { this->_delegateUpdateError(EAssetUpdateErrorType::IO_ERROR, "Failed to save local version."); return false; } _localVersion = _newVersion; return true; } string MWAssetManager::_fullLocalAssetPath(const std::string &path) { return MWIOUtils::getInstance()->splicePath(_assetRoot, path); } string MWAssetManager::_fullServerAssetPath(const std::string &path) { return MWIOUtils::getInstance()->splicePath(_serverUrl, path); } void MWAssetManager::_configSearchPath() { vector<string> searchPaths = FileUtils::getInstance()->getSearchPaths(); string assetPath = this->_fullLocalAssetPath(AM_ASSET_DIR); // check whether the asset resource path is already set. bool didSet = false; for (const auto &path : searchPaths) { if (path == assetPath) { didSet = true; break; } } // set if non-exist. if (!didSet) { // the asset path must occupy the highest priority. searchPaths.insert(searchPaths.cbegin(), assetPath); FileUtils::getInstance()->setSearchPaths(searchPaths); // set search order, the asset resource path should be the prepreerence. FileUtils::getInstance()->addSearchResolutionsOrder(assetPath, true); // add lua script package path. #if MW_ENABLE_SCRIPT_BINDING vector<string> packages; packages.push_back(MWIOUtils::getInstance()->splicePath(this->_fullLocalAssetPath(AM_ASSET_DIR), AM_SCRIPT_DIR)); MWLuaUtils::getInstance()->addPackagePaths(packages); // CCLOG("%s", MWLuaUtils::getInstance()->getPackagePath().c_str()); #endif } } void MWAssetManager::_delegateVersionCheckCompleted(bool latest, int fileCount, bool needUpdateProgram, const std::string &programUpdateUrl) { if (_delegate) { _delegate->onVersionCheckCompleted(latest, fileCount, needUpdateProgram, programUpdateUrl); } } void MWAssetManager::_delegateVersionUpdated() { if (_delegate) { _delegate->onVersionUpdated(); } } void MWAssetManager::_delegateAssetFileDownloaded(const std::string &relativePath) { if (_delegate) { _delegate->onAssetFileDownloaded(relativePath); } } void MWAssetManager::_delegateAssetFileDownloading(const std::string &relativePath, double downloaded, double totalToDownload) { if (_delegate) { _delegate->onAssetFileDownloading(relativePath, downloaded, totalToDownload); } } void MWAssetManager::_delegateUpdateError(mwframework::EAssetUpdateErrorType errorType, const std::string &errorMsg) { if (_delegate) { _delegate->onUpdateError(errorType, errorMsg); } } void MWAssetManager::onDownloadStarted(mwframework::MWHttpDownloader *downloader, cocos2d::Ref *userdata) { MW_UNUSED_PARAM(downloader); string fileId = static_cast<__String *>(userdata)->getCString(); if (fileId == string(AM_VERSION_FILE_ID)) { CCLOG("开始下载版本文件..."); } else if (fileId == string(AM_CONFIG_FILE_ID)) { CCLOG("开始下载Asset配置文件..."); } else if (fileId == string(AM_BUNDLE_MD5_FILE_ID)) { CCLOG("开始下载Bundle Md5文件..."); } else { CCLOG("开始下载%s", static_cast<__String *>(userdata)->getCString()); } } void MWAssetManager::onDownloading(mwframework::MWHttpDownloader *downloader, float progress, cocos2d::Ref *userdata) { MW_UNUSED_PARAM(downloader); string fileId = static_cast<__String *>(userdata)->getCString(); if (fileId != string(AM_VERSION_FILE_ID) && fileId != string(AM_CONFIG_FILE_ID) && fileId != string(AM_BUNDLE_MD5_FILE_ID)) { long totalSize = _fileSizeMap[fileId]; this->_delegateAssetFileDownloading(fileId, (double) progress * totalSize, (double) totalSize); } } void MWAssetManager::onDownloadCompleted(mwframework::MWHttpDownloader *downloader, cocos2d::Ref *userdata) { MW_UNUSED_PARAM(downloader); string fileId = static_cast<__String *>(userdata)->getCString(); if (fileId == string(AM_VERSION_FILE_ID)) { this->_processAfterDownloadVersionFile(); } else if (fileId == string(AM_CONFIG_FILE_ID)) { this->_processAfterDownloadAssetConfigFile(); } else if (fileId == string(AM_BUNDLE_MD5_FILE_ID)) { if (_localVersion == _newVersion) { this->_saveVersion(); this->_delegateVersionCheckCompleted(true, 0, false, ""); } else { this->_processAfterDownloadBundleMd5File(); } } else { this->_delegateAssetFileDownloaded(fileId); _downloadFileList.pop(); this->_downloadNextAssetFile(); } } void MWAssetManager::onDownloadFailed(mwframework::MWHttpDownloader *downloader, const std::string &errorMsg, cocos2d::Ref *userdata) { MW_UNUSED_PARAM(downloader); CCLOG("下载错误: %s", errorMsg.c_str()); if (_downloader->retry(userdata)) { CCLOG("重试下载..."); return; } this->_delegateUpdateError(EAssetUpdateErrorType::NETWORK_ERROR, errorMsg); } MW_FRAMEWORK_END
fix save version
fix save version
C++
apache-2.0
wanmaple/MWFrameworkForCocosLua,wanmaple/MWFrameworkForCocosLua,wanmaple/MWFrameworkForCocosLua,wanmaple/MWFrameworkForCocosLua,wanmaple/MWFrameworkForCocosLua,wanmaple/MWFrameworkForCocosLua,wanmaple/MWFrameworkForCocosLua
413d7f945015d4da3f247a058ef07fb91d8c0ab3
walude/ultrabool.hpp
walude/ultrabool.hpp
#ifndef WALUDE_ULTRABOOL #define WALUDE_ULTRABOOL #include <random> #include <ctime> bool darkurza_bool() { // Do not try and fix it with any of that mt199937 or sane random seeding // nonsense. Here we adhere to darkurza principles only. std::srand(std::time(0)); auto success = std::rand(); return success & 0x40; } // Pollute the namespace, we want as many surprises as possible. No enum class // allowed anywhere. enum megabool { megatrue, megafalse, megamaybe, megaultra }; // std::deque is a valid ultraboolean value. struct ultrabool { template <class T> ultrabool(T &&) { } }; // I don't know. bool operator==(megabool a, megabool b) { if(a == megabool::megamaybe || b == megabool::megamaybe) { return darkurza_bool(); } if(a == b && (a != megabool::megamaybe || a != megabool::megaultra)) { return false; } return a == megabool::megaultra; } // I really don't know. bool operator==(ultrabool a, ultrabool b) { return darkurza_bool(); } #endif
#ifndef WALUDE_ULTRABOOL #define WALUDE_ULTRABOOL #include <random> #include <ctime> volatile bool darkurza_bool() { // Do not try and fix it with any of that mt199937 or sane random seeding // nonsense. Here we adhere to darkurza principles only. std::srand(std::time(0)); return std::rand() & 0x40; } // Pollute the namespace, we want as many surprises as possible. No enum class // allowed anywhere. enum megabool { megatrue, megafalse, megamaybe, megaultra }; // std::deque is a valid ultraboolean value. struct ultrabool { template <class T> ultrabool(T &&) { } }; // I don't know. bool operator==(volatile megabool a, volatile megabool b) { if(a == megabool::megamaybe || b == megabool::megamaybe) { return darkurza_bool(); } if(a == b && (a != megabool::megamaybe || a != megabool::megaultra)) { return false; } return a == megabool::megaultra; } // I really don't know. bool operator==(volatile ultrabool a, volatile ultrabool b) { return darkurza_bool(); } #endif
Make things super stable.
Make things super stable.
C++
mit
Reisen/Walude
96c9e31d97fc7250aafc47fdc73ddd20750d534b
source/Plugins/ExpressionParser/Swift/SwiftExpressionSourceCode.cpp
source/Plugins/ExpressionParser/Swift/SwiftExpressionSourceCode.cpp
//===-- SwiftExpressionSourceCode.cpp --------------------------------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "SwiftExpressionSourceCode.h" #include "Plugins/ExpressionParser/Swift/SwiftASTManipulator.h" #include "lldb/Target/Language.h" #include "lldb/Target/Platform.h" #include "lldb/Target/Target.h" #include "lldb/Utility/StreamString.h" #include "llvm/ADT/StringRef.h" using namespace lldb; using namespace lldb_private; /// Format the OS name the way that Swift availability attributes do. static llvm::StringRef getAvailabilityName(llvm::Triple::OSType os) { switch (os) { case llvm::Triple::MacOSX: return "macOS"; case llvm::Triple::IOS: return "iOS"; case llvm::Triple::TvOS: return "tvOS"; case llvm::Triple::WatchOS: return "watchOS"; default: return llvm::Triple::getOSTypeName(os); } } uint32_t SwiftExpressionSourceCode::GetNumBodyLines() { if (m_num_body_lines == 0) // 2 = <one for zero indexing> + <one for the body start marker> m_num_body_lines = 2 + std::count(m_body.begin(), m_body.end(), '\n'); return m_num_body_lines; } bool SwiftExpressionSourceCode::GetText( std::string &text, lldb::LanguageType wrapping_language, bool needs_object_ptr, bool static_method, bool is_class, bool weak_self, const EvaluateExpressionOptions &options, ExecutionContext &exe_ctx, uint32_t &first_body_line) const { Target *target = exe_ctx.GetTargetPtr(); if (m_wrap) { const char *body = m_body.c_str(); const char *pound_file = options.GetPoundLineFilePath(); const uint32_t pound_line = options.GetPoundLineLine(); StreamString pound_body; if (pound_file && pound_line) { if (wrapping_language == eLanguageTypeSwift) { pound_body.Printf("#sourceLocation(file: \"%s\", line: %u)\n%s", pound_file, pound_line, body); } else { pound_body.Printf("#line %u \"%s\"\n%s", pound_line, pound_file, body); } body = pound_body.GetString().data(); } if (wrapping_language != eLanguageTypeSwift) { return false; } StreamString wrap_stream; // First construct a tagged form of the user expression so we can find it // later: std::string tagged_body; llvm::SmallString<16> buffer; llvm::raw_svector_ostream os_vers(buffer); auto arch_spec = target->GetArchitecture(); auto triple = arch_spec.GetTriple(); if (triple.isOSDarwin()) { if (auto process_sp = exe_ctx.GetProcessSP()) { os_vers << getAvailabilityName(triple.getOS()) << " "; auto platform = target->GetPlatform(); bool is_simulator = platform->GetPluginName().GetStringRef().endswith("-simulator"); if (is_simulator) { // The simulators look like the host OS to Process, but Platform // can the version out of an environment variable. os_vers << platform->GetOSVersion(process_sp.get()).getAsString(); } else { llvm::VersionTuple version = process_sp->GetHostOSVersion(); os_vers << version.getAsString(); } } } SwiftPersistentExpressionState *persistent_state = llvm::cast<SwiftPersistentExpressionState>(target->GetPersistentExpressionStateForLanguage(lldb::eLanguageTypeSwift)); std::vector<swift::ValueDecl *> persistent_results; // Check if we have already declared the playground stub debug functions persistent_state->GetSwiftPersistentDecls(ConstString("__builtin_log_with_id"), {}, persistent_results); size_t num_persistent_results = persistent_results.size(); bool need_to_declare_log_functions = num_persistent_results == 0; EvaluateExpressionOptions localOptions(options); localOptions.SetPreparePlaygroundStubFunctions(need_to_declare_log_functions); SwiftASTManipulator::WrapExpression(wrap_stream, m_body.c_str(), needs_object_ptr, static_method, is_class, weak_self, localOptions, os_vers.str(), first_body_line); text = wrap_stream.GetString(); } else { text.append(m_body); } return true; } bool SwiftExpressionSourceCode::GetOriginalBodyBounds( std::string transformed_text, size_t &start_loc, size_t &end_loc) { const char *start_marker; const char *end_marker; start_marker = SwiftASTManipulator::GetUserCodeStartMarker(); end_marker = SwiftASTManipulator::GetUserCodeEndMarker(); start_loc = transformed_text.find(start_marker); if (start_loc == std::string::npos) return false; start_loc += strlen(start_marker); end_loc = transformed_text.find(end_marker); return end_loc != std::string::npos; return false; }
//===-- SwiftExpressionSourceCode.cpp --------------------------------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "SwiftExpressionSourceCode.h" #include "Plugins/ExpressionParser/Swift/SwiftASTManipulator.h" #include "lldb/Target/Language.h" #include "lldb/Target/Platform.h" #include "lldb/Target/Target.h" #include "lldb/Utility/StreamString.h" #include "llvm/ADT/StringRef.h" using namespace lldb; using namespace lldb_private; /// Format the OS name the way that Swift availability attributes do. static llvm::StringRef getAvailabilityName(const llvm::Triple &triple) { swift::LangOptions lang_options; lang_options.setTarget(triple); return swift::platformString(swift::targetPlatform(lang_options)); } uint32_t SwiftExpressionSourceCode::GetNumBodyLines() { if (m_num_body_lines == 0) // 2 = <one for zero indexing> + <one for the body start marker> m_num_body_lines = 2 + std::count(m_body.begin(), m_body.end(), '\n'); return m_num_body_lines; } bool SwiftExpressionSourceCode::GetText( std::string &text, lldb::LanguageType wrapping_language, bool needs_object_ptr, bool static_method, bool is_class, bool weak_self, const EvaluateExpressionOptions &options, ExecutionContext &exe_ctx, uint32_t &first_body_line) const { Target *target = exe_ctx.GetTargetPtr(); if (m_wrap) { const char *body = m_body.c_str(); const char *pound_file = options.GetPoundLineFilePath(); const uint32_t pound_line = options.GetPoundLineLine(); StreamString pound_body; if (pound_file && pound_line) { if (wrapping_language == eLanguageTypeSwift) { pound_body.Printf("#sourceLocation(file: \"%s\", line: %u)\n%s", pound_file, pound_line, body); } else { pound_body.Printf("#line %u \"%s\"\n%s", pound_line, pound_file, body); } body = pound_body.GetString().data(); } if (wrapping_language != eLanguageTypeSwift) { return false; } StreamString wrap_stream; // First construct a tagged form of the user expression so we can find it // later: std::string tagged_body; llvm::SmallString<16> buffer; llvm::raw_svector_ostream os_vers(buffer); auto arch_spec = target->GetArchitecture(); auto triple = arch_spec.GetTriple(); if (triple.isOSDarwin()) { if (auto process_sp = exe_ctx.GetProcessSP()) { os_vers << getAvailabilityName(triple) << " "; auto platform = target->GetPlatform(); bool is_simulator = platform->GetPluginName().GetStringRef().endswith("-simulator"); if (is_simulator) { // The simulators look like the host OS to Process, but Platform // can the version out of an environment variable. os_vers << platform->GetOSVersion(process_sp.get()).getAsString(); } else { llvm::VersionTuple version = process_sp->GetHostOSVersion(); os_vers << version.getAsString(); } } } SwiftPersistentExpressionState *persistent_state = llvm::cast<SwiftPersistentExpressionState>(target->GetPersistentExpressionStateForLanguage(lldb::eLanguageTypeSwift)); std::vector<swift::ValueDecl *> persistent_results; // Check if we have already declared the playground stub debug functions persistent_state->GetSwiftPersistentDecls(ConstString("__builtin_log_with_id"), {}, persistent_results); size_t num_persistent_results = persistent_results.size(); bool need_to_declare_log_functions = num_persistent_results == 0; EvaluateExpressionOptions localOptions(options); localOptions.SetPreparePlaygroundStubFunctions(need_to_declare_log_functions); SwiftASTManipulator::WrapExpression(wrap_stream, m_body.c_str(), needs_object_ptr, static_method, is_class, weak_self, localOptions, os_vers.str(), first_body_line); text = wrap_stream.GetString(); } else { text.append(m_body); } return true; } bool SwiftExpressionSourceCode::GetOriginalBodyBounds( std::string transformed_text, size_t &start_loc, size_t &end_loc) { const char *start_marker; const char *end_marker; start_marker = SwiftASTManipulator::GetUserCodeStartMarker(); end_marker = SwiftASTManipulator::GetUserCodeEndMarker(); start_loc = transformed_text.find(start_marker); if (start_loc == std::string::npos) return false; start_loc += strlen(start_marker); end_loc = transformed_text.find(end_marker); return end_loc != std::string::npos; return false; }
Move swift-lldb changes from ExpressionSourceCode.cpp to SwiftExpressionSourceCode.cpp (NFC)
Move swift-lldb changes from ExpressionSourceCode.cpp to SwiftExpressionSourceCode.cpp (NFC)
C++
apache-2.0
apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb
f00ecb94211905c063a2707828fab149fd35b615
engine/core/NativeWindow.hpp
engine/core/NativeWindow.hpp
// Ouzel by Elviss Strazdins #ifndef OUZEL_CORE_NATIVEWINDOW_HPP #define OUZEL_CORE_NATIVEWINDOW_HPP #include <mutex> #include <string> #include <queue> #include "../math/Size.hpp" namespace ouzel::core { class NativeWindow { public: class Command final { public: enum class Type { changeSize, changeFullscreen, close, setTitle, bringToFront, show, hide, minimize, maximize, restore }; Command() = default; explicit Command(Type initType) noexcept: type{initType} {} Type type; Size<std::uint32_t, 2> size; bool fullscreen = false; std::string title; }; class Event final { public: enum class Type { sizeChange, resolutionChange, fullscreenChange, screenChange, focusChange, close, show, hide, minimize, maximize, restore }; Event() = default; explicit Event(Type initType) noexcept: type{initType} {} Type type; Size<std::uint32_t, 2> size; union { bool fullscreen = false; std::uint32_t displayId; bool focus; }; }; NativeWindow(const std::function<void(const Event&)>& initCallback, const Size<std::uint32_t, 2>& newSize, bool newResizable, bool newFullscreen, bool newExclusiveFullscreen, const std::string& newTitle, bool newHighDpi); virtual ~NativeWindow() = default; NativeWindow(const NativeWindow&) = delete; NativeWindow& operator=(const NativeWindow&) = delete; NativeWindow(NativeWindow&&) = delete; NativeWindow& operator=(NativeWindow&&) = delete; void addCommand(const Command& command); auto& getSize() const noexcept { return size; } auto& getResolution() const noexcept { return resolution; } auto getContentScale() const noexcept { return contentScale; } auto isResizable() const noexcept { return resizable; } auto isFullscreen() const noexcept { return fullscreen; } auto isExclusiveFullscreen() const noexcept { return exclusiveFullscreen; } auto& getTitle() const noexcept { return title; } protected: virtual void executeCommand(const Command&) {} void sendEvent(const Event& event); Size<std::uint32_t, 2> size; Size<std::uint32_t, 2> resolution; float contentScale = 1.0F; bool resizable = false; bool fullscreen = false; bool exclusiveFullscreen = false; bool highDpi = true; std::string title; private: std::function<void(const Event&)> callback; std::mutex commandQueueMutex; std::queue<Event> commandQueue; }; } #endif // OUZEL_CORE_NATIVEWINDOW_HPP
// Ouzel by Elviss Strazdins #ifndef OUZEL_CORE_NATIVEWINDOW_HPP #define OUZEL_CORE_NATIVEWINDOW_HPP #include <string> #include "../math/Size.hpp" namespace ouzel::core { class NativeWindow { public: class Command final { public: enum class Type { changeSize, changeFullscreen, close, setTitle, bringToFront, show, hide, minimize, maximize, restore }; Command() = default; explicit Command(Type initType) noexcept: type{initType} {} Type type; Size<std::uint32_t, 2> size; bool fullscreen = false; std::string title; }; class Event final { public: enum class Type { sizeChange, resolutionChange, fullscreenChange, screenChange, focusChange, close, show, hide, minimize, maximize, restore }; Event() = default; explicit Event(Type initType) noexcept: type{initType} {} Type type; Size<std::uint32_t, 2> size; union { bool fullscreen = false; std::uint32_t displayId; bool focus; }; }; NativeWindow(const std::function<void(const Event&)>& initCallback, const Size<std::uint32_t, 2>& newSize, bool newResizable, bool newFullscreen, bool newExclusiveFullscreen, const std::string& newTitle, bool newHighDpi); virtual ~NativeWindow() = default; NativeWindow(const NativeWindow&) = delete; NativeWindow& operator=(const NativeWindow&) = delete; NativeWindow(NativeWindow&&) = delete; NativeWindow& operator=(NativeWindow&&) = delete; void addCommand(const Command& command); auto& getSize() const noexcept { return size; } auto& getResolution() const noexcept { return resolution; } auto getContentScale() const noexcept { return contentScale; } auto isResizable() const noexcept { return resizable; } auto isFullscreen() const noexcept { return fullscreen; } auto isExclusiveFullscreen() const noexcept { return exclusiveFullscreen; } auto& getTitle() const noexcept { return title; } protected: virtual void executeCommand(const Command&) {} void sendEvent(const Event& event); Size<std::uint32_t, 2> size; Size<std::uint32_t, 2> resolution; float contentScale = 1.0F; bool resizable = false; bool fullscreen = false; bool exclusiveFullscreen = false; bool highDpi = true; std::string title; private: std::function<void(const Event&)> callback; }; } #endif // OUZEL_CORE_NATIVEWINDOW_HPP
Remove the command queue from NativeWindow
Remove the command queue from NativeWindow
C++
unlicense
elnormous/ouzel,elnormous/ouzel,elnormous/ouzel
6a21c1ad5155e58c8d0f414c13d1a9bc328fae25
fbhackcup/2020/round1/10/10.cpp
fbhackcup/2020/round1/10/10.cpp
/* ======================================== * File Name : 10.cpp * Creation Date : 16-08-2020 * Last Modified : Ne 16. srpna 2020, 14:13:25 * Created By : Karel Ha <[email protected]> * URL : https://www.facebook.com/codingcompetitions/hacker-cup/2020/round-1/problems/A1 * Points Gained (in case of online contest) : ==========================================*/ #include <bits/stdc++.h> using namespace std; #define REP(I,N) FOR(I,0,N) #define FOR(i, begin, end) for (__typeof(end) i = (begin) - ((begin) > (end)); i != (end) - ((begin) > (end)); i += 1 - 2 * ((begin) > (end))) #define ALL(A) (A).begin(), (A).end() #define MSG(a) cout << #a << " == " << (a) << endl; const int CLEAN = -1; template <typename T> string NumberToString ( T Number ) { ostringstream ss; ss << Number; return ss.str(); } #define ERR(args...) { vector<string> _v = split(#args, ','); err(_v.begin(), args); } vector<string> split(const string& s, char c) { vector<string> v; stringstream ss(s); string x; while (getline(ss, x, c)) v.emplace_back(x); return move(v); } void err(vector<string>::iterator it) {} template<typename T, typename... Args> void err(vector<string>::iterator it, T a, Args... args) { cout << it -> substr((*it)[0] == ' ', it -> length()) << " = " << a << endl; err(++it, args...); } int N, K, W; long long AL, BL, CL, DL; long long AH, BH, CH, DH; int get_result(const vector<int> & L, const vector<int> & H) { // REP(k,K) MSG(L[k]); // REP(k,K) MSG(H[k]); int Li, Hi; // streamline via the recurrence deque<int> deqL; deqL.push_back(L[K-2]); deqL.push_back(L[K-1]); deque<int> deqH; deqH.push_back(H[K-2]); deqH.push_back(H[K-1]); REP(i,N) { // cout << endl; MSG(i); if (i < K) { Li = L[i]; Hi = H[i]; } else { Li = (AL * (long long) deqL[0] + BL * (long long) deqL[1] + CL) % DL + 1; deqL.push_back(Li); deqL.pop_front(); Hi = (AH * (long long) deqH[0] + BH * (long long) deqH[1] + CH) % DH + 1; deqH.push_back(Hi); deqH.pop_front(); // MSG(deqL.size()); for (auto & v: deqL) cout << v << " "; cout << endl; // MSG(deqH.size()); for (auto & v: deqH) cout << v << " "; cout << endl; } // MSG(Li); // MSG(Hi); // TODO } int result = -1; // mock result return result; } int main() { int T; cin >> T; // MSG(T); REP(t,T) { cin >> N >> K >> W; // cout << endl; MSG(N); MSG(K); MSG(W); vector<int> L(N); REP(k,K) { cin >> L[k]; } cin >> AL >> BL >> CL >> DL; // MSG(AL); MSG(BL); MSG(CL); MSG(DL); vector<int> H(N); REP(k,K) { cin >> H[k]; } cin >> AH >> BH >> CH >> DH; // MSG(AH); MSG(BH); MSG(CH); MSG(DH); cout << "Case #" << t + 1 << ": " << get_result(L, H) << endl; } return 0; }
/* ======================================== * File Name : 10.cpp * Creation Date : 16-08-2020 * Last Modified : Ne 16. srpna 2020, 14:16:20 * Created By : Karel Ha <[email protected]> * URL : https://www.facebook.com/codingcompetitions/hacker-cup/2020/round-1/problems/A1 * Points Gained (in case of online contest) : ==========================================*/ #include <bits/stdc++.h> using namespace std; #define REP(I,N) FOR(I,0,N) #define FOR(i, begin, end) for (__typeof(end) i = (begin) - ((begin) > (end)); i != (end) - ((begin) > (end)); i += 1 - 2 * ((begin) > (end))) #define ALL(A) (A).begin(), (A).end() #define MSG(a) cout << #a << " == " << (a) << endl; const int CLEAN = -1; template <typename T> string NumberToString ( T Number ) { ostringstream ss; ss << Number; return ss.str(); } #define ERR(args...) { vector<string> _v = split(#args, ','); err(_v.begin(), args); } vector<string> split(const string& s, char c) { vector<string> v; stringstream ss(s); string x; while (getline(ss, x, c)) v.emplace_back(x); return move(v); } void err(vector<string>::iterator it) {} template<typename T, typename... Args> void err(vector<string>::iterator it, T a, Args... args) { cout << it -> substr((*it)[0] == ' ', it -> length()) << " = " << a << endl; err(++it, args...); } typedef pair<int, int> coord; int N, K, W; long long AL, BL, CL, DL; long long AH, BH, CH, DH; int get_result(const vector<int> & L, const vector<int> & H) { // REP(k,K) MSG(L[k]); // REP(k,K) MSG(H[k]); int Li, Hi; deque<coord> deq_pts; // streamline via the recurrence deque<int> deqL; deqL.push_back(L[K-2]); deqL.push_back(L[K-1]); deque<int> deqH; deqH.push_back(H[K-2]); deqH.push_back(H[K-1]); REP(i,N) { // cout << endl; MSG(i); if (i < K) { Li = L[i]; Hi = H[i]; } else { Li = (AL * (long long) deqL[0] + BL * (long long) deqL[1] + CL) % DL + 1; deqL.push_back(Li); deqL.pop_front(); Hi = (AH * (long long) deqH[0] + BH * (long long) deqH[1] + CH) % DH + 1; deqH.push_back(Hi); deqH.pop_front(); // MSG(deqL.size()); for (auto & v: deqL) cout << v << " "; cout << endl; // MSG(deqH.size()); for (auto & v: deqH) cout << v << " "; cout << endl; } // MSG(Li); // MSG(Hi); // TODO } int result = -1; // mock result return result; } int main() { int T; cin >> T; // MSG(T); REP(t,T) { cin >> N >> K >> W; // cout << endl; MSG(N); MSG(K); MSG(W); vector<int> L(N); REP(k,K) { cin >> L[k]; } cin >> AL >> BL >> CL >> DL; // MSG(AL); MSG(BL); MSG(CL); MSG(DL); vector<int> H(N); REP(k,K) { cin >> H[k]; } cin >> AH >> BH >> CH >> DH; // MSG(AH); MSG(BH); MSG(CH); MSG(DH); cout << "Case #" << t + 1 << ": " << get_result(L, H) << endl; } return 0; }
Define coord and deq_pts
Define coord and deq_pts - Fb Hackercup '20 Round 1, 10 Signed-off-by: Karel Ha <[email protected]>
C++
mit
mathemage/CompetitiveProgramming,mathemage/CompetitiveProgramming,mathemage/CompetitiveProgramming,mathemage/CompetitiveProgramming,mathemage/CompetitiveProgramming,mathemage/CompetitiveProgramming
af103f3dd6176b993052d42c2f038e38ae74962f
examples/undocumented/libshogun/classifier_multiclasslibsvm.cpp
examples/undocumented/libshogun/classifier_multiclasslibsvm.cpp
#include <shogun/labels/MulticlassLabels.h> #include <shogun/features/DenseFeatures.h> #include <shogun/kernel/GaussianKernel.h> #include <shogun/multiclass/MulticlassLibSVM.h> #include <shogun/base/init.h> using namespace shogun; void print_message(FILE* target, const char* str) { fprintf(target, "%s", str); } int main(int argc, char** argv) { init_shogun(&print_message); index_t num_vec=3; index_t num_feat=2; index_t num_class=2; // create some data SGMatrix<float64_t> matrix(num_feat, num_vec); SGVector<float64_t>::range_fill_vector(matrix.matrix, num_feat*num_vec); // create vectors // shogun will now own the matrix created CDenseFeatures<float64_t>* features=new CDenseFeatures<float64_t>(matrix); // create three labels CMulticlassLabels* labels=new CMulticlassLabels(num_vec); for (index_t i=0; i<num_vec; ++i) labels->set_label(i, i%num_class); // create gaussian kernel with cache 10MB, width 0.5 CGaussianKernel* kernel = new CGaussianKernel(10, 0.5); kernel->init(features, features); // create libsvm with C=10 and train CMulticlassLibSVM* svm = new CMulticlassLibSVM(10, kernel, labels); svm->train(); // classify on training examples CMulticlassLabels* output=CMulticlassLabels::obtain_from_generic(svm->apply()); SGVector<float64_t>::display_vector(output->get_labels().vector, output->get_num_labels(), "batch output"); /* assert that batch apply and apply(index_t) give same result */ for (index_t i=0; i<output->get_num_labels(); ++i) { float64_t label=svm->apply_one(i); SG_SPRINT("single output[%d]=%f\n", i, label); ASSERT(output->get_label(i)==label); } SG_UNREF(output); // free up memory SG_UNREF(svm); exit_shogun(); return 0; }
#include <shogun/labels/MulticlassLabels.h> #include <shogun/features/DenseFeatures.h> #include <shogun/kernel/GaussianKernel.h> #include <shogun/multiclass/MulticlassLibSVM.h> #include <shogun/base/init.h> using namespace shogun; int main(int argc, char** argv) { init_shogun_with_defaults(); index_t num_vec=3; index_t num_feat=2; index_t num_class=2; // create some data SGMatrix<float64_t> matrix(num_feat, num_vec); SGVector<float64_t>::range_fill_vector(matrix.matrix, num_feat*num_vec); // create vectors // shogun will now own the matrix created CDenseFeatures<float64_t>* features=new CDenseFeatures<float64_t>(matrix); // create three labels CMulticlassLabels* labels=new CMulticlassLabels(num_vec); for (index_t i=0; i<num_vec; ++i) labels->set_label(i, i%num_class); // create gaussian kernel with cache 10MB, width 0.5 CGaussianKernel* kernel = new CGaussianKernel(10, 0.5); kernel->init(features, features); // create libsvm with C=10 and train CMulticlassLibSVM* svm = new CMulticlassLibSVM(10, kernel, labels); svm->train(); // classify on training examples CMulticlassLabels* output=CMulticlassLabels::obtain_from_generic(svm->apply()); SGVector<float64_t>::display_vector(output->get_labels().vector, output->get_num_labels(), "batch output"); /* assert that batch apply and apply(index_t) give same result */ for (index_t i=0; i<output->get_num_labels(); ++i) { float64_t label=svm->apply_one(i); SG_SPRINT("single output[%d]=%f\n", i, label); ASSERT(output->get_label(i)==label); } SG_UNREF(output); // free up memory SG_UNREF(svm); exit_shogun(); return 0; }
simplify example
simplify example
C++
bsd-3-clause
lisitsyn/shogun,shogun-toolbox/shogun,shogun-toolbox/shogun,karlnapf/shogun,karlnapf/shogun,geektoni/shogun,geektoni/shogun,shogun-toolbox/shogun,karlnapf/shogun,geektoni/shogun,geektoni/shogun,lisitsyn/shogun,lambday/shogun,Saurabh7/shogun,besser82/shogun,lisitsyn/shogun,lambday/shogun,Saurabh7/shogun,lambday/shogun,Saurabh7/shogun,Saurabh7/shogun,Saurabh7/shogun,besser82/shogun,sorig/shogun,geektoni/shogun,geektoni/shogun,Saurabh7/shogun,lisitsyn/shogun,shogun-toolbox/shogun,Saurabh7/shogun,besser82/shogun,sorig/shogun,besser82/shogun,lambday/shogun,sorig/shogun,karlnapf/shogun,sorig/shogun,lisitsyn/shogun,shogun-toolbox/shogun,shogun-toolbox/shogun,lisitsyn/shogun,besser82/shogun,besser82/shogun,lambday/shogun,sorig/shogun,Saurabh7/shogun,karlnapf/shogun,sorig/shogun,karlnapf/shogun,lambday/shogun,Saurabh7/shogun
b0b2d8862d2b1efcef3d7e9734fc817c44e34dfd
network/src/EmptyFmu.cpp
network/src/EmptyFmu.cpp
/* * NetworkFmu.cpp * * Created on: 03.06.2016 * Author: hartung */ #include "../include/EmptyFmu.hpp" namespace FMI { EmptyFmu::EmptyFmu(const Initialization::FmuPlan & in) : AbstractFmu(in) { } EmptyFmu::~EmptyFmu() { } AbstractFmu* EmptyFmu::duplicate() { throw std::runtime_error("Network FMUs can't be duplicated."); } void EmptyFmu::stepCompleted() { } FmuEventInfo EmptyFmu::eventUpdate() { return FmuEventInfo(); } double EmptyFmu::getDefaultStart() const { return 0.0; } double EmptyFmu::getDefaultStop() const { return 0.0; } void EmptyFmu::initialize() { } void EmptyFmu::getValuesInternal(vector<real_type>& out, const vector<size_type>& references) const { _values.getValues<real_type>(out,references); } void EmptyFmu::getValuesInternal(vector<int_type>& out, const vector<size_type>& references) const { _values.getValues<int_type>(out,references); } void EmptyFmu::getValuesInternal(vector<bool_type>& out, const vector<size_type>& references) const { _values.getValues<bool_type>(out,references); } void EmptyFmu::getValuesInternal(vector<string_type>& out, const vector<size_type>& references) const { _values.getValues<string_type>(out,references); } void EmptyFmu::setValuesInternal(const vector<real_type>& out, const vector<size_type>& references) { _values.setValues<real_type>(out,references); } void EmptyFmu::setValuesInternal(const vector<int_type>& out, const vector<size_type>& references) { _values.setValues<int_type>(out,references); } void EmptyFmu::setValuesInternal(const vector<bool_type>& out, const vector<size_type>& references) { _values.setValues<bool_type>(out,references); } void EmptyFmu::setValuesInternal(const vector<string_type>& out, const vector<size_type>& references) { _values.setValues<string_type>(out,references); } void EmptyFmu::getStatesInternal(real_type* states) const { } void EmptyFmu::setStatesInternal(const real_type* states) { } void EmptyFmu::getStateDerivativesInternal(real_type* stateDerivatives) { } void EmptyFmu::setNumValues(const size_type& numReals, const size_type& numInts, const size_type& numBools, const size_type& numStrings) { _values = ValueCollection(numReals,numInts,numBools,numStrings); ValueReferenceCollection collection(numReals,numInts,numBools,numStrings); for(size_type i=0;i<collection.getValues<real_type>().size();++i) collection.getValues<real_type>()[i] = i; for(size_type i=0;i<collection.getValues<int_type>().size();++i) collection.getValues<int_type>()[i] = i; for(size_type i=0;i<collection.getValues<bool_type>().size();++i) collection.getValues<bool_type>()[i] = i; for(size_type i=0;i<collection.getValues<string_type>().size();++i) collection.getValues<string_type>()[i] = i; this->_allValueReferences = collection; this->_eventValueReferences = collection; } const ValueCollection & EmptyFmu::getEmptyFmuValues() const { return _values; } void EmptyFmu::getEventIndicatorsInternal(real_type* eventIndicators) { } } /* namespace Network */
/* * NetworkFmu.cpp * * Created on: 03.06.2016 * Author: hartung */ #include "EmptyFmu.hpp" namespace FMI { EmptyFmu::EmptyFmu(const Initialization::FmuPlan & in) : AbstractFmu(in) { } EmptyFmu::~EmptyFmu() { } AbstractFmu* EmptyFmu::duplicate() { throw std::runtime_error("Network FMUs can't be duplicated."); } void EmptyFmu::stepCompleted() { } FmuEventInfo EmptyFmu::eventUpdate() { return FmuEventInfo(); } double EmptyFmu::getDefaultStart() const { return 0.0; } double EmptyFmu::getDefaultStop() const { return 0.0; } void EmptyFmu::initialize() { } void EmptyFmu::getValuesInternal(vector<real_type>& out, const vector<size_type>& references) const { _values.getValues<real_type>(out,references); } void EmptyFmu::getValuesInternal(vector<int_type>& out, const vector<size_type>& references) const { _values.getValues<int_type>(out,references); } void EmptyFmu::getValuesInternal(vector<bool_type>& out, const vector<size_type>& references) const { _values.getValues<bool_type>(out,references); } void EmptyFmu::getValuesInternal(vector<string_type>& out, const vector<size_type>& references) const { _values.getValues<string_type>(out,references); } void EmptyFmu::setValuesInternal(const vector<real_type>& out, const vector<size_type>& references) { _values.setValues<real_type>(out,references); } void EmptyFmu::setValuesInternal(const vector<int_type>& out, const vector<size_type>& references) { _values.setValues<int_type>(out,references); } void EmptyFmu::setValuesInternal(const vector<bool_type>& out, const vector<size_type>& references) { _values.setValues<bool_type>(out,references); } void EmptyFmu::setValuesInternal(const vector<string_type>& out, const vector<size_type>& references) { _values.setValues<string_type>(out,references); } void EmptyFmu::getStatesInternal(real_type* states) const { } void EmptyFmu::setStatesInternal(const real_type* states) { } void EmptyFmu::getStateDerivativesInternal(real_type* stateDerivatives) { } void EmptyFmu::setNumValues(const size_type& numReals, const size_type& numInts, const size_type& numBools, const size_type& numStrings) { _values = ValueCollection(numReals,numInts,numBools,numStrings); ValueReferenceCollection collection(numReals,numInts,numBools,numStrings); for(size_type i=0;i<collection.getValues<real_type>().size();++i) collection.getValues<real_type>()[i] = i; for(size_type i=0;i<collection.getValues<int_type>().size();++i) collection.getValues<int_type>()[i] = i; for(size_type i=0;i<collection.getValues<bool_type>().size();++i) collection.getValues<bool_type>()[i] = i; for(size_type i=0;i<collection.getValues<string_type>().size();++i) collection.getValues<string_type>()[i] = i; this->_allValueReferences = collection; this->_eventValueReferences = collection; } const ValueCollection & EmptyFmu::getEmptyFmuValues() const { return _values; } void EmptyFmu::getEventIndicatorsInternal(real_type* eventIndicators) { } } /* namespace Network */
Fix include
Fix include
C++
bsd-3-clause
marchartung/ParallelFMU
9cf1d007a7de1e743b596456be74ad289272e6af
include/abaclade/collections/detail/type_void_adapter.hxx
include/abaclade/collections/detail/type_void_adapter.hxx
/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*- Copyright 2010, 2011, 2012, 2013, 2014, 2015 Raffaello D. Di Napoli This file is part of Abaclade. Abaclade 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 3 of the License, or (at your option) any later version. Abaclade 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 Abaclade. If not, see <http://www.gnu.org/licenses/>. --------------------------------------------------------------------------------------------------*/ #ifndef _ABACLADE_HXX_INTERNAL #error "Please #include <abaclade.hxx> instead of this file" #endif //////////////////////////////////////////////////////////////////////////////////////////////////// // abc::collections::detail::type_void_adapter namespace abc { namespace collections { namespace detail { /*! DOC:3395 Move constructors and exceptions In this section, “move constructor” will strictly refer to class::class(class &&). All classes must provide move constructors and assignment operators if the copy constructor would result in execution of exception-prone code (e.g. resource allocation). Because move constructors are employed widely in container classes that need to provide strong exception guarantee (fully transacted operation) even in case of moves, move constructors must not throw exceptions. This requirement is relaxed for moves that involve two different classes, since these will not be used by container classes. */ //! Encapsulates raw constructors, destructors and assignment operators for a type. struct type_void_adapter { public: /*! Prototype of a function that copies items from one array to another. @param pDstBegin Pointer to the start of the destination array. The items are supposed to be uninitialized. @param pSrcBegin Pointer to the first item to copy. @param pSrcEnd Pointer to beyond the last item to copy. */ typedef void (* copy_fn)(void * pDstBegin, void const * pSrcBegin, void const * pSrcEnd); /*! Prototype of a function that destructs a range of items in an array. @param pBegin Pointer to the first item to destruct. @param pEnd Pointer to beyond the last item to destruct. */ typedef void (* destr_fn)(void const * pBegin, void const * pEnd); /*! Prototype of a function that compares two values for equality. @param pComparator Pointer to an object able to compare the two values. @param p1 Pointer to the first item. @param p2 Pointer to the second item. @return true if the items are equal, or false otherwise. */ typedef bool (* equal_fn)(void const * pComparator, void const * p1, void const * p2); /*! Prototype of a function that moves items from one array to another. @param pDstBegin Pointer to the start of the destination array. The items are supposed to be uninitialized. @param pSrcBegin Pointer to the first item to move. @param pSrcEnd Pointer to beyond the last item to move. */ typedef void (* move_fn)(void * pDstBegin, void * pSrcBegin, void * pSrcEnd); public: //! Size of a variable of this type, in bytes. std::size_t cb; //! Function to copy items from one array to another. copy_fn copy_constr; //! Function to destruct items in an array. destr_fn destruct; //! Function to compare two items for equality. equal_fn equal; //! Function to move items from one array to another. move_fn move_constr; public: //! Constructor. type_void_adapter() : cb(0), copy_constr(nullptr), destruct(nullptr), equal(nullptr), move_constr(nullptr) { } //! Initializes this->copy_constr. template <typename T> void set_copy_fn() { copy_constr = reinterpret_cast<copy_fn>(_typed_copy_constr<typename std::remove_cv<T>::type>); #if ABC_HOST_CXX_GCC && ABC_HOST_CXX_GCC < 40700 // Force instantiating the template, even if (obviously) never executed. if (!copy_constr) { _typed_copy_constr<typename std::remove_cv<T>::type>(nullptr, nullptr, nullptr); } #endif } //! Initializes this->destruct. template <typename T> void set_destr_fn() { destruct = reinterpret_cast<destr_fn>(_typed_destruct<typename std::remove_cv<T>::type>); #if ABC_HOST_CXX_GCC && ABC_HOST_CXX_GCC < 40700 // Force instantiating the template, even if (obviously) never executed. if (!destruct) { _typed_destruct<typename std::remove_cv<T>::type>(nullptr, nullptr); } #endif } //! Initializes this->equal. template <typename T> void set_equal_fn() { equal = reinterpret_cast<equal_fn>(_typed_equal<typename std::remove_cv<T>::type>); #if ABC_HOST_CXX_GCC && ABC_HOST_CXX_GCC < 40700 // Force instantiating the template, even if (obviously) never executed. if (!equal) { _typed_equal<typename std::remove_cv<T>::type>(nullptr, nullptr, nullptr); } #endif } //! Initializes this->move_constr. template <typename T> void set_move_fn() { move_constr = reinterpret_cast<move_fn>(_typed_move_constr<typename std::remove_cv<T>::type>); #if ABC_HOST_CXX_GCC && ABC_HOST_CXX_GCC < 40700 // Force instantiating the template, even if (obviously) never executed. if (!move_constr) { _typed_move_constr<typename std::remove_cv<T>::type>(nullptr, nullptr, nullptr); } #endif } //! Initializes this->cb. template <typename T> void set_size() { cb = sizeof(T); } private: /*! Copies a range of items from one array to another, overwriting any existing contents in the destination. @param ptDstBegin Pointer to the start of the destination array. The items are supposed to be uninitialized. @param ptSrcBegin Pointer to the first item to copy. @param ptSrcEnd Pointer to beyond the last item to copy. */ #if ABC_HOST_CXX_MSC /* MSC applies SFINAE too late, and when asked to get the address of the *one and only* valid version of _typed_copy_constr() (see non-MSC code in the #else branch), it will raise an error saying it doesn’t know which one to choose. */ template <typename T> static void _typed_copy_constr(T * ptDstBegin, T const * ptSrcBegin, T const * ptSrcEnd) { if (std::has_trivial_copy_constructor<T>::value) { // No constructor, fastest copy possible. memory::copy(ptDstBegin, ptSrcBegin, static_cast<std::size_t>(ptSrcEnd - ptSrcBegin)); } else { /* Assume that since it’s not trivial, it can throw exceptions, so perform a transactional copy. */ T * ptDst = ptDstBegin; try { for (T const * ptSrc = ptSrcBegin; ptSrc < ptSrcEnd; ++ptSrc, ++ptDst) { ::new(ptDst) T(*ptSrc); } } catch (...) { // Undo (destruct) all the copies instantiated. while (--ptDst >= ptDstBegin) { ptDst->~T(); } throw; } } } #else //if ABC_HOST_CXX_MSC // Only enabled if the copy constructor is trivial. template <typename T> static void _typed_copy_constr( typename std::enable_if< #ifdef ABC_CXX_STL_CXX11_TYPE_TRAITS std::is_trivially_copy_constructible<T>::value, #else std::has_trivial_copy_constructor<T>::value, #endif T *>::type ptDstBegin, T const * ptSrcBegin, T const * ptSrcEnd ) { // No constructor, fastest copy possible. memory::copy(ptDstBegin, ptSrcBegin, static_cast<std::size_t>(ptSrcEnd - ptSrcBegin)); } // Only enabled if the copy constructor is not trivial. template <typename T> static void _typed_copy_constr( typename std::enable_if< #ifdef ABC_CXX_STL_CXX11_TYPE_TRAITS !std::is_trivially_copy_constructible<T>::value, #else !std::has_trivial_copy_constructor<T>::value, #endif T * >::type ptDstBegin, T const * ptSrcBegin, T const * ptSrcEnd ) { /* Assume that since it’s not trivial, it can throw exceptions, so perform a transactional copy. */ T * ptDst = ptDstBegin; try { for (T const * ptSrc = ptSrcBegin; ptSrc < ptSrcEnd; ++ptSrc, ++ptDst) { ::new(ptDst) T(*ptSrc); } } catch (...) { // Undo (destruct) all the copies instantiated. while (--ptDst >= ptDstBegin) { ptDst->~T(); } throw; } } #endif //if ABC_HOST_CXX_MSC … else /*! Destructs a range of items in an array. @param ptBegin Pointer to the first item to destruct. @param ptEnd Pointer to beyond the last item to destruct. */ template <typename T> static void _typed_destruct(T const * ptBegin, T const * ptEnd) { #if defined(ABC_CXX_STL_CXX11_TYPE_TRAITS) || defined(ABC_CXX_STL_CXX11_GLIBCXX_PARTIAL_TYPE_TRAITS) if (!std::is_trivially_destructible<T>::value) { #else if (!std::has_trivial_destructor<T>::value) { #endif // The destructor is not a no-op. for (T const * pt = ptBegin; pt < ptEnd; ++pt) { pt->~T(); } } } /*! Compares two values for equality. @param pcomparator Pointer to an object able to compare the two values. @param pt1 Pointer to the first item. @param pt2 Pointer to the second item. @return true if the items are equal, or false otherwise. */ template <typename TComparator, typename T> static bool _typed_equal(TComparator const * pcomparator, T const * pt1, T const * pt2) { return pcomparator->_compare(*pt1, *pt2); } /*! Moves a range of items from one array to another, overwriting any existing contents in the destination. @param ptDstBegin Pointer to the start of the destination array. The items are supposed to be uninitialized. @param ptSrcBegin Pointer to the first item to copy. @param ptSrcEnd Pointer to beyond the last item to copy. */ template <typename T> static void _typed_move_constr(T * ptDstBegin, T * ptSrcBegin, T * ptSrcEnd) { for (T * ptSrc = ptSrcBegin, * ptDst = ptDstBegin; ptSrc < ptSrcEnd; ++ptSrc, ++ptDst) { ::new(ptDst) T(std::move(*ptSrc)); } } }; } //namespace detail } //namespace collections } //namespace abc ////////////////////////////////////////////////////////////////////////////////////////////////////
/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*- Copyright 2010, 2011, 2012, 2013, 2014, 2015 Raffaello D. Di Napoli This file is part of Abaclade. Abaclade 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 3 of the License, or (at your option) any later version. Abaclade 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 Abaclade. If not, see <http://www.gnu.org/licenses/>. --------------------------------------------------------------------------------------------------*/ #ifndef _ABACLADE_HXX_INTERNAL #error "Please #include <abaclade.hxx> instead of this file" #endif //////////////////////////////////////////////////////////////////////////////////////////////////// // abc::collections::detail::type_void_adapter namespace abc { namespace collections { namespace detail { /*! DOC:3395 Move constructors and exceptions In this section, “move constructor” will strictly refer to class::class(class &&). All classes must provide move constructors and assignment operators if the copy constructor would result in execution of exception-prone code (e.g. resource allocation). Because move constructors are employed widely in container classes that need to provide strong exception guarantee (fully transacted operation) even in case of moves, move constructors must not throw exceptions. This requirement is relaxed for moves that involve two different classes, since these will not be used by container classes. */ //! Encapsulates raw constructors, destructors and assignment operators for a type. struct type_void_adapter { public: /*! Prototype of a function that copies items from one array to another. @param pDstBegin Pointer to the start of the destination array. The items are supposed to be uninitialized. @param pSrcBegin Pointer to the first item to copy. @param pSrcEnd Pointer to beyond the last item to copy. */ typedef void (* copy_fn)(void * pDstBegin, void const * pSrcBegin, void const * pSrcEnd); /*! Prototype of a function that destructs a range of items in an array. @param pBegin Pointer to the first item to destruct. @param pEnd Pointer to beyond the last item to destruct. */ typedef void (* destr_fn)(void const * pBegin, void const * pEnd); /*! Prototype of a function that moves items from one array to another. @param pDstBegin Pointer to the start of the destination array. The items are supposed to be uninitialized. @param pSrcBegin Pointer to the first item to move. @param pSrcEnd Pointer to beyond the last item to move. */ typedef void (* move_fn)(void * pDstBegin, void * pSrcBegin, void * pSrcEnd); public: //! Size of a variable of this type, in bytes. std::size_t cb; //! Function to copy items from one array to another. copy_fn copy_constr; //! Function to destruct items in an array. destr_fn destruct; //! Function to move items from one array to another. move_fn move_constr; public: //! Constructor. type_void_adapter() : cb(0), copy_constr(nullptr), destruct(nullptr), move_constr(nullptr) { } //! Initializes this->copy_constr. template <typename T> void set_copy_fn() { copy_constr = reinterpret_cast<copy_fn>(_typed_copy_constr<typename std::remove_cv<T>::type>); #if ABC_HOST_CXX_GCC && ABC_HOST_CXX_GCC < 40700 // Force instantiating the template, even if (obviously) never executed. if (!copy_constr) { _typed_copy_constr<typename std::remove_cv<T>::type>(nullptr, nullptr, nullptr); } #endif } //! Initializes this->destruct. template <typename T> void set_destr_fn() { destruct = reinterpret_cast<destr_fn>(_typed_destruct<typename std::remove_cv<T>::type>); #if ABC_HOST_CXX_GCC && ABC_HOST_CXX_GCC < 40700 // Force instantiating the template, even if (obviously) never executed. if (!destruct) { _typed_destruct<typename std::remove_cv<T>::type>(nullptr, nullptr); } #endif } //! Initializes this->move_constr. template <typename T> void set_move_fn() { move_constr = reinterpret_cast<move_fn>(_typed_move_constr<typename std::remove_cv<T>::type>); #if ABC_HOST_CXX_GCC && ABC_HOST_CXX_GCC < 40700 // Force instantiating the template, even if (obviously) never executed. if (!move_constr) { _typed_move_constr<typename std::remove_cv<T>::type>(nullptr, nullptr, nullptr); } #endif } //! Initializes this->cb. template <typename T> void set_size() { cb = sizeof(T); } private: /*! Copies a range of items from one array to another, overwriting any existing contents in the destination. @param ptDstBegin Pointer to the start of the destination array. The items are supposed to be uninitialized. @param ptSrcBegin Pointer to the first item to copy. @param ptSrcEnd Pointer to beyond the last item to copy. */ #if ABC_HOST_CXX_MSC /* MSC applies SFINAE too late, and when asked to get the address of the *one and only* valid version of _typed_copy_constr() (see non-MSC code in the #else branch), it will raise an error saying it doesn’t know which one to choose. */ template <typename T> static void _typed_copy_constr(T * ptDstBegin, T const * ptSrcBegin, T const * ptSrcEnd) { if (std::has_trivial_copy_constructor<T>::value) { // No constructor, fastest copy possible. memory::copy(ptDstBegin, ptSrcBegin, static_cast<std::size_t>(ptSrcEnd - ptSrcBegin)); } else { /* Assume that since it’s not trivial, it can throw exceptions, so perform a transactional copy. */ T * ptDst = ptDstBegin; try { for (T const * ptSrc = ptSrcBegin; ptSrc < ptSrcEnd; ++ptSrc, ++ptDst) { ::new(ptDst) T(*ptSrc); } } catch (...) { // Undo (destruct) all the copies instantiated. while (--ptDst >= ptDstBegin) { ptDst->~T(); } throw; } } } #else //if ABC_HOST_CXX_MSC // Only enabled if the copy constructor is trivial. template <typename T> static void _typed_copy_constr( typename std::enable_if< #ifdef ABC_CXX_STL_CXX11_TYPE_TRAITS std::is_trivially_copy_constructible<T>::value, #else std::has_trivial_copy_constructor<T>::value, #endif T *>::type ptDstBegin, T const * ptSrcBegin, T const * ptSrcEnd ) { // No constructor, fastest copy possible. memory::copy(ptDstBegin, ptSrcBegin, static_cast<std::size_t>(ptSrcEnd - ptSrcBegin)); } // Only enabled if the copy constructor is not trivial. template <typename T> static void _typed_copy_constr( typename std::enable_if< #ifdef ABC_CXX_STL_CXX11_TYPE_TRAITS !std::is_trivially_copy_constructible<T>::value, #else !std::has_trivial_copy_constructor<T>::value, #endif T * >::type ptDstBegin, T const * ptSrcBegin, T const * ptSrcEnd ) { /* Assume that since it’s not trivial, it can throw exceptions, so perform a transactional copy. */ T * ptDst = ptDstBegin; try { for (T const * ptSrc = ptSrcBegin; ptSrc < ptSrcEnd; ++ptSrc, ++ptDst) { ::new(ptDst) T(*ptSrc); } } catch (...) { // Undo (destruct) all the copies instantiated. while (--ptDst >= ptDstBegin) { ptDst->~T(); } throw; } } #endif //if ABC_HOST_CXX_MSC … else /*! Destructs a range of items in an array. @param ptBegin Pointer to the first item to destruct. @param ptEnd Pointer to beyond the last item to destruct. */ template <typename T> static void _typed_destruct(T const * ptBegin, T const * ptEnd) { #if defined(ABC_CXX_STL_CXX11_TYPE_TRAITS) || defined(ABC_CXX_STL_CXX11_GLIBCXX_PARTIAL_TYPE_TRAITS) if (!std::is_trivially_destructible<T>::value) { #else if (!std::has_trivial_destructor<T>::value) { #endif // The destructor is not a no-op. for (T const * pt = ptBegin; pt < ptEnd; ++pt) { pt->~T(); } } } /*! Moves a range of items from one array to another, overwriting any existing contents in the destination. @param ptDstBegin Pointer to the start of the destination array. The items are supposed to be uninitialized. @param ptSrcBegin Pointer to the first item to copy. @param ptSrcEnd Pointer to beyond the last item to copy. */ template <typename T> static void _typed_move_constr(T * ptDstBegin, T * ptSrcBegin, T * ptSrcEnd) { for (T * ptSrc = ptSrcBegin, * ptDst = ptDstBegin; ptSrc < ptSrcEnd; ++ptSrc, ++ptDst) { ::new(ptDst) T(std::move(*ptSrc)); } } }; } //namespace detail } //namespace collections } //namespace abc ////////////////////////////////////////////////////////////////////////////////////////////////////
Remove unusable type_void_adapter::equal and related code
Remove unusable type_void_adapter::equal and related code Equality comparison is typically provided by a functor that only the most derived class of a container, being a template, has access to, and as a member method, not a static function. This means that either type_void_adapter be changed to store a this pointer, or that two function calls be used (tva.equal -> static wrapper -> operator() ). A better alternative is to follow the pattern used by map/map_impl, which involves only the static wrapper for operator().
C++
lgpl-2.1
raffaellod/lofty,raffaellod/lofty
63d58f84532d86b71da2f8d4b040f84ae0e247cc
include/alpaka/block/shared/st/BlockSharedMemStMember.hpp
include/alpaka/block/shared/st/BlockSharedMemStMember.hpp
/* Copyright 2020 Jeffrey Kelling * * This file is part of alpaka. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #pragma once #include <alpaka/block/shared/st/Traits.hpp> #include <alpaka/core/Assert.hpp> #include <alpaka/core/Vectorize.hpp> #include <type_traits> #include <cstdint> #include <algorithm> namespace alpaka { namespace block { namespace shared { namespace st { namespace detail { //############################################################################# //! Implementation of static block shared memory provider. template<unsigned int TDataAlignBytes = core::vectorization::defaultAlignment> class BlockSharedMemStMemberImpl { public: //----------------------------------------------------------------------------- #ifndef NDEBUG BlockSharedMemStMemberImpl(uint8_t* mem, unsigned int capacity) : m_mem(mem), m_capacity(capacity) { #ifdef ALPAKA_DEBUG_OFFLOAD_ASSUME_HOST ALPAKA_ASSERT( ( m_mem == nullptr ) == ( m_capacity == 0u ) ); #endif } #else BlockSharedMemStMemberImpl(uint8_t* mem, unsigned int) : m_mem(mem) {} #endif //----------------------------------------------------------------------------- BlockSharedMemStMemberImpl(BlockSharedMemStMemberImpl const &) = delete; //----------------------------------------------------------------------------- BlockSharedMemStMemberImpl(BlockSharedMemStMemberImpl &&) = delete; //----------------------------------------------------------------------------- auto operator=(BlockSharedMemStMemberImpl const &) -> BlockSharedMemStMemberImpl & = delete; //----------------------------------------------------------------------------- auto operator=(BlockSharedMemStMemberImpl &&) -> BlockSharedMemStMemberImpl & = delete; //----------------------------------------------------------------------------- /*virtual*/ ~BlockSharedMemStMemberImpl() = default; template <typename T> void alloc() const { m_allocdBytes = allocPitch<T>(); uint8_t* buf = &m_mem[m_allocdBytes]; new (buf) T(); m_allocdBytes += sizeof(T); #if (defined ALPAKA_DEBUG_OFFLOAD_ASSUME_HOST) && (! defined NDEBUG) ALPAKA_ASSERT(m_allocdBytes <= m_capacity); #endif } #if BOOST_COMP_GNUC #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wcast-align" // "cast from 'unsigned char*' to 'unsigned int*' increases required alignment of target type" #endif template <typename T> T& getLatestVar() const { return *reinterpret_cast<T*>(&m_mem[m_allocdBytes-sizeof(T)]); } #if BOOST_COMP_GNUC #pragma GCC diagnostic pop #endif void free() const { m_allocdBytes = 0u; } private: mutable unsigned int m_allocdBytes = 0; mutable uint8_t* m_mem; #ifndef NDEBUG const unsigned int m_capacity; #endif template<typename T> unsigned int allocPitch() const { static_assert( core::vectorization::defaultAlignment >= alignof(T), "Unable to get block shared static memory for types with alignment higher than defaultAlignment!"); constexpr unsigned int align = std::max(TDataAlignBytes, static_cast<unsigned int>(alignof(T))); return (m_allocdBytes/align + (m_allocdBytes%align>0))*align; } }; } //############################################################################# //! Static block shared memory provider using a pointer to //! externally allocated fixed-size memory, likely provided by //! BlockSharedMemDynMember. template<unsigned int TDataAlignBytes = core::vectorization::defaultAlignment> class BlockSharedMemStMember : public detail::BlockSharedMemStMemberImpl<TDataAlignBytes>, public concepts::Implements<ConceptBlockSharedSt, BlockSharedMemStMember<TDataAlignBytes>> { public: using detail::BlockSharedMemStMemberImpl<TDataAlignBytes>::BlockSharedMemStMemberImpl; }; namespace traits { //############################################################################# template< typename T, unsigned int TDataAlignBytes, std::size_t TuniqueId> struct AllocVar< T, TuniqueId, BlockSharedMemStMember<TDataAlignBytes>> { //----------------------------------------------------------------------------- static auto allocVar( block::shared::st::BlockSharedMemStMember<TDataAlignBytes> const &smem) -> T & { smem.template alloc<T>(); return smem.template getLatestVar<T>(); } }; //############################################################################# template< unsigned int TDataAlignBytes> struct FreeMem< BlockSharedMemStMember<TDataAlignBytes>> { //----------------------------------------------------------------------------- static auto freeMem( block::shared::st::BlockSharedMemStMember<TDataAlignBytes> const &mem) -> void { mem.free(); } }; } } } } }
/* Copyright 2020 Jeffrey Kelling * * This file is part of alpaka. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #pragma once #include <alpaka/block/shared/st/Traits.hpp> #include <alpaka/core/Assert.hpp> #include <alpaka/core/Vectorize.hpp> #include <type_traits> #include <cstdint> #include <algorithm> namespace alpaka { namespace block { namespace shared { namespace st { namespace detail { //############################################################################# //! Implementation of static block shared memory provider. template<unsigned int TDataAlignBytes = core::vectorization::defaultAlignment> class BlockSharedMemStMemberImpl { public: //----------------------------------------------------------------------------- #ifndef NDEBUG BlockSharedMemStMemberImpl(uint8_t* mem, unsigned int capacity) : m_mem(mem), m_capacity(capacity) { #ifdef ALPAKA_DEBUG_OFFLOAD_ASSUME_HOST ALPAKA_ASSERT( ( m_mem == nullptr ) == ( m_capacity == 0u ) ); #endif } #else BlockSharedMemStMemberImpl(uint8_t* mem, unsigned int) : m_mem(mem) {} #endif //----------------------------------------------------------------------------- BlockSharedMemStMemberImpl(BlockSharedMemStMemberImpl const &) = delete; //----------------------------------------------------------------------------- BlockSharedMemStMemberImpl(BlockSharedMemStMemberImpl &&) = delete; //----------------------------------------------------------------------------- auto operator=(BlockSharedMemStMemberImpl const &) -> BlockSharedMemStMemberImpl & = delete; //----------------------------------------------------------------------------- auto operator=(BlockSharedMemStMemberImpl &&) -> BlockSharedMemStMemberImpl & = delete; //----------------------------------------------------------------------------- /*virtual*/ ~BlockSharedMemStMemberImpl() = default; template <typename T> void alloc() const { m_allocdBytes = allocPitch<T>(); m_allocdBytes += sizeof(T); #if (defined ALPAKA_DEBUG_OFFLOAD_ASSUME_HOST) && (! defined NDEBUG) ALPAKA_ASSERT(m_allocdBytes <= m_capacity); #endif } #if BOOST_COMP_GNUC #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wcast-align" // "cast from 'unsigned char*' to 'unsigned int*' increases required alignment of target type" #endif template <typename T> T& getLatestVar() const { return *reinterpret_cast<T*>(&m_mem[m_allocdBytes-sizeof(T)]); } #if BOOST_COMP_GNUC #pragma GCC diagnostic pop #endif void free() const { m_allocdBytes = 0u; } private: mutable unsigned int m_allocdBytes = 0; mutable uint8_t* m_mem; #ifndef NDEBUG const unsigned int m_capacity; #endif template<typename T> unsigned int allocPitch() const { static_assert( core::vectorization::defaultAlignment >= alignof(T), "Unable to get block shared static memory for types with alignment higher than defaultAlignment!"); constexpr unsigned int align = std::max(TDataAlignBytes, static_cast<unsigned int>(alignof(T))); return (m_allocdBytes/align + (m_allocdBytes%align>0))*align; } }; } //############################################################################# //! Static block shared memory provider using a pointer to //! externally allocated fixed-size memory, likely provided by //! BlockSharedMemDynMember. template<unsigned int TDataAlignBytes = core::vectorization::defaultAlignment> class BlockSharedMemStMember : public detail::BlockSharedMemStMemberImpl<TDataAlignBytes>, public concepts::Implements<ConceptBlockSharedSt, BlockSharedMemStMember<TDataAlignBytes>> { public: using detail::BlockSharedMemStMemberImpl<TDataAlignBytes>::BlockSharedMemStMemberImpl; }; namespace traits { //############################################################################# template< typename T, unsigned int TDataAlignBytes, std::size_t TuniqueId> struct AllocVar< T, TuniqueId, BlockSharedMemStMember<TDataAlignBytes>> { //----------------------------------------------------------------------------- static auto allocVar( block::shared::st::BlockSharedMemStMember<TDataAlignBytes> const &smem) -> T & { smem.template alloc<T>(); return smem.template getLatestVar<T>(); } }; //############################################################################# template< unsigned int TDataAlignBytes> struct FreeMem< BlockSharedMemStMember<TDataAlignBytes>> { //----------------------------------------------------------------------------- static auto freeMem( block::shared::st::BlockSharedMemStMember<TDataAlignBytes> const &mem) -> void { mem.free(); } }; } } } } }
Remove placement new call from BlockSharedMemStMemberImpl
Remove placement new call from BlockSharedMemStMemberImpl As discussed in #1128, this is not consistent with other implementations of shared memory As a side product, when out of memory this allows the debug assert to shoot before the segfault happens Co-authored-by: Jeffrey Kelling <[email protected]>
C++
mpl-2.0
BenjaminW3/alpaka,BenjaminW3/alpaka
d73afda478960c72d01ec8875c88cfab6f3bb112
src/master/gru.cc
src/master/gru.cc
#include "gru.h" #include <sstream> #include <gflags/gflags.h> #include <boost/algorithm/string.hpp> #include <vector> #include "logging.h" DECLARE_int32(galaxy_deploy_step); DECLARE_string(minion_path); DECLARE_string(nexus_server_list); DECLARE_string(nexus_root_path); DECLARE_string(master_path); DECLARE_bool(enable_cpu_soft_limit); DECLARE_bool(enable_memory_soft_limit); DECLARE_string(galaxy_node_label); DECLARE_string(galaxy_user); DECLARE_string(galaxy_token); DECLARE_string(galaxy_pool); DECLARE_int32(max_minions_per_host); namespace baidu { namespace shuttle { static const int64_t default_additional_map_memory = 1024l * 1024 * 1024; static const int64_t default_additional_reduce_memory = 2048l * 1024 * 1024; static const int default_map_additional_millicores = 0; static const int default_reduce_additional_millicores = 500; int Gru::additional_map_millicores = default_map_additional_millicores; int Gru::additional_reduce_millicores = default_reduce_additional_millicores; int64_t Gru::additional_map_memory = default_additional_map_memory; int64_t Gru::additional_reduce_memory = default_additional_reduce_memory; Gru::Gru(::baidu::galaxy::sdk::AppMaster* galaxy, JobDescriptor* job, const std::string& job_id, WorkMode mode) : galaxy_(galaxy), job_(job), job_id_(job_id), mode_(mode) { mode_str_ = ((mode == kReduce) ? "reduce" : "map"); minion_name_ = job->name() + "_" + mode_str_; } Status Gru::Start() { ::baidu::galaxy::sdk::SubmitJobRequest galaxy_job; galaxy_job.user.user = FLAGS_galaxy_user; galaxy_job.user.token = FLAGS_galaxy_token; galaxy_job.job.deploy.pools.push_back(FLAGS_galaxy_pool); galaxy_job.job.name = minion_name_ + "@minion";; galaxy_job.job.type = ::baidu::galaxy::sdk::kJobBatch; galaxy_job.job.deploy.replica = (mode_ == kReduce) ? job_->reduce_capacity() : job_->map_capacity(); galaxy_job.job.deploy.step = FLAGS_galaxy_deploy_step; galaxy_job.job.deploy.interval = 1; galaxy_job.job.deploy.max_per_host = FLAGS_max_minions_per_host; galaxy_job.job.version = "1.0.0"; galaxy_job.job.run_user = "galaxy"; if (!FLAGS_galaxy_node_label.empty()) { galaxy_job.job.deploy.tag = FLAGS_galaxy_node_label; } ::baidu::galaxy::sdk::PodDescription & pod_desc = galaxy_job.job.pod; pod_desc.workspace_volum.size = (3L << 30); pod_desc.workspace_volum.medium = ::baidu::galaxy::sdk::kDisk; pod_desc.workspace_volum.exclusive = false; pod_desc.workspace_volum.readonly = false; pod_desc.workspace_volum.use_symlink = false; pod_desc.workspace_volum.dest_path = "/home/shuttle"; ::baidu::galaxy::sdk::TaskDescription task_desc; if (mode_str_ == "map") { task_desc.cpu.milli_core = job_->millicores() + additional_map_millicores; } else { task_desc.cpu.milli_core = job_->millicores() + additional_reduce_millicores; } task_desc.memory.size = job_->memory() + ((mode_ == kReduce) ? additional_reduce_memory : additional_map_memory); std::string app_package; std::vector<std::string> cache_archive_list; int file_size = job_->files().size(); for (int i = 0; i < file_size; ++i) { const std::string& file = job_->files(i); if (boost::starts_with(file, "hdfs://")) { cache_archive_list.push_back(file); } else { app_package = file; } } std::stringstream ss; if (!job_->input_dfs().user().empty()) { ss << "hadoop_job_ugi=" << job_->input_dfs().user() << "," << job_->input_dfs().password() << " fs_default_name=hdfs://" << job_->input_dfs().host() << ":" << job_->input_dfs().port() << " "; } for (size_t i = 0; i < cache_archive_list.size(); i++) { ss << "cache_archive_" << i << "=" << cache_archive_list[i] << " "; } ss << "app_package=" << app_package << " ./minion_boot.sh -jobid=" << job_id_ << " -nexus_addr=" << FLAGS_nexus_server_list << " -master_nexus_path=" << FLAGS_nexus_root_path + FLAGS_master_path << " -work_mode=" << ((mode_ == kMapOnly) ? "map-only" : mode_str_); std::stringstream ss_stop; ss_stop << "source hdfs_env.sh; ./minion -jobid=" << job_id_ << " -nexus_addr=" << FLAGS_nexus_server_list << " -master_nexus_path=" << FLAGS_nexus_root_path + FLAGS_master_path << " -work_mode=" << ((mode_ == kMapOnly) ? "map-only" : mode_str_) << " -kill_task"; task_desc.exe_package.package.source_path = FLAGS_minion_path; task_desc.exe_package.package.dest_path = "."; task_desc.exe_package.start_cmd = ss.str().c_str(); task_desc.exe_package.stop_cmd = ss_stop.str().c_str(); task_desc.tcp_throt.recv_bps_quota = (50L << 20); task_desc.tcp_throt.send_bps_quota = (50L << 20); ::baidu::galaxy::sdk::PortRequired port_req; port_req.port = "dynamic"; port_req.port_name = "NFS_CLIENT_PORT"; task_desc.ports.push_back(port_req); port_req.port = "dynamic"; port_req.port_name = "MINION_PORT"; task_desc.ports.push_back(port_req); if (FLAGS_enable_cpu_soft_limit) { task_desc.cpu.excess = true; } else { task_desc.cpu.excess = false; } if (FLAGS_enable_memory_soft_limit) { task_desc.memory.excess = true; } else { task_desc.memory.excess = false; } pod_desc.tasks.push_back(task_desc); std::string minion_id; ::baidu::galaxy::sdk::SubmitJobResponse rsps; if (galaxy_->SubmitJob(galaxy_job, &rsps)) { minion_id = rsps.jobid; LOG(INFO, "galaxy job id: %s", minion_id.c_str()); minion_id_ = minion_id; galaxy_job_ = galaxy_job; if (minion_id_.empty()) { LOG(INFO, "can not get galaxy job id"); return kGalaxyError; } return kOk; } else { LOG(WARNING, "galaxy error: %s", rsps.error_code.reason.c_str()); } return kGalaxyError; } Status Gru::Kill() { LOG(INFO, "kill galaxy job: %s", minion_id_.c_str()); if (minion_id_.empty()) { return kOk; } ::baidu::galaxy::sdk::RemoveJobRequest rqst; ::baidu::galaxy::sdk::RemoveJobResponse rsps; rqst.jobid = minion_id_; rqst.user = galaxy_job_.user; if (galaxy_->RemoveJob(rqst, &rsps)) { return kOk; } else { LOG(WARNING, "galaxy error: %s", rsps.error_code.reason.c_str()); } return kGalaxyError; } Status Gru::Update(const std::string& priority, int capacity) { ::baidu::galaxy::sdk::JobDescription job_desc = galaxy_job_.job; if (!priority.empty()) { //job_desc.priority = priority; } if (capacity != -1) { job_desc.deploy.replica = capacity; } ::baidu::galaxy::sdk::UpdateJobRequest rqst; ::baidu::galaxy::sdk::UpdateJobResponse rsps; rqst.user = galaxy_job_.user; rqst.job = job_desc; rqst.jobid = minion_id_; if (galaxy_->UpdateJob(rqst, &rsps)) { if (!priority.empty()) { //galaxy_job_.priority = priority; } if (capacity != -1) { galaxy_job_.job.deploy.replica = capacity; } return kOk; } else { LOG(WARNING, "galaxy error: %s", rsps.error_code.reason.c_str()); } return kGalaxyError; } } }
#include "gru.h" #include <sstream> #include <gflags/gflags.h> #include <boost/algorithm/string.hpp> #include <vector> #include "logging.h" #include "util.h" DECLARE_int32(galaxy_deploy_step); DECLARE_string(minion_path); DECLARE_string(nexus_server_list); DECLARE_string(nexus_root_path); DECLARE_string(master_path); DECLARE_bool(enable_cpu_soft_limit); DECLARE_bool(enable_memory_soft_limit); DECLARE_string(galaxy_node_label); DECLARE_string(galaxy_user); DECLARE_string(galaxy_token); DECLARE_string(galaxy_pool); DECLARE_int32(max_minions_per_host); namespace baidu { namespace shuttle { static const int64_t default_additional_map_memory = 1024l * 1024 * 1024; static const int64_t default_additional_reduce_memory = 2048l * 1024 * 1024; static const int default_map_additional_millicores = 0; static const int default_reduce_additional_millicores = 500; int Gru::additional_map_millicores = default_map_additional_millicores; int Gru::additional_reduce_millicores = default_reduce_additional_millicores; int64_t Gru::additional_map_memory = default_additional_map_memory; int64_t Gru::additional_reduce_memory = default_additional_reduce_memory; Gru::Gru(::baidu::galaxy::sdk::AppMaster* galaxy, JobDescriptor* job, const std::string& job_id, WorkMode mode) : galaxy_(galaxy), job_(job), job_id_(job_id), mode_(mode) { mode_str_ = ((mode == kReduce) ? "reduce" : "map"); minion_name_ = job->name() + "_" + mode_str_; } Status Gru::Start() { ::baidu::galaxy::sdk::SubmitJobRequest galaxy_job; galaxy_job.user.user = FLAGS_galaxy_user; galaxy_job.user.token = FLAGS_galaxy_token; galaxy_job.hostname = ::baidu::common::util::GetLocalHostName(); galaxy_job.job.deploy.pools.push_back(FLAGS_galaxy_pool); galaxy_job.job.name = minion_name_ + "@minion"; galaxy_job.job.type = ::baidu::galaxy::sdk::kJobBatch; galaxy_job.job.deploy.replica = (mode_ == kReduce) ? job_->reduce_capacity() : job_->map_capacity(); galaxy_job.job.deploy.step = FLAGS_galaxy_deploy_step; galaxy_job.job.deploy.interval = 1; galaxy_job.job.deploy.max_per_host = FLAGS_max_minions_per_host; galaxy_job.job.deploy.update_break_count = 0; galaxy_job.job.version = "1.0.0"; galaxy_job.job.run_user = "galaxy"; if (!FLAGS_galaxy_node_label.empty()) { galaxy_job.job.deploy.tag = FLAGS_galaxy_node_label; } ::baidu::galaxy::sdk::PodDescription & pod_desc = galaxy_job.job.pod; pod_desc.workspace_volum.size = (3L << 30); pod_desc.workspace_volum.medium = ::baidu::galaxy::sdk::kDisk; pod_desc.workspace_volum.exclusive = false; pod_desc.workspace_volum.readonly = false; pod_desc.workspace_volum.use_symlink = false; pod_desc.workspace_volum.dest_path = "/home/shuttle"; pod_desc.workspace_volum.type = ::baidu::galaxy::sdk::kEmptyDir; ::baidu::galaxy::sdk::TaskDescription task_desc; if (mode_str_ == "map") { task_desc.cpu.milli_core = job_->millicores() + additional_map_millicores; } else { task_desc.cpu.milli_core = job_->millicores() + additional_reduce_millicores; } task_desc.memory.size = job_->memory() + ((mode_ == kReduce) ? additional_reduce_memory : additional_map_memory); std::string app_package; std::vector<std::string> cache_archive_list; int file_size = job_->files().size(); for (int i = 0; i < file_size; ++i) { const std::string& file = job_->files(i); if (boost::starts_with(file, "hdfs://")) { cache_archive_list.push_back(file); } else { app_package = file; } } std::stringstream ss; if (!job_->input_dfs().user().empty()) { ss << "hadoop_job_ugi=" << job_->input_dfs().user() << "," << job_->input_dfs().password() << " fs_default_name=hdfs://" << job_->input_dfs().host() << ":" << job_->input_dfs().port() << " "; } for (size_t i = 0; i < cache_archive_list.size(); i++) { ss << "cache_archive_" << i << "=" << cache_archive_list[i] << " "; } ss << "app_package=" << app_package << " ./minion_boot.sh -jobid=" << job_id_ << " -nexus_addr=" << FLAGS_nexus_server_list << " -master_nexus_path=" << FLAGS_nexus_root_path + FLAGS_master_path << " -work_mode=" << ((mode_ == kMapOnly) ? "map-only" : mode_str_); std::stringstream ss_stop; ss_stop << "source hdfs_env.sh; ./minion -jobid=" << job_id_ << " -nexus_addr=" << FLAGS_nexus_server_list << " -master_nexus_path=" << FLAGS_nexus_root_path + FLAGS_master_path << " -work_mode=" << ((mode_ == kMapOnly) ? "map-only" : mode_str_) << " -kill_task"; task_desc.exe_package.package.source_path = FLAGS_minion_path; task_desc.exe_package.package.dest_path = "."; task_desc.exe_package.package.version = "1.0"; task_desc.exe_package.start_cmd = ss.str().c_str(); task_desc.exe_package.stop_cmd = ss_stop.str().c_str(); task_desc.tcp_throt.recv_bps_quota = (50L << 20); task_desc.tcp_throt.send_bps_quota = (50L << 20); task_desc.blkio.weight = 100; ::baidu::galaxy::sdk::PortRequired port_req; port_req.port = "dynamic"; port_req.port_name = "NFS_CLIENT_PORT"; task_desc.ports.push_back(port_req); port_req.port = "dynamic"; port_req.port_name = "MINION_PORT"; task_desc.ports.push_back(port_req); if (FLAGS_enable_cpu_soft_limit) { task_desc.cpu.excess = true; } else { task_desc.cpu.excess = false; } if (FLAGS_enable_memory_soft_limit) { task_desc.memory.excess = true; } else { task_desc.memory.excess = false; } pod_desc.tasks.push_back(task_desc); std::string minion_id; ::baidu::galaxy::sdk::SubmitJobResponse rsps; if (galaxy_->SubmitJob(galaxy_job, &rsps)) { minion_id = rsps.jobid; LOG(INFO, "galaxy job id: %s", minion_id.c_str()); minion_id_ = minion_id; galaxy_job_ = galaxy_job; if (minion_id_.empty()) { LOG(INFO, "can not get galaxy job id"); return kGalaxyError; } return kOk; } else { LOG(WARNING, "galaxy error: %s", rsps.error_code.reason.c_str()); } return kGalaxyError; } Status Gru::Kill() { LOG(INFO, "kill galaxy job: %s", minion_id_.c_str()); if (minion_id_.empty()) { return kOk; } ::baidu::galaxy::sdk::RemoveJobRequest rqst; ::baidu::galaxy::sdk::RemoveJobResponse rsps; rqst.jobid = minion_id_; rqst.user = galaxy_job_.user; rqst.hostname = ::baidu::common::util::GetLocalHostName(); if (galaxy_->RemoveJob(rqst, &rsps)) { return kOk; } else { LOG(WARNING, "galaxy error: %s", rsps.error_code.reason.c_str()); } return kGalaxyError; } Status Gru::Update(const std::string& priority, int capacity) { ::baidu::galaxy::sdk::JobDescription job_desc = galaxy_job_.job; if (!priority.empty()) { //job_desc.priority = priority; } if (capacity != -1) { job_desc.deploy.replica = capacity; } ::baidu::galaxy::sdk::UpdateJobRequest rqst; ::baidu::galaxy::sdk::UpdateJobResponse rsps; rqst.user = galaxy_job_.user; rqst.job = job_desc; rqst.jobid = minion_id_; rqst.oprate = ::baidu::galaxy::sdk::kUpdateJobDefault; rqst.hostname = ::baidu::common::util::GetLocalHostName(); if (galaxy_->UpdateJob(rqst, &rsps)) { if (!priority.empty()) { //galaxy_job_.priority = priority; } if (capacity != -1) { galaxy_job_.job.deploy.replica = capacity; } return kOk; } else { LOG(WARNING, "galaxy error: %s", rsps.error_code.reason.c_str()); } return kGalaxyError; } } }
fix bugs for the new galaxy3 sdk
fix bugs for the new galaxy3 sdk
C++
bsd-3-clause
fxsjy/shuttle,fxsjy/shuttle,fxsjy/shuttle,baidu/shuttle,baidu/shuttle,baidu/shuttle
9d4aa420a580af1b228caafc23dd374d399a4212
src/math/math.cpp
src/math/math.cpp
#include "math.hpp" namespace math { double pointDistance(double x1, double y1, double x2, double y2) { return sqrt(pow(x2 - x1, 2) + pow(y2 - y1, 2)); } double pointDirection(double x1, double y1, double x2, double y2) { return radtodeg(acos((x2 - x1) / pointDistance(x1, y1, x2, y2))); } double lengthdirX(double len, double dir) { return len * cos(degtorad(dir)); } double lengthdirY(double len, double dir) { return -len * sin(degtorad(dir)); } double adaptDirection(double dir) { return (dir < 0 ? 360 : 0) + fmod(dir, 360.0); } }
#include "math/math.hpp" namespace math { double pointDistance(double x1, double y1, double x2, double y2) { return sqrt(pow(x2 - x1, 2) + pow(y2 - y1, 2)); } double pointDirection(double x1, double y1, double x2, double y2) { return radtodeg(acos((x2 - x1) / pointDistance(x1, y1, x2, y2))); } double lengthdirX(double len, double dir) { return len * cos(degtorad(dir)); } double lengthdirY(double len, double dir) { return -len * sin(degtorad(dir)); } double adaptDirection(double dir) { return (dir < 0 ? 360 : 0) + fmod(dir, 360.0); } }
Fix include of math.hpp
Fix include of math.hpp
C++
mit
mall0c/cppmath,mphe/cppmath
175b74d303c11e6cb760f4d6e6e2c5821c827c48
service/reference-update/TypeReference.cpp
service/reference-update/TypeReference.cpp
/** * Copyright (c) 2018-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ #include "TypeReference.h" #include "MethodReference.h" #include "Resolver.h" #include "VirtualScope.h" #include "Walkers.h" using CallSites = std::vector<std::pair<DexMethod*, IRInstruction*>>; namespace { void fix_colliding_method( const Scope& scope, const std::unordered_map<DexMethod*, DexProto*>& colliding_methods) { // Fix colliding methods by appending an additional param. TRACE(REFU, 9, "sig: colliding_methods %d\n", colliding_methods.size()); for (auto it : colliding_methods) { auto meth = it.first; auto new_proto = it.second; auto new_arg_list = type_reference::append_and_make(new_proto->get_args(), get_int_type()); new_proto = DexProto::make_proto(new_proto->get_rtype(), new_arg_list); DexMethodSpec spec; spec.proto = new_proto; meth->change(spec, false); auto code = meth->get_code(); auto new_param_reg = code->allocate_temp(); auto& last_param = code->get_param_instructions().back().insn; auto new_param_load = new IRInstruction(IOPCODE_LOAD_PARAM); new_param_load->set_dest(new_param_reg); code->insert_after(last_param, std::vector<IRInstruction*>{new_param_load}); TRACE(REFU, 9, "sig: patching colliding method %s\n", SHOW(meth)); } walk::parallel::code(scope, [&](DexMethod* meth, IRCode& code) { CallSites callsites; for (auto& mie : InstructionIterable(code)) { auto insn = mie.insn; if (!insn->has_method()) { continue; } const auto callee = resolve_method(insn->get_method(), opcode_to_search(const_cast<IRInstruction*>(insn))); if (callee == nullptr || colliding_methods.find(callee) == colliding_methods.end()) { continue; } callsites.emplace_back(callee, insn); } for (const auto& pair : callsites) { auto callee = pair.first; auto insn = pair.second; always_assert(callee != nullptr); TRACE(REFU, 9, "sig: patching colliding method callsite to %s in %s\n", SHOW(callee), SHOW(meth)); // 42 is a dummy int val as the additional argument to the patched // colliding method. method_reference::CallSiteSpec spec{meth, insn, callee}; method_reference::patch_callsite(spec, boost::optional<uint32_t>(42)); } }); } } // namespace namespace type_reference { bool proto_has_reference_to(const DexProto* proto, const TypeSet& targets) { auto rtype = get_array_type_or_self(proto->get_rtype()); if (targets.count(rtype) > 0) { return true; } std::deque<DexType*> lst; for (const auto arg_type : proto->get_args()->get_type_list()) { auto extracted_arg_type = get_array_type_or_self(arg_type); if (targets.count(extracted_arg_type) > 0) { return true; } } return false; } DexProto* update_proto_reference( const DexProto* proto, const std::unordered_map<const DexType*, DexType*>& old_to_new) { auto rtype = get_array_type_or_self(proto->get_rtype()); if (old_to_new.count(rtype) > 0) { auto merger_type = old_to_new.at(rtype); rtype = is_array(proto->get_rtype()) ? make_array_type(merger_type) : const_cast<DexType*>(merger_type); } std::deque<DexType*> lst; for (const auto arg_type : proto->get_args()->get_type_list()) { auto extracted_arg_type = get_array_type_or_self(arg_type); if (old_to_new.count(extracted_arg_type) > 0) { auto merger_type = old_to_new.at(extracted_arg_type); auto new_arg_type = is_array(arg_type) ? make_array_type(merger_type) : const_cast<DexType*>(merger_type); lst.push_back(new_arg_type); } else { lst.push_back(arg_type); } } return DexProto::make_proto(const_cast<DexType*>(rtype), DexTypeList::make_type_list(std::move(lst))); } DexTypeList* prepend_and_make(const DexTypeList* list, DexType* new_type) { auto old_list = list->get_type_list(); auto prepended = std::deque<DexType*>(old_list.begin(), old_list.end()); prepended.push_front(new_type); return DexTypeList::make_type_list(std::move(prepended)); } DexTypeList* append_and_make(const DexTypeList* list, DexType* new_type) { auto old_list = list->get_type_list(); auto appended = std::deque<DexType*>(old_list.begin(), old_list.end()); appended.push_back(new_type); return DexTypeList::make_type_list(std::move(appended)); } DexTypeList* append_and_make(const DexTypeList* list, const std::vector<DexType*>& new_types) { auto old_list = list->get_type_list(); auto appended = std::deque<DexType*>(old_list.begin(), old_list.end()); appended.insert(appended.end(), new_types.begin(), new_types.end()); return DexTypeList::make_type_list(std::move(appended)); } DexTypeList* replace_head_and_make(const DexTypeList* list, DexType* new_head) { auto old_list = list->get_type_list(); auto new_list = std::deque<DexType*>(old_list.begin(), old_list.end()); always_assert(!new_list.empty()); new_list.pop_front(); new_list.push_front(new_head); return DexTypeList::make_type_list(std::move(new_list)); } void update_method_signature_type_references( const Scope& scope, const std::unordered_map<const DexType*, DexType*>& old_to_new) { std::unordered_map<DexMethod*, DexProto*> colliding_candidates; TypeSet mergeables; for (const auto& pair : old_to_new) { mergeables.insert(pair.first); } const auto update_sig = [&](DexMethod* meth) { auto proto = meth->get_proto(); if (!proto_has_reference_to(proto, mergeables)) { return; } auto new_proto = update_proto_reference(proto, old_to_new); DexMethodSpec spec; spec.proto = new_proto; if (!is_init(meth) && !meth->is_virtual()) { TRACE(REFU, 9, "sig: updating non ctor/virt method %s\n", SHOW(meth)); meth->change(spec, true); return; } auto type = meth->get_class(); auto name = meth->get_name(); auto existing_meth = DexMethod::get_method(type, name, new_proto); if (existing_meth == nullptr) { TRACE(REFU, 9, "sig: updating method %s\n", SHOW(meth)); meth->change(spec, true); return; } TRACE(REFU, 9, "sig: found colliding candidate %s with %s\n", SHOW(existing_meth), SHOW(meth)); colliding_candidates[meth] = new_proto; }; walk::methods(scope, update_sig); if (colliding_candidates.empty()) { return; } // Compute virtual scopes and filter out non-virtuals. // Perform simple signature update and renaming for non-virtuals. auto non_virtuals = devirtualize(scope); std::unordered_set<DexMethod*> non_virt_set(non_virtuals.begin(), non_virtuals.end()); std::unordered_map<DexMethod*, DexProto*> colliding_methods; for (const auto& pair : colliding_candidates) { auto meth = pair.first; auto new_proto = pair.second; if (non_virt_set.count(meth) > 0) { DexMethodSpec spec; spec.proto = new_proto; TRACE(REFU, 9, "sig: updating non virt method %s\n", SHOW(meth)); meth->change(spec, true); continue; } // We cannot handle the renaming of true virtuals. always_assert_log(!meth->is_virtual(), "sig: found true virtual colliding method %s\n", SHOW(meth)); colliding_methods[meth] = new_proto; } // Last resort. Fix colliding methods for non-virtuals. fix_colliding_method(scope, colliding_methods); } } // namespace type_reference
/** * Copyright (c) 2018-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ #include "TypeReference.h" #include "MethodReference.h" #include "Resolver.h" #include "VirtualScope.h" #include "Walkers.h" using CallSites = std::vector<std::pair<DexMethod*, IRInstruction*>>; namespace { void fix_colliding_method( const Scope& scope, const std::unordered_map<DexMethod*, DexProto*>& colliding_methods) { // Fix colliding methods by appending an additional param. TRACE(REFU, 9, "sig: colliding_methods %d\n", colliding_methods.size()); for (auto it : colliding_methods) { auto meth = it.first; auto new_proto = it.second; auto new_arg_list = type_reference::append_and_make(new_proto->get_args(), get_int_type()); new_proto = DexProto::make_proto(new_proto->get_rtype(), new_arg_list); DexMethodSpec spec; spec.proto = new_proto; meth->change(spec, false); auto code = meth->get_code(); auto new_param_reg = code->allocate_temp(); auto& last_param = code->get_param_instructions().back().insn; auto new_param_load = new IRInstruction(IOPCODE_LOAD_PARAM); new_param_load->set_dest(new_param_reg); code->insert_after(last_param, std::vector<IRInstruction*>{new_param_load}); TRACE(REFU, 9, "sig: patching colliding method %s\n", SHOW(meth)); } walk::parallel::code(scope, [&](DexMethod* meth, IRCode& code) { CallSites callsites; for (auto& mie : InstructionIterable(code)) { auto insn = mie.insn; if (!insn->has_method()) { continue; } const auto callee = resolve_method(insn->get_method(), opcode_to_search(const_cast<IRInstruction*>(insn))); if (callee == nullptr || colliding_methods.find(callee) == colliding_methods.end()) { continue; } callsites.emplace_back(callee, insn); } for (const auto& pair : callsites) { auto callee = pair.first; auto insn = pair.second; always_assert(callee != nullptr); TRACE(REFU, 9, "sig: patching colliding method callsite to %s in %s\n", SHOW(callee), SHOW(meth)); // 42 is a dummy int val as the additional argument to the patched // colliding method. method_reference::CallSiteSpec spec{meth, insn, callee}; method_reference::patch_callsite(spec, boost::optional<uint32_t>(42)); } }); } } // namespace namespace type_reference { bool proto_has_reference_to(const DexProto* proto, const TypeSet& targets) { auto rtype = get_array_type_or_self(proto->get_rtype()); if (targets.count(rtype) > 0) { return true; } std::deque<DexType*> lst; for (const auto arg_type : proto->get_args()->get_type_list()) { auto extracted_arg_type = get_array_type_or_self(arg_type); if (targets.count(extracted_arg_type) > 0) { return true; } } return false; } DexProto* update_proto_reference( const DexProto* proto, const std::unordered_map<const DexType*, DexType*>& old_to_new) { auto rtype = get_array_type_or_self(proto->get_rtype()); if (old_to_new.count(rtype) > 0) { auto merger_type = old_to_new.at(rtype); rtype = is_array(proto->get_rtype()) ? make_array_type(merger_type) : const_cast<DexType*>(merger_type); } else { rtype = proto->get_rtype(); } std::deque<DexType*> lst; for (const auto arg_type : proto->get_args()->get_type_list()) { auto extracted_arg_type = get_array_type_or_self(arg_type); if (old_to_new.count(extracted_arg_type) > 0) { auto merger_type = old_to_new.at(extracted_arg_type); auto new_arg_type = is_array(arg_type) ? make_array_type(merger_type) : const_cast<DexType*>(merger_type); lst.push_back(new_arg_type); } else { lst.push_back(arg_type); } } return DexProto::make_proto(const_cast<DexType*>(rtype), DexTypeList::make_type_list(std::move(lst))); } DexTypeList* prepend_and_make(const DexTypeList* list, DexType* new_type) { auto old_list = list->get_type_list(); auto prepended = std::deque<DexType*>(old_list.begin(), old_list.end()); prepended.push_front(new_type); return DexTypeList::make_type_list(std::move(prepended)); } DexTypeList* append_and_make(const DexTypeList* list, DexType* new_type) { auto old_list = list->get_type_list(); auto appended = std::deque<DexType*>(old_list.begin(), old_list.end()); appended.push_back(new_type); return DexTypeList::make_type_list(std::move(appended)); } DexTypeList* append_and_make(const DexTypeList* list, const std::vector<DexType*>& new_types) { auto old_list = list->get_type_list(); auto appended = std::deque<DexType*>(old_list.begin(), old_list.end()); appended.insert(appended.end(), new_types.begin(), new_types.end()); return DexTypeList::make_type_list(std::move(appended)); } DexTypeList* replace_head_and_make(const DexTypeList* list, DexType* new_head) { auto old_list = list->get_type_list(); auto new_list = std::deque<DexType*>(old_list.begin(), old_list.end()); always_assert(!new_list.empty()); new_list.pop_front(); new_list.push_front(new_head); return DexTypeList::make_type_list(std::move(new_list)); } void update_method_signature_type_references( const Scope& scope, const std::unordered_map<const DexType*, DexType*>& old_to_new) { std::unordered_map<DexMethod*, DexProto*> colliding_candidates; TypeSet mergeables; for (const auto& pair : old_to_new) { mergeables.insert(pair.first); } const auto update_sig = [&](DexMethod* meth) { auto proto = meth->get_proto(); if (!proto_has_reference_to(proto, mergeables)) { return; } auto new_proto = update_proto_reference(proto, old_to_new); DexMethodSpec spec; spec.proto = new_proto; if (!is_init(meth) && !meth->is_virtual()) { TRACE(REFU, 9, "sig: updating non ctor/virt method %s\n", SHOW(meth)); meth->change(spec, true); return; } auto type = meth->get_class(); auto name = meth->get_name(); auto existing_meth = DexMethod::get_method(type, name, new_proto); if (existing_meth == nullptr) { TRACE(REFU, 9, "sig: updating method %s\n", SHOW(meth)); meth->change(spec, true); return; } TRACE(REFU, 9, "sig: found colliding candidate %s with %s\n", SHOW(existing_meth), SHOW(meth)); colliding_candidates[meth] = new_proto; }; walk::methods(scope, update_sig); if (colliding_candidates.empty()) { return; } // Compute virtual scopes and filter out non-virtuals. // Perform simple signature update and renaming for non-virtuals. auto non_virtuals = devirtualize(scope); std::unordered_set<DexMethod*> non_virt_set(non_virtuals.begin(), non_virtuals.end()); std::unordered_map<DexMethod*, DexProto*> colliding_methods; for (const auto& pair : colliding_candidates) { auto meth = pair.first; auto new_proto = pair.second; if (non_virt_set.count(meth) > 0) { DexMethodSpec spec; spec.proto = new_proto; TRACE(REFU, 9, "sig: updating non virt method %s\n", SHOW(meth)); meth->change(spec, true); continue; } // We cannot handle the renaming of true virtuals. always_assert_log(!meth->is_virtual(), "sig: found true virtual colliding method %s\n", SHOW(meth)); colliding_methods[meth] = new_proto; } // Last resort. Fix colliding methods for non-virtuals. fix_colliding_method(scope, colliding_methods); } } // namespace type_reference
Handle array return type when updating reference in proto
Handle array return type when updating reference in proto Summary: We had this bug for a long time in `update_proto_reference`. When updating a proto with reference to a mergeable type, we didn't handle the return type correctly. We flatten the return type if it is an array type. But if the flatten type is not a mergeable we should keep it as an array type, which was missing. Also I disabled type erasure devirtualization and enabled ir_type_checker for TypeErasurePass. Will propagate this change to staging and stable as well. Reviewed By: emma0303 Differential Revision: D7997764 fbshipit-source-id: 9c93d14fd8584f3b749556243d72e894e00aee39
C++
mit
facebook/redex,facebook/redex,facebook/redex,facebook/redex,facebook/redex,facebook/redex,facebook/redex,facebook/redex,facebook/redex
29be253e452cf3586adf9d0552ae60479343e92c
source/examples/qtexample-es/WindowQt.cpp
source/examples/qtexample-es/WindowQt.cpp
#include "WindowQt.h" #include <QApplication> #include <QDebug> #include <QResizeEvent> #include <QSurfaceFormat> #include <QOpenGLContext> QSurfaceFormat defaultFormat() { QSurfaceFormat format; format.setProfile(QSurfaceFormat::CoreProfile); #ifndef NDEBUG format.setOption(QSurfaceFormat::DebugContext); #endif return format; } WindowQt::WindowQt(QApplication & app, const QSurfaceFormat & format) : m_context(new QOpenGLContext) , m_updatePending(false) , m_initialized(false) { QSurfaceFormat f(format); //f.setRenderableType(QSurfaceFormat::OpenGLES); setSurfaceType(OpenGLSurface); create(); m_context->setFormat(format); if (!m_context->create()) { qDebug() << "Could not create OpenGL context."; QApplication::quit(); } QObject::connect(&app, &QGuiApplication::lastWindowClosed, [this]() { if (m_initialized) { makeCurrent(); deinitializeGL(); doneCurrent(); } }); } WindowQt::~WindowQt() { // cannot deinitialize OpenGL here as it would require the call of a virtual member function } QOpenGLContext * WindowQt::context() { return m_context.data(); } void WindowQt::makeCurrent() { m_context->makeCurrent(this); } void WindowQt::doneCurrent() { m_context->doneCurrent(); } void WindowQt::resizeEvent(QResizeEvent * event) { resize(event); paint(); } void WindowQt::exposeEvent(QExposeEvent * ) { paint(); } void WindowQt::initialize() { makeCurrent(); initializeGL(); doneCurrent(); m_initialized = true; } void WindowQt::resize(QResizeEvent * event) { if (!m_initialized) initialize(); makeCurrent(); QResizeEvent deviceSpecificResizeEvent(event->size() * devicePixelRatio(), event->oldSize() * devicePixelRatio()); resizeGL(&deviceSpecificResizeEvent); doneCurrent(); } void WindowQt::paint() { if (!m_initialized) initialize(); if (!isExposed()) return; m_updatePending = false; makeCurrent(); paintGL(); m_context->swapBuffers(this); doneCurrent(); } void WindowQt::updateGL() { if (!m_updatePending) { m_updatePending = true; QCoreApplication::postEvent(this, new QEvent(QEvent::UpdateRequest)); } } bool WindowQt::event(QEvent * event) { switch (event->type()) { case QEvent::UpdateRequest: paint(); return true; case QEvent::Enter: enterEvent(event); return true; case QEvent::Leave: leaveEvent(event); return true; default: return QWindow::event(event); } } bool WindowQt::initializeGL() { return false; } void WindowQt::deinitializeGL() { } void WindowQt::resizeGL(QResizeEvent *) { } void WindowQt::paintGL() { updateGL(); } void WindowQt::enterEvent(QEvent *) { } void WindowQt::leaveEvent(QEvent *) { } glbinding::ProcAddress WindowQt::getProcAddress(const char * name) { if (name == nullptr) { return nullptr; } const auto symbol = std::string(name); #if (QT_VERSION >= QT_VERSION_CHECK(5, 4, 0)) const auto qtSymbol = QByteArray::fromStdString(symbol); #else const auto qtSymbol = QByteArray::fromRawData(symbol.c_str(), symbol.size()); #endif return m_context->getProcAddress(qtSymbol); }
#include "WindowQt.h" #include <QApplication> #include <QDebug> #include <QResizeEvent> #include <QSurfaceFormat> #include <QOpenGLContext> QSurfaceFormat defaultFormat() { QSurfaceFormat format; format.setProfile(QSurfaceFormat::CoreProfile); #ifndef NDEBUG format.setOption(QSurfaceFormat::DebugContext); #endif return format; } WindowQt::WindowQt(QApplication & app, const QSurfaceFormat & format) : m_context(new QOpenGLContext) , m_updatePending(false) , m_initialized(false) { QSurfaceFormat f(format); //f.setRenderableType(QSurfaceFormat::OpenGLES); setSurfaceType(OpenGLSurface); create(); m_context->setFormat(format); if (!m_context->create()) { qDebug() << "Could not create OpenGL context."; QApplication::quit(); } QObject::connect(&app, &QGuiApplication::lastWindowClosed, [this]() { if (m_initialized) { makeCurrent(); deinitializeGL(); doneCurrent(); } }); } WindowQt::~WindowQt() { // cannot deinitialize OpenGL here as it would require the call of a virtual member function } QOpenGLContext * WindowQt::context() { return m_context.data(); } void WindowQt::makeCurrent() { m_context->makeCurrent(this); } void WindowQt::doneCurrent() { m_context->doneCurrent(); } void WindowQt::resizeEvent(QResizeEvent * event) { resize(event); paint(); } void WindowQt::exposeEvent(QExposeEvent * ) { paint(); } void WindowQt::initialize() { makeCurrent(); m_initialized = initializeGL(); doneCurrent(); } void WindowQt::resize(QResizeEvent * event) { if (!m_initialized) initialize(); makeCurrent(); QResizeEvent deviceSpecificResizeEvent(event->size() * devicePixelRatio(), event->oldSize() * devicePixelRatio()); resizeGL(&deviceSpecificResizeEvent); doneCurrent(); } void WindowQt::paint() { if (!m_initialized) initialize(); if (!isExposed()) return; m_updatePending = false; makeCurrent(); paintGL(); m_context->swapBuffers(this); doneCurrent(); } void WindowQt::updateGL() { if (!m_updatePending) { m_updatePending = true; QCoreApplication::postEvent(this, new QEvent(QEvent::UpdateRequest)); } } bool WindowQt::event(QEvent * event) { switch (event->type()) { case QEvent::UpdateRequest: paint(); return true; case QEvent::Enter: enterEvent(event); return true; case QEvent::Leave: leaveEvent(event); return true; default: return QWindow::event(event); } } bool WindowQt::initializeGL() { return false; } void WindowQt::deinitializeGL() { } void WindowQt::resizeGL(QResizeEvent *) { } void WindowQt::paintGL() { updateGL(); } void WindowQt::enterEvent(QEvent *) { } void WindowQt::leaveEvent(QEvent *) { } glbinding::ProcAddress WindowQt::getProcAddress(const char * name) { if (name == nullptr) { return nullptr; } const auto symbol = std::string(name); #if (QT_VERSION >= QT_VERSION_CHECK(5, 4, 0)) const auto qtSymbol = QByteArray::fromStdString(symbol); #else const auto qtSymbol = QByteArray::fromRawData(symbol.c_str(), symbol.size()); #endif return m_context->getProcAddress(qtSymbol); }
Add missing fix
Add missing fix
C++
mit
j-o/globjects,j-o/globjects,j-o/globjects,cginternals/globjects,cginternals/globjects,j-o/globjects
c881c4f49177c6ad2fc0f0e419fbc51758a0c6d7
MatrixStore_Ver00.00_01/main.cpp
MatrixStore_Ver00.00_01/main.cpp
#include <stdio.h> #include <iostream> #include "MatrixStore.hpp" int main(){ class MatrixStore<double> MatA(3, 3); MatA.Zeros(); class MatrixStore<double> MatB(3, 3); MatB.Zeros(); for(unsigned int q=0; q<MatA.ColNum; q++){ for(unsigned int p=0; p<MatA.RowNum; p++){ MatA(p, q) = (MatA.ColNum)*p + q; } } printm(MatA);printf("\n"); MatB(':', 0) = MatA(':', 1); // MatB(':', 1) = MatA(':', 2); // MatB(':', 2) = MatA(':', 0); printm(MatB);printf("\n"); MatB(0, ':') = MatA(0, ':'); // MatB(1, ':') = MatA(1, ':'); MatB(2, ':') = MatA(2, ':'); printm(MatB);printf("\n"); return 0; }
#include <stdio.h> #include <iostream> #include "MatrixStore.hpp" int main(){ class MatrixStore<double> MatA(3, 3); MatA.Zeros(); class MatrixStore<double> MatB(3, 3); MatB.Zeros(); for(unsigned int q=0; q<MatA.ColNum; q++){ for(unsigned int p=0; p<MatA.RowNum; p++){ MatA(p, q) = (MatA.ColNum)*p + q; } } printm(MatA); printf("\n"); MatB(':', 0) = MatA(':', 1); // MatB(':', 1) = MatA(':', 2); // MatB(':', 2) = MatA(':', 0); printm(MatB); printf("\n"); MatB(0, ':') = MatA(0, ':'); // MatB(1, ':') = MatA(1, ':'); MatB(2, ':') = MatA(2, ':'); printm(MatB); return 0; }
Update main.cpp
Update main.cpp
C++
mit
admiswalker/MatrixStore,admiswalker/MatrixStore
335e4b9d52a978aa6a7a845a24b044ab0927c91e
paddle/fluid/framework/details/threaded_ssa_graph_executor.cc
paddle/fluid/framework/details/threaded_ssa_graph_executor.cc
// Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "paddle/fluid/framework/details/threaded_ssa_graph_executor.h" namespace paddle { namespace framework { namespace details { ThreadedSSAGraphExecutor::ThreadedSSAGraphExecutor( const ExecutionStrategy &strategy, const std::vector<Scope *> &local_scopes, const std::vector<platform::Place> &places, std::unique_ptr<SSAGraph> &&graph) : graph_(std::move(graph)), pool_(strategy.num_threads_ >= 2 ? new ::ThreadPool(strategy.num_threads_) : nullptr), local_scopes_(local_scopes), places_(places), fetch_ctxs_(places), running_ops_(0), strategy_(strategy) {} FeedFetchList ThreadedSSAGraphExecutor::Run( const std::vector<std::string> &fetch_tensors) { std::unordered_map<OpHandleBase *, size_t> pending_ops; std::unordered_set<VarHandleBase *> pending_vars; BlockingQueue<VarHandleBase *> ready_vars; std::unordered_set<OpHandleBase *> ready_ops; // For ops (e.g. nccl_all_reduce) that need to coordinate multiple // streams from multiple GPUs, it's faster to buffer them and schedule // together since we currently cannot overlap computation and memcpy streams. // Should revisit it if overlapping is available. std::unordered_set<OpHandleBase *> delayed_ops; // Transform SSAGraph to pending_ops & pending_vars for (auto &var_map : graph_->vars_) { for (auto &name_pair : var_map) { for (auto &version_pair : name_pair.second) { InsertPendingVar(&pending_vars, &ready_vars, version_pair.get()); } } } for (auto &var : graph_->dep_vars_) { InsertPendingVar(&pending_vars, &ready_vars, var.get()); } for (auto &op : graph_->ops_) { if (op->Inputs().empty()) { // Special case, Op has no input. ready_ops.insert(op.get()); } else { InsertPendingOp(&pending_ops, op.get()); } } // Step 2. Insert FetchOps std::vector<std::unique_ptr<FetchOpHandle>> fetch_ops; std::unordered_set<std::unique_ptr<VarHandleBase>> fetch_dependencies; FeedFetchList fetch_data(fetch_tensors.size()); InsertFetchOps(fetch_tensors, &fetch_ops, &fetch_dependencies, &pending_ops, &pending_vars, &ready_vars, &fetch_data); auto run_all_ops = [&](std::unordered_set<OpHandleBase *> &set) { for (auto *op : set) { running_ops_++; RunOp(&ready_vars, op); } set.clear(); }; // Clean run context run_op_futures_.clear(); exception_.reset(); // Step 3. Execution while (!pending_vars.empty()) { // 1. Run All Ready ops // Keep loop until all vars are ready. // // NOTE: DelayedOps have a lower priority. It will be scheduled after all // ready_ops have been performed. if (ready_ops.empty() && strategy_.allow_op_delay_ && running_ops_ == 0) { run_all_ops(delayed_ops); } else { run_all_ops(ready_ops); } // 2. Find ready variable bool timeout; auto cur_ready_vars = ready_vars.PopAll(1, &timeout); if (timeout) { std::lock_guard<std::mutex> l(exception_mu_); if (exception_) { for (auto &run_op_future : run_op_futures_) { run_op_future.wait(); } std::exception *exp = exception_.get(); if (dynamic_cast<platform::EOFException *>(exp)) { auto e = *static_cast<platform::EOFException *>(exp); throw e; } else if (dynamic_cast<platform::EnforceNotMet *>(exp)) { auto e = *static_cast<platform::EnforceNotMet *>(exp); throw e; } else { LOG(FATAL) << "Unknown exception."; } } else { continue; } } // 3. Remove the dependency of ready_var. // Find the ready_ops after the ready_var. for (auto ready_var : cur_ready_vars) { pending_vars.erase(ready_var); for (auto *op : ready_var->pending_ops_) { auto &deps = pending_ops[op]; --deps; if (deps == 0) { if (op->IsMultiDeviceTransfer() && strategy_.allow_op_delay_) { delayed_ops.insert(op); } else { ready_ops.insert(op); } } } } } PADDLE_ENFORCE(ready_ops.empty()); // Wait FetchOps. if (!fetch_ops.empty()) { fetch_ops.clear(); } return fetch_data; } void ThreadedSSAGraphExecutor::InsertFetchOps( const std::vector<std::string> &fetch_tensors, std::vector<std::unique_ptr<FetchOpHandle>> *fetch_ops, std::unordered_set<std::unique_ptr<VarHandleBase>> *fetch_dependencies, std::unordered_map<OpHandleBase *, size_t> *pending_ops, std::unordered_set<VarHandleBase *> *pending_vars, BlockingQueue<VarHandleBase *> *ready_vars, FeedFetchList *fetch_data) { std::unordered_map<std::string, std::vector<VarHandleBase *>> fetched_vars; for (auto &fetch_var_name : fetch_tensors) { for (auto &var_map : graph_->vars_) { auto it = var_map.find(fetch_var_name); if (it != var_map.end()) { fetched_vars[fetch_var_name].push_back(it->second.rbegin()->get()); } } } for (size_t i = 0; i < fetch_tensors.size(); ++i) { auto &var_name = fetch_tensors[i]; auto &vars = fetched_vars.at(var_name); auto *op = new FetchOpHandle(fetch_data, i, &local_scopes_); fetch_ops->emplace_back(op); for (auto &p : places_) { op->SetDeviceContext(p, fetch_ctxs_.Get(p)); } for (auto *var : vars) { op->AddInput(var); } auto *fetch_dummy = new DummyVarHandle(); op->AddOutput(fetch_dummy); fetch_dependencies->emplace(fetch_dummy); this->InsertPendingVar(pending_vars, ready_vars, fetch_dummy); this->InsertPendingOp(pending_ops, op); } } void ThreadedSSAGraphExecutor::InsertPendingOp( std::unordered_map<OpHandleBase *, size_t> *pending_ops, OpHandleBase *op_instance) const { pending_ops->insert({op_instance, op_instance->NoDupInputSize()}); } void ThreadedSSAGraphExecutor::InsertPendingVar( std::unordered_set<VarHandleBase *> *pending_vars, BlockingQueue<VarHandleBase *> *ready_vars, VarHandleBase *var) const { pending_vars->insert(var); if (var->generated_op_ == nullptr) { ready_vars->Push(var); } } void ThreadedSSAGraphExecutor::RunOp( BlockingQueue<VarHandleBase *> *ready_var_q, details::OpHandleBase *op) { auto op_run = [ready_var_q, op, this] { try { if (VLOG_IS_ON(10)) { VLOG(10) << op << " " << op->Name() << " : " << op->DebugString(); } op->Run(strategy_.use_cuda_); VLOG(10) << op << " " << op->Name() << " Done "; running_ops_--; ready_var_q->Extend(op->Outputs()); VLOG(10) << op << " " << op->Name() << "Signal posted"; } catch (platform::EOFException ex) { std::lock_guard<std::mutex> l(exception_mu_); // EOFException will not cover up existing EnforceNotMet. if (exception_.get() == nullptr) { exception_.reset(new platform::EOFException(ex)); } } catch (platform::EnforceNotMet ex) { std::lock_guard<std::mutex> l(exception_mu_); exception_.reset(new platform::EnforceNotMet(ex)); } catch (...) { LOG(FATAL) << "Unknown exception catched"; } }; if (pool_) { run_op_futures_.emplace_back(pool_->enqueue(op_run)); } else { op_run(); } } } // namespace details } // namespace framework } // namespace paddle
// Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "paddle/fluid/framework/details/threaded_ssa_graph_executor.h" namespace paddle { namespace framework { namespace details { ThreadedSSAGraphExecutor::ThreadedSSAGraphExecutor( const ExecutionStrategy &strategy, const std::vector<Scope *> &local_scopes, const std::vector<platform::Place> &places, std::unique_ptr<SSAGraph> &&graph) : graph_(std::move(graph)), pool_(strategy.num_threads_ >= 2 ? new ::ThreadPool(strategy.num_threads_) : nullptr), local_scopes_(local_scopes), places_(places), fetch_ctxs_(places), running_ops_(0), strategy_(strategy) {} FeedFetchList ThreadedSSAGraphExecutor::Run( const std::vector<std::string> &fetch_tensors) { std::unordered_map<OpHandleBase *, size_t> pending_ops; std::unordered_set<VarHandleBase *> pending_vars; BlockingQueue<VarHandleBase *> ready_vars; std::unordered_set<OpHandleBase *> ready_ops; // For ops (e.g. nccl_all_reduce) that need to coordinate multiple // streams from multiple GPUs, it's faster to buffer them and schedule // together since we currently cannot overlap computation and memcpy streams. // Should revisit it if overlapping is available. std::unordered_set<OpHandleBase *> delayed_ops; // Transform SSAGraph to pending_ops & pending_vars for (auto &var_map : graph_->vars_) { for (auto &name_pair : var_map) { for (auto &version_pair : name_pair.second) { InsertPendingVar(&pending_vars, &ready_vars, version_pair.get()); } } } for (auto &var : graph_->dep_vars_) { InsertPendingVar(&pending_vars, &ready_vars, var.get()); } for (auto &op : graph_->ops_) { if (op->Inputs().empty()) { // Special case, Op has no input. ready_ops.insert(op.get()); } else { InsertPendingOp(&pending_ops, op.get()); } } // Step 2. Insert FetchOps std::vector<std::unique_ptr<FetchOpHandle>> fetch_ops; std::unordered_set<std::unique_ptr<VarHandleBase>> fetch_dependencies; FeedFetchList fetch_data(fetch_tensors.size()); InsertFetchOps(fetch_tensors, &fetch_ops, &fetch_dependencies, &pending_ops, &pending_vars, &ready_vars, &fetch_data); auto run_all_ops = [&](std::unordered_set<OpHandleBase *> &set) { for (auto *op : set) { running_ops_++; RunOp(&ready_vars, op); } set.clear(); }; // Clean run context run_op_futures_.clear(); exception_.reset(); // Step 3. Execution while (!pending_vars.empty()) { // 1. Run All Ready ops // Keep loop until all vars are ready. // // NOTE: DelayedOps have a lower priority. It will be scheduled after all // ready_ops have been performed. if (ready_ops.empty() && strategy_.allow_op_delay_ && running_ops_ == 0) { run_all_ops(delayed_ops); } else { run_all_ops(ready_ops); } // 2. Find ready variable bool timeout; auto cur_ready_vars = ready_vars.PopAll(1, &timeout); if (timeout) { std::unique_lock<std::mutex> l(exception_mu_); if (exception_) { l.unlock(); for (auto &run_op_future : run_op_futures_) { run_op_future.wait(); } l.lock(); std::exception *exp = exception_.get(); if (dynamic_cast<platform::EOFException *>(exp)) { auto e = *static_cast<platform::EOFException *>(exp); throw e; } else if (dynamic_cast<platform::EnforceNotMet *>(exp)) { auto e = *static_cast<platform::EnforceNotMet *>(exp); throw e; } else { LOG(FATAL) << "Unknown exception."; } } else { continue; } } // 3. Remove the dependency of ready_var. // Find the ready_ops after the ready_var. for (auto ready_var : cur_ready_vars) { pending_vars.erase(ready_var); for (auto *op : ready_var->pending_ops_) { auto &deps = pending_ops[op]; --deps; if (deps == 0) { if (op->IsMultiDeviceTransfer() && strategy_.allow_op_delay_) { delayed_ops.insert(op); } else { ready_ops.insert(op); } } } } } PADDLE_ENFORCE(ready_ops.empty()); // Wait FetchOps. if (!fetch_ops.empty()) { fetch_ops.clear(); } return fetch_data; } void ThreadedSSAGraphExecutor::InsertFetchOps( const std::vector<std::string> &fetch_tensors, std::vector<std::unique_ptr<FetchOpHandle>> *fetch_ops, std::unordered_set<std::unique_ptr<VarHandleBase>> *fetch_dependencies, std::unordered_map<OpHandleBase *, size_t> *pending_ops, std::unordered_set<VarHandleBase *> *pending_vars, BlockingQueue<VarHandleBase *> *ready_vars, FeedFetchList *fetch_data) { std::unordered_map<std::string, std::vector<VarHandleBase *>> fetched_vars; for (auto &fetch_var_name : fetch_tensors) { for (auto &var_map : graph_->vars_) { auto it = var_map.find(fetch_var_name); if (it != var_map.end()) { fetched_vars[fetch_var_name].push_back(it->second.rbegin()->get()); } } } for (size_t i = 0; i < fetch_tensors.size(); ++i) { auto &var_name = fetch_tensors[i]; auto &vars = fetched_vars.at(var_name); auto *op = new FetchOpHandle(fetch_data, i, &local_scopes_); fetch_ops->emplace_back(op); for (auto &p : places_) { op->SetDeviceContext(p, fetch_ctxs_.Get(p)); } for (auto *var : vars) { op->AddInput(var); } auto *fetch_dummy = new DummyVarHandle(); op->AddOutput(fetch_dummy); fetch_dependencies->emplace(fetch_dummy); this->InsertPendingVar(pending_vars, ready_vars, fetch_dummy); this->InsertPendingOp(pending_ops, op); } } void ThreadedSSAGraphExecutor::InsertPendingOp( std::unordered_map<OpHandleBase *, size_t> *pending_ops, OpHandleBase *op_instance) const { pending_ops->insert({op_instance, op_instance->NoDupInputSize()}); } void ThreadedSSAGraphExecutor::InsertPendingVar( std::unordered_set<VarHandleBase *> *pending_vars, BlockingQueue<VarHandleBase *> *ready_vars, VarHandleBase *var) const { pending_vars->insert(var); if (var->generated_op_ == nullptr) { ready_vars->Push(var); } } void ThreadedSSAGraphExecutor::RunOp( BlockingQueue<VarHandleBase *> *ready_var_q, details::OpHandleBase *op) { auto op_run = [ready_var_q, op, this] { try { if (VLOG_IS_ON(10)) { VLOG(10) << op << " " << op->Name() << " : " << op->DebugString(); } op->Run(strategy_.use_cuda_); VLOG(10) << op << " " << op->Name() << " Done "; running_ops_--; ready_var_q->Extend(op->Outputs()); VLOG(10) << op << " " << op->Name() << "Signal posted"; } catch (platform::EOFException ex) { std::lock_guard<std::mutex> l(exception_mu_); // EOFException will not cover up existing EnforceNotMet. if (exception_.get() == nullptr) { exception_.reset(new platform::EOFException(ex)); } } catch (platform::EnforceNotMet ex) { std::lock_guard<std::mutex> l(exception_mu_); exception_.reset(new platform::EnforceNotMet(ex)); } catch (...) { LOG(FATAL) << "Unknown exception catched"; } }; if (pool_) { run_op_futures_.emplace_back(pool_->enqueue(op_run)); } else { op_run(); } } } // namespace details } // namespace framework } // namespace paddle
fix a dead lock bug
fix a dead lock bug
C++
apache-2.0
chengduoZH/Paddle,jacquesqiao/Paddle,tensor-tang/Paddle,jacquesqiao/Paddle,jacquesqiao/Paddle,baidu/Paddle,jacquesqiao/Paddle,reyoung/Paddle,jacquesqiao/Paddle,PaddlePaddle/Paddle,luotao1/Paddle,QiJune/Paddle,chengduoZH/Paddle,PaddlePaddle/Paddle,chengduoZH/Paddle,baidu/Paddle,tensor-tang/Paddle,PaddlePaddle/Paddle,reyoung/Paddle,luotao1/Paddle,luotao1/Paddle,QiJune/Paddle,tensor-tang/Paddle,reyoung/Paddle,luotao1/Paddle,luotao1/Paddle,baidu/Paddle,luotao1/Paddle,chengduoZH/Paddle,PaddlePaddle/Paddle,QiJune/Paddle,PaddlePaddle/Paddle,baidu/Paddle,QiJune/Paddle,reyoung/Paddle,QiJune/Paddle,jacquesqiao/Paddle,tensor-tang/Paddle,luotao1/Paddle,QiJune/Paddle,chengduoZH/Paddle,PaddlePaddle/Paddle,baidu/Paddle,tensor-tang/Paddle,reyoung/Paddle,reyoung/Paddle,PaddlePaddle/Paddle
4196095975bb0778c7cf02d535f60ca80ba81620
Maze/src/maze/proceduralmaze.cpp
Maze/src/maze/proceduralmaze.cpp
#include <algorithm> #include <cstdlib> #include <iostream> #include <ctime> #include "proceduralmaze.h" ProceduralMaze::ProceduralMaze(int width, int height) { std::srand(std::time(NULL)); this->width = width % 2 == 0 ? width + 1 : width; this->height = height % 2 == 0 ? height + 1 : height; this->grid = std::map<std::pair<int, int>, Tile>(); clearGrid(); } void ProceduralMaze::generate() { clearGrid(); int x = std::rand() % (width - 2) + 1; int y = std::rand() % (height - 2) + 1; // Odd start numbers to make sure we have borders x = x % 2 == 0 ? x + 1 : x; y = y % 2 == 0 ? y + 1 : y; std::pair<int, int> cell_pos = std::make_pair(x, y); grid[cell_pos] = Tile::EMPTY; std::vector<std::pair<int, int>> frontiers = getAdjCells(cell_pos, Tile::WALL, 2); while (!frontiers.empty()) { int index = std::rand() % frontiers.size(); cell_pos = frontiers[index]; frontiers.erase(frontiers.begin() + index); std::vector<std::pair<int, int>> neighboors = getAdjCells(cell_pos, Tile::EMPTY, 2); if (neighboors.empty()) { continue; } index = std::rand() % neighboors.size(); std::pair<int, int> neighboor = neighboors[index]; int passage_x = (neighboor.first - cell_pos.first)/2 + cell_pos.first; int passage_y = (neighboor.second - cell_pos.second)/2 + cell_pos.second; grid[std::make_pair(passage_x, passage_y)] = Tile::EMPTY; grid[cell_pos] = Tile::EMPTY; for (auto value : getAdjCells(cell_pos, Tile::WALL, 2)) { if (std::find(frontiers.begin(), frontiers.end(), value) == frontiers.end()) { frontiers.push_back(value); } } } std::pair<int, int> entry_pos = std::make_pair(1, 0); grid[entry_pos] = Tile::ENTRY; std::pair<int, int> exit_pos = std::make_pair(width - 2, height - 1); grid[exit_pos] = Tile::EXIT; generateLight(); } void ProceduralMaze::generateLight() { } void ProceduralMaze::clearGrid() { for (int x = 0; x < width; ++x) { for (int y = 0; y < height; ++y) { grid[std::make_pair(x, y)] = Tile::WALL; } } } std::vector<std::pair<int, int>> ProceduralMaze::getDiagCells(std::pair<int, int> center) { std::vector<std::pair<int, int>> neighboors = std::vector<std::pair<int, int>>(); for (int x = -1; x <= 1; x = x + 2) { for (int y = -1; y <= 1; y = y + 2) { try { std::pair<int, int> n_cell = std::make_pair(center.first + x, center.second + y); if (grid.at(n_cell) == Tile::EMPTY) { neighboors.push_back(n_cell); } } catch (std::out_of_range) {} } } return neighboors; } std::vector<std::pair<int, int>> ProceduralMaze::getAdjCells(std::pair<int, int> center, Tile tile_state, int dist) { std::vector<std::pair<int, int>> pos = { std::make_pair(center.first + dist, center.second), std::make_pair(center.first - dist, center.second), std::make_pair(center.first, center.second + dist), std::make_pair(center.first, center.second - dist), }; std::vector<std::pair<int, int>> result = std::vector<std::pair<int, int>>(); for (auto adj_pos : pos) { try { switch (grid.at(adj_pos)) { case Tile::WALL: if (tile_state == Tile::WALL) { result.push_back(adj_pos); } break; case Tile::LIGHT: case Tile::EMPTY: if (tile_state != Tile::WALL) { result.push_back(adj_pos); } break; default: break; } } catch (std::out_of_range) { } } return result; } void ProceduralMaze::print() { for (int y = 0; y < height; ++y) { for (int x = 0; x < width; ++x) { char c = ' '; switch (grid[std::make_pair(x, y)]) { case Tile::ENTRY: c = 'E'; break; case Tile::EXIT: c = 'S'; break; case Tile::WALL: c = '#'; break; case Tile::LIGHT: c = ' '; break; default: break; } std::cout << c; } std::cout << std::endl; } } int main(int argc, char* argv[]) { ProceduralMaze* maze = new ProceduralMaze(15, 15); maze->generate(); maze->print(); return 0; }
#include <algorithm> #include <cstdlib> #include <iostream> #include <ctime> #include "proceduralmaze.h" ProceduralMaze::ProceduralMaze(int width, int height) { std::srand(std::time(NULL)); this->width = width % 2 == 0 ? width + 1 : width; this->height = height % 2 == 0 ? height + 1 : height; clearGrid(); } void ProceduralMaze::generate() { clearGrid(); int x = std::rand() % (width - 2) + 1; int y = std::rand() % (height - 2) + 1; // Odd start numbers to make sure we have borders x = x % 2 == 0 ? x + 1 : x; y = y % 2 == 0 ? y + 1 : y; std::pair<int, int> cell_pos = std::make_pair(x, y); grid[cell_pos] = Tile::EMPTY; std::vector<std::pair<int, int>> frontiers = getAdjCells(cell_pos, Tile::WALL, 2); while (!frontiers.empty()) { int index = std::rand() % frontiers.size(); cell_pos = frontiers[index]; frontiers.erase(frontiers.begin() + index); std::vector<std::pair<int, int>> neighboors = getAdjCells(cell_pos, Tile::EMPTY, 2); if (neighboors.empty()) { continue; } index = std::rand() % neighboors.size(); std::pair<int, int> neighboor = neighboors[index]; int passage_x = (neighboor.first - cell_pos.first)/2 + cell_pos.first; int passage_y = (neighboor.second - cell_pos.second)/2 + cell_pos.second; grid[std::make_pair(passage_x, passage_y)] = Tile::EMPTY; grid[cell_pos] = Tile::EMPTY; for (auto value : getAdjCells(cell_pos, Tile::WALL, 2)) { if (std::find(frontiers.begin(), frontiers.end(), value) == frontiers.end()) { frontiers.push_back(value); } } } std::pair<int, int> entry_pos = std::make_pair(1, 0); grid[entry_pos] = Tile::ENTRY; std::pair<int, int> exit_pos = std::make_pair(width - 2, height - 1); grid[exit_pos] = Tile::EXIT; generateLight(); } void ProceduralMaze::generateLight() { std::vector<std::pair<int, int>> check_stack; std::vector<std::pair<int, int>> visited_cells; std::vector<std::pair<int, int>> illuminated_cells; check_stack.push_back(std::make_pair(1, 1)); int steps = 0; while (!check_stack.empty()) { std::pair<int, int> check_pos = check_stack.back(); check_stack.pop_back(); visited_cells.push_back(check_pos); auto neighboors = getAdjCells(check_pos, Tile::EMPTY, 1); for (auto n_pos : neighboors) { if (std::find(visited_cells.begin(), visited_cells.end(), n_pos) == visited_cells.end()) { check_stack.push_back(n_pos); } } steps++; if (steps < 4) { continue; } if (std::find(illuminated_cells.begin(), illuminated_cells.end(), check_pos) == illuminated_cells.end()) { auto diag_cells = getDiagCells(check_pos); neighboors.insert(neighboors.end(), diag_cells.begin(), diag_cells.end()); auto far_neighboors = getAdjCells(check_pos, Tile::EMPTY, 2); for (auto it = far_neighboors.rbegin(); it != far_neighboors.rend(); ++it) { int passage_x = ((*it).first - check_pos.first)/2 + check_pos.first; int passage_y = ((*it).second - check_pos.second)/2 + check_pos.second; std::pair<int, int> passage = std::make_pair(passage_x, passage_y); if (std::find(neighboors.begin(), neighboors.end(), passage) != neighboors.end()) { neighboors.push_back(*it); } } bool intersect_illuminated_cell = false; for (auto neighboor : neighboors) { if (std::find(illuminated_cells.begin(), illuminated_cells.end(), neighboor) != illuminated_cells.end()) { intersect_illuminated_cell = true; } } if (intersect_illuminated_cell) { continue; } grid[check_pos] = Tile::LIGHT; illuminated_cells.insert(illuminated_cells.end(), neighboors.begin(), neighboors.end()); illuminated_cells.push_back(check_pos); steps = 0; } } } void ProceduralMaze::clearGrid() { for (int x = 0; x < width; ++x) { for (int y = 0; y < height; ++y) { grid[std::make_pair(x, y)] = Tile::WALL; } } } std::vector<std::pair<int, int>> ProceduralMaze::getDiagCells(std::pair<int, int> center) { std::vector<std::pair<int, int>> neighboors; for (int x = -1; x <= 1; x = x + 2) { for (int y = -1; y <= 1; y = y + 2) { try { std::pair<int, int> n_cell = std::make_pair(center.first + x, center.second + y); if (grid.at(n_cell) == Tile::EMPTY) { neighboors.push_back(n_cell); } } catch (std::out_of_range) {} } } return neighboors; } std::vector<std::pair<int, int>> ProceduralMaze::getAdjCells(std::pair<int, int> center, Tile tile_state, int dist) { std::vector<std::pair<int, int>> pos = { std::make_pair(center.first, center.second - dist), std::make_pair(center.first + dist, center.second), std::make_pair(center.first, center.second + dist), std::make_pair(center.first - dist, center.second), }; std::vector<std::pair<int, int>> result = std::vector<std::pair<int, int>>(); for (auto adj_pos : pos) { try { switch (grid.at(adj_pos)) { case Tile::WALL: if (tile_state == Tile::WALL) { result.push_back(adj_pos); } break; case Tile::LIGHT: case Tile::EMPTY: if (tile_state != Tile::WALL) { result.push_back(adj_pos); } break; default: break; } } catch (std::out_of_range) { } } return result; } void ProceduralMaze::print() { for (int y = 0; y < height; ++y) { for (int x = 0; x < width; ++x) { char c = ' '; switch (grid[std::make_pair(x, y)]) { case Tile::ENTRY: c = 'E'; break; case Tile::EXIT: c = 'S'; break; case Tile::WALL: c = '#'; break; case Tile::EMPTY: c = ' '; break; case Tile::LIGHT: c = '.'; break; default: break; } std::cout << c; } std::cout << std::endl; } } int main(int argc, char* argv[]) { ProceduralMaze* maze = new ProceduralMaze(15, 15); maze->generate(); maze->print(); return 0; }
add ProceDuralMaze::generateLight
add ProceDuralMaze::generateLight
C++
mit
gfceccon/Maze,gfceccon/Maze
34b697cd04e7d645f8bf95d5c1a2dfeb623181f1
src/mem/packet.hh
src/mem/packet.hh
/* * Copyright (c) 2006 The Regents of The University of Michigan * 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 holders 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. * * Authors: Ron Dreslinski * Steve Reinhardt * Ali Saidi */ /** * @file * Declaration of the Packet class. */ #ifndef __MEM_PACKET_HH__ #define __MEM_PACKET_HH__ #include "mem/request.hh" #include "sim/host.hh" #include "sim/root.hh" #include <list> #include <cassert> struct Packet; typedef Packet* PacketPtr; typedef uint8_t* PacketDataPtr; typedef std::list<PacketPtr> PacketList; //Coherence Flags #define NACKED_LINE 1 << 0 #define SATISFIED 1 << 1 #define SHARED_LINE 1 << 2 #define CACHE_LINE_FILL 1 << 3 #define COMPRESSED 1 << 4 #define NO_ALLOCATE 1 << 5 #define SNOOP_COMMIT 1 << 6 //For statistics we need max number of commands, hard code it at //20 for now. @todo fix later #define NUM_MEM_CMDS 1 << 9 /** * A Packet is used to encapsulate a transfer between two objects in * the memory system (e.g., the L1 and L2 cache). (In contrast, a * single Request travels all the way from the requester to the * ultimate destination and back, possibly being conveyed by several * different Packets along the way.) */ class Packet { public: /** Temporary FLAGS field until cache gets working, this should be in coherence/sender state. */ uint64_t flags; private: /** A pointer to the data being transfered. It can be differnt * sizes at each level of the heirarchy so it belongs in the * packet, not request. This may or may not be populated when a * responder recieves the packet. If not populated it memory * should be allocated. */ PacketDataPtr data; /** Is the data pointer set to a value that shouldn't be freed * when the packet is destroyed? */ bool staticData; /** The data pointer points to a value that should be freed when * the packet is destroyed. */ bool dynamicData; /** the data pointer points to an array (thus delete [] ) needs to * be called on it rather than simply delete.*/ bool arrayData; /** The address of the request. This address could be virtual or * physical, depending on the system configuration. */ Addr addr; /** The size of the request or transfer. */ int size; /** Device address (e.g., bus ID) of the source of the * transaction. The source is not responsible for setting this * field; it is set implicitly by the interconnect when the * packet * is first sent. */ short src; /** Device address (e.g., bus ID) of the destination of the * transaction. The special value Broadcast indicates that the * packet should be routed based on its address. This field is * initialized in the constructor and is thus always valid * (unlike * addr, size, and src). */ short dest; /** Are the 'addr' and 'size' fields valid? */ bool addrSizeValid; /** Is the 'src' field valid? */ bool srcValid; public: /** Used to calculate latencies for each packet.*/ Tick time; /** The special destination address indicating that the packet * should be routed based on its address. */ static const short Broadcast = -1; /** A pointer to the original request. */ RequestPtr req; /** A virtual base opaque structure used to hold coherence-related * state. A specific subclass would be derived from this to * carry state specific to a particular coherence protocol. */ class CoherenceState { public: virtual ~CoherenceState() {} }; /** This packet's coherence state. Caches should use * dynamic_cast<> to cast to the state appropriate for the * system's coherence protocol. */ CoherenceState *coherence; /** A virtual base opaque structure used to hold state associated * with the packet but specific to the sending device (e.g., an * MSHR). A pointer to this state is returned in the packet's * response so that the sender can quickly look up the state * needed to process it. A specific subclass would be derived * from this to carry state specific to a particular sending * device. */ class SenderState { public: virtual ~SenderState() {} }; /** This packet's sender state. Devices should use dynamic_cast<> * to cast to the state appropriate to the sender. */ SenderState *senderState; private: /** List of command attributes. */ enum CommandAttribute { IsRead = 1 << 0, IsWrite = 1 << 1, IsPrefetch = 1 << 2, IsInvalidate = 1 << 3, IsRequest = 1 << 4, IsResponse = 1 << 5, NeedsResponse = 1 << 6, IsSWPrefetch = 1 << 7, IsHWPrefetch = 1 << 8, HasData = 1 << 9 }; public: /** List of all commands associated with a packet. */ enum Command { InvalidCmd = 0, ReadReq = IsRead | IsRequest | NeedsResponse, WriteReq = IsWrite | IsRequest | NeedsResponse,// | HasData, WriteReqNoAck = IsWrite | IsRequest,// | HasData, ReadResp = IsRead | IsResponse | NeedsResponse,// | HasData, WriteResp = IsWrite | IsResponse | NeedsResponse, Writeback = IsWrite | IsRequest,// | HasData, SoftPFReq = IsRead | IsRequest | IsSWPrefetch | NeedsResponse, HardPFReq = IsRead | IsRequest | IsHWPrefetch | NeedsResponse, SoftPFResp = IsRead | IsResponse | IsSWPrefetch | NeedsResponse,// | HasData, HardPFResp = IsRead | IsResponse | IsHWPrefetch | NeedsResponse,// | HasData, InvalidateReq = IsInvalidate | IsRequest, WriteInvalidateReq = IsWrite | IsInvalidate | IsRequest,// | HasData, UpgradeReq = IsInvalidate | IsRequest | NeedsResponse, UpgradeResp = IsInvalidate | IsResponse | NeedsResponse, ReadExReq = IsRead | IsInvalidate | IsRequest | NeedsResponse, ReadExResp = IsRead | IsInvalidate | IsResponse | NeedsResponse,// | HasData }; /** Return the string name of the cmd field (for debugging and * tracing). */ const std::string &cmdString() const; /** Reutrn the string to a cmd given by idx. */ const std::string &cmdIdxToString(Command idx); /** Return the index of this command. */ inline int cmdToIndex() const { return (int) cmd; } /** The command field of the packet. */ Command cmd; bool isRead() { return (cmd & IsRead) != 0; } bool isWrite() { return (cmd & IsWrite) != 0; } bool isRequest() { return (cmd & IsRequest) != 0; } bool isResponse() { return (cmd & IsResponse) != 0; } bool needsResponse() { return (cmd & NeedsResponse) != 0; } bool isInvalidate() { return (cmd & IsInvalidate) != 0; } bool hasData() { return (cmd & HasData) != 0; } bool isCacheFill() { return (flags & CACHE_LINE_FILL) != 0; } bool isNoAllocate() { return (flags & NO_ALLOCATE) != 0; } bool isCompressed() { return (flags & COMPRESSED) != 0; } bool nic_pkt() { assert("Unimplemented\n" && 0); return false; } /** Possible results of a packet's request. */ enum Result { Success, BadAddress, Nacked, Unknown }; /** The result of this packet's request. */ Result result; /** Accessor function that returns the source index of the packet. */ short getSrc() const { assert(srcValid); return src; } void setSrc(short _src) { src = _src; srcValid = true; } /** Accessor function that returns the destination index of the packet. */ short getDest() const { return dest; } void setDest(short _dest) { dest = _dest; } Addr getAddr() const { assert(addrSizeValid); return addr; } int getSize() const { assert(addrSizeValid); return size; } Addr getOffset(int blkSize) const { return addr & (Addr)(blkSize - 1); } void addrOverride(Addr newAddr) { assert(addrSizeValid); addr = newAddr; } void cmdOverride(Command newCmd) { cmd = newCmd; } /** Constructor. Note that a Request object must be constructed * first, but the Requests's physical address and size fields * need not be valid. The command and destination addresses * must be supplied. */ Packet(Request *_req, Command _cmd, short _dest) : data(NULL), staticData(false), dynamicData(false), arrayData(false), addr(_req->paddr), size(_req->size), dest(_dest), addrSizeValid(_req->validPaddr), srcValid(false), req(_req), coherence(NULL), senderState(NULL), cmd(_cmd), result(Unknown) { flags = 0; time = curTick; } /** Alternate constructor if you are trying to create a packet with * a request that is for a whole block, not the address from the req. * this allows for overriding the size/addr of the req.*/ Packet(Request *_req, Command _cmd, short _dest, int _blkSize) : data(NULL), staticData(false), dynamicData(false), arrayData(false), addr(_req->paddr & ~(_blkSize - 1)), size(_blkSize), dest(_dest), addrSizeValid(_req->validPaddr), srcValid(false), req(_req), coherence(NULL), senderState(NULL), cmd(_cmd), result(Unknown) { flags = 0; time = curTick; } /** Destructor. */ ~Packet() { deleteData(); } /** Reinitialize packet address and size from the associated * Request object, and reset other fields that may have been * modified by a previous transaction. Typically called when a * statically allocated Request/Packet pair is reused for * multiple transactions. */ void reinitFromRequest() { assert(req->validPaddr); addr = req->paddr; size = req->size; time = req->time; addrSizeValid = true; result = Unknown; if (dynamicData) { deleteData(); dynamicData = false; arrayData = false; } } /** Take a request packet and modify it in place to be suitable * for returning as a response to that request. Used for timing * accesses only. For atomic and functional accesses, the * request packet is always implicitly passed back *without* * modifying the command or destination fields, so this function * should not be called. */ void makeTimingResponse() { assert(needsResponse()); assert(isRequest()); int icmd = (int)cmd; icmd &= ~(IsRequest); icmd |= IsResponse; cmd = (Command)icmd; dest = src; srcValid = false; } /** Take a request packet that has been returned as NACKED and modify it so * that it can be sent out again. Only packets that need a response can be * NACKED, so verify that that is true. */ void reinitNacked() { assert(needsResponse() && result == Nacked); dest = Broadcast; result = Unknown; } /** Set the data pointer to the following value that should not be freed. */ template <typename T> void dataStatic(T *p); /** Set the data pointer to a value that should have delete [] called on it. */ template <typename T> void dataDynamicArray(T *p); /** set the data pointer to a value that should have delete called on it. */ template <typename T> void dataDynamic(T *p); /** return the value of what is pointed to in the packet. */ template <typename T> T get(); /** get a pointer to the data ptr. */ template <typename T> T* getPtr(); /** set the value in the data pointer to v. */ template <typename T> void set(T v); /** delete the data pointed to in the data pointer. Ok to call to matter how * data was allocted. */ void deleteData(); /** If there isn't data in the packet, allocate some. */ void allocate(); /** Do the packet modify the same addresses. */ bool intersect(Packet *p); }; bool fixPacket(Packet *func, Packet *timing); #endif //__MEM_PACKET_HH
/* * Copyright (c) 2006 The Regents of The University of Michigan * 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 holders 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. * * Authors: Ron Dreslinski * Steve Reinhardt * Ali Saidi */ /** * @file * Declaration of the Packet class. */ #ifndef __MEM_PACKET_HH__ #define __MEM_PACKET_HH__ #include "mem/request.hh" #include "sim/host.hh" #include "sim/root.hh" #include <list> #include <cassert> struct Packet; typedef Packet* PacketPtr; typedef uint8_t* PacketDataPtr; typedef std::list<PacketPtr> PacketList; //Coherence Flags #define NACKED_LINE 1 << 0 #define SATISFIED 1 << 1 #define SHARED_LINE 1 << 2 #define CACHE_LINE_FILL 1 << 3 #define COMPRESSED 1 << 4 #define NO_ALLOCATE 1 << 5 #define SNOOP_COMMIT 1 << 6 /** * A Packet is used to encapsulate a transfer between two objects in * the memory system (e.g., the L1 and L2 cache). (In contrast, a * single Request travels all the way from the requester to the * ultimate destination and back, possibly being conveyed by several * different Packets along the way.) */ class Packet { public: /** Temporary FLAGS field until cache gets working, this should be in coherence/sender state. */ uint64_t flags; private: /** A pointer to the data being transfered. It can be differnt * sizes at each level of the heirarchy so it belongs in the * packet, not request. This may or may not be populated when a * responder recieves the packet. If not populated it memory * should be allocated. */ PacketDataPtr data; /** Is the data pointer set to a value that shouldn't be freed * when the packet is destroyed? */ bool staticData; /** The data pointer points to a value that should be freed when * the packet is destroyed. */ bool dynamicData; /** the data pointer points to an array (thus delete [] ) needs to * be called on it rather than simply delete.*/ bool arrayData; /** The address of the request. This address could be virtual or * physical, depending on the system configuration. */ Addr addr; /** The size of the request or transfer. */ int size; /** Device address (e.g., bus ID) of the source of the * transaction. The source is not responsible for setting this * field; it is set implicitly by the interconnect when the * packet * is first sent. */ short src; /** Device address (e.g., bus ID) of the destination of the * transaction. The special value Broadcast indicates that the * packet should be routed based on its address. This field is * initialized in the constructor and is thus always valid * (unlike * addr, size, and src). */ short dest; /** Are the 'addr' and 'size' fields valid? */ bool addrSizeValid; /** Is the 'src' field valid? */ bool srcValid; public: /** Used to calculate latencies for each packet.*/ Tick time; /** The special destination address indicating that the packet * should be routed based on its address. */ static const short Broadcast = -1; /** A pointer to the original request. */ RequestPtr req; /** A virtual base opaque structure used to hold coherence-related * state. A specific subclass would be derived from this to * carry state specific to a particular coherence protocol. */ class CoherenceState { public: virtual ~CoherenceState() {} }; /** This packet's coherence state. Caches should use * dynamic_cast<> to cast to the state appropriate for the * system's coherence protocol. */ CoherenceState *coherence; /** A virtual base opaque structure used to hold state associated * with the packet but specific to the sending device (e.g., an * MSHR). A pointer to this state is returned in the packet's * response so that the sender can quickly look up the state * needed to process it. A specific subclass would be derived * from this to carry state specific to a particular sending * device. */ class SenderState { public: virtual ~SenderState() {} }; /** This packet's sender state. Devices should use dynamic_cast<> * to cast to the state appropriate to the sender. */ SenderState *senderState; private: /** List of command attributes. */ // If you add a new CommandAttribute, make sure to increase NUM_MEM_CMDS // as well. enum CommandAttribute { IsRead = 1 << 0, IsWrite = 1 << 1, IsPrefetch = 1 << 2, IsInvalidate = 1 << 3, IsRequest = 1 << 4, IsResponse = 1 << 5, NeedsResponse = 1 << 6, IsSWPrefetch = 1 << 7, IsHWPrefetch = 1 << 8, HasData = 1 << 9 }; //For statistics we need max number of commands, hard code it at //20 for now. @todo fix later #define NUM_MEM_CMDS 1 << 10 public: /** List of all commands associated with a packet. */ enum Command { InvalidCmd = 0, ReadReq = IsRead | IsRequest | NeedsResponse, WriteReq = IsWrite | IsRequest | NeedsResponse | HasData, WriteReqNoAck = IsWrite | IsRequest | HasData, ReadResp = IsRead | IsResponse | NeedsResponse | HasData, WriteResp = IsWrite | IsResponse | NeedsResponse, Writeback = IsWrite | IsRequest | HasData, SoftPFReq = IsRead | IsRequest | IsSWPrefetch | NeedsResponse, HardPFReq = IsRead | IsRequest | IsHWPrefetch | NeedsResponse, SoftPFResp = IsRead | IsResponse | IsSWPrefetch | NeedsResponse | HasData, HardPFResp = IsRead | IsResponse | IsHWPrefetch | NeedsResponse | HasData, InvalidateReq = IsInvalidate | IsRequest, WriteInvalidateReq = IsWrite | IsInvalidate | IsRequest | HasData, UpgradeReq = IsInvalidate | IsRequest | NeedsResponse, UpgradeResp = IsInvalidate | IsResponse | NeedsResponse, ReadExReq = IsRead | IsInvalidate | IsRequest | NeedsResponse, ReadExResp = IsRead | IsInvalidate | IsResponse | NeedsResponse | HasData }; /** Return the string name of the cmd field (for debugging and * tracing). */ const std::string &cmdString() const; /** Reutrn the string to a cmd given by idx. */ const std::string &cmdIdxToString(Command idx); /** Return the index of this command. */ inline int cmdToIndex() const { return (int) cmd; } /** The command field of the packet. */ Command cmd; bool isRead() { return (cmd & IsRead) != 0; } bool isWrite() { return (cmd & IsWrite) != 0; } bool isRequest() { return (cmd & IsRequest) != 0; } bool isResponse() { return (cmd & IsResponse) != 0; } bool needsResponse() { return (cmd & NeedsResponse) != 0; } bool isInvalidate() { return (cmd & IsInvalidate) != 0; } bool hasData() { return (cmd & HasData) != 0; } bool isCacheFill() { return (flags & CACHE_LINE_FILL) != 0; } bool isNoAllocate() { return (flags & NO_ALLOCATE) != 0; } bool isCompressed() { return (flags & COMPRESSED) != 0; } bool nic_pkt() { assert("Unimplemented\n" && 0); return false; } /** Possible results of a packet's request. */ enum Result { Success, BadAddress, Nacked, Unknown }; /** The result of this packet's request. */ Result result; /** Accessor function that returns the source index of the packet. */ short getSrc() const { assert(srcValid); return src; } void setSrc(short _src) { src = _src; srcValid = true; } /** Accessor function that returns the destination index of the packet. */ short getDest() const { return dest; } void setDest(short _dest) { dest = _dest; } Addr getAddr() const { assert(addrSizeValid); return addr; } int getSize() const { assert(addrSizeValid); return size; } Addr getOffset(int blkSize) const { return addr & (Addr)(blkSize - 1); } void addrOverride(Addr newAddr) { assert(addrSizeValid); addr = newAddr; } void cmdOverride(Command newCmd) { cmd = newCmd; } /** Constructor. Note that a Request object must be constructed * first, but the Requests's physical address and size fields * need not be valid. The command and destination addresses * must be supplied. */ Packet(Request *_req, Command _cmd, short _dest) : data(NULL), staticData(false), dynamicData(false), arrayData(false), addr(_req->paddr), size(_req->size), dest(_dest), addrSizeValid(_req->validPaddr), srcValid(false), req(_req), coherence(NULL), senderState(NULL), cmd(_cmd), result(Unknown) { flags = 0; time = curTick; } /** Alternate constructor if you are trying to create a packet with * a request that is for a whole block, not the address from the req. * this allows for overriding the size/addr of the req.*/ Packet(Request *_req, Command _cmd, short _dest, int _blkSize) : data(NULL), staticData(false), dynamicData(false), arrayData(false), addr(_req->paddr & ~(_blkSize - 1)), size(_blkSize), dest(_dest), addrSizeValid(_req->validPaddr), srcValid(false), req(_req), coherence(NULL), senderState(NULL), cmd(_cmd), result(Unknown) { flags = 0; time = curTick; } /** Destructor. */ ~Packet() { deleteData(); } /** Reinitialize packet address and size from the associated * Request object, and reset other fields that may have been * modified by a previous transaction. Typically called when a * statically allocated Request/Packet pair is reused for * multiple transactions. */ void reinitFromRequest() { assert(req->validPaddr); addr = req->paddr; size = req->size; time = req->time; addrSizeValid = true; result = Unknown; if (dynamicData) { deleteData(); dynamicData = false; arrayData = false; } } /** Take a request packet and modify it in place to be suitable * for returning as a response to that request. Used for timing * accesses only. For atomic and functional accesses, the * request packet is always implicitly passed back *without* * modifying the command or destination fields, so this function * should not be called. */ void makeTimingResponse() { assert(needsResponse()); assert(isRequest()); int icmd = (int)cmd; icmd &= ~(IsRequest); icmd |= IsResponse; cmd = (Command)icmd; dest = src; srcValid = false; } /** Take a request packet that has been returned as NACKED and modify it so * that it can be sent out again. Only packets that need a response can be * NACKED, so verify that that is true. */ void reinitNacked() { assert(needsResponse() && result == Nacked); dest = Broadcast; result = Unknown; } /** Set the data pointer to the following value that should not be freed. */ template <typename T> void dataStatic(T *p); /** Set the data pointer to a value that should have delete [] called on it. */ template <typename T> void dataDynamicArray(T *p); /** set the data pointer to a value that should have delete called on it. */ template <typename T> void dataDynamic(T *p); /** return the value of what is pointed to in the packet. */ template <typename T> T get(); /** get a pointer to the data ptr. */ template <typename T> T* getPtr(); /** set the value in the data pointer to v. */ template <typename T> void set(T v); /** delete the data pointed to in the data pointer. Ok to call to matter how * data was allocted. */ void deleteData(); /** If there isn't data in the packet, allocate some. */ void allocate(); /** Do the packet modify the same addresses. */ bool intersect(Packet *p); }; bool fixPacket(Packet *func, Packet *timing); #endif //__MEM_PACKET_HH
Add in HasData, and move the define of NUM_MEM_CMDS to a more visible location.
Add in HasData, and move the define of NUM_MEM_CMDS to a more visible location. --HG-- extra : convert_revision : 4379efe892ca0a39363ee04009e1bbb8c8f77afa
C++
bsd-3-clause
aclifton/cpeg853-gem5,SanchayanMaity/gem5,HwisooSo/gemV-update,powerjg/gem5-ci-test,Weil0ng/gem5,yb-kim/gemV,samueldotj/TeeRISC-Simulator,KuroeKurose/gem5,kaiyuanl/gem5,HwisooSo/gemV-update,austinharris/gem5-riscv,austinharris/gem5-riscv,gedare/gem5,TUD-OS/gem5-dtu,zlfben/gem5,gem5/gem5,aclifton/cpeg853-gem5,rallylee/gem5,SanchayanMaity/gem5,powerjg/gem5-ci-test,sobercoder/gem5,KuroeKurose/gem5,rallylee/gem5,markoshorro/gem5,rallylee/gem5,gedare/gem5,powerjg/gem5-ci-test,joerocklin/gem5,joerocklin/gem5,cancro7/gem5,cancro7/gem5,zlfben/gem5,KuroeKurose/gem5,joerocklin/gem5,qizenguf/MLC-STT,rjschof/gem5,austinharris/gem5-riscv,briancoutinho0905/2dsampling,briancoutinho0905/2dsampling,briancoutinho0905/2dsampling,KuroeKurose/gem5,gem5/gem5,markoshorro/gem5,aclifton/cpeg853-gem5,markoshorro/gem5,qizenguf/MLC-STT,rjschof/gem5,samueldotj/TeeRISC-Simulator,aclifton/cpeg853-gem5,kaiyuanl/gem5,SanchayanMaity/gem5,briancoutinho0905/2dsampling,powerjg/gem5-ci-test,TUD-OS/gem5-dtu,SanchayanMaity/gem5,zlfben/gem5,sobercoder/gem5,qizenguf/MLC-STT,Weil0ng/gem5,powerjg/gem5-ci-test,kaiyuanl/gem5,yb-kim/gemV,markoshorro/gem5,gem5/gem5,HwisooSo/gemV-update,TUD-OS/gem5-dtu,rallylee/gem5,gedare/gem5,austinharris/gem5-riscv,qizenguf/MLC-STT,yb-kim/gemV,HwisooSo/gemV-update,KuroeKurose/gem5,aclifton/cpeg853-gem5,joerocklin/gem5,gedare/gem5,SanchayanMaity/gem5,qizenguf/MLC-STT,zlfben/gem5,zlfben/gem5,HwisooSo/gemV-update,joerocklin/gem5,sobercoder/gem5,aclifton/cpeg853-gem5,TUD-OS/gem5-dtu,markoshorro/gem5,cancro7/gem5,samueldotj/TeeRISC-Simulator,briancoutinho0905/2dsampling,rjschof/gem5,austinharris/gem5-riscv,markoshorro/gem5,rjschof/gem5,yb-kim/gemV,yb-kim/gemV,Weil0ng/gem5,cancro7/gem5,yb-kim/gemV,kaiyuanl/gem5,gedare/gem5,gem5/gem5,cancro7/gem5,rallylee/gem5,kaiyuanl/gem5,rjschof/gem5,samueldotj/TeeRISC-Simulator,qizenguf/MLC-STT,cancro7/gem5,yb-kim/gemV,austinharris/gem5-riscv,HwisooSo/gemV-update,HwisooSo/gemV-update,joerocklin/gem5,KuroeKurose/gem5,samueldotj/TeeRISC-Simulator,gem5/gem5,gem5/gem5,sobercoder/gem5,zlfben/gem5,Weil0ng/gem5,Weil0ng/gem5,powerjg/gem5-ci-test,joerocklin/gem5,SanchayanMaity/gem5,austinharris/gem5-riscv,Weil0ng/gem5,TUD-OS/gem5-dtu,sobercoder/gem5,briancoutinho0905/2dsampling,markoshorro/gem5,TUD-OS/gem5-dtu,SanchayanMaity/gem5,samueldotj/TeeRISC-Simulator,zlfben/gem5,rjschof/gem5,yb-kim/gemV,qizenguf/MLC-STT,cancro7/gem5,powerjg/gem5-ci-test,Weil0ng/gem5,aclifton/cpeg853-gem5,kaiyuanl/gem5,briancoutinho0905/2dsampling,TUD-OS/gem5-dtu,samueldotj/TeeRISC-Simulator,sobercoder/gem5,gedare/gem5,gedare/gem5,joerocklin/gem5,kaiyuanl/gem5,rallylee/gem5,rjschof/gem5,KuroeKurose/gem5,sobercoder/gem5,gem5/gem5,rallylee/gem5
d5482a6a30b6619699684f307039337a00d4f101
src/core/kext/RemapFunc/common/DependingPressingPeriodKeyToKey.cpp
src/core/kext/RemapFunc/common/DependingPressingPeriodKeyToKey.cpp
#include <IOKit/IOLib.h> #include "Config.hpp" #include "DependingPressingPeriodKeyToKey.hpp" #include "IOLogWrapper.hpp" #include "KeyboardRepeat.hpp" #include "RemapClass.hpp" namespace org_pqrs_Karabiner { namespace RemapFunc { TimerWrapper DependingPressingPeriodKeyToKey::fire_timer_; DependingPressingPeriodKeyToKey* DependingPressingPeriodKeyToKey::target_ = NULL; DependingPressingPeriodKeyToKey::PeriodMS::PeriodMS(void) : mode_(Mode::NONE) { for (size_t m = 0; m < Mode::__END__; ++m) { for (size_t t = 0; t < Type::__END__; ++t) { overwritten_value_[m][t] = -1; } } } void DependingPressingPeriodKeyToKey::PeriodMS::set(PeriodMS::Mode::Value newval) { mode_ = newval; } unsigned int DependingPressingPeriodKeyToKey::PeriodMS::get(PeriodMS::Type::Value type) { if (overwritten_value_[mode_][type] >= 0) { return overwritten_value_[mode_][type]; } switch (mode_) { case Mode::HOLDING_KEY_TO_KEY: switch (type) { case Type::SHORT_PERIOD: return Config::get_holdingkeytokey_wait(); case Type::LONG_LONG_PERIOD: return 0; case Type::PRESSING_TARGET_KEY_ONLY: return 0; case Type::__END__: return 0; } case Mode::KEY_OVERLAID_MODIFIER: switch (type) { case Type::SHORT_PERIOD: return Config::get_keyoverlaidmodifier_initial_modifier_wait(); case Type::LONG_LONG_PERIOD: return 0; case Type::PRESSING_TARGET_KEY_ONLY: return Config::get_keyoverlaidmodifier_timeout(); case Type::__END__: return 0; } case Mode::KEY_OVERLAID_MODIFIER_WITH_REPEAT: switch (type) { case Type::SHORT_PERIOD: return Config::get_keyoverlaidmodifier_initial_modifier_wait(); case Type::LONG_LONG_PERIOD: return Config::get_keyoverlaidmodifier_initial_wait(); case Type::PRESSING_TARGET_KEY_ONLY: return Config::get_keyoverlaidmodifier_timeout(); case Type::__END__: return 0; } case Mode::NONE: case Mode::__END__: IOLOG_ERROR("Invalid DependingPressingPeriodKeyToKey::PeriodMS::get\n"); return 0; } return 0; } bool DependingPressingPeriodKeyToKey::PeriodMS::enabled(PeriodMS::Type::Value type) { switch (mode_) { case Mode::HOLDING_KEY_TO_KEY: switch (type) { case Type::SHORT_PERIOD: return true; case Type::LONG_LONG_PERIOD: return false; case Type::PRESSING_TARGET_KEY_ONLY: return false; case Type::__END__: return false; } case Mode::KEY_OVERLAID_MODIFIER: switch (type) { case Type::SHORT_PERIOD: return true; case Type::LONG_LONG_PERIOD: return false; case Type::PRESSING_TARGET_KEY_ONLY: return true; case Type::__END__: return false; } case Mode::KEY_OVERLAID_MODIFIER_WITH_REPEAT: switch (type) { case Type::SHORT_PERIOD: return true; case Type::LONG_LONG_PERIOD: return true; case Type::PRESSING_TARGET_KEY_ONLY: return true; case Type::__END__: return false; } case Mode::NONE: case Mode::__END__: IOLOG_ERROR("Invalid DependingPressingPeriodKeyToKey::PeriodMS::enabled\n"); return false; } return false; } // ====================================================================== void DependingPressingPeriodKeyToKey::static_initialize(IOWorkLoop& workloop) { fire_timer_.initialize(&workloop, NULL, DependingPressingPeriodKeyToKey::fire_timer_callback); } void DependingPressingPeriodKeyToKey::static_terminate(void) { fire_timer_.terminate(); } DependingPressingPeriodKeyToKey::DependingPressingPeriodKeyToKey(RemapFunc::RemapFuncBase* owner) : owner_(owner), active_(false), periodtype_(PeriodType::NONE), keyboardRepeatID_(0), interruptibleByScrollWheel_(true) { for (size_t i = 0; i < KeyToKeyType::END_; ++i) { keytokey_[i].add(KeyCode::VK_PSEUDO_KEY); } beforeAfterKeys_.add(KeyCode::VK_PSEUDO_KEY); } DependingPressingPeriodKeyToKey::~DependingPressingPeriodKeyToKey(void) { if (target_ == this) { fire_timer_.cancelTimeout(); target_ = NULL; } } void DependingPressingPeriodKeyToKey::add(KeyToKeyType::Value type, AddDataType datatype, AddValue newval) { if (type == KeyToKeyType::END_) return; if (datatype == BRIDGE_DATATYPE_OPTION && Option::UNINTERRUPTIBLE_BY_SCROLL_WHEEL == Option(newval)) { interruptibleByScrollWheel_ = false; } else { keytokey_[type].add(datatype, newval); } } void DependingPressingPeriodKeyToKey::prepare(RemapParams& remapParams) { // Params_ScrollWheelEventCallback { auto params = remapParams.paramsBase.get_Params_ScrollWheelEventCallback(); if (params) { if (interruptibleByScrollWheel_) { dokeydown(); } } } } bool DependingPressingPeriodKeyToKey::remap(RemapParams& remapParams) { // Params_KeyboardEventCallBack, Params_KeyboardSpecialEventCallback, Params_RelativePointerEventCallback { bool iskeydown = false; if (remapParams.paramsBase.iskeydown(iskeydown)) { if (remapParams.isremapped || !fromEvent_.changePressingState(remapParams.paramsBase, FlagStatus::globalFlagStatus(), fromModifierFlags_)) { if (iskeydown) { // another key is pressed. dokeydown(); } return false; } remapParams.isremapped = true; if (iskeydown) { target_ = this; active_ = true; periodtype_ = PeriodType::NONE; FlagStatus::globalFlagStatus().decrease(fromEvent_.getModifierFlag()); FlagStatus::globalFlagStatus().decrease(pureFromModifierFlags_); beforeAfterKeys_.call_remap_with_VK_PSEUDO_KEY(EventType::DOWN); // We need save FlagStatus at keydown. // For example, "Change Space to Shift_L" is enabled, // // (1) Control_L down // (2) Space down // (3) Control_L up // (4) Space up -> We should send Control_L+Space here. // // At (4), Control_L is not presssed. // We should send Control_L+Space at (4) because user pressed Space with Control_L at (2). // // Therefore, we need to save FlagStatus at (2). // And restore it at (4). // flagStatusWhenKeyPressed_ = FlagStatus::globalFlagStatus(); unsigned int ms = periodMS_.get(PeriodMS::Type::SHORT_PERIOD); if (ms == 0) { fire_timer_callback(NULL, NULL); } else { fire_timer_.setTimeoutMS(ms); } RemapClassManager::registerPrepareTargetItem(owner_); } else { FlagStatus::globalFlagStatus().increase(fromEvent_.getModifierFlag()); dokeydown(); dokeyup(); FlagStatus::globalFlagStatus().increase(pureFromModifierFlags_); beforeAfterKeys_.call_remap_with_VK_PSEUDO_KEY(EventType::UP); RemapClassManager::unregisterPrepareTargetItem(owner_); } return true; } } return false; } void DependingPressingPeriodKeyToKey::dokeydown(void) { if (!active_) return; active_ = false; if (target_ == this) { fire_timer_.cancelTimeout(); } switch (periodtype_) { case PeriodType::NONE: { periodtype_ = PeriodType::SHORT_PERIOD; keytokey_[KeyToKeyType::SHORT_PERIOD].call_remap_with_VK_PSEUDO_KEY(EventType::DOWN); break; } case PeriodType::SHORT_PERIOD: case PeriodType::LONG_PERIOD: case PeriodType::LONG_LONG_PERIOD: // do nothing break; } } void DependingPressingPeriodKeyToKey::dokeyup(void) { switch (periodtype_) { case PeriodType::SHORT_PERIOD: { periodtype_ = PeriodType::NONE; keytokey_[KeyToKeyType::SHORT_PERIOD].call_remap_with_VK_PSEUDO_KEY(EventType::UP); break; } case PeriodType::LONG_PERIOD: { periodtype_ = PeriodType::NONE; keytokey_[KeyToKeyType::LONG_PERIOD].call_remap_with_VK_PSEUDO_KEY(EventType::UP); // ---------------------------------------- // handle PRESSING_TARGET_KEY_ONLY if (periodMS_.enabled(PeriodMS::Type::PRESSING_TARGET_KEY_ONLY)) { if (!eventWatcherTarget_.isAnyEventHappen() && ic_.getmillisec() < periodMS_.get(PeriodMS::Type::PRESSING_TARGET_KEY_ONLY)) { // ---------------------------------------- // Restore FlagStatus at key down. Vector_ModifierFlag added; Vector_ModifierFlag removed; FlagStatus::globalFlagStatus().subtract(flagStatusWhenKeyPressed_, added); flagStatusWhenKeyPressed_.subtract(FlagStatus::globalFlagStatus(), removed); for (size_t i = 0; i < added.size(); ++i) { FlagStatus::globalFlagStatus().decrease(added[i]); } for (size_t i = 0; i < removed.size(); ++i) { FlagStatus::globalFlagStatus().increase(removed[i]); } // ---------------------------------------- keytokey_[KeyToKeyType::PRESSING_TARGET_KEY_ONLY].call_remap_with_VK_PSEUDO_KEY(EventType::DOWN); keytokey_[KeyToKeyType::PRESSING_TARGET_KEY_ONLY].call_remap_with_VK_PSEUDO_KEY(EventType::UP); // ---------------------------------------- // Restore current FlagStatus. for (size_t i = 0; i < added.size(); ++i) { FlagStatus::globalFlagStatus().increase(added[i]); } for (size_t i = 0; i < removed.size(); ++i) { FlagStatus::globalFlagStatus().decrease(removed[i]); } } } break; } case PeriodType::LONG_LONG_PERIOD: { periodtype_ = PeriodType::NONE; keytokey_[KeyToKeyType::LONG_LONG_PERIOD].call_remap_with_VK_PSEUDO_KEY(EventType::UP); break; } case PeriodType::NONE: // do nothing break; } eventWatcherTarget_.unobserve(); } void DependingPressingPeriodKeyToKey::fire_timer_callback(OSObject* /* owner */, IOTimerEventSource* /* sender */) { if (!target_) return; switch (target_->periodtype_) { case PeriodType::NONE: { target_->periodtype_ = PeriodType::LONG_PERIOD; (target_->keytokey_[KeyToKeyType::LONG_PERIOD]).call_remap_with_VK_PSEUDO_KEY(EventType::DOWN); (target_->eventWatcherTarget_).observe(); (target_->ic_).begin(); if (target_->periodMS_.enabled(PeriodMS::Type::LONG_LONG_PERIOD)) { KeyboardRepeat::cancel(); target_->keyboardRepeatID_ = KeyboardRepeat::getID(); fire_timer_.setTimeoutMS(target_->periodMS_.get(PeriodMS::Type::LONG_LONG_PERIOD)); } break; } case PeriodType::LONG_PERIOD: { // If keyboard repeat cancellation occured while pressing LONG_PERIOD key, // we cancel LONG_LONG_PERIOD event. bool isKeyboardRepeatCanceled = (target_->keyboardRepeatID_ != KeyboardRepeat::getID()); (target_->keytokey_[KeyToKeyType::LONG_PERIOD]).call_remap_with_VK_PSEUDO_KEY(EventType::UP); if (isKeyboardRepeatCanceled) { target_->periodtype_ = PeriodType::NONE; } else { target_->periodtype_ = PeriodType::LONG_LONG_PERIOD; // clear temporary flags. FlagStatus::globalFlagStatus().set(); (target_->keytokey_[KeyToKeyType::LONG_LONG_PERIOD]).call_remap_with_VK_PSEUDO_KEY(EventType::DOWN); } break; } case PeriodType::SHORT_PERIOD: case PeriodType::LONG_LONG_PERIOD: // do nothing break; } } } }
#include <IOKit/IOLib.h> #include "Config.hpp" #include "DependingPressingPeriodKeyToKey.hpp" #include "IOLogWrapper.hpp" #include "KeyboardRepeat.hpp" #include "RemapClass.hpp" namespace org_pqrs_Karabiner { namespace RemapFunc { TimerWrapper DependingPressingPeriodKeyToKey::fire_timer_; DependingPressingPeriodKeyToKey* DependingPressingPeriodKeyToKey::target_ = NULL; DependingPressingPeriodKeyToKey::PeriodMS::PeriodMS(void) : mode_(Mode::NONE) { for (size_t m = 0; m < Mode::__END__; ++m) { for (size_t t = 0; t < Type::__END__; ++t) { overwritten_value_[m][t] = -1; } } } void DependingPressingPeriodKeyToKey::PeriodMS::set(PeriodMS::Mode::Value newval) { mode_ = newval; } unsigned int DependingPressingPeriodKeyToKey::PeriodMS::get(PeriodMS::Type::Value type) { if (overwritten_value_[mode_][type] >= 0) { return overwritten_value_[mode_][type]; } switch (mode_) { case Mode::HOLDING_KEY_TO_KEY: switch (type) { case Type::SHORT_PERIOD: return Config::get_holdingkeytokey_wait(); case Type::LONG_LONG_PERIOD: return 0; case Type::PRESSING_TARGET_KEY_ONLY: return 0; case Type::__END__: return 0; } case Mode::KEY_OVERLAID_MODIFIER: switch (type) { case Type::SHORT_PERIOD: return Config::get_keyoverlaidmodifier_initial_modifier_wait(); case Type::LONG_LONG_PERIOD: return 0; case Type::PRESSING_TARGET_KEY_ONLY: return Config::get_keyoverlaidmodifier_timeout(); case Type::__END__: return 0; } case Mode::KEY_OVERLAID_MODIFIER_WITH_REPEAT: switch (type) { case Type::SHORT_PERIOD: return Config::get_keyoverlaidmodifier_initial_modifier_wait(); case Type::LONG_LONG_PERIOD: return Config::get_keyoverlaidmodifier_initial_wait(); case Type::PRESSING_TARGET_KEY_ONLY: return Config::get_keyoverlaidmodifier_timeout(); case Type::__END__: return 0; } case Mode::NONE: case Mode::__END__: IOLOG_ERROR("Invalid DependingPressingPeriodKeyToKey::PeriodMS::get\n"); return 0; } return 0; } bool DependingPressingPeriodKeyToKey::PeriodMS::enabled(PeriodMS::Type::Value type) { switch (mode_) { case Mode::HOLDING_KEY_TO_KEY: switch (type) { case Type::SHORT_PERIOD: return true; case Type::LONG_LONG_PERIOD: return false; case Type::PRESSING_TARGET_KEY_ONLY: return false; case Type::__END__: return false; } case Mode::KEY_OVERLAID_MODIFIER: switch (type) { case Type::SHORT_PERIOD: return true; case Type::LONG_LONG_PERIOD: return false; case Type::PRESSING_TARGET_KEY_ONLY: return true; case Type::__END__: return false; } case Mode::KEY_OVERLAID_MODIFIER_WITH_REPEAT: switch (type) { case Type::SHORT_PERIOD: return true; case Type::LONG_LONG_PERIOD: return true; case Type::PRESSING_TARGET_KEY_ONLY: return true; case Type::__END__: return false; } case Mode::NONE: case Mode::__END__: IOLOG_ERROR("Invalid DependingPressingPeriodKeyToKey::PeriodMS::enabled\n"); return false; } return false; } // ====================================================================== void DependingPressingPeriodKeyToKey::static_initialize(IOWorkLoop& workloop) { fire_timer_.initialize(&workloop, NULL, DependingPressingPeriodKeyToKey::fire_timer_callback); } void DependingPressingPeriodKeyToKey::static_terminate(void) { fire_timer_.terminate(); } DependingPressingPeriodKeyToKey::DependingPressingPeriodKeyToKey(RemapFunc::RemapFuncBase* owner) : owner_(owner), active_(false), periodtype_(PeriodType::NONE), keyboardRepeatID_(0), interruptibleByScrollWheel_(true) { for (size_t i = 0; i < KeyToKeyType::END_; ++i) { keytokey_[i].add(KeyCode::VK_PSEUDO_KEY); } beforeAfterKeys_.add(KeyCode::VK_PSEUDO_KEY); } DependingPressingPeriodKeyToKey::~DependingPressingPeriodKeyToKey(void) { if (target_ == this) { fire_timer_.cancelTimeout(); target_ = NULL; } } void DependingPressingPeriodKeyToKey::add(KeyToKeyType::Value type, AddDataType datatype, AddValue newval) { if (type == KeyToKeyType::END_) return; if (datatype == BRIDGE_DATATYPE_OPTION && Option::UNINTERRUPTIBLE_BY_SCROLL_WHEEL == Option(newval)) { interruptibleByScrollWheel_ = false; } else { keytokey_[type].add(datatype, newval); } } void DependingPressingPeriodKeyToKey::prepare(RemapParams& remapParams) { // Params_ScrollWheelEventCallback { auto params = remapParams.paramsBase.get_Params_ScrollWheelEventCallback(); if (params) { if (interruptibleByScrollWheel_) { dokeydown(); } } } // Params_KeyboardEventCallBack, Params_KeyboardSpecialEventCallback, Params_RelativePointerEventCallback { bool iskeydown = false; if (remapParams.paramsBase.iskeydown(iskeydown)) { if (iskeydown) { // another key is pressed. dokeydown(); } } } } bool DependingPressingPeriodKeyToKey::remap(RemapParams& remapParams) { // Params_KeyboardEventCallBack, Params_KeyboardSpecialEventCallback, Params_RelativePointerEventCallback { bool iskeydown = false; if (remapParams.paramsBase.iskeydown(iskeydown)) { if (remapParams.isremapped || !fromEvent_.changePressingState(remapParams.paramsBase, FlagStatus::globalFlagStatus(), fromModifierFlags_)) { return false; } remapParams.isremapped = true; if (iskeydown) { target_ = this; active_ = true; periodtype_ = PeriodType::NONE; FlagStatus::globalFlagStatus().decrease(fromEvent_.getModifierFlag()); FlagStatus::globalFlagStatus().decrease(pureFromModifierFlags_); beforeAfterKeys_.call_remap_with_VK_PSEUDO_KEY(EventType::DOWN); // We need save FlagStatus at keydown. // For example, "Change Space to Shift_L" is enabled, // // (1) Control_L down // (2) Space down // (3) Control_L up // (4) Space up -> We should send Control_L+Space here. // // At (4), Control_L is not presssed. // We should send Control_L+Space at (4) because user pressed Space with Control_L at (2). // // Therefore, we need to save FlagStatus at (2). // And restore it at (4). // flagStatusWhenKeyPressed_ = FlagStatus::globalFlagStatus(); unsigned int ms = periodMS_.get(PeriodMS::Type::SHORT_PERIOD); if (ms == 0) { fire_timer_callback(NULL, NULL); } else { fire_timer_.setTimeoutMS(ms); } RemapClassManager::registerPrepareTargetItem(owner_); } else { FlagStatus::globalFlagStatus().increase(fromEvent_.getModifierFlag()); dokeydown(); dokeyup(); FlagStatus::globalFlagStatus().increase(pureFromModifierFlags_); beforeAfterKeys_.call_remap_with_VK_PSEUDO_KEY(EventType::UP); RemapClassManager::unregisterPrepareTargetItem(owner_); } return true; } } return false; } void DependingPressingPeriodKeyToKey::dokeydown(void) { if (!active_) return; active_ = false; if (target_ == this) { fire_timer_.cancelTimeout(); } switch (periodtype_) { case PeriodType::NONE: { periodtype_ = PeriodType::SHORT_PERIOD; keytokey_[KeyToKeyType::SHORT_PERIOD].call_remap_with_VK_PSEUDO_KEY(EventType::DOWN); break; } case PeriodType::SHORT_PERIOD: case PeriodType::LONG_PERIOD: case PeriodType::LONG_LONG_PERIOD: // do nothing break; } } void DependingPressingPeriodKeyToKey::dokeyup(void) { switch (periodtype_) { case PeriodType::SHORT_PERIOD: { periodtype_ = PeriodType::NONE; keytokey_[KeyToKeyType::SHORT_PERIOD].call_remap_with_VK_PSEUDO_KEY(EventType::UP); break; } case PeriodType::LONG_PERIOD: { periodtype_ = PeriodType::NONE; keytokey_[KeyToKeyType::LONG_PERIOD].call_remap_with_VK_PSEUDO_KEY(EventType::UP); // ---------------------------------------- // handle PRESSING_TARGET_KEY_ONLY if (periodMS_.enabled(PeriodMS::Type::PRESSING_TARGET_KEY_ONLY)) { if (!eventWatcherTarget_.isAnyEventHappen() && ic_.getmillisec() < periodMS_.get(PeriodMS::Type::PRESSING_TARGET_KEY_ONLY)) { // ---------------------------------------- // Restore FlagStatus at key down. Vector_ModifierFlag added; Vector_ModifierFlag removed; FlagStatus::globalFlagStatus().subtract(flagStatusWhenKeyPressed_, added); flagStatusWhenKeyPressed_.subtract(FlagStatus::globalFlagStatus(), removed); for (size_t i = 0; i < added.size(); ++i) { FlagStatus::globalFlagStatus().decrease(added[i]); } for (size_t i = 0; i < removed.size(); ++i) { FlagStatus::globalFlagStatus().increase(removed[i]); } // ---------------------------------------- keytokey_[KeyToKeyType::PRESSING_TARGET_KEY_ONLY].call_remap_with_VK_PSEUDO_KEY(EventType::DOWN); keytokey_[KeyToKeyType::PRESSING_TARGET_KEY_ONLY].call_remap_with_VK_PSEUDO_KEY(EventType::UP); // ---------------------------------------- // Restore current FlagStatus. for (size_t i = 0; i < added.size(); ++i) { FlagStatus::globalFlagStatus().increase(added[i]); } for (size_t i = 0; i < removed.size(); ++i) { FlagStatus::globalFlagStatus().decrease(removed[i]); } } } break; } case PeriodType::LONG_LONG_PERIOD: { periodtype_ = PeriodType::NONE; keytokey_[KeyToKeyType::LONG_LONG_PERIOD].call_remap_with_VK_PSEUDO_KEY(EventType::UP); break; } case PeriodType::NONE: // do nothing break; } eventWatcherTarget_.unobserve(); } void DependingPressingPeriodKeyToKey::fire_timer_callback(OSObject* /* owner */, IOTimerEventSource* /* sender */) { if (!target_) return; switch (target_->periodtype_) { case PeriodType::NONE: { target_->periodtype_ = PeriodType::LONG_PERIOD; (target_->keytokey_[KeyToKeyType::LONG_PERIOD]).call_remap_with_VK_PSEUDO_KEY(EventType::DOWN); (target_->eventWatcherTarget_).observe(); (target_->ic_).begin(); if (target_->periodMS_.enabled(PeriodMS::Type::LONG_LONG_PERIOD)) { KeyboardRepeat::cancel(); target_->keyboardRepeatID_ = KeyboardRepeat::getID(); fire_timer_.setTimeoutMS(target_->periodMS_.get(PeriodMS::Type::LONG_LONG_PERIOD)); } break; } case PeriodType::LONG_PERIOD: { // If keyboard repeat cancellation occured while pressing LONG_PERIOD key, // we cancel LONG_LONG_PERIOD event. bool isKeyboardRepeatCanceled = (target_->keyboardRepeatID_ != KeyboardRepeat::getID()); (target_->keytokey_[KeyToKeyType::LONG_PERIOD]).call_remap_with_VK_PSEUDO_KEY(EventType::UP); if (isKeyboardRepeatCanceled) { target_->periodtype_ = PeriodType::NONE; } else { target_->periodtype_ = PeriodType::LONG_LONG_PERIOD; // clear temporary flags. FlagStatus::globalFlagStatus().set(); (target_->keytokey_[KeyToKeyType::LONG_LONG_PERIOD]).call_remap_with_VK_PSEUDO_KEY(EventType::DOWN); } break; } case PeriodType::SHORT_PERIOD: case PeriodType::LONG_LONG_PERIOD: // do nothing break; } } } }
call dokeydown in prepare
call dokeydown in prepare
C++
unlicense
wataash/Karabiner,wataash/Karabiner,astachurski/Karabiner,chzyer-dev/Karabiner,miaotaizi/Karabiner,tekezo/Karabiner,tekezo/Karabiner,wataash/Karabiner,muramasa64/Karabiner,tekezo/Karabiner,e-gaulue/Karabiner,chzyer-dev/Karabiner,e-gaulue/Karabiner,runarbu/Karabiner,muramasa64/Karabiner,chzyer-dev/Karabiner,astachurski/Karabiner,miaotaizi/Karabiner,runarbu/Karabiner,runarbu/Karabiner,e-gaulue/Karabiner,muramasa64/Karabiner,miaotaizi/Karabiner,e-gaulue/Karabiner,miaotaizi/Karabiner,muramasa64/Karabiner,wataash/Karabiner,chzyer-dev/Karabiner,tekezo/Karabiner,runarbu/Karabiner,astachurski/Karabiner,astachurski/Karabiner
58195db582aed858c58118b0d84d0a88ae1cf149
irkick/irkick.cpp
irkick/irkick.cpp
/*************************************************************************** irkick.cpp - Implementation of the main window ------------------- copyright : (C) 2002 by Gav Wood email : [email protected] ***************************************************************************/ // This program is free software. #include <qwidget.h> #include <qdialog.h> #include <qtooltip.h> #include <qregexp.h> #include <kapplication.h> #include <kaction.h> #if KDE_IS_VERSION(3, 1, 90) #include <kactioncollection.h> #endif #include <ksimpleconfig.h> #include <ksystemtray.h> #include <kiconloader.h> #include <kpassivepopup.h> #include <kmessagebox.h> #include <kpopupmenu.h> #include <kdebug.h> #include <klocale.h> #include <kaboutdialog.h> #include <kaboutkde.h> #include <kwinmodule.h> #include <kwin.h> #include <khelpmenu.h> #include <kglobal.h> #include <dcopclient.h> #include <dcopref.h> #include "profileserver.h" #include "irkick.h" /*extern "C" { KDEDModule *create_irkick(const QCString &name) { return new IRKick(name); } } */ IRKick::IRKick(const QCString &obj) : /*KDEDModule*/QObject(), DCOPObject(obj), npApp(QString::null) { theClient = new KLircClient(); theTrayIcon = new KSystemTray(); theTrayIcon->setPixmap(SmallIcon("irkick")); QToolTip::add(theTrayIcon, i18n("KDE Lirc Server: Ready.")); theResetCount = 0; slotReloadConfiguration(); connect(theClient, SIGNAL(remotesRead()), this, SLOT(resetModes())); connect(theClient, SIGNAL(commandReceived(const QString &, const QString &, int)), this, SLOT(gotMessage(const QString &, const QString &, int))); #if KDE_IS_VERSION(3, 1, 90) theTrayIcon->contextMenu()->changeTitle(0, "IRKick"); theTrayIcon->contextMenu()->insertItem(i18n("&Configure..."), this, SLOT(slotConfigure())); theTrayIcon->contextMenu()->insertSeparator(); theTrayIcon->contextMenu()->insertItem(i18n("&Help"), (new KHelpMenu(theTrayIcon, KGlobal::instance()->aboutData()))->menu()); connect(theTrayIcon->actionCollection()->action("file_quit"), SIGNAL(activated()), this, SLOT(doQuit())); #endif theTrayIcon->show(); } IRKick::~IRKick() { delete theTrayIcon; for(QMap<QString,KSystemTray *>::iterator i = currentModeIcons.begin(); i != currentModeIcons.end(); i++) if(*i) delete *i; } void IRKick::doQuit() { KSimpleConfig theConfig("irkickrc"); theConfig.setGroup("General"); if(theConfig.readBoolEntry("AutoStart", true) == true) switch(KMessageBox::questionYesNoCancel(0, i18n("Would you like the Infrared Remote Control server to start automatically when you begin KDE?"), i18n("Stop Permenantly?"))) { case KMessageBox::No: theConfig.writeEntry("AutoStart", false); break; case KMessageBox::Cancel: return; } KApplication::kApplication()->quit(); } void IRKick::resetModes() { if(theResetCount > 1) KPassivePopup::message("IRKick", i18n("Resetting all modes."), SmallIcon("package_applications"), theTrayIcon); if(!theResetCount) allModes.generateNulls(theClient->remotes()); QStringList remotes = theClient->remotes(); for(QStringList::iterator i = remotes.begin(); i != remotes.end(); i++) { currentModes[*i] = allModes.getDefault(*i).name(); if(theResetCount && currentModeIcons[*i]) delete currentModeIcons[*i]; currentModeIcons[*i] = 0; } updateModeIcons(); theResetCount++; } void IRKick::slotReloadConfiguration() { // load configuration from config file KSimpleConfig theConfig("irkickrc"); allActions.loadFromConfig(theConfig); allModes.loadFromConfig(theConfig); if(currentModes.count() && theResetCount) resetModes(); } void IRKick::slotConfigure() { KApplication::startServiceByName("Remote Controls"); } void IRKick::updateModeIcons() { for(QMap<QString,QString>::iterator i = currentModes.begin(); i != currentModes.end(); i++) { Mode mode = allModes.getMode(i.key(), i.data()); if(mode.iconFile() == QString::null || mode.iconFile() == "") { if(currentModeIcons[i.key()]) { delete currentModeIcons[i.key()]; currentModeIcons[i.key()] = 0; } } else { if(!currentModeIcons[i.key()]) { currentModeIcons[i.key()] = new KSystemTray(); currentModeIcons[i.key()]->show(); #if KDE_IS_VERSION(3, 1, 90) currentModeIcons[i.key()]->contextMenu()->changeTitle(0, mode.remoteName()); currentModeIcons[i.key()]->actionCollection()->action("file_quit")->setEnabled(false); #endif } currentModeIcons[i.key()]->setPixmap(KIconLoader().loadIcon(mode.iconFile(), KIcon::Panel)); QToolTip::add(currentModeIcons[i.key()], mode.remoteName() + ": <b>" + mode.name() + "</b>"); } } } bool IRKick::getPrograms(const IRAction &action, QStringList &programs) { DCOPClient *theDC = KApplication::dcopClient(); programs.clear(); if(action.unique()) { if(theDC->isApplicationRegistered(action.program().utf8())) programs += action.program(); } else { QRegExp r = QRegExp("^" + action.program() + "-(\\d+)$"); // find all instances... QCStringList buf = theDC->registeredApplications(); for(QCStringList::iterator i = buf.begin(); i != buf.end(); i++) { QString program = QString::fromUtf8(*i); if(program.contains(r)) programs += program; } if(programs.size() > 1 && action.ifMulti() == IM_DONTSEND) return false; else if(programs.size() > 1 && action.ifMulti() == IM_SENDTOTOP) { QValueList<WId> s = KWinModule().stackingOrder(); // go through all the (ordered) window pids for(QValueList<WId>::iterator i = s.fromLast(); i != s.end(); i--) { int p = KWin::info(*i).pid; QString id = action.program() + "-" + QString().setNum(p); if(programs.contains(id)) { programs.clear(); programs += id; break; } } while(programs.size() > 1) programs.remove(programs.begin()); } else if(programs.size() > 1 && action.ifMulti() == IM_SENDTOBOTTOM) { QValueList<WId> s = KWinModule().stackingOrder(); // go through all the (ordered) window pids for(QValueList<WId>::iterator i = s.begin(); i != s.end(); i++) { int p = KWin::info(*i).pid; QString id = action.program() + "-" + QString().setNum(p); if(programs.contains(id)) { programs.clear(); programs += id; break; } } while(programs.size() > 1) programs.remove(programs.begin()); } } return true; } void IRKick::executeAction(const IRAction &action) { DCOPClient *theDC = KApplication::dcopClient(); QStringList programs; if(!getPrograms(action, programs)) return; // if programs.size()==0 here, then the app is definately not running. if(action.autoStart() && !programs.size()) { QString sname = ProfileServer::profileServer()->getServiceName(action.program()); if(sname != QString::null) { KPassivePopup::message("IRKick", i18n("Starting <b>%1</b>...").arg(action.application()), SmallIcon("package_applications"), theTrayIcon); KApplication::startServiceByName(sname); } } if(action.isJustStart()) return; if(!getPrograms(action, programs)) return; for(QStringList::iterator i = programs.begin(); i != programs.end(); i++) { const QString &program = *i; if(theDC->isApplicationRegistered(program.utf8())) { QByteArray data; QDataStream arg(data, IO_WriteOnly); kdDebug() << "Sending data (" << program << ", " << action.object() << ", " << action.method().prototypeNR() << endl; for(Arguments::const_iterator j = action.arguments().begin(); j != action.arguments().end(); j++) { kdDebug() << "Got argument..." << endl; switch((*j).type()) { case QVariant::Int: arg << (*j).toInt(); break; case QVariant::CString: arg << (*j).toCString(); break; case QVariant::StringList: arg << (*j).toStringList(); break; case QVariant::UInt: arg << (*j).toUInt(); break; case QVariant::Bool: arg << (*j).toBool(); break; case QVariant::Double: arg << (*j).toDouble(); break; default: arg << (*j).toString(); break; } } theDC->send(program.utf8(), action.object().utf8(), action.method().prototypeNR().utf8(), data); } } } void IRKick::gotMessage(const QString &theRemote, const QString &theButton, int theRepeatCounter) { kdDebug() << "Got message: " << theRemote << ": " << theButton << " (" << theRepeatCounter << ")" << endl; if(npApp != QString::null) { QString theApp = npApp; npApp = QString::null; // send notifier by DCOP to npApp/npModule/npMethod(theRemote, theButton); QByteArray data; QDataStream arg(data, IO_WriteOnly); arg << theRemote << theButton; KApplication::dcopClient()->send(theApp.utf8(), npModule.utf8(), npMethod.utf8(), data); } else { if(currentModes[theRemote].isNull()) currentModes[theRemote] = ""; IRAItList l = allActions.findByModeButton(Mode(theRemote, currentModes[theRemote]), theButton); if(currentModes[theRemote] != "") l += allActions.findByModeButton(Mode(theRemote, ""), theButton); bool doBefore = true, doAfter = false; for(IRAItList::const_iterator i = l.begin(); i != l.end(); i++) if((**i).isModeChange() && !theRepeatCounter) { // mode switch currentModes[theRemote] = (**i).modeChange(); Mode mode = allModes.getMode(theRemote, (**i).modeChange()); updateModeIcons(); doBefore = (**i).doBefore(); doAfter = (**i).doAfter(); break; } for(int after = 0; after < 2; after++) { if(doBefore && !after || doAfter && after) for(IRAItList::const_iterator i = l.begin(); i != l.end(); i++) if(!(**i).isModeChange() && ((**i).repeat() || !theRepeatCounter)) { executeAction(**i); } if(!after && doAfter) { l = allActions.findByModeButton(Mode(theRemote, currentModes[theRemote]), theButton); if(currentModes[theRemote] != "") l += allActions.findByModeButton(Mode(theRemote, ""), theButton); } } } } void IRKick::stealNextPress(QString app, QString module, QString method) { npApp = app; npModule = module; npMethod = method; } void IRKick::dontStealNextPress() { npApp = QString::null; } #include "irkick.moc"
/*************************************************************************** irkick.cpp - Implementation of the main window ------------------- copyright : (C) 2002 by Gav Wood email : [email protected] ***************************************************************************/ // This program is free software. #include <qwidget.h> #include <qdialog.h> #include <qtooltip.h> #include <qregexp.h> #include <kapplication.h> #include <kaction.h> #if KDE_IS_VERSION(3, 1, 90) #include <kactioncollection.h> #endif #include <ksimpleconfig.h> #include <ksystemtray.h> #include <kiconloader.h> #include <kpassivepopup.h> #include <kmessagebox.h> #include <kpopupmenu.h> #include <kdebug.h> #include <klocale.h> #include <kaboutdialog.h> #include <kaboutkde.h> #include <kwinmodule.h> #include <kwin.h> #include <khelpmenu.h> #include <kglobal.h> #include <dcopclient.h> #include <dcopref.h> #include "profileserver.h" #include "irkick.h" /*extern "C" { KDEDModule *create_irkick(const QCString &name) { return new IRKick(name); } } */ IRKick::IRKick(const QCString &obj) : /*KDEDModule*/QObject(), DCOPObject(obj), npApp(QString::null) { theClient = new KLircClient(); theTrayIcon = new KSystemTray(); theTrayIcon->setPixmap(SmallIcon("irkick")); QToolTip::add(theTrayIcon, i18n("KDE Lirc Server: Ready.")); theResetCount = 0; slotReloadConfiguration(); connect(theClient, SIGNAL(remotesRead()), this, SLOT(resetModes())); connect(theClient, SIGNAL(commandReceived(const QString &, const QString &, int)), this, SLOT(gotMessage(const QString &, const QString &, int))); #if KDE_IS_VERSION(3, 1, 90) theTrayIcon->contextMenu()->changeTitle(0, "IRKick"); theTrayIcon->contextMenu()->insertItem(i18n("&Configure..."), this, SLOT(slotConfigure())); theTrayIcon->contextMenu()->insertSeparator(); theTrayIcon->contextMenu()->insertItem(i18n("&Help"), (new KHelpMenu(theTrayIcon, KGlobal::instance()->aboutData()))->menu()); connect(theTrayIcon->actionCollection()->action("file_quit"), SIGNAL(activated()), this, SLOT(doQuit())); #endif theTrayIcon->show(); } IRKick::~IRKick() { delete theTrayIcon; for(QMap<QString,KSystemTray *>::iterator i = currentModeIcons.begin(); i != currentModeIcons.end(); i++) if(*i) delete *i; } void IRKick::doQuit() { KSimpleConfig theConfig("irkickrc"); theConfig.setGroup("General"); if(theConfig.readBoolEntry("AutoStart", true) == true) switch(KMessageBox::questionYesNoCancel(0, i18n("Should the Infrared Remote Control server start automatically when you login?"), i18n("Automatically start?"))) { case KMessageBox::No: theConfig.writeEntry("AutoStart", false); break; case KMessageBox::Cancel: return; } KApplication::kApplication()->quit(); } void IRKick::resetModes() { if(theResetCount > 1) KPassivePopup::message("IRKick", i18n("Resetting all modes."), SmallIcon("package_applications"), theTrayIcon); if(!theResetCount) allModes.generateNulls(theClient->remotes()); QStringList remotes = theClient->remotes(); for(QStringList::iterator i = remotes.begin(); i != remotes.end(); i++) { currentModes[*i] = allModes.getDefault(*i).name(); if(theResetCount && currentModeIcons[*i]) delete currentModeIcons[*i]; currentModeIcons[*i] = 0; } updateModeIcons(); theResetCount++; } void IRKick::slotReloadConfiguration() { // load configuration from config file KSimpleConfig theConfig("irkickrc"); allActions.loadFromConfig(theConfig); allModes.loadFromConfig(theConfig); if(currentModes.count() && theResetCount) resetModes(); } void IRKick::slotConfigure() { KApplication::startServiceByName("Remote Controls"); } void IRKick::updateModeIcons() { for(QMap<QString,QString>::iterator i = currentModes.begin(); i != currentModes.end(); i++) { Mode mode = allModes.getMode(i.key(), i.data()); if(mode.iconFile() == QString::null || mode.iconFile() == "") { if(currentModeIcons[i.key()]) { delete currentModeIcons[i.key()]; currentModeIcons[i.key()] = 0; } } else { if(!currentModeIcons[i.key()]) { currentModeIcons[i.key()] = new KSystemTray(); currentModeIcons[i.key()]->show(); #if KDE_IS_VERSION(3, 1, 90) currentModeIcons[i.key()]->contextMenu()->changeTitle(0, mode.remoteName()); currentModeIcons[i.key()]->actionCollection()->action("file_quit")->setEnabled(false); #endif } currentModeIcons[i.key()]->setPixmap(KIconLoader().loadIcon(mode.iconFile(), KIcon::Panel)); QToolTip::add(currentModeIcons[i.key()], mode.remoteName() + ": <b>" + mode.name() + "</b>"); } } } bool IRKick::getPrograms(const IRAction &action, QStringList &programs) { DCOPClient *theDC = KApplication::dcopClient(); programs.clear(); if(action.unique()) { if(theDC->isApplicationRegistered(action.program().utf8())) programs += action.program(); } else { QRegExp r = QRegExp("^" + action.program() + "-(\\d+)$"); // find all instances... QCStringList buf = theDC->registeredApplications(); for(QCStringList::iterator i = buf.begin(); i != buf.end(); i++) { QString program = QString::fromUtf8(*i); if(program.contains(r)) programs += program; } if(programs.size() > 1 && action.ifMulti() == IM_DONTSEND) return false; else if(programs.size() > 1 && action.ifMulti() == IM_SENDTOTOP) { QValueList<WId> s = KWinModule().stackingOrder(); // go through all the (ordered) window pids for(QValueList<WId>::iterator i = s.fromLast(); i != s.end(); i--) { int p = KWin::info(*i).pid; QString id = action.program() + "-" + QString().setNum(p); if(programs.contains(id)) { programs.clear(); programs += id; break; } } while(programs.size() > 1) programs.remove(programs.begin()); } else if(programs.size() > 1 && action.ifMulti() == IM_SENDTOBOTTOM) { QValueList<WId> s = KWinModule().stackingOrder(); // go through all the (ordered) window pids for(QValueList<WId>::iterator i = s.begin(); i != s.end(); i++) { int p = KWin::info(*i).pid; QString id = action.program() + "-" + QString().setNum(p); if(programs.contains(id)) { programs.clear(); programs += id; break; } } while(programs.size() > 1) programs.remove(programs.begin()); } } return true; } void IRKick::executeAction(const IRAction &action) { DCOPClient *theDC = KApplication::dcopClient(); QStringList programs; if(!getPrograms(action, programs)) return; // if programs.size()==0 here, then the app is definately not running. if(action.autoStart() && !programs.size()) { QString sname = ProfileServer::profileServer()->getServiceName(action.program()); if(sname != QString::null) { KPassivePopup::message("IRKick", i18n("Starting <b>%1</b>...").arg(action.application()), SmallIcon("package_applications"), theTrayIcon); KApplication::startServiceByName(sname); } } if(action.isJustStart()) return; if(!getPrograms(action, programs)) return; for(QStringList::iterator i = programs.begin(); i != programs.end(); i++) { const QString &program = *i; if(theDC->isApplicationRegistered(program.utf8())) { QByteArray data; QDataStream arg(data, IO_WriteOnly); kdDebug() << "Sending data (" << program << ", " << action.object() << ", " << action.method().prototypeNR() << endl; for(Arguments::const_iterator j = action.arguments().begin(); j != action.arguments().end(); j++) { kdDebug() << "Got argument..." << endl; switch((*j).type()) { case QVariant::Int: arg << (*j).toInt(); break; case QVariant::CString: arg << (*j).toCString(); break; case QVariant::StringList: arg << (*j).toStringList(); break; case QVariant::UInt: arg << (*j).toUInt(); break; case QVariant::Bool: arg << (*j).toBool(); break; case QVariant::Double: arg << (*j).toDouble(); break; default: arg << (*j).toString(); break; } } theDC->send(program.utf8(), action.object().utf8(), action.method().prototypeNR().utf8(), data); } } } void IRKick::gotMessage(const QString &theRemote, const QString &theButton, int theRepeatCounter) { kdDebug() << "Got message: " << theRemote << ": " << theButton << " (" << theRepeatCounter << ")" << endl; if(npApp != QString::null) { QString theApp = npApp; npApp = QString::null; // send notifier by DCOP to npApp/npModule/npMethod(theRemote, theButton); QByteArray data; QDataStream arg(data, IO_WriteOnly); arg << theRemote << theButton; KApplication::dcopClient()->send(theApp.utf8(), npModule.utf8(), npMethod.utf8(), data); } else { if(currentModes[theRemote].isNull()) currentModes[theRemote] = ""; IRAItList l = allActions.findByModeButton(Mode(theRemote, currentModes[theRemote]), theButton); if(currentModes[theRemote] != "") l += allActions.findByModeButton(Mode(theRemote, ""), theButton); bool doBefore = true, doAfter = false; for(IRAItList::const_iterator i = l.begin(); i != l.end(); i++) if((**i).isModeChange() && !theRepeatCounter) { // mode switch currentModes[theRemote] = (**i).modeChange(); Mode mode = allModes.getMode(theRemote, (**i).modeChange()); updateModeIcons(); doBefore = (**i).doBefore(); doAfter = (**i).doAfter(); break; } for(int after = 0; after < 2; after++) { if(doBefore && !after || doAfter && after) for(IRAItList::const_iterator i = l.begin(); i != l.end(); i++) if(!(**i).isModeChange() && ((**i).repeat() || !theRepeatCounter)) { executeAction(**i); } if(!after && doAfter) { l = allActions.findByModeButton(Mode(theRemote, currentModes[theRemote]), theButton); if(currentModes[theRemote] != "") l += allActions.findByModeButton(Mode(theRemote, ""), theButton); } } } } void IRKick::stealNextPress(QString app, QString module, QString method) { npApp = app; npModule = module; npMethod = method; } void IRKick::dontStealNextPress() { npApp = QString::null; } #include "irkick.moc"
Make the dialog EXACTLY like the klipper one
Make the dialog EXACTLY like the klipper one svn path=/trunk/kdeutils/kdelirc/; revision=246193
C++
lgpl-2.1
KDE/kremotecontrol,KDE/kremotecontrol,KDE/kremotecontrol
1d814da24d62772afceca0b1a0def3e2b46b87f3
Modules/Applications/AppClassification/app/otbZonalStatistics.cxx
Modules/Applications/AppClassification/app/otbZonalStatistics.cxx
/* * Copyright (C) 2017 National Research Institute of Science and * Technology for Environment and Agriculture (IRSTEA) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.org/ * * 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 "itkFixedArray.h" #include "itkObjectFactory.h" // Elevation handler #include "otbWrapperElevationParametersHandler.h" #include "otbWrapperApplicationFactory.h" // Application engine #include "otbStandardFilterWatcher.h" // Process objects #include "otbVectorDataToLabelImageFilter.h" #include "otbVectorDataIntoImageProjectionFilter.h" #include "otbStreamingStatisticsMapFromLabelImageFilter.h" #include "otbStatisticsXMLFileWriter.h" // Raster --> Vector #include "otbLabelImageToVectorDataFilter.h" #include "itkBinaryThresholdImageFilter.h" namespace otb { namespace Wrapper { class ZonalStatistics : public Application { public: /** Standard class typedefs. */ typedef ZonalStatistics Self; typedef Application Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; /* Typedefs */ typedef Int32ImageType LabelImageType; typedef LabelImageType::ValueType LabelValueType; typedef otb::VectorData<double, 2> VectorDataType; typedef otb::VectorDataIntoImageProjectionFilter<VectorDataType, FloatVectorImageType> VectorDataReprojFilterType; typedef otb::VectorDataToLabelImageFilter<VectorDataType, LabelImageType> RasterizeFilterType; typedef VectorDataType::DataTreeType DataTreeType; typedef itk::PreOrderTreeIterator<DataTreeType> TreeIteratorType; typedef VectorDataType::DataNodeType DataNodeType; typedef DataNodeType::PolygonListPointerType PolygonListPointerType; typedef otb::StreamingStatisticsMapFromLabelImageFilter<FloatVectorImageType, LabelImageType> StatsFilterType; typedef otb::StatisticsXMLFileWriter<FloatVectorImageType::PixelType> StatsWriterType; typedef otb::LabelImageToVectorDataFilter<LabelImageType> LabelImageToVectorFilterType; typedef itk::BinaryThresholdImageFilter<LabelImageType, LabelImageType> ThresholdFilterType; /** Standard macro */ itkNewMacro(Self); itkTypeMacro(ZonalStatistics, Application); void DoInit() { SetName("ZonalStatistics"); SetDescription("This application computes zonal statistics"); // Documentation SetDocName("ZonalStatistics"); SetDocLongDescription("This application computes zonal statistics from label image, or vector data. " "The application inputs one input multiband image, and a label input. " "If the label input is a raster, the output statistics are exported in a XML file. If the label " "input is a vector data, the output statistics are exported in a new vector data with statistics " "in the attribute table. The computed statistics are mean, min, max, and standard deviation."); SetDocLimitations("The shapefile must fit in memory"); SetDocAuthors("Remi Cresson"); AddDocTag(Tags::Manip); AddDocTag(Tags::Analysis); // Input image AddParameter(ParameterType_InputImage, "in", "Input Image"); AddParameter(ParameterType_Float, "inbv", "Background value to ignore in statistics computation"); MandatoryOff ("inbv"); // Input zone mode AddParameter(ParameterType_Choice, "inzone", "Type of input for the zone definitions"); AddChoice("inzone.vector", "Input objects from vector data"); AddChoice("inzone.labelimage", "Input objects from label image"); // Input for vector mode AddParameter(ParameterType_InputVectorData, "inzone.vector.in", "Input vector data"); AddParameter(ParameterType_Bool, "inzone.vector.reproject", "Reproject the input vector"); // Input for label image mode AddParameter(ParameterType_InputImage, "inzone.labelimage.in", "Input label image"); AddParameter(ParameterType_Int, "inzone.labelimage.nodata", "No-data value for the input label image"); MandatoryOff ("inzone.labelimage.nodata"); // Output stats mode AddParameter(ParameterType_Choice, "out", "Format of the output stats"); AddChoice("out.vector", "Output vector data"); AddParameter(ParameterType_OutputVectorData, "out.vector.filename", "Filename for the output vector data"); AddChoice("out.xml", "Output XML file"); AddParameter(ParameterType_String, "out.xml.filename", ""); // AddChoice("out.raster", "Output raster image"); // AddParameter(ParameterType_OutputImage, "out.raster.filename", ""); AddRAMParameter(); // Doc example parameter settings SetDocExampleParameterValue("in", "input.tif"); SetDocExampleParameterValue("inzone.vector.in", "myvector.shp"); SetDocExampleParameterValue("out.vector.filename", "myvector_with_stats.shp"); } void DoUpdateParameters() { // Nothing to do here : all parameters are independent } // Returns a string of the kind "prefix_i" const std::string CreateFieldName(const std::string & prefix, const unsigned int i) { std::stringstream ss; ss << prefix << "_" << i; return ss.str(); } // Returns a null pixel which has the same number of components per pixels as img FloatVectorImageType::PixelType NullPixel(FloatVectorImageType::Pointer & img) { const unsigned int nBands = img->GetNumberOfComponentsPerPixel(); FloatVectorImageType::PixelType pix(nBands); pix.Fill(0); return pix; } void PrepareForLabelImageInput() { otbAppLogINFO("Zone definition: label image"); // Computing stats m_StatsFilter->SetInputLabelImage(GetParameterInt32Image("inzone.labelimage.in")); m_StatsFilter->Update(); // In this zone definition mode, the user can provide a no-data value for the labels if (HasUserValue("inzone.labelimage.nodata")) m_IntNoData = GetParameterInt("inzone.labelimage.nodata"); } void PrepareForVectorDataInput() { otbAppLogINFO("Zone definition: vector"); otbAppLogINFO("Loading vector data..."); shp = GetParameterVectorData("inzone.vector.in"); // Reproject vector data if (GetParameterInt("inzone.vector.reproject") != 0) { ReprojectVectorDataIntoInputImage(); } else { m_VectorDataSrc = shp; } RasterizeInputVectorData(); // Computing stats m_StatsFilter->SetInputLabelImage(m_RasterizeFilter->GetOutput()); m_StatsFilter->Update(); } void ReprojectVectorDataIntoInputImage() { otbAppLogINFO("Vector data reprojection enabled"); m_VectorDataReprojectionFilter = VectorDataReprojFilterType::New(); m_VectorDataReprojectionFilter->SetInputVectorData(shp); m_VectorDataReprojectionFilter->SetInputImage(m_InputImage); AddProcess(m_VectorDataReprojectionFilter, "Reproject vector data"); m_VectorDataReprojectionFilter->Update(); m_VectorDataSrc = m_VectorDataReprojectionFilter->GetOutput(); } void RasterizeInputVectorData() { // Rasterize vector data m_RasterizeFilter = RasterizeFilterType::New(); m_RasterizeFilter->AddVectorData(m_VectorDataSrc); m_RasterizeFilter->SetOutputOrigin(m_InputImage->GetOrigin()); m_RasterizeFilter->SetOutputSpacing(m_InputImage->GetSignedSpacing()); m_RasterizeFilter->SetOutputSize(m_InputImage->GetLargestPossibleRegion().GetSize()); m_RasterizeFilter->SetOutputProjectionRef(m_InputImage->GetProjectionRef()); m_RasterizeFilter->SetBurnAttribute("________"); m_RasterizeFilter->SetDefaultBurnValue(0); m_RasterizeFilter->SetGlobalWarningDisplay(false); m_RasterizeFilter->SetBackgroundValue(m_IntNoData); } void RemoveNoDataEntry() { m_CountMap = m_StatsFilter->GetLabelPopulationMap(); m_MeanMap = m_StatsFilter->GetMeanValueMap(); m_StdMap = m_StatsFilter->GetStandardDeviationValueMap(); m_MinMap = m_StatsFilter->GetMinValueMap(); m_MaxMap = m_StatsFilter->GetMaxValueMap(); if (( GetParameterAsString("inzone") == "labelimage" && HasUserValue("inzone.labelimage.nodata")) || (GetParameterAsString("inzone") == "vector") ) { otbAppLogINFO("Removing entries for label value " << m_IntNoData); m_CountMap.erase(m_IntNoData); m_MeanMap.erase(m_IntNoData); m_StdMap.erase(m_IntNoData); m_MinMap.erase(m_IntNoData); m_MaxMap.erase(m_IntNoData); } } void GenerateVectorDataFromLabelImage() { // Mask for label image m_ThresholdFilter = ThresholdFilterType::New(); m_ThresholdFilter->SetInput(GetParameterInt32Image("inzone.labelimage.in")); m_ThresholdFilter->SetInsideValue(0); m_ThresholdFilter->SetOutsideValue(1); m_ThresholdFilter->SetLowerThreshold(m_IntNoData); m_ThresholdFilter->SetUpperThreshold(m_IntNoData); // Vectorize the image m_LabelImageToVectorFilter = LabelImageToVectorFilterType::New(); m_LabelImageToVectorFilter->SetInput(GetParameterInt32Image("inzone.labelimage.in")); m_LabelImageToVectorFilter->SetInputMask(m_ThresholdFilter->GetOutput()); m_LabelImageToVectorFilter->SetFieldName("polygon_id"); AddProcess(m_LabelImageToVectorFilter, "Vectorize label image"); m_LabelImageToVectorFilter->Update(); // The source vector data is the vectorized label image m_VectorDataSrc = m_LabelImageToVectorFilter->GetOutput(); } void WriteVectorData() { // Add statistics fields otbAppLogINFO("Writing output vector data"); LabelValueType internalFID = -1; m_NewVectorData = VectorDataType::New(); DataNodeType::Pointer root = m_NewVectorData->GetDataTree()->GetRoot()->Get(); DataNodeType::Pointer document = DataNodeType::New(); document->SetNodeType(otb::DOCUMENT); m_NewVectorData->GetDataTree()->Add(document, root); DataNodeType::Pointer folder = DataNodeType::New(); folder->SetNodeType(otb::FOLDER); m_NewVectorData->GetDataTree()->Add(folder, document); m_NewVectorData->SetProjectionRef(m_VectorDataSrc->GetProjectionRef()); TreeIteratorType itVector(m_VectorDataSrc->GetDataTree()); itVector.GoToBegin(); while (!itVector.IsAtEnd()) { if (!itVector.Get()->IsRoot() && !itVector.Get()->IsDocument() && !itVector.Get()->IsFolder()) { DataNodeType::Pointer currentGeometry = itVector.Get(); if (m_FromLabelImage) internalFID = currentGeometry->GetFieldAsInt("polygon_id"); else internalFID++; // Add the geometry with the new fields if (m_CountMap.count(internalFID) > 0) { currentGeometry->SetFieldAsDouble("count", m_CountMap[internalFID] ); for (unsigned int band = 0 ; band < m_InputImage->GetNumberOfComponentsPerPixel() ; band++) { currentGeometry->SetFieldAsDouble(CreateFieldName("mean", band), m_MeanMap[internalFID][band] ); currentGeometry->SetFieldAsDouble(CreateFieldName("stdev", band), m_StdMap [internalFID][band] ); currentGeometry->SetFieldAsDouble(CreateFieldName("min", band), m_MinMap [internalFID][band] ); currentGeometry->SetFieldAsDouble(CreateFieldName("max", band), m_MaxMap [internalFID][band] ); } m_NewVectorData->GetDataTree()->Add(currentGeometry, folder); } } ++itVector; } // next feature SetParameterOutputVectorData("out.vector.filename", m_NewVectorData); } void WriteXMLStatsFile() { // Write statistics in XML file const std::string outXMLFile = this->GetParameterString("out.xml.filename"); otbAppLogINFO("Writing " + outXMLFile) StatsWriterType::Pointer statWriter = StatsWriterType::New(); statWriter->SetFileName(outXMLFile); statWriter->AddInputMap<StatsFilterType::LabelPopulationMapType>("count",m_CountMap); statWriter->AddInputMap<StatsFilterType::PixelValueMapType>("mean",m_MeanMap); statWriter->AddInputMap<StatsFilterType::PixelValueMapType>("std",m_StdMap); statWriter->AddInputMap<StatsFilterType::PixelValueMapType>("min",m_MinMap); statWriter->AddInputMap<StatsFilterType::PixelValueMapType>("max",m_MaxMap); statWriter->Update(); } void DoExecute() { // Get input image m_InputImage = GetParameterImage("in"); // Statistics filter m_StatsFilter = StatsFilterType::New(); m_StatsFilter->SetInput(m_InputImage); if (HasUserValue("inbv")) { m_StatsFilter->SetUseNoDataValue(true); m_StatsFilter->SetNoDataValue(GetParameterFloat("inbv")); } m_StatsFilter->GetStreamer()->SetAutomaticAdaptativeStreaming(GetParameterInt("ram")); AddProcess(m_StatsFilter->GetStreamer(), "Computing statistics"); // Internal no-data value m_IntNoData = itk::NumericTraits<LabelValueType>::max(); // Select zone definition mode m_FromLabelImage = (GetParameterAsString("inzone") == "labelimage"); if (m_FromLabelImage) { PrepareForLabelImageInput(); } else if (GetParameterAsString("inzone") == "vector") { PrepareForVectorDataInput(); } else { otbAppLogFATAL("Unknown zone definition mode"); } // Remove the no-data entry RemoveNoDataEntry(); // Generate output if (GetParameterAsString("out") == "vector") { if (m_FromLabelImage) { GenerateVectorDataFromLabelImage(); } WriteVectorData(); } else if (GetParameterAsString("out") == "xml") { WriteXMLStatsFile(); } else { otbAppLogFATAL("Unknown output mode"); } } VectorDataType::Pointer m_VectorDataSrc; VectorDataType::Pointer m_NewVectorData; VectorDataType* shp; VectorDataReprojFilterType::Pointer m_VectorDataReprojectionFilter; RasterizeFilterType::Pointer m_RasterizeFilter; StatsFilterType::Pointer m_StatsFilter; LabelImageToVectorFilterType::Pointer m_LabelImageToVectorFilter; ThresholdFilterType::Pointer m_ThresholdFilter; FloatVectorImageType::Pointer m_InputImage; LabelValueType m_IntNoData; bool m_FromLabelImage; StatsFilterType::LabelPopulationMapType m_CountMap; StatsFilterType::PixelValueMapType m_MeanMap; StatsFilterType::PixelValueMapType m_StdMap; StatsFilterType::PixelValueMapType m_MinMap; StatsFilterType::PixelValueMapType m_MaxMap; }; } } OTB_APPLICATION_EXPORT( otb::Wrapper::ZonalStatistics )
/* * Copyright (C) 2017 National Research Institute of Science and * Technology for Environment and Agriculture (IRSTEA) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.org/ * * 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 "itkFixedArray.h" #include "itkObjectFactory.h" // Elevation handler #include "otbWrapperElevationParametersHandler.h" #include "otbWrapperApplicationFactory.h" // Application engine #include "otbStandardFilterWatcher.h" // Process objects #include "otbVectorDataToLabelImageFilter.h" #include "otbVectorDataIntoImageProjectionFilter.h" #include "otbStreamingStatisticsMapFromLabelImageFilter.h" #include "otbStatisticsXMLFileWriter.h" // Raster --> Vector #include "otbLabelImageToVectorDataFilter.h" #include "itkBinaryThresholdImageFilter.h" namespace otb { namespace Wrapper { class ZonalStatistics : public Application { public: /** Standard class typedefs. */ typedef ZonalStatistics Self; typedef Application Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; /* Typedefs */ typedef Int32ImageType LabelImageType; typedef LabelImageType::ValueType LabelValueType; typedef otb::VectorData<double, 2> VectorDataType; typedef otb::VectorDataIntoImageProjectionFilter<VectorDataType, FloatVectorImageType> VectorDataReprojFilterType; typedef otb::VectorDataToLabelImageFilter<VectorDataType, LabelImageType> RasterizeFilterType; typedef VectorDataType::DataTreeType DataTreeType; typedef itk::PreOrderTreeIterator<DataTreeType> TreeIteratorType; typedef VectorDataType::DataNodeType DataNodeType; typedef DataNodeType::PolygonListPointerType PolygonListPointerType; typedef otb::StreamingStatisticsMapFromLabelImageFilter<FloatVectorImageType, LabelImageType> StatsFilterType; typedef otb::StatisticsXMLFileWriter<FloatVectorImageType::PixelType> StatsWriterType; typedef otb::LabelImageToVectorDataFilter<LabelImageType> LabelImageToVectorFilterType; typedef itk::BinaryThresholdImageFilter<LabelImageType, LabelImageType> ThresholdFilterType; /** Standard macro */ itkNewMacro(Self); itkTypeMacro(ZonalStatistics, Application); void DoInit() { SetName("ZonalStatistics"); SetDescription("This application computes zonal statistics"); // Documentation SetDocName("ZonalStatistics"); SetDocLongDescription("This application computes zonal statistics from label image, or vector data. " "The application inputs one input multiband image, and a label input. " "If the label input is a raster, the output statistics are exported in a XML file. If the label " "input is a vector data, the output statistics are exported in a new vector data with statistics " "in the attribute table. The computed statistics are mean, min, max, and standard deviation."); SetDocLimitations("The shapefile must fit in memory"); SetDocAuthors("Remi Cresson"); AddDocTag(Tags::Manip); AddDocTag(Tags::Analysis); // Input image AddParameter(ParameterType_InputImage, "in", "Input Image"); AddParameter(ParameterType_Float, "inbv", "Background value to ignore in statistics computation"); MandatoryOff ("inbv"); // Input zone mode AddParameter(ParameterType_Choice, "inzone", "Type of input for the zone definitions"); AddChoice("inzone.vector", "Input objects from vector data"); AddChoice("inzone.labelimage", "Input objects from label image"); // Input for vector mode AddParameter(ParameterType_InputVectorData, "inzone.vector.in", "Input vector data"); AddParameter(ParameterType_Bool, "inzone.vector.reproject", "Reproject the input vector"); // Input for label image mode AddParameter(ParameterType_InputImage, "inzone.labelimage.in", "Input label image"); AddParameter(ParameterType_Int, "inzone.labelimage.nodata", "No-data value for the input label image"); MandatoryOff ("inzone.labelimage.nodata"); // Output stats mode AddParameter(ParameterType_Choice, "out", "Format of the output stats"); AddChoice("out.vector", "Output vector data"); AddParameter(ParameterType_OutputVectorData, "out.vector.filename", "Filename for the output vector data"); AddChoice("out.xml", "Output XML file"); AddParameter(ParameterType_String, "out.xml.filename", ""); // AddChoice("out.raster", "Output raster image"); // AddParameter(ParameterType_OutputImage, "out.raster.filename", ""); AddRAMParameter(); // Doc example parameter settings SetDocExampleParameterValue("in", "input.tif"); SetDocExampleParameterValue("inzone.vector.in", "myvector.shp"); SetDocExampleParameterValue("out.vector.filename", "myvector_with_stats.shp"); } void DoUpdateParameters() { // Nothing to do here : all parameters are independent } // Returns a string of the kind "prefix_i" const std::string CreateFieldName(const std::string & prefix, const unsigned int i) { std::stringstream ss; ss << prefix << "_" << i; return ss.str(); } // Returns a null pixel which has the same number of components per pixels as img FloatVectorImageType::PixelType NullPixel(FloatVectorImageType::Pointer & img) { const unsigned int nBands = img->GetNumberOfComponentsPerPixel(); FloatVectorImageType::PixelType pix(nBands); pix.Fill(0); return pix; } void PrepareForLabelImageInput() { otbAppLogINFO("Zone definition: label image"); // Computing stats m_StatsFilter->SetInputLabelImage(GetParameterInt32Image("inzone.labelimage.in")); m_StatsFilter->Update(); // In this zone definition mode, the user can provide a no-data value for the labels if (HasUserValue("inzone.labelimage.nodata")) m_IntNoData = GetParameterInt("inzone.labelimage.nodata"); } void PrepareForVectorDataInput() { otbAppLogINFO("Zone definition: vector"); otbAppLogINFO("Loading vector data..."); m_VectorDataSrc = GetParameterVectorData("inzone.vector.in"); // Reproject vector data if (GetParameterInt("inzone.vector.reproject") != 0) { ReprojectVectorDataIntoInputImage(); } RasterizeInputVectorData(); // Computing stats m_StatsFilter->SetInputLabelImage(m_RasterizeFilter->GetOutput()); m_StatsFilter->Update(); } void ReprojectVectorDataIntoInputImage() { otbAppLogINFO("Vector data reprojection enabled"); m_VectorDataReprojectionFilter = VectorDataReprojFilterType::New(); m_VectorDataReprojectionFilter->SetInputVectorData(m_VectorDataSrc.GetPointer()); m_VectorDataReprojectionFilter->SetInputImage(m_InputImage); AddProcess(m_VectorDataReprojectionFilter, "Reproject vector data"); m_VectorDataReprojectionFilter->Update(); m_VectorDataSrc = m_VectorDataReprojectionFilter->GetOutput(); } void RasterizeInputVectorData() { // Rasterize vector data m_RasterizeFilter = RasterizeFilterType::New(); m_RasterizeFilter->AddVectorData(m_VectorDataSrc); m_RasterizeFilter->SetOutputOrigin(m_InputImage->GetOrigin()); m_RasterizeFilter->SetOutputSpacing(m_InputImage->GetSignedSpacing()); m_RasterizeFilter->SetOutputSize(m_InputImage->GetLargestPossibleRegion().GetSize()); m_RasterizeFilter->SetOutputProjectionRef(m_InputImage->GetProjectionRef()); m_RasterizeFilter->SetBurnAttribute("________"); m_RasterizeFilter->SetDefaultBurnValue(0); m_RasterizeFilter->SetGlobalWarningDisplay(false); m_RasterizeFilter->SetBackgroundValue(m_IntNoData); } void RemoveNoDataEntry() { m_CountMap = m_StatsFilter->GetLabelPopulationMap(); m_MeanMap = m_StatsFilter->GetMeanValueMap(); m_StdMap = m_StatsFilter->GetStandardDeviationValueMap(); m_MinMap = m_StatsFilter->GetMinValueMap(); m_MaxMap = m_StatsFilter->GetMaxValueMap(); if (( GetParameterAsString("inzone") == "labelimage" && HasUserValue("inzone.labelimage.nodata")) || (GetParameterAsString("inzone") == "vector") ) { otbAppLogINFO("Removing entries for label value " << m_IntNoData); m_CountMap.erase(m_IntNoData); m_MeanMap.erase(m_IntNoData); m_StdMap.erase(m_IntNoData); m_MinMap.erase(m_IntNoData); m_MaxMap.erase(m_IntNoData); } } void GenerateVectorDataFromLabelImage() { // Mask for label image m_ThresholdFilter = ThresholdFilterType::New(); m_ThresholdFilter->SetInput(GetParameterInt32Image("inzone.labelimage.in")); m_ThresholdFilter->SetInsideValue(0); m_ThresholdFilter->SetOutsideValue(1); m_ThresholdFilter->SetLowerThreshold(m_IntNoData); m_ThresholdFilter->SetUpperThreshold(m_IntNoData); // Vectorize the image m_LabelImageToVectorFilter = LabelImageToVectorFilterType::New(); m_LabelImageToVectorFilter->SetInput(GetParameterInt32Image("inzone.labelimage.in")); m_LabelImageToVectorFilter->SetInputMask(m_ThresholdFilter->GetOutput()); m_LabelImageToVectorFilter->SetFieldName("polygon_id"); AddProcess(m_LabelImageToVectorFilter, "Vectorize label image"); m_LabelImageToVectorFilter->Update(); // The source vector data is the vectorized label image m_VectorDataSrc = m_LabelImageToVectorFilter->GetOutput(); } void WriteVectorData() { // Add statistics fields otbAppLogINFO("Writing output vector data"); LabelValueType internalFID = -1; m_NewVectorData = VectorDataType::New(); DataNodeType::Pointer root = m_NewVectorData->GetDataTree()->GetRoot()->Get(); DataNodeType::Pointer document = DataNodeType::New(); document->SetNodeType(otb::DOCUMENT); m_NewVectorData->GetDataTree()->Add(document, root); DataNodeType::Pointer folder = DataNodeType::New(); folder->SetNodeType(otb::FOLDER); m_NewVectorData->GetDataTree()->Add(folder, document); m_NewVectorData->SetProjectionRef(m_VectorDataSrc->GetProjectionRef()); TreeIteratorType itVector(m_VectorDataSrc->GetDataTree()); itVector.GoToBegin(); while (!itVector.IsAtEnd()) { if (!itVector.Get()->IsRoot() && !itVector.Get()->IsDocument() && !itVector.Get()->IsFolder()) { DataNodeType::Pointer currentGeometry = itVector.Get(); if (m_FromLabelImage) internalFID = currentGeometry->GetFieldAsInt("polygon_id"); else internalFID++; // Add the geometry with the new fields if (m_CountMap.count(internalFID) > 0) { currentGeometry->SetFieldAsDouble("count", m_CountMap[internalFID] ); for (unsigned int band = 0 ; band < m_InputImage->GetNumberOfComponentsPerPixel() ; band++) { currentGeometry->SetFieldAsDouble(CreateFieldName("mean", band), m_MeanMap[internalFID][band] ); currentGeometry->SetFieldAsDouble(CreateFieldName("stdev", band), m_StdMap [internalFID][band] ); currentGeometry->SetFieldAsDouble(CreateFieldName("min", band), m_MinMap [internalFID][band] ); currentGeometry->SetFieldAsDouble(CreateFieldName("max", band), m_MaxMap [internalFID][band] ); } m_NewVectorData->GetDataTree()->Add(currentGeometry, folder); } } ++itVector; } // next feature SetParameterOutputVectorData("out.vector.filename", m_NewVectorData); } void WriteXMLStatsFile() { // Write statistics in XML file const std::string outXMLFile = this->GetParameterString("out.xml.filename"); otbAppLogINFO("Writing " + outXMLFile) StatsWriterType::Pointer statWriter = StatsWriterType::New(); statWriter->SetFileName(outXMLFile); statWriter->AddInputMap<StatsFilterType::LabelPopulationMapType>("count",m_CountMap); statWriter->AddInputMap<StatsFilterType::PixelValueMapType>("mean",m_MeanMap); statWriter->AddInputMap<StatsFilterType::PixelValueMapType>("std",m_StdMap); statWriter->AddInputMap<StatsFilterType::PixelValueMapType>("min",m_MinMap); statWriter->AddInputMap<StatsFilterType::PixelValueMapType>("max",m_MaxMap); statWriter->Update(); } void DoExecute() { // Get input image m_InputImage = GetParameterImage("in"); // Statistics filter m_StatsFilter = StatsFilterType::New(); m_StatsFilter->SetInput(m_InputImage); if (HasUserValue("inbv")) { m_StatsFilter->SetUseNoDataValue(true); m_StatsFilter->SetNoDataValue(GetParameterFloat("inbv")); } m_StatsFilter->GetStreamer()->SetAutomaticAdaptativeStreaming(GetParameterInt("ram")); AddProcess(m_StatsFilter->GetStreamer(), "Computing statistics"); // Internal no-data value m_IntNoData = itk::NumericTraits<LabelValueType>::max(); // Select zone definition mode m_FromLabelImage = (GetParameterAsString("inzone") == "labelimage"); if (m_FromLabelImage) { PrepareForLabelImageInput(); } else if (GetParameterAsString("inzone") == "vector") { PrepareForVectorDataInput(); } else { otbAppLogFATAL("Unknown zone definition mode"); } // Remove the no-data entry RemoveNoDataEntry(); // Generate output if (GetParameterAsString("out") == "vector") { if (m_FromLabelImage) { GenerateVectorDataFromLabelImage(); } WriteVectorData(); } else if (GetParameterAsString("out") == "xml") { WriteXMLStatsFile(); } else { otbAppLogFATAL("Unknown output mode"); } } VectorDataType::Pointer m_VectorDataSrc; VectorDataType::Pointer m_NewVectorData; VectorDataReprojFilterType::Pointer m_VectorDataReprojectionFilter; RasterizeFilterType::Pointer m_RasterizeFilter; StatsFilterType::Pointer m_StatsFilter; LabelImageToVectorFilterType::Pointer m_LabelImageToVectorFilter; ThresholdFilterType::Pointer m_ThresholdFilter; FloatVectorImageType::Pointer m_InputImage; LabelValueType m_IntNoData; bool m_FromLabelImage; StatsFilterType::LabelPopulationMapType m_CountMap; StatsFilterType::PixelValueMapType m_MeanMap; StatsFilterType::PixelValueMapType m_StdMap; StatsFilterType::PixelValueMapType m_MinMap; StatsFilterType::PixelValueMapType m_MaxMap; }; } } OTB_APPLICATION_EXPORT( otb::Wrapper::ZonalStatistics )
remove shp from members
ENH: remove shp from members
C++
apache-2.0
orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB
fc8c7ab30b94888e6527553fe4d47a33fca124a8
Modules/Numerics/Statistics/include/itkCovarianceSampleFilter.hxx
Modules/Numerics/Statistics/include/itkCovarianceSampleFilter.hxx
/*========================================================================= * * Copyright Insight Software Consortium * * 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.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #ifndef __itkCovarianceSampleFilter_hxx #define __itkCovarianceSampleFilter_hxx #include "itkCovarianceSampleFilter.h" #include "itkMeanSampleFilter.h" namespace itk { namespace Statistics { template< class TSample > CovarianceSampleFilter< TSample > ::CovarianceSampleFilter() { this->ProcessObject::SetNumberOfRequiredInputs(1); this->ProcessObject::SetNumberOfRequiredOutputs(2); this->ProcessObject::SetNthOutput( 0, this->MakeOutput(0) ); this->ProcessObject::SetNthOutput( 1, this->MakeOutput(1) ); } template< class TSample > CovarianceSampleFilter< TSample > ::~CovarianceSampleFilter() {} template< class TSample > void CovarianceSampleFilter< TSample > ::PrintSelf(std::ostream & os, Indent indent) const { Superclass::PrintSelf(os, indent); } template< class TSample > void CovarianceSampleFilter< TSample > ::SetInput(const SampleType *sample) { this->ProcessObject::SetNthInput( 0, const_cast< SampleType * >( sample ) ); } template< class TSample > const TSample * CovarianceSampleFilter< TSample > ::GetInput() const { return itkDynamicCastInDebugMode< const SampleType * >( this->GetPrimaryInput() ); } template< class TSample > typename CovarianceSampleFilter< TSample >::DataObjectPointer CovarianceSampleFilter< TSample > ::MakeOutput(DataObjectPointerArraySizeType index) { MeasurementVectorSizeType measurementVectorSize = this->GetMeasurementVectorSize(); if ( index == 0 ) { MatrixType covarianceMatrix(measurementVectorSize, measurementVectorSize); covarianceMatrix.SetIdentity(); MatrixDecoratedType::Pointer decoratedCovarianceMatrix = MatrixDecoratedType::New(); decoratedCovarianceMatrix->Set(covarianceMatrix); return decoratedCovarianceMatrix.GetPointer(); } if ( index == 1 ) { MeasurementVectorRealType mean; (void)mean; // for complainty pants : valgrind NumericTraits<MeasurementVectorRealType>::SetLength(mean, this->GetMeasurementVectorSize()); mean.Fill( NumericTraits< MeasurementRealType >::Zero ); typename MeasurementVectorDecoratedType::Pointer decoratedMean = MeasurementVectorDecoratedType::New(); decoratedMean->Set( mean ); return decoratedMean.GetPointer(); } itkExceptionMacro("Trying to create output of index " << index << " larger than the number of output"); } template< class TSample > typename CovarianceSampleFilter< TSample >::MeasurementVectorSizeType CovarianceSampleFilter< TSample > ::GetMeasurementVectorSize() const { const SampleType *input = this->GetInput(); if ( input ) { return input->GetMeasurementVectorSize(); } // Test if the Vector type knows its length MeasurementVectorType vector; MeasurementVectorSizeType measurementVectorSize = NumericTraits<MeasurementVectorType>::GetLength(vector); if ( measurementVectorSize ) { return measurementVectorSize; } measurementVectorSize = 1; // Otherwise set it to an innocuous value return measurementVectorSize; } template< class TSample > inline void CovarianceSampleFilter< TSample > ::GenerateData() { const SampleType *input = this->GetInput(); MeasurementVectorSizeType measurementVectorSize = input->GetMeasurementVectorSize(); MatrixDecoratedType *decoratedOutput = itkDynamicCastInDebugMode< MatrixDecoratedType * >( this->ProcessObject::GetOutput(0) ); MatrixType output = decoratedOutput->Get(); MeasurementVectorDecoratedType *decoratedMeanOutput = itkDynamicCastInDebugMode< MeasurementVectorDecoratedType * >(this->ProcessObject::GetOutput(1)); output.SetSize(measurementVectorSize, measurementVectorSize); output.Fill(0.0); double totalFrequency = 0.0; typename TSample::ConstIterator iter = input->Begin(); typename TSample::ConstIterator end = input->End(); MeasurementVectorRealType diff; MeasurementVectorType measurements; NumericTraits<MeasurementVectorRealType>::SetLength(diff, measurementVectorSize); NumericTraits<MeasurementVectorType>::SetLength(measurements, measurementVectorSize); typedef MeanSampleFilter< TSample > MeanFilterType; typename MeanFilterType::Pointer meanFilter = MeanFilterType::New(); meanFilter->SetInput( input ); meanFilter->Update(); const typename MeanFilterType::MeasurementVectorDecoratedType * decorator = meanFilter->GetOutput(); const typename MeanFilterType::MeasurementVectorRealType mean = decorator->Get(); decoratedMeanOutput->Set( mean ); iter = input->Begin(); // fills the lower triangle and the diagonal cells in the covariance matrix while ( iter != end ) { const double frequency = iter.GetFrequency(); totalFrequency += frequency; measurements = iter.GetMeasurementVector(); for ( unsigned int i = 0; i < measurementVectorSize; ++i ) { diff[i] = static_cast< MeasurementRealType >( measurements[i] ) - mean[i]; } // updates the covariance matrix for ( unsigned int row = 0; row < measurementVectorSize; row++ ) { for ( unsigned int col = 0; col < row + 1; col++ ) { output(row, col) += frequency * diff[row] * diff[col]; } } ++iter; } // fills the upper triangle using the lower triangle for ( unsigned int row = 1; row < measurementVectorSize; row++ ) { for ( unsigned int col = 0; col < row; col++ ) { output(col, row) = output(row, col); } } if( totalFrequency - 1.0 > vnl_math::eps ) { output /= ( totalFrequency - 1.0 ); decoratedOutput->Set(output); } else { itkExceptionMacro("Total Frequency was too close to 1.0. Value = " << totalFrequency ); } } template< class TSample > const typename CovarianceSampleFilter< TSample >::MatrixDecoratedType * CovarianceSampleFilter< TSample > ::GetCovarianceMatrixOutput() const { return static_cast< const MatrixDecoratedType * >( this->ProcessObject::GetOutput(0) ); } template< class TSample > const typename CovarianceSampleFilter< TSample >::MatrixType CovarianceSampleFilter< TSample > ::GetCovarianceMatrix() const { return this->GetCovarianceMatrixOutput()->Get(); } template< class TSample > const typename CovarianceSampleFilter< TSample >::MeasurementVectorDecoratedType * CovarianceSampleFilter< TSample > ::GetMeanOutput() const { return static_cast< const MeasurementVectorDecoratedType * >( this->ProcessObject::GetOutput(1) ); } template< class TSample > const typename CovarianceSampleFilter< TSample >::MeasurementVectorRealType CovarianceSampleFilter< TSample > ::GetMean() const { return this->GetMeanOutput()->Get(); } } // end of namespace Statistics } // end of namespace itk #endif
/*========================================================================= * * Copyright Insight Software Consortium * * 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.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #ifndef __itkCovarianceSampleFilter_hxx #define __itkCovarianceSampleFilter_hxx #include "itkCovarianceSampleFilter.h" #include "itkMeanSampleFilter.h" namespace itk { namespace Statistics { template< class TSample > CovarianceSampleFilter< TSample > ::CovarianceSampleFilter() { this->ProcessObject::SetNumberOfRequiredInputs(1); this->ProcessObject::SetNumberOfRequiredOutputs(2); this->ProcessObject::SetNthOutput( 0, this->MakeOutput(0) ); this->ProcessObject::SetNthOutput( 1, this->MakeOutput(1) ); } template< class TSample > CovarianceSampleFilter< TSample > ::~CovarianceSampleFilter() {} template< class TSample > void CovarianceSampleFilter< TSample > ::PrintSelf(std::ostream & os, Indent indent) const { Superclass::PrintSelf(os, indent); } template< class TSample > void CovarianceSampleFilter< TSample > ::SetInput(const SampleType *sample) { this->ProcessObject::SetNthInput( 0, const_cast< SampleType * >( sample ) ); } template< class TSample > const TSample * CovarianceSampleFilter< TSample > ::GetInput() const { return itkDynamicCastInDebugMode< const SampleType * >( this->GetPrimaryInput() ); } template< class TSample > typename CovarianceSampleFilter< TSample >::DataObjectPointer CovarianceSampleFilter< TSample > ::MakeOutput(DataObjectPointerArraySizeType index) { MeasurementVectorSizeType measurementVectorSize = this->GetMeasurementVectorSize(); if ( index == 0 ) { MatrixType covarianceMatrix(measurementVectorSize, measurementVectorSize); covarianceMatrix.SetIdentity(); MatrixDecoratedType::Pointer decoratedCovarianceMatrix = MatrixDecoratedType::New(); decoratedCovarianceMatrix->Set(covarianceMatrix); return decoratedCovarianceMatrix.GetPointer(); } if ( index == 1 ) { MeasurementVectorRealType mean; (void)mean; // for complainty pants : valgrind NumericTraits<MeasurementVectorRealType>::SetLength(mean, this->GetMeasurementVectorSize()); mean.Fill( NumericTraits< MeasurementRealType >::Zero ); typename MeasurementVectorDecoratedType::Pointer decoratedMean = MeasurementVectorDecoratedType::New(); decoratedMean->Set( mean ); return decoratedMean.GetPointer(); } itkExceptionMacro("Trying to create output of index " << index << " larger than the number of output"); } template< class TSample > typename CovarianceSampleFilter< TSample >::MeasurementVectorSizeType CovarianceSampleFilter< TSample > ::GetMeasurementVectorSize() const { const SampleType *input = this->GetInput(); if ( input ) { return input->GetMeasurementVectorSize(); } // Test if the Vector type knows its length MeasurementVectorType vector; MeasurementVectorSizeType measurementVectorSize = NumericTraits<MeasurementVectorType>::GetLength(vector); if ( measurementVectorSize ) { return measurementVectorSize; } measurementVectorSize = 1; // Otherwise set it to an innocuous value return measurementVectorSize; } template< class TSample > inline void CovarianceSampleFilter< TSample > ::GenerateData() { const SampleType *input = this->GetInput(); MeasurementVectorSizeType measurementVectorSize = input->GetMeasurementVectorSize(); MatrixDecoratedType *decoratedOutput = itkDynamicCastInDebugMode< MatrixDecoratedType * >( this->ProcessObject::GetOutput(0) ); MatrixType output = decoratedOutput->Get(); MeasurementVectorDecoratedType *decoratedMeanOutput = itkDynamicCastInDebugMode< MeasurementVectorDecoratedType * >(this->ProcessObject::GetOutput(1)); output.SetSize(measurementVectorSize, measurementVectorSize); output.Fill(0.0); double totalFrequency = 0.0; typename TSample::ConstIterator iter = input->Begin(); typename TSample::ConstIterator end = input->End(); MeasurementVectorRealType diff; MeasurementVectorType measurements; NumericTraits<MeasurementVectorRealType>::SetLength(diff, measurementVectorSize); NumericTraits<MeasurementVectorType>::SetLength(measurements, measurementVectorSize); typedef MeanSampleFilter< TSample > MeanFilterType; typename MeanFilterType::Pointer meanFilter = MeanFilterType::New(); meanFilter->SetInput( input ); meanFilter->Update(); const typename MeanFilterType::MeasurementVectorDecoratedType * decorator = meanFilter->GetOutput(); const typename MeanFilterType::MeasurementVectorRealType mean = decorator->Get(); decoratedMeanOutput->Set( mean ); iter = input->Begin(); // fills the lower triangle and the diagonal cells in the covariance matrix while ( iter != end ) { const double frequency = iter.GetFrequency(); totalFrequency += frequency; measurements = iter.GetMeasurementVector(); for ( unsigned int i = 0; i < measurementVectorSize; ++i ) { diff[i] = static_cast< MeasurementRealType >( measurements[i] ) - mean[i]; } // updates the covariance matrix for ( unsigned int row = 0; row < measurementVectorSize; row++ ) { for ( unsigned int col = 0; col < row + 1; col++ ) { output(row, col) += frequency * diff[row] * diff[col]; } } ++iter; } // fills the upper triangle using the lower triangle for ( unsigned int row = 1; row < measurementVectorSize; row++ ) { for ( unsigned int col = 0; col < row; col++ ) { output(col, row) = output(row, col); } } if( totalFrequency - 1.0 > vnl_math::eps ) { const double factor = 1.0 / ( totalFrequency - 1.0 ); for ( unsigned int col = 0; col < measurementVectorSize; col++ ) { for ( unsigned int row = 0; row < measurementVectorSize; row++ ) { output(col, row) *= factor; } } decoratedOutput->Set(output); } else { itkExceptionMacro("Total Frequency was too close to 1.0. Value = " << totalFrequency ); } } template< class TSample > const typename CovarianceSampleFilter< TSample >::MatrixDecoratedType * CovarianceSampleFilter< TSample > ::GetCovarianceMatrixOutput() const { return static_cast< const MatrixDecoratedType * >( this->ProcessObject::GetOutput(0) ); } template< class TSample > const typename CovarianceSampleFilter< TSample >::MatrixType CovarianceSampleFilter< TSample > ::GetCovarianceMatrix() const { return this->GetCovarianceMatrixOutput()->Get(); } template< class TSample > const typename CovarianceSampleFilter< TSample >::MeasurementVectorDecoratedType * CovarianceSampleFilter< TSample > ::GetMeanOutput() const { return static_cast< const MeasurementVectorDecoratedType * >( this->ProcessObject::GetOutput(1) ); } template< class TSample > const typename CovarianceSampleFilter< TSample >::MeasurementVectorRealType CovarianceSampleFilter< TSample > ::GetMean() const { return this->GetMeanOutput()->Get(); } } // end of namespace Statistics } // end of namespace itk #endif
Fix warnings in matrix division by scalar.
COMP: Fix warnings in matrix division by scalar. At compilation time we were observing the following warning in Debian 7 with gcc 4.7: itkFixedArray.h:197:82: warning: array subscript is above array bounds A binary disection of the code lead to identifying the division by a scalar of a VariableSizeMatrix as the culprit. Expanding the division expression using two nested for loops resolves the warning. It is still unclear why a method in the itkVariableSizeMatrix class would trigger a warning in the itkFixedArray class. Change-Id: I10a2d4d83cc4d1e5ebc4f9a6cdbcaf134da22c99
C++
apache-2.0
Kitware/ITK,msmolens/ITK,BRAINSia/ITK,zachary-williamson/ITK,InsightSoftwareConsortium/ITK,thewtex/ITK,thewtex/ITK,fbudin69500/ITK,Kitware/ITK,zachary-williamson/ITK,eile/ITK,fbudin69500/ITK,hendradarwin/ITK,spinicist/ITK,blowekamp/ITK,LucasGandel/ITK,hjmjohnson/ITK,jmerkow/ITK,jcfr/ITK,biotrump/ITK,atsnyder/ITK,blowekamp/ITK,eile/ITK,hjmjohnson/ITK,ajjl/ITK,PlutoniumHeart/ITK,stnava/ITK,msmolens/ITK,BlueBrain/ITK,malaterre/ITK,fedral/ITK,jmerkow/ITK,blowekamp/ITK,msmolens/ITK,msmolens/ITK,LucHermitte/ITK,hjmjohnson/ITK,fbudin69500/ITK,msmolens/ITK,LucHermitte/ITK,LucasGandel/ITK,jmerkow/ITK,heimdali/ITK,ajjl/ITK,jmerkow/ITK,eile/ITK,jcfr/ITK,richardbeare/ITK,BRAINSia/ITK,msmolens/ITK,InsightSoftwareConsortium/ITK,PlutoniumHeart/ITK,spinicist/ITK,zachary-williamson/ITK,fbudin69500/ITK,jmerkow/ITK,InsightSoftwareConsortium/ITK,eile/ITK,PlutoniumHeart/ITK,richardbeare/ITK,eile/ITK,LucasGandel/ITK,hendradarwin/ITK,biotrump/ITK,hendradarwin/ITK,BlueBrain/ITK,ajjl/ITK,biotrump/ITK,malaterre/ITK,jmerkow/ITK,zachary-williamson/ITK,malaterre/ITK,spinicist/ITK,heimdali/ITK,stnava/ITK,LucHermitte/ITK,hendradarwin/ITK,BRAINSia/ITK,stnava/ITK,Kitware/ITK,heimdali/ITK,Kitware/ITK,InsightSoftwareConsortium/ITK,zachary-williamson/ITK,spinicist/ITK,BRAINSia/ITK,atsnyder/ITK,heimdali/ITK,vfonov/ITK,eile/ITK,fbudin69500/ITK,LucasGandel/ITK,zachary-williamson/ITK,hendradarwin/ITK,fedral/ITK,LucasGandel/ITK,blowekamp/ITK,hjmjohnson/ITK,richardbeare/ITK,richardbeare/ITK,eile/ITK,eile/ITK,fbudin69500/ITK,stnava/ITK,thewtex/ITK,ajjl/ITK,thewtex/ITK,heimdali/ITK,jmerkow/ITK,malaterre/ITK,ajjl/ITK,biotrump/ITK,LucHermitte/ITK,LucasGandel/ITK,spinicist/ITK,BlueBrain/ITK,spinicist/ITK,LucHermitte/ITK,fedral/ITK,vfonov/ITK,zachary-williamson/ITK,LucHermitte/ITK,jcfr/ITK,PlutoniumHeart/ITK,richardbeare/ITK,hendradarwin/ITK,atsnyder/ITK,hjmjohnson/ITK,stnava/ITK,jcfr/ITK,LucasGandel/ITK,BlueBrain/ITK,BlueBrain/ITK,fedral/ITK,biotrump/ITK,malaterre/ITK,thewtex/ITK,heimdali/ITK,Kitware/ITK,hendradarwin/ITK,biotrump/ITK,BRAINSia/ITK,vfonov/ITK,fedral/ITK,atsnyder/ITK,jcfr/ITK,spinicist/ITK,atsnyder/ITK,vfonov/ITK,BRAINSia/ITK,LucasGandel/ITK,vfonov/ITK,spinicist/ITK,heimdali/ITK,stnava/ITK,BlueBrain/ITK,ajjl/ITK,hendradarwin/ITK,blowekamp/ITK,PlutoniumHeart/ITK,blowekamp/ITK,heimdali/ITK,fbudin69500/ITK,stnava/ITK,spinicist/ITK,LucHermitte/ITK,fedral/ITK,vfonov/ITK,ajjl/ITK,vfonov/ITK,atsnyder/ITK,hjmjohnson/ITK,fedral/ITK,ajjl/ITK,stnava/ITK,blowekamp/ITK,fbudin69500/ITK,blowekamp/ITK,msmolens/ITK,jcfr/ITK,Kitware/ITK,BlueBrain/ITK,richardbeare/ITK,atsnyder/ITK,zachary-williamson/ITK,PlutoniumHeart/ITK,BRAINSia/ITK,vfonov/ITK,malaterre/ITK,thewtex/ITK,atsnyder/ITK,jmerkow/ITK,InsightSoftwareConsortium/ITK,Kitware/ITK,vfonov/ITK,InsightSoftwareConsortium/ITK,eile/ITK,atsnyder/ITK,PlutoniumHeart/ITK,biotrump/ITK,malaterre/ITK,fedral/ITK,jcfr/ITK,thewtex/ITK,biotrump/ITK,richardbeare/ITK,stnava/ITK,malaterre/ITK,InsightSoftwareConsortium/ITK,zachary-williamson/ITK,PlutoniumHeart/ITK,msmolens/ITK,BlueBrain/ITK,malaterre/ITK,jcfr/ITK,LucHermitte/ITK,hjmjohnson/ITK
499c3c57d57c62de6f749ceb6362faa979c757c6
examples/clients/TrackerState.cpp
examples/clients/TrackerState.cpp
/** @file @brief Implementation @date 2014 @author Ryan Pavlik <[email protected]> <http://sensics.com> */ // Copyright 2014 Sensics, Inc. // // All rights reserved. // // (Final version intended to be licensed under // the Apache License, Version 2.0) // Internal Includes #include <osvr/ClientKit/ContextC.h> #include <osvr/ClientKit/InterfaceC.h> #include <osvr/ClientKit/InterfaceStateC.h> // Library/third-party includes // - none // Standard includes #include <iostream> int main() { OSVR_ClientContext ctx = osvrClientInit("org.opengoggles.exampleclients.TrackerState"); OSVR_ClientInterface lefthand = NULL; // This is just one of the paths. You can also use: // /me/hands/right // /me/head osvrClientGetInterface(ctx, "/me/hands/left", &lefthand); // Pretend that this is your application's mainloop. for (int i = 0; i < 1000000; ++i) { osvrClientUpdate(ctx); if (i % 100) { // Every so often let's read the tracker state. // Similar methods exist for all other stock report types. OSVR_PoseState state; OSVR_TimeValue timestamp; OSVR_ReturnCode ret = osvrGetPoseState(lefthand, &timestamp, &state); if (ret != OSVR_RETURN_SUCCESS) { std::cout << "No pose state!" << std::endl; } else { std::cout << "Got POSE state: Position = (" << state.translation.data[0] << ", " << state.translation.data[1] << ", " << state.translation.data[2] << "), orientation = (" << osvrQuatGetW(&(state.rotation)) << ", (" << osvrQuatGetX(&(state.rotation)) << ", " << osvrQuatGetY(&(state.rotation)) << ", " << osvrQuatGetZ(&(state.rotation)) << ")" << std::endl; } } } osvrClientShutdown(ctx); std::cout << "Library shut down, exiting." << std::endl; return 0; }
/** @file @brief Implementation @date 2014 @author Ryan Pavlik <[email protected]> <http://sensics.com> */ // Copyright 2014 Sensics, Inc. // // All rights reserved. // // (Final version intended to be licensed under // the Apache License, Version 2.0) // Internal Includes #include <osvr/ClientKit/Context.h> #include <osvr/ClientKit/Interface.h> #include <osvr/ClientKit/InterfaceStateC.h> // Library/third-party includes // - none // Standard includes #include <iostream> int main() { osvr::clientkit::ClientContext context( "org.opengoggles.exampleclients.TrackerState"); // This is just one of the paths. You can also use: // /me/hands/right // /me/head osvr::clientkit::Interface lefthand = context.getInterface("/me/hands/left"); // Pretend that this is your application's mainloop. for (int i = 0; i < 1000000; ++i) { context.update(); if (i % 100) { // Every so often let's read the tracker state. // Similar methods exist for all other stock report types. // Note that there is not currently a tidy C++ wrapper for // state access, so we're using the C API call directly here. OSVR_PoseState state; OSVR_TimeValue timestamp; OSVR_ReturnCode ret = osvrGetPoseState(lefthand.get(), &timestamp, &state); if (OSVR_RETURN_SUCCESS != ret) { std::cout << "No pose state!" << std::endl; } else { std::cout << "Got POSE state: Position = (" << state.translation.data[0] << ", " << state.translation.data[1] << ", " << state.translation.data[2] << "), orientation = (" << osvrQuatGetW(&(state.rotation)) << ", (" << osvrQuatGetX(&(state.rotation)) << ", " << osvrQuatGetY(&(state.rotation)) << ", " << osvrQuatGetZ(&(state.rotation)) << ")" << std::endl; } } } std::cout << "Library shut down, exiting." << std::endl; return 0; }
Update tracker state C++ example to use the C++ wrapper as much as possible.
Update tracker state C++ example to use the C++ wrapper as much as possible.
C++
apache-2.0
leemichaelRazer/OSVR-Core,d235j/OSVR-Core,d235j/OSVR-Core,leemichaelRazer/OSVR-Core,godbyk/OSVR-Core,feilen/OSVR-Core,godbyk/OSVR-Core,Armada651/OSVR-Core,godbyk/OSVR-Core,feilen/OSVR-Core,OSVR/OSVR-Core,godbyk/OSVR-Core,OSVR/OSVR-Core,OSVR/OSVR-Core,d235j/OSVR-Core,godbyk/OSVR-Core,godbyk/OSVR-Core,leemichaelRazer/OSVR-Core,Armada651/OSVR-Core,leemichaelRazer/OSVR-Core,d235j/OSVR-Core,leemichaelRazer/OSVR-Core,OSVR/OSVR-Core,feilen/OSVR-Core,OSVR/OSVR-Core,OSVR/OSVR-Core,Armada651/OSVR-Core,d235j/OSVR-Core,feilen/OSVR-Core,Armada651/OSVR-Core,Armada651/OSVR-Core,feilen/OSVR-Core
361bd613eb9bd46650d3ce8386e81931041b27a9
sipXmediaLib/src/test/mp/MpMMTimerTest.cpp
sipXmediaLib/src/test/mp/MpMMTimerTest.cpp
// // Copyright (C) 2007 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2007 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // $$ /////////////////////////////////////////////////////////////////////////////// #include <cppunit/extensions/HelperMacros.h> #include <cppunit/TestCase.h> #include <sipxunit/TestUtilities.h> #include <mp/MpMMTimer.h> #include <os/OsDateTime.h> #include <os/OsSysLog.h> #include <os/OsNotification.h> #include <os/OsTask.h> #ifdef WIN32 #define WIN32_LEAN_AND_MEAN #include <windows.h> #include <mp/MpMMTimerWnt.h> #endif // Forward Decl's class MpMMTimerTest; class TimerNotification : public OsNotification { public: TimerNotification(MpMMTimerTest* pMMTimerTest); virtual ~TimerNotification() {} OsStatus signal(const intptr_t eventData); private: MpMMTimerTest* mpMMTimerTest; }; /** * Unittest for MpMMTimer and its successors */ class MpMMTimerTest : public CppUnit::TestCase { CPPUNIT_TEST_SUITE(MpMMTimerTest); CPPUNIT_TEST(testGetResolution); CPPUNIT_TEST(testPeriodRange); CPPUNIT_TEST(testLinearTimer); CPPUNIT_TEST(testNotificationTimer); CPPUNIT_TEST_SUITE_END(); public: void setUp() { mpPerfCounts = NULL; mPerfCountsSz = 0; mCurNPerfCounts = 0; } void tearDown() { if(mpPerfCounts != NULL) { delete[] mpPerfCounts; } mpPerfCounts = NULL; mPerfCountsSz = 0; mCurNPerfCounts = 0; } #ifdef WIN32 double initializeWin32PerfMeasurementTools() { // Initialize performance counting measurement tools LARGE_INTEGER perfFreqPerSec; CPPUNIT_ASSERT(QueryPerformanceFrequency(&perfFreqPerSec) > 0); //printf("Performance frequency is %I64d ticks per sec\n", // perfFreqPerSec.QuadPart); // Convert it to per usec instead of per sec. double perfFreqPerUSec = double(perfFreqPerSec.QuadPart) / double(1000000.0); //printf("Performance frequency is %f ticks per usec\n", // perfFreqPerUSec); return perfFreqPerUSec; } #endif void checkDeltasAgainstThresholds(long deltas[], unsigned nDeltas, unsigned targetDelta, // <-- was periodUSecs long lowerThresh, long upperThresh, long lowerMeanThresh, long upperMeanThresh) { CPPUNIT_ASSERT_MESSAGE("Timer didn't fire or deltas were not collected!", nDeltas > 0); printf("Timing values in microseconds, CSV: \n"); long valOutsideThreshs = targetDelta; // initialize to exactly what we want. long meanAvg = 0; unsigned i; for(i = 0; i < nDeltas; i++) { // Tack on the current delta to our mean avg meanAvg += deltas[i]; // Print output in CSV format, for easy graphing. printf("%ld", deltas[i]); printf((i < nDeltas-1) ? ", " : "\n"); // Check if we're outside some reasonable thresholds. if(i > 0 && // don't include the first value in our tests - it's always high. valOutsideThreshs == targetDelta) // Only check if we haven't already gone outside threshold. { if(deltas[i]-(long)targetDelta < lowerThresh || deltas[i]-(long)targetDelta > upperThresh) { valOutsideThreshs = deltas[i]; } } } // Finalize determining mean. meanAvg /= nDeltas; printf("Mean: %ld us\n", meanAvg); // Assert when single value outside error range specified above. char errStrBuf[256]; snprintf(errStrBuf, 256, "Single timer value %ld falls outside threshold of %ld to %ld us", valOutsideThreshs, lowerThresh, upperThresh); CPPUNIT_ASSERT_MESSAGE(errStrBuf, (valOutsideThreshs-(long)targetDelta >= lowerThresh && valOutsideThreshs-(long)targetDelta <= upperThresh)); // Assert when mean is outside error range specified above. snprintf(errStrBuf, 256, "Mean timer value %ld falls outside threshold of %ld to %ld us", meanAvg, lowerMeanThresh, upperMeanThresh); CPPUNIT_ASSERT_MESSAGE(errStrBuf, (meanAvg-(long)targetDelta >= lowerMeanThresh && meanAvg-(long)targetDelta <= upperMeanThresh)); } void testGetResolution() { // Test getting the resolution, and get it.. unsigned resolution; CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, MpMMTimer::getResolution(resolution)); printf("Minimum timer resolution is %d usecs\n", resolution); } void testPeriodRange() { // Test the period range static method.. unsigned unusedMin = 0; unsigned unusedMax = 0; CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, MpMMTimer::getPeriodRange(&unusedMin, &unusedMax)); } void testLinearTimer() { // Set the below variables and preprocessor defines to tweak this test. // TLT_LOOP_COUNT defines the number of timer fire repetitions to do // (set this to an even value), // and periodUSecs defines how long to wait in each one. # define TLT_LOOP_CNT 200 unsigned periodUSecs = 10000; long lowerThresh = -3000; // Assert when outside an error range long lowerMeanThresh = -50; // specified below. long upperThresh = 3000; // One for single values long upperMeanThresh = 50; // One for mean values MpMMTimer* pMMTimer = NULL; #ifdef WIN32 MpMMTimerWnt mmTimerWnt(MpMMTimer::Linear); pMMTimer = &mmTimerWnt; double perfFreqPerUSec = initializeWin32PerfMeasurementTools(); LARGE_INTEGER perfCount[TLT_LOOP_CNT]; #else // Right now MMTimers are only implemented for win32. // as other platforms are implemented, change this. printf("MMTimer not implemented for this platform. Test disabled.\n"); return; #endif // Initialize the timer. printf("Firing every %d usecs\n", periodUSecs); CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, pMMTimer->run(periodUSecs)); // Perform the timing measurements. int i; for(i = 0; i < TLT_LOOP_CNT; i++) { #ifdef WIN32 CPPUNIT_ASSERT(QueryPerformanceCounter(&perfCount[i]) > 0); #endif CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, pMMTimer->waitForNextTick()); } // Determine delta times from individual time measurements.. long deltas[TLT_LOOP_CNT/2]; for(i = 0; i < TLT_LOOP_CNT; i = i+2) { deltas[(i+1)/2] = #ifdef WIN32 (long)(__int64(perfCount[i+1].QuadPart / perfFreqPerUSec) - __int64(perfCount[i].QuadPart / perfFreqPerUSec)); #else 0; #endif } checkDeltasAgainstThresholds(deltas, TLT_LOOP_CNT/2, periodUSecs, lowerThresh, upperThresh, lowerMeanThresh, upperMeanThresh); CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, pMMTimer->stop()); } void notificationTimerRecordTick() { #ifdef WIN32 int x; x = mPerfCountsSz; CPPUNIT_ASSERT(mpPerfCounts != NULL); CPPUNIT_ASSERT(mPerfCountsSz > 0); // Collect measurements while we have space left. if(mCurNPerfCounts < mPerfCountsSz) { CPPUNIT_ASSERT(QueryPerformanceCounter(&mpPerfCounts[mCurNPerfCounts++]) > 0); } #else // Nothing is currently done on other platforms, as none are implemented // on other platforms #endif } void testNotificationTimer() { // Set the below variables and preprocessor defines to tweak this test. // mPerfCountsSz defines the number of timer fire repetitions to do // (set this to an even value), // and periodUSecs defines how long to wait in each one. mPerfCountsSz = 200; unsigned periodUSecs = 10000; long lowerThresh = -3000; // Assert when outside an error range long lowerMeanThresh = -50; // specified below. long upperThresh = 3000; // One for single values long upperMeanThresh = 50; // One for mean values TimerNotification timerNotification(this); MpMMTimer* pMMTimer = NULL; #ifdef WIN32 MpMMTimerWnt mmTimerWnt(MpMMTimer::Notification); pMMTimer = &mmTimerWnt; double perfFreqPerUSec = initializeWin32PerfMeasurementTools(); mpPerfCounts = new LARGE_INTEGER[mPerfCountsSz]; #else // Right now MMTimers are only implemented for win32. // as other platforms are implemented, change this. printf("MMTimer not implemented for this platform. Test disabled.\n"); return; #endif // Set the notification.. pMMTimer->setNotification(&timerNotification); // Initialize the timer. printf("Firing every %d usecs\n", periodUSecs); CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, pMMTimer->run(periodUSecs)); // Wait for the callbacks to perform the timing measurements. OsTask::delay(periodUSecs*mPerfCountsSz/1000 + 50); // The callbacks should be done by now, so if they aren't, // then bitch. //We should have a current count of the actual size of the perf buffer. CPPUNIT_ASSERT_EQUAL(mPerfCountsSz, mCurNPerfCounts); // Clear the OsNotification, as it doesn't need to be continuing to notify. pMMTimer->setNotification(NULL); // Determine delta times from individual time measurements.. long* pDeltas = new long[mPerfCountsSz/2]; unsigned i; for(i = 0; i < mPerfCountsSz; i = i+2) { pDeltas[(i+1)/2] = #ifdef WIN32 (long)(__int64(mpPerfCounts[i+1].QuadPart / perfFreqPerUSec) - __int64(mpPerfCounts[i].QuadPart / perfFreqPerUSec)); #else 0; #endif } checkDeltasAgainstThresholds(pDeltas, mPerfCountsSz/2, periodUSecs, lowerThresh, upperThresh, lowerMeanThresh, upperMeanThresh); CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, pMMTimer->stop()); // Cleanup! delete[] pDeltas; pDeltas = NULL; delete[] mpPerfCounts; mpPerfCounts = NULL; mCurNPerfCounts = 0; mPerfCountsSz = 0; } protected: #ifdef WIN32 LARGE_INTEGER* mpPerfCounts; unsigned mPerfCountsSz; unsigned mCurNPerfCounts; #endif }; CPPUNIT_TEST_SUITE_REGISTRATION(MpMMTimerTest); // Implementation of TimerNotification methods. TimerNotification::TimerNotification(MpMMTimerTest* pMMTimerTest) : mpMMTimerTest(pMMTimerTest) { CPPUNIT_ASSERT(pMMTimerTest != NULL); } OsStatus TimerNotification::signal(const intptr_t eventData) { mpMMTimerTest->notificationTimerRecordTick(); return OS_SUCCESS; }
// // Copyright (C) 2007 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2007 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // $$ /////////////////////////////////////////////////////////////////////////////// #include <cppunit/extensions/HelperMacros.h> #include <cppunit/TestCase.h> #include <sipxunit/TestUtilities.h> #include <mp/MpMMTimer.h> #include <os/OsDateTime.h> #include <os/OsSysLog.h> #include <os/OsNotification.h> #include <os/OsTask.h> #ifdef WIN32 #define WIN32_LEAN_AND_MEAN #include <windows.h> #include <mp/MpMMTimerWnt.h> #endif // Forward Decl's class MpMMTimerTest; class TimerNotification : public OsNotification { public: TimerNotification(MpMMTimerTest* pMMTimerTest); virtual ~TimerNotification() {} OsStatus signal(const intptr_t eventData); private: MpMMTimerTest* mpMMTimerTest; }; /** * Unittest for MpMMTimer and its successors */ class MpMMTimerTest : public CppUnit::TestCase { CPPUNIT_TEST_SUITE(MpMMTimerTest); CPPUNIT_TEST(testGetResolution); CPPUNIT_TEST(testPeriodRange); CPPUNIT_TEST(testLinearTimer); CPPUNIT_TEST(testNotificationTimer); CPPUNIT_TEST_SUITE_END(); public: void setUp() { mpPerfCounts = NULL; mPerfCountsSz = 0; mCurNPerfCounts = 0; } void tearDown() { if(mpPerfCounts != NULL) { delete[] mpPerfCounts; } mpPerfCounts = NULL; mPerfCountsSz = 0; mCurNPerfCounts = 0; } #ifdef WIN32 double initializeWin32PerfMeasurementTools() { // Initialize performance counting measurement tools LARGE_INTEGER perfFreqPerSec; CPPUNIT_ASSERT(QueryPerformanceFrequency(&perfFreqPerSec) > 0); //printf("Performance frequency is %I64d ticks per sec\n", // perfFreqPerSec.QuadPart); // Convert it to per usec instead of per sec. double perfFreqPerUSec = double(perfFreqPerSec.QuadPart) / double(1000000.0); //printf("Performance frequency is %f ticks per usec\n", // perfFreqPerUSec); return perfFreqPerUSec; } #endif void checkDeltasAgainstThresholds(long deltas[], unsigned nDeltas, unsigned targetDelta, // <-- was periodUSecs long lowerThresh, long upperThresh) { CPPUNIT_ASSERT_MESSAGE("Timer didn't fire or deltas were not collected!", nDeltas > 0); printf("Timing values in microseconds, CSV: \n"); long valOutsideThreshs = targetDelta; // initialize to exactly what we want. unsigned i; for(i = 0; i < nDeltas; i++) { // Print output in CSV format, for easy graphing. printf("%ld", deltas[i]); printf((i < nDeltas-1) ? ", " : "\n"); // Check if we're outside some reasonable thresholds. if(i > 0 && // don't include the first value in our tests - it's always high. valOutsideThreshs == targetDelta) // Only check if we haven't already gone outside threshold. { if(deltas[i]-(long)targetDelta < lowerThresh || deltas[i]-(long)targetDelta > upperThresh) { valOutsideThreshs = deltas[i]; } } } // Assert when single value outside error range specified above. char errStrBuf[256]; snprintf(errStrBuf, 256, "Single timer value %ld falls outside threshold of %ld to %ld us", valOutsideThreshs, lowerThresh, upperThresh); CPPUNIT_ASSERT_MESSAGE(errStrBuf, (valOutsideThreshs-(long)targetDelta >= lowerThresh && valOutsideThreshs-(long)targetDelta <= upperThresh)); } void checkMeanAgainstThresholds(long start, long stop, unsigned nDeltas, unsigned targetDelta, // <-- was periodUSecs long lowerMeanThresh, long upperMeanThresh) { CPPUNIT_ASSERT_MESSAGE("Timer didn't fire or deltas were not collected!", nDeltas > 0); double meanAvg = 0; meanAvg = (stop-start)/(double)nDeltas; printf("Mean: %.2f us\n", meanAvg); // Assert when mean is outside error range specified above. char errStrBuf[256]; snprintf(errStrBuf, 256, "Mean timer value %ld falls outside threshold of %ld to %ld us", meanAvg, lowerMeanThresh, upperMeanThresh); CPPUNIT_ASSERT_MESSAGE(errStrBuf, (meanAvg-(long)targetDelta >= lowerMeanThresh && meanAvg-(long)targetDelta <= upperMeanThresh)); } void testGetResolution() { // Test getting the resolution, and get it.. unsigned resolution; CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, MpMMTimer::getResolution(resolution)); printf("Minimum timer resolution is %d usecs\n", resolution); } void testPeriodRange() { // Test the period range static method.. unsigned unusedMin = 0; unsigned unusedMax = 0; CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, MpMMTimer::getPeriodRange(&unusedMin, &unusedMax)); } void testLinearTimer() { // Set the below variables and preprocessor defines to tweak this test. // TLT_LOOP_COUNT defines the number of timer fire repetitions to do // (set this to an even value), // and periodUSecs defines how long to wait in each one. # define TLT_LOOP_CNT 500 unsigned periodUSecs = 10000; long lowerThresh = -3000; // Assert when outside an error range long lowerMeanThresh = -50; // specified below. long upperThresh = 3000; // One for single values long upperMeanThresh = 50; // One for mean values MpMMTimer* pMMTimer = NULL; #ifdef WIN32 MpMMTimerWnt mmTimerWnt(MpMMTimer::Linear); pMMTimer = &mmTimerWnt; double perfFreqPerUSec = initializeWin32PerfMeasurementTools(); LARGE_INTEGER perfCount[TLT_LOOP_CNT]; #else // Right now MMTimers are only implemented for win32. // as other platforms are implemented, change this. printf("MMTimer not implemented for this platform. Test disabled.\n"); return; #endif // Initialize the timer. printf("Firing every %d usecs\n", periodUSecs); CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, pMMTimer->run(periodUSecs)); // Perform the timing measurements. int i; for(i = 0; i < TLT_LOOP_CNT; i++) { #ifdef WIN32 CPPUNIT_ASSERT(QueryPerformanceCounter(&perfCount[i]) > 0); #endif CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, pMMTimer->waitForNextTick()); } CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, pMMTimer->stop()); // Determine delta times from individual time measurements.. long deltas[TLT_LOOP_CNT-1]; for(i = 0; i < TLT_LOOP_CNT-1; i++) { deltas[i] = #ifdef WIN32 (long)(__int64(perfCount[i+1].QuadPart / perfFreqPerUSec) - __int64(perfCount[i].QuadPart / perfFreqPerUSec)); #else 0; #endif } checkDeltasAgainstThresholds(deltas, TLT_LOOP_CNT-1, periodUSecs, lowerThresh, upperThresh); checkMeanAgainstThresholds((long)(perfCount[0].QuadPart / perfFreqPerUSec), (long)(perfCount[TLT_LOOP_CNT-1].QuadPart / perfFreqPerUSec), TLT_LOOP_CNT-1, periodUSecs, lowerMeanThresh, upperMeanThresh); } void notificationTimerRecordTick() { #ifdef WIN32 int x; x = mPerfCountsSz; CPPUNIT_ASSERT(mpPerfCounts != NULL); CPPUNIT_ASSERT(mPerfCountsSz > 0); // Collect measurements while we have space left. if(mCurNPerfCounts < mPerfCountsSz) { CPPUNIT_ASSERT(QueryPerformanceCounter(&mpPerfCounts[mCurNPerfCounts++]) > 0); } #else // Nothing is currently done on other platforms, as none are implemented // on other platforms #endif } void testNotificationTimer() { // Set the below variables and preprocessor defines to tweak this test. // mPerfCountsSz defines the number of timer fire repetitions to do // (set this to an even value), // and periodUSecs defines how long to wait in each one. mPerfCountsSz = 500; unsigned periodUSecs = 10000; long lowerThresh = -3000; // Assert when outside an error range long lowerMeanThresh = -50; // specified below. long upperThresh = 3000; // One for single values long upperMeanThresh = 50; // One for mean values TimerNotification timerNotification(this); MpMMTimer* pMMTimer = NULL; #ifdef WIN32 MpMMTimerWnt mmTimerWnt(MpMMTimer::Notification); pMMTimer = &mmTimerWnt; double perfFreqPerUSec = initializeWin32PerfMeasurementTools(); mpPerfCounts = new LARGE_INTEGER[mPerfCountsSz]; #else // Right now MMTimers are only implemented for win32. // as other platforms are implemented, change this. printf("MMTimer not implemented for this platform. Test disabled.\n"); return; #endif // Set the notification.. pMMTimer->setNotification(&timerNotification); // Initialize the timer. printf("Firing every %d usecs\n", periodUSecs); CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, pMMTimer->run(periodUSecs)); // Wait for the callbacks to perform the timing measurements. OsTask::delay(periodUSecs*mPerfCountsSz/1000 + 50); // The callbacks should be done by now, so if they aren't, // then bitch. //We should have a current count of the actual size of the perf buffer. CPPUNIT_ASSERT_EQUAL(mPerfCountsSz, mCurNPerfCounts); // Clear the OsNotification, as it doesn't need to be continuing to notify. pMMTimer->setNotification(NULL); CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, pMMTimer->stop()); // Determine delta times from individual time measurements.. long* pDeltas = new long[mPerfCountsSz-1]; unsigned i; for(i = 0; i < mPerfCountsSz-1; i = i++) { pDeltas[i] = #ifdef WIN32 (long)(__int64(mpPerfCounts[i+1].QuadPart / perfFreqPerUSec) - __int64(mpPerfCounts[i].QuadPart / perfFreqPerUSec)); #else 0; #endif } checkDeltasAgainstThresholds(pDeltas, mPerfCountsSz-1, periodUSecs, lowerThresh, upperThresh); checkMeanAgainstThresholds((long)(mpPerfCounts[0].QuadPart / perfFreqPerUSec), (long)(mpPerfCounts[mPerfCountsSz-1].QuadPart / perfFreqPerUSec), mPerfCountsSz-1, periodUSecs, lowerMeanThresh, upperMeanThresh); // Cleanup! delete[] pDeltas; pDeltas = NULL; delete[] mpPerfCounts; mpPerfCounts = NULL; mCurNPerfCounts = 0; mPerfCountsSz = 0; } protected: #ifdef WIN32 LARGE_INTEGER* mpPerfCounts; unsigned mPerfCountsSz; unsigned mCurNPerfCounts; #endif }; CPPUNIT_TEST_SUITE_REGISTRATION(MpMMTimerTest); // Implementation of TimerNotification methods. TimerNotification::TimerNotification(MpMMTimerTest* pMMTimerTest) : mpMMTimerTest(pMMTimerTest) { CPPUNIT_ASSERT(pMMTimerTest != NULL); } OsStatus TimerNotification::signal(const intptr_t eventData) { mpMMTimerTest->notificationTimerRecordTick(); return OS_SUCCESS; }
Update MMTimers unittest: * Separate checking of delta and mean values, because mean value may be calculated easier and more presice from raw data. * Increase number of test fires from 200 to 500 for better results. * Generate (N-1) deltas from raw data instead of (N/2) deltas.
Update MMTimers unittest: * Separate checking of delta and mean values, because mean value may be calculated easier and more presice from raw data. * Increase number of test fires from 200 to 500 for better results. * Generate (N-1) deltas from raw data instead of (N/2) deltas. git-svn-id: 5274dacc98e2a95d0b0452670772bfdffe61ca90@9852 a612230a-c5fa-0310-af8b-88eea846685b
C++
lgpl-2.1
sipXtapi/sipXtapi-svn-mirror,sipXtapi/sipXtapi-svn-mirror,sipXtapi/sipXtapi-svn-mirror,sipXtapi/sipXtapi-svn-mirror,sipXtapi/sipXtapi-svn-mirror,sipXtapi/sipXtapi-svn-mirror,sipXtapi/sipXtapi-svn-mirror
54beb059264815955cb82d2100bdc2b0f62dd171
src/nfs/Cache.cxx
src/nfs/Cache.cxx
/* * Copyright 2007-2017 Content Management AG * All rights reserved. * * author: Max Kellermann <[email protected]> * * 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. * * 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 * FOUNDATION 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 "Cache.hxx" #include "Stock.hxx" #include "Client.hxx" #include "Handler.hxx" #include "Istream.hxx" #include "strmap.hxx" #include "pool/pool.hxx" #include "rubber.hxx" #include "sink_rubber.hxx" #include "istream_unlock.hxx" #include "istream_rubber.hxx" #include "istream/UnusedPtr.hxx" #include "istream/istream_null.hxx" #include "istream/istream_tee.hxx" #include "AllocatorStats.hxx" #include "cache.hxx" #include "event/TimerEvent.hxx" #include "io/Logger.hxx" #include "util/Cancellable.hxx" #include <boost/intrusive/list.hpp> #include <sys/stat.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <errno.h> static constexpr struct timeval nfs_cache_compress_interval = { 600, 0 }; struct NfsCache; struct NfsCacheItem; struct NfsCacheStore; struct NfsCacheStore final : public boost::intrusive::list_base_hook<boost::intrusive::link_mode<boost::intrusive::normal_link>>, RubberSinkHandler { struct pool &pool; NfsCache &cache; const char *key; struct stat stat; TimerEvent timeout_event; CancellablePointer cancel_ptr; NfsCacheStore(struct pool &_pool, NfsCache &_cache, const char *_key, const struct stat &_st); /** * Release resources held by this request. */ void Release(); /** * Abort the request. */ void Abort(); void Put(RubberAllocation &&a); void OnTimeout() { /* reading the response has taken too long already; don't store this resource */ LogConcat(4, "NfsCache", "timeout ", key); Abort(); } /* virtual methods from class RubberSinkHandler */ void RubberDone(RubberAllocation &&a, size_t size) override; void RubberOutOfMemory() override; void RubberTooLarge() override; void RubberError(std::exception_ptr ep) override; }; struct NfsCache { struct pool &pool; NfsStock &stock; EventLoop &event_loop; Cache cache; TimerEvent compress_timer; Rubber rubber; /** * A list of requests that are currently saving their contents to * the cache. */ boost::intrusive::list<NfsCacheStore, boost::intrusive::constant_time_size<false>> requests; NfsCache(struct pool &_pool, size_t max_size, NfsStock &_stock, EventLoop &_event_loop); ~NfsCache() { compress_timer.Cancel(); pool_unref(&pool); } private: void OnCompressTimer() { rubber.Compress(); compress_timer.Add(nfs_cache_compress_interval); } }; struct NfsCacheRequest final : NfsStockGetHandler, NfsClientOpenFileHandler { struct pool &pool; NfsCache &cache; const char *key; const char *path; NfsCacheHandler &handler; CancellablePointer &cancel_ptr; NfsCacheRequest(struct pool &_pool, NfsCache &_cache, const char *_key, const char *_path, NfsCacheHandler &_handler, CancellablePointer &_cancel_ptr) :pool(_pool), cache(_cache), key(_key), path(_path), handler(_handler), cancel_ptr(_cancel_ptr) {} void Error(std::exception_ptr ep) { handler.OnNfsCacheError(ep); } /* virtual methods from class NfsStockGetHandler */ void OnNfsStockReady(NfsClient &client) override; void OnNfsStockError(std::exception_ptr ep) override; /* virtual methods from class NfsClientOpenFileHandler */ void OnNfsOpen(NfsFileHandle *handle, const struct stat *st) override; void OnNfsOpenError(std::exception_ptr ep) override { Error(ep); } }; struct NfsCacheHandle { NfsCache &cache; const char *key; NfsFileHandle *file; NfsCacheItem *item; const struct stat &stat; }; struct NfsCacheItem final : CacheItem { const PoolPtr pool; struct stat stat; const RubberAllocation body; NfsCacheItem(PoolPtr &&_pool, const NfsCacheStore &store, RubberAllocation &&_body) noexcept :CacheItem(std::chrono::minutes(1), store.stat.st_size), pool(std::move(_pool)), stat(store.stat), body(std::move(_body)) { } /* virtual methods from class CacheItem */ void Destroy() override { pool_trash(pool); DeleteFromPool(pool, this); } }; static constexpr off_t cacheable_size_limit = 512 * 1024; static constexpr struct timeval nfs_cache_timeout = { 60, 0 }; static const char * nfs_cache_key(struct pool &pool, const char *server, const char *_export, const char *path) { return p_strcat(&pool, server, ":", _export, path, nullptr); } NfsCacheStore::NfsCacheStore(struct pool &_pool, NfsCache &_cache, const char *_key, const struct stat &_st) :pool(_pool), cache(_cache), key(_key), stat(_st), timeout_event(cache.event_loop, BIND_THIS_METHOD(OnTimeout)) {} void NfsCacheStore::Release() { assert(!cancel_ptr); timeout_event.Cancel(); cache.requests.erase(cache.requests.iterator_to(*this)); pool_unref(&pool); } void NfsCacheStore::Abort() { assert(cancel_ptr); cancel_ptr.CancelAndClear(); Release(); } void NfsCacheStore::Put(RubberAllocation &&a) { LogConcat(4, "NfsCache", "put ", key); const auto item = NewFromPool<NfsCacheItem>(PoolPtr(PoolPtr::donate, *pool_new_libc(&cache.pool, "NfsCacheItem")), *this, std::move(a)); cache.cache.Put(p_strdup(item->pool, key), *item); } /* * sink_rubber_handler * */ void NfsCacheStore::RubberDone(RubberAllocation &&a, gcc_unused size_t size) { assert((off_t)size == stat.st_size); cancel_ptr = nullptr; /* the request was successful, and all of the body data has been saved: add it to the cache */ Put(std::move(a)); Release(); } void NfsCacheStore::RubberOutOfMemory() { cancel_ptr = nullptr; LogConcat(4, "NfsCache", "nocache oom ", key); Release(); } void NfsCacheStore::RubberTooLarge() { cancel_ptr = nullptr; LogConcat(4, "NfsCache", "nocache too large ", key); Release(); } void NfsCacheStore::RubberError(std::exception_ptr ep) { cancel_ptr = nullptr; LogConcat(4, "NfsCache", "body_abort ", key, ": ", ep); Release(); } /* * NfsClientOpenFileHandler * */ void NfsCacheRequest::OnNfsOpen(NfsFileHandle *handle, const struct stat *st) { NfsCacheHandle handle2 = { .cache = cache, .key = key, .file = handle, .item = nullptr, .stat = *st, }; handler.OnNfsCacheResponse(handle2, *st); if (handle2.file != nullptr) nfs_client_close_file(*handle2.file); } /* * nfs_stock_get_handler * */ void NfsCacheRequest::OnNfsStockReady(NfsClient &client) { nfs_client_open_file(client, pool, path, *this, cancel_ptr); } void NfsCacheRequest::OnNfsStockError(std::exception_ptr ep) { Error(ep); } /* * constructor * */ inline NfsCache::NfsCache(struct pool &_pool, size_t max_size, NfsStock &_stock, EventLoop &_event_loop) :pool(*pool_new_libc(&_pool, "nfs_cache")), stock(_stock), event_loop(_event_loop), cache(event_loop, 65521, max_size * 7 / 8), compress_timer(event_loop, BIND_THIS_METHOD(OnCompressTimer)), rubber(max_size) { compress_timer.Add(nfs_cache_compress_interval); } NfsCache * nfs_cache_new(struct pool &_pool, size_t max_size, NfsStock &stock, EventLoop &event_loop) { return new NfsCache(_pool, max_size, stock, event_loop); } void nfs_cache_free(NfsCache *cache) { assert(cache != nullptr); delete cache; } AllocatorStats nfs_cache_get_stats(const NfsCache &cache) { return pool_children_stats(cache.pool) + cache.rubber.GetStats(); } void nfs_cache_fork_cow(NfsCache &cache, bool inherit) { cache.rubber.ForkCow(inherit); } void nfs_cache_request(struct pool &pool, NfsCache &cache, const char *server, const char *_export, const char *path, NfsCacheHandler &handler, CancellablePointer &cancel_ptr) { const char *key = nfs_cache_key(pool, server, _export, path); const auto item = (NfsCacheItem *)cache.cache.Get(key); if (item != nullptr) { LogConcat(4, "NfsCache", "hit ", key); NfsCacheHandle handle2 = { .cache = cache, .key = key, .file = nullptr, .item = item, .stat = item->stat, }; handler.OnNfsCacheResponse(handle2, item->stat); return; } LogConcat(4, "NfsCache", "miss ", key); auto r = NewFromPool<NfsCacheRequest>(pool, pool, cache, key, path, handler, cancel_ptr); nfs_stock_get(&cache.stock, &pool, server, _export, *r, cancel_ptr); } static UnusedIstreamPtr nfs_cache_item_open(struct pool &pool, NfsCacheItem &item, uint64_t start, uint64_t end) { assert(start <= end); assert(end <= (uint64_t)item.stat.st_size); assert(item.body); return istream_unlock_new(pool, istream_rubber_new(pool, item.body.GetRubber(), item.body.GetId(), start, end, false), item); } static UnusedIstreamPtr nfs_cache_file_open(struct pool &pool, NfsCache &cache, const char *key, NfsFileHandle &file, const struct stat &st, uint64_t start, uint64_t end) { assert(start <= end); assert(end <= (uint64_t)st.st_size); auto body = istream_nfs_new(pool, file, start, end); if (st.st_size > cacheable_size_limit || start != 0 || end != (uint64_t)st.st_size) { /* don't cache */ LogConcat(4, "NfsCache", "nocache ", key); return body; } /* move all this stuff to a new pool, so istream_tee's second head can continue to fill the cache even if our caller gave up on it */ struct pool *pool2 = pool_new_linear(&cache.pool, "nfs_cache_tee", 1024); auto store = NewFromPool<NfsCacheStore>(*pool2, *pool2, cache, p_strdup(pool2, key), st); /* tee the body: one goes to our client, and one goes into the cache */ auto tee = istream_tee_new(*pool2, std::move(body), cache.event_loop, false, true, /* just in case our handler closes the body without looking at it: defer an Istream::Read() call for the Rubber sink */ true); cache.requests.push_back(*store); store->timeout_event.Add(nfs_cache_timeout); sink_rubber_new(*pool2, std::move(tee.second), cache.rubber, cacheable_size_limit, *store, store->cancel_ptr); return std::move(tee.first); } UnusedIstreamPtr nfs_cache_handle_open(struct pool &pool, NfsCacheHandle &handle, uint64_t start, uint64_t end) { assert((handle.file == nullptr) != (handle.item == nullptr)); assert(start <= end); assert(end <= (uint64_t)handle.stat.st_size); if (start == end) return istream_null_new(pool); if (handle.item != nullptr) { /* cache hit: serve cached file */ LogConcat(5, "NfsCache", "serve ", handle.key); return nfs_cache_item_open(pool, *handle.item, start, end); } else { /* cache miss: load from NFS server */ NfsFileHandle *const file = handle.file; handle.file = nullptr; return nfs_cache_file_open(pool, handle.cache, handle.key, *file, handle.stat, start, end); } }
/* * Copyright 2007-2017 Content Management AG * All rights reserved. * * author: Max Kellermann <[email protected]> * * 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. * * 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 * FOUNDATION 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 "Cache.hxx" #include "Stock.hxx" #include "Client.hxx" #include "Handler.hxx" #include "Istream.hxx" #include "strmap.hxx" #include "pool/pool.hxx" #include "rubber.hxx" #include "sink_rubber.hxx" #include "istream_unlock.hxx" #include "istream_rubber.hxx" #include "istream/UnusedPtr.hxx" #include "istream/istream_null.hxx" #include "istream/istream_tee.hxx" #include "AllocatorStats.hxx" #include "cache.hxx" #include "event/TimerEvent.hxx" #include "io/Logger.hxx" #include "util/Cancellable.hxx" #include <boost/intrusive/list.hpp> #include <sys/stat.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <errno.h> static constexpr struct timeval nfs_cache_compress_interval = { 600, 0 }; struct NfsCache; struct NfsCacheItem; struct NfsCacheStore; struct NfsCacheStore final : public boost::intrusive::list_base_hook<boost::intrusive::link_mode<boost::intrusive::normal_link>>, RubberSinkHandler { struct pool &pool; NfsCache &cache; const char *key; struct stat stat; TimerEvent timeout_event; CancellablePointer cancel_ptr; NfsCacheStore(struct pool &_pool, NfsCache &_cache, const char *_key, const struct stat &_st); /** * Release resources held by this request. */ void Release(); /** * Abort the request. */ void Abort(); void Put(RubberAllocation &&a); void OnTimeout() { /* reading the response has taken too long already; don't store this resource */ LogConcat(4, "NfsCache", "timeout ", key); Abort(); } /* virtual methods from class RubberSinkHandler */ void RubberDone(RubberAllocation &&a, size_t size) override; void RubberOutOfMemory() override; void RubberTooLarge() override; void RubberError(std::exception_ptr ep) override; }; struct NfsCache { struct pool &pool; NfsStock &stock; EventLoop &event_loop; Rubber rubber; Cache cache; TimerEvent compress_timer; /** * A list of requests that are currently saving their contents to * the cache. */ boost::intrusive::list<NfsCacheStore, boost::intrusive::constant_time_size<false>> requests; NfsCache(struct pool &_pool, size_t max_size, NfsStock &_stock, EventLoop &_event_loop); ~NfsCache() { compress_timer.Cancel(); pool_unref(&pool); } private: void OnCompressTimer() { rubber.Compress(); compress_timer.Add(nfs_cache_compress_interval); } }; struct NfsCacheRequest final : NfsStockGetHandler, NfsClientOpenFileHandler { struct pool &pool; NfsCache &cache; const char *key; const char *path; NfsCacheHandler &handler; CancellablePointer &cancel_ptr; NfsCacheRequest(struct pool &_pool, NfsCache &_cache, const char *_key, const char *_path, NfsCacheHandler &_handler, CancellablePointer &_cancel_ptr) :pool(_pool), cache(_cache), key(_key), path(_path), handler(_handler), cancel_ptr(_cancel_ptr) {} void Error(std::exception_ptr ep) { handler.OnNfsCacheError(ep); } /* virtual methods from class NfsStockGetHandler */ void OnNfsStockReady(NfsClient &client) override; void OnNfsStockError(std::exception_ptr ep) override; /* virtual methods from class NfsClientOpenFileHandler */ void OnNfsOpen(NfsFileHandle *handle, const struct stat *st) override; void OnNfsOpenError(std::exception_ptr ep) override { Error(ep); } }; struct NfsCacheHandle { NfsCache &cache; const char *key; NfsFileHandle *file; NfsCacheItem *item; const struct stat &stat; }; struct NfsCacheItem final : CacheItem { const PoolPtr pool; struct stat stat; const RubberAllocation body; NfsCacheItem(PoolPtr &&_pool, const NfsCacheStore &store, RubberAllocation &&_body) noexcept :CacheItem(std::chrono::minutes(1), store.stat.st_size), pool(std::move(_pool)), stat(store.stat), body(std::move(_body)) { } /* virtual methods from class CacheItem */ void Destroy() override { pool_trash(pool); DeleteFromPool(pool, this); } }; static constexpr off_t cacheable_size_limit = 512 * 1024; static constexpr struct timeval nfs_cache_timeout = { 60, 0 }; static const char * nfs_cache_key(struct pool &pool, const char *server, const char *_export, const char *path) { return p_strcat(&pool, server, ":", _export, path, nullptr); } NfsCacheStore::NfsCacheStore(struct pool &_pool, NfsCache &_cache, const char *_key, const struct stat &_st) :pool(_pool), cache(_cache), key(_key), stat(_st), timeout_event(cache.event_loop, BIND_THIS_METHOD(OnTimeout)) {} void NfsCacheStore::Release() { assert(!cancel_ptr); timeout_event.Cancel(); cache.requests.erase(cache.requests.iterator_to(*this)); pool_unref(&pool); } void NfsCacheStore::Abort() { assert(cancel_ptr); cancel_ptr.CancelAndClear(); Release(); } void NfsCacheStore::Put(RubberAllocation &&a) { LogConcat(4, "NfsCache", "put ", key); const auto item = NewFromPool<NfsCacheItem>(PoolPtr(PoolPtr::donate, *pool_new_libc(&cache.pool, "NfsCacheItem")), *this, std::move(a)); cache.cache.Put(p_strdup(item->pool, key), *item); } /* * sink_rubber_handler * */ void NfsCacheStore::RubberDone(RubberAllocation &&a, gcc_unused size_t size) { assert((off_t)size == stat.st_size); cancel_ptr = nullptr; /* the request was successful, and all of the body data has been saved: add it to the cache */ Put(std::move(a)); Release(); } void NfsCacheStore::RubberOutOfMemory() { cancel_ptr = nullptr; LogConcat(4, "NfsCache", "nocache oom ", key); Release(); } void NfsCacheStore::RubberTooLarge() { cancel_ptr = nullptr; LogConcat(4, "NfsCache", "nocache too large ", key); Release(); } void NfsCacheStore::RubberError(std::exception_ptr ep) { cancel_ptr = nullptr; LogConcat(4, "NfsCache", "body_abort ", key, ": ", ep); Release(); } /* * NfsClientOpenFileHandler * */ void NfsCacheRequest::OnNfsOpen(NfsFileHandle *handle, const struct stat *st) { NfsCacheHandle handle2 = { .cache = cache, .key = key, .file = handle, .item = nullptr, .stat = *st, }; handler.OnNfsCacheResponse(handle2, *st); if (handle2.file != nullptr) nfs_client_close_file(*handle2.file); } /* * nfs_stock_get_handler * */ void NfsCacheRequest::OnNfsStockReady(NfsClient &client) { nfs_client_open_file(client, pool, path, *this, cancel_ptr); } void NfsCacheRequest::OnNfsStockError(std::exception_ptr ep) { Error(ep); } /* * constructor * */ inline NfsCache::NfsCache(struct pool &_pool, size_t max_size, NfsStock &_stock, EventLoop &_event_loop) :pool(*pool_new_libc(&_pool, "nfs_cache")), stock(_stock), event_loop(_event_loop), rubber(max_size), cache(event_loop, 65521, max_size * 7 / 8), compress_timer(event_loop, BIND_THIS_METHOD(OnCompressTimer)) { compress_timer.Add(nfs_cache_compress_interval); } NfsCache * nfs_cache_new(struct pool &_pool, size_t max_size, NfsStock &stock, EventLoop &event_loop) { return new NfsCache(_pool, max_size, stock, event_loop); } void nfs_cache_free(NfsCache *cache) { assert(cache != nullptr); delete cache; } AllocatorStats nfs_cache_get_stats(const NfsCache &cache) { return pool_children_stats(cache.pool) + cache.rubber.GetStats(); } void nfs_cache_fork_cow(NfsCache &cache, bool inherit) { cache.rubber.ForkCow(inherit); } void nfs_cache_request(struct pool &pool, NfsCache &cache, const char *server, const char *_export, const char *path, NfsCacheHandler &handler, CancellablePointer &cancel_ptr) { const char *key = nfs_cache_key(pool, server, _export, path); const auto item = (NfsCacheItem *)cache.cache.Get(key); if (item != nullptr) { LogConcat(4, "NfsCache", "hit ", key); NfsCacheHandle handle2 = { .cache = cache, .key = key, .file = nullptr, .item = item, .stat = item->stat, }; handler.OnNfsCacheResponse(handle2, item->stat); return; } LogConcat(4, "NfsCache", "miss ", key); auto r = NewFromPool<NfsCacheRequest>(pool, pool, cache, key, path, handler, cancel_ptr); nfs_stock_get(&cache.stock, &pool, server, _export, *r, cancel_ptr); } static UnusedIstreamPtr nfs_cache_item_open(struct pool &pool, NfsCacheItem &item, uint64_t start, uint64_t end) { assert(start <= end); assert(end <= (uint64_t)item.stat.st_size); assert(item.body); return istream_unlock_new(pool, istream_rubber_new(pool, item.body.GetRubber(), item.body.GetId(), start, end, false), item); } static UnusedIstreamPtr nfs_cache_file_open(struct pool &pool, NfsCache &cache, const char *key, NfsFileHandle &file, const struct stat &st, uint64_t start, uint64_t end) { assert(start <= end); assert(end <= (uint64_t)st.st_size); auto body = istream_nfs_new(pool, file, start, end); if (st.st_size > cacheable_size_limit || start != 0 || end != (uint64_t)st.st_size) { /* don't cache */ LogConcat(4, "NfsCache", "nocache ", key); return body; } /* move all this stuff to a new pool, so istream_tee's second head can continue to fill the cache even if our caller gave up on it */ struct pool *pool2 = pool_new_linear(&cache.pool, "nfs_cache_tee", 1024); auto store = NewFromPool<NfsCacheStore>(*pool2, *pool2, cache, p_strdup(pool2, key), st); /* tee the body: one goes to our client, and one goes into the cache */ auto tee = istream_tee_new(*pool2, std::move(body), cache.event_loop, false, true, /* just in case our handler closes the body without looking at it: defer an Istream::Read() call for the Rubber sink */ true); cache.requests.push_back(*store); store->timeout_event.Add(nfs_cache_timeout); sink_rubber_new(*pool2, std::move(tee.second), cache.rubber, cacheable_size_limit, *store, store->cancel_ptr); return std::move(tee.first); } UnusedIstreamPtr nfs_cache_handle_open(struct pool &pool, NfsCacheHandle &handle, uint64_t start, uint64_t end) { assert((handle.file == nullptr) != (handle.item == nullptr)); assert(start <= end); assert(end <= (uint64_t)handle.stat.st_size); if (start == end) return istream_null_new(pool); if (handle.item != nullptr) { /* cache hit: serve cached file */ LogConcat(5, "NfsCache", "serve ", handle.key); return nfs_cache_item_open(pool, *handle.item, start, end); } else { /* cache miss: load from NFS server */ NfsFileHandle *const file = handle.file; handle.file = nullptr; return nfs_cache_file_open(pool, handle.cache, handle.key, *file, handle.stat, start, end); } }
move Rubber before Cache to fix ordering problem
nfs/Cache: move Rubber before Cache to fix ordering problem The Cache destructor must be called first to remove all items from Rubber.
C++
bsd-2-clause
CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy
ab955ea7c7acafc0d7cc9b82ce274a0933d10140
src/opencvros.cpp
src/opencvros.cpp
#include <ros/ros.h> #include "std_msgs/Int32.h" #include <sstream> #include <geometry_msgs/Twist.h> #include <stdlib.h> #include <image_transport/image_transport.h> #include <image_transport/subscriber_filter.h> #include <cv_bridge/cv_bridge.h> #include <sensor_msgs/image_encodings.h> #include <sensor_msgs/LaserScan.h> #include "std_msgs/String.h" #include <message_filters/sync_policies/approximate_time.h> #include <sensor_msgs/Image.h> #include <message_filters/time_synchronizer.h> #include <message_filters/subscriber.h> #include <sensor_msgs/CameraInfo.h> #include <message_filters/sync_policies/exact_time.h> #include <boost/bind/protect.hpp> #include <boost/bind.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/highgui/highgui.hpp> static const std::string OPENCV_WINDOW = "Image window"; using namespace cv; using namespace std; using namespace message_filters; using namespace sensor_msgs; int drivestate = 1; static int camcenter; static int funcscan = 0; static int mainscan = 0; /* Groen flesje int iLowH = 30; int iHighH = 69; int iLowS = 152; int iHighS = 255; int iLowV = 41; int iHighV = 166; */ /*Blauw Flesje int iLowH = 94; int iHighH = 134; int iLowS = 65; int iHighS = 180; int iLowV = 29; int iHighV = 127; */ /*Rood Cola int iLowH = 0; int iHighH = 29; int iLowS = 211; int iHighS = 255; int iLowV = 11; int iHighV = 190; */ //Groen Arizona int iLowH = 19; int iHighH = 98; int iLowS = 155; int iHighS = 255; int iLowV = 47; int iHighV = 255; typedef union U_FloatParse { float float_data; unsigned char byte_data[4]; } U_FloatConvert; int ReadDepthData(unsigned int height_pos, unsigned int width_pos, sensor_msgs::ImageConstPtr depth_image) { //credits opencv math to Kyle Hounslaw // If position is invalid if ((height_pos >= depth_image->height) || (width_pos >= depth_image->width)) return -1; int index = (height_pos*depth_image->step) + (width_pos*(depth_image->step/depth_image->width)); // If data is 4 byte floats (rectified depth image) if ((depth_image->step/depth_image->width) == 4) { U_FloatConvert depth_data; int i, endian_check = 1; // If big endian if ((depth_image->is_bigendian && (*(char*)&endian_check != 1)) || // Both big endian ((!depth_image->is_bigendian) && (*(char*)&endian_check == 1))) // Both lil endian { for (i = 0; i < 4; i++) depth_data.byte_data[i] = depth_image->data[index + i]; // Make sure data is valid (check if NaN) if (depth_data.float_data == depth_data.float_data) return int(depth_data.float_data*1000); return -1; // If depth data invalid } // else, one little endian, one big endian for (i = 0; i < 4; i++) depth_data.byte_data[i] = depth_image->data[3 + index - i]; // Make sure data is valid (check if NaN) if (depth_data.float_data == depth_data.float_data) return int(depth_data.float_data*1000); return -1; // If depth data invalid } // Otherwise, data is 2 byte integers (raw depth image) int temp_val; // If big endian if (depth_image->is_bigendian) temp_val = (depth_image->data[index] << 8) + depth_image->data[index + 1]; // If little endian else temp_val = depth_image->data[index] + (depth_image->data[index + 1] << 8); // Make sure data is valid (check if NaN) if (temp_val == temp_val) return temp_val; return -1; // If depth data invalid } void imageCallback(const sensor_msgs::ImageConstPtr& msg, const sensor_msgs::ImageConstPtr& msg_depth, const sensor_msgs::CameraInfoConstPtr& right_camera) { cv_bridge::CvImagePtr cv_ptr; try { cv_ptr = cv_bridge::toCvCopy(msg, sensor_msgs::image_encodings::BGR8); } catch (cv_bridge::Exception& e) { ROS_ERROR("cv_bridge exception: %s", e.what()); return; } Mat imgOriginal; Mat imgHSV; cv::cvtColor(cv_ptr->image, imgHSV, cv::COLOR_BGR2HSV); //Convert the captured frame from RGB to HSV Mat imgThresholded; inRange(imgHSV, Scalar(iLowH, iLowS, iLowV), Scalar(iHighH, iHighS, iHighV), imgThresholded); //Threshold the image double m01, m10, area; int posX = 0, posY = 0; Moments oMoments = moments(imgThresholded); m01 = oMoments.m01; m10 = oMoments.m10; area = oMoments.m00; // Filter position if (area > 1000000) { // Position posX = m10 / area; posY = m01 / area; } //morphological opening (remove small objects from the foreground) //morphsize to filter out small objects int ms = 25; int ds = 5; erode(imgThresholded, imgThresholded, getStructuringElement(MORPH_ELLIPSE, Size(ms, ms)) ); dilate( imgThresholded, imgThresholded, getStructuringElement(MORPH_ELLIPSE, Size(ms, ms)) ); //morphological closing (fill small holes in the foreground) dilate( imgThresholded, imgThresholded, getStructuringElement(MORPH_ELLIPSE, Size(ds, ds)) ); erode(imgThresholded, imgThresholded, getStructuringElement(MORPH_ELLIPSE, Size(ds, ds)) ); imshow("hsv", imgThresholded); //show the thresholded image int largest_area = 0; int largest_contour_index = 0; double width, height; vector< vector<Point> > contours; // Vector for storing contour vector<Vec4i> hierarchy; Rect bounding_rect; // Find all contours in thresholded image findContours(imgThresholded, contours, hierarchy, CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE); // Find the biggest contour and calculate bounding box for(int i = 0; i < contours.size(); i++) { double a = contourArea(contours[i], false); if(a > largest_area) { largest_area = a; largest_contour_index = i; bounding_rect = boundingRect(contours[i]); } } // Calculate width and heigt of bounding box width = bounding_rect.br().x - bounding_rect.tl().x; height = bounding_rect.br().y - bounding_rect.tl().y; // Calculate center.x Point center = Point(((width/2) + bounding_rect.tl().x), ((height/2) + bounding_rect.tl().y)); int depth = ReadDepthData(center.y, center.x, msg_depth); // print coordinates from the object //ROS_INFO("Center x: %d, center y: %d\n", center.x, center.y); drawContours(cv_ptr->image, contours, largest_contour_index, Scalar(255), 1, 8, hierarchy); // Draw the largest contour using previously stored index. circle(cv_ptr->image, center, 3, Scalar(255,255,0), -1, 8, 0); // Draw dot in center of bb rectangle(cv_ptr->image, bounding_rect.tl(), bounding_rect.br(), Scalar(255,255,0), 2, 8, 0); // Draw bounding box imshow("original", cv_ptr->image); //show the original image camcenter = center.x; ros::NodeHandle nc; ros::Publisher ctr_pub = nc.advertise<std_msgs::Int32>("centerdata", 1); if (camcenter>0) { std_msgs::Int32 ctr; ctr.data = camcenter; ROS_INFO("center: %d", ctr.data); ctr_pub.publish(ctr); } ros::NodeHandle nd; ros::Publisher dpt_pub = nd.advertise<std_msgs::Int32>("depthdata", 1); if (camcenter>0) { std_msgs::Int32 dpt; dpt.data = depth; ROS_INFO("depth: %d", dpt.data); dpt_pub.publish(dpt); } } int main(int argc, char** argv) { ros::init(argc, argv, "opencvnode"); ros::NodeHandle nh; message_filters::Subscriber<CameraInfo> camera_info_sub(nh, "/camera/depth_registered/camera_info", 1); message_filters::Subscriber<Image> depth_image_sub(nh, "/camera/depth/image_raw", 1); message_filters::Subscriber<Image> rgb_image_sub(nh, "/camera/rgb/image_raw", 1); ros::NodeHandle nc; ros::Publisher ctr_pub = nc.advertise<std_msgs::Int32>("centerdata", 1); ros::NodeHandle nd; ros::Publisher dpt_pub = nd.advertise<std_msgs::Int32>("depthdata", 1); //message_filters::Subscriber<std_msgs::String> coordinates_array(nh_, "chatter" , 1); typedef sync_policies::ApproximateTime<Image, Image, CameraInfo> MySyncPolicy; Synchronizer<MySyncPolicy> sync(MySyncPolicy(1), rgb_image_sub, depth_image_sub, camera_info_sub); //TimeSynchronizer<Image, Image, CameraInfo> sync(rgb_image_sub, depth_image_sub, camera_info_sub, 10); sync.registerCallback(boost::bind(&imageCallback, _1, _2, _3)); //cv::namedWindow(OPENCV_WINDOW); namedWindow("original", CV_WINDOW_AUTOSIZE); //create a window called "Control" namedWindow("hsv", CV_WINDOW_AUTOSIZE); // TODO change to hsv values loaded in. For the green card it is: H:42, 90. S:90,255. V:0,255 //Create trackbars in "Control" window cvCreateTrackbar("LowH", "original", &iLowH, 179); //Hue (0 - 179) cvCreateTrackbar("HighH", "original", &iHighH, 179); cvCreateTrackbar("LowS", "original", &iLowS, 255); //Saturation (0 - 255) cvCreateTrackbar("HighS", "original", &iHighS, 255); cvCreateTrackbar("LowV", "original", &iLowV, 255); //Value (0 - 255) cvCreateTrackbar("HighV", "original", &iHighV, 255); cvStartWindowThread(); ros::spin(); return 0; }
#include <ros/ros.h> #include "std_msgs/Int32.h" #include <sstream> #include <geometry_msgs/Twist.h> #include <stdlib.h> #include <image_transport/image_transport.h> #include <image_transport/subscriber_filter.h> #include <cv_bridge/cv_bridge.h> #include <sensor_msgs/image_encodings.h> #include <sensor_msgs/LaserScan.h> #include "std_msgs/String.h" #include <message_filters/sync_policies/approximate_time.h> #include <sensor_msgs/Image.h> #include <message_filters/time_synchronizer.h> #include <message_filters/subscriber.h> #include <sensor_msgs/CameraInfo.h> #include <message_filters/sync_policies/exact_time.h> #include <boost/bind/protect.hpp> #include <boost/bind.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/highgui/highgui.hpp> static const std::string OPENCV_WINDOW = "Image window"; using namespace cv; using namespace std; using namespace message_filters; using namespace sensor_msgs; int drivestate = 1; static int camcenter; static int funcscan = 0; static int mainscan = 0; /* Groen flesje int iLowH = 30; int iHighH = 69; int iLowS = 152; int iHighS = 255; int iLowV = 41; int iHighV = 166; */ /*Blauw Flesje int iLowH = 94; int iHighH = 134; int iLowS = 65; int iHighS = 180; int iLowV = 29; int iHighV = 127; */ /*Rood Cola int iLowH = 0; int iHighH = 29; int iLowS = 211; int iHighS = 255; int iLowV = 11; int iHighV = 190; */ //Groen Arizona int iLowH = 19; int iHighH = 98; int iLowS = 155; int iHighS = 255; int iLowV = 47; int iHighV = 255; typedef union U_FloatParse { float float_data; unsigned char byte_data[4]; } U_FloatConvert; int ReadDepthData(unsigned int height_pos, unsigned int width_pos, sensor_msgs::ImageConstPtr depth_image) { //credits opencv math and tutorial to Kyle Hounslaw // If position is invalid if ((height_pos >= depth_image->height) || (width_pos >= depth_image->width)) return -1; int index = (height_pos*depth_image->step) + (width_pos*(depth_image->step/depth_image->width)); // If data is 4 byte floats (rectified depth image) if ((depth_image->step/depth_image->width) == 4) { U_FloatConvert depth_data; int i, endian_check = 1; // If big endian if ((depth_image->is_bigendian && (*(char*)&endian_check != 1)) || // Both big endian ((!depth_image->is_bigendian) && (*(char*)&endian_check == 1))) // Both lil endian { for (i = 0; i < 4; i++) depth_data.byte_data[i] = depth_image->data[index + i]; // Make sure data is valid (check if NaN) if (depth_data.float_data == depth_data.float_data) return int(depth_data.float_data*1000); return -1; // If depth data invalid } // else, one little endian, one big endian for (i = 0; i < 4; i++) depth_data.byte_data[i] = depth_image->data[3 + index - i]; // Make sure data is valid (check if NaN) if (depth_data.float_data == depth_data.float_data) return int(depth_data.float_data*1000); return -1; // If depth data invalid } // Otherwise, data is 2 byte integers (raw depth image) int temp_val; // If big endian if (depth_image->is_bigendian) temp_val = (depth_image->data[index] << 8) + depth_image->data[index + 1]; // If little endian else temp_val = depth_image->data[index] + (depth_image->data[index + 1] << 8); // Make sure data is valid (check if NaN) if (temp_val == temp_val) return temp_val; return -1; // If depth data invalid } //imagecallback takes the camera sensor values, extracts the wanted HSV values from them and then finds the biggest part of the image which has this given value. //After this a bounding box is put around that part of the image, and from the center of this box the depth value and position on the screen is calculated. void imageCallback(const sensor_msgs::ImageConstPtr& msg, const sensor_msgs::ImageConstPtr& msg_depth, const sensor_msgs::CameraInfoConstPtr& right_camera) { //CVBridge is used to convert the image from ROS to OpenCV format in order to use OpenCV's functions. cv_bridge::CvImagePtr cv_ptr; try { cv_ptr = cv_bridge::toCvCopy(msg, sensor_msgs::image_encodings::BGR8); } catch (cv_bridge::Exception& e) { ROS_ERROR("cv_bridge exception: %s", e.what()); return; } Mat imgOriginal; Mat imgHSV; cv::cvtColor(cv_ptr->image, imgHSV, cv::COLOR_BGR2HSV); //Convert the captured frame from RGB to HSV Mat imgThresholded; inRange(imgHSV, Scalar(iLowH, iLowS, iLowV), Scalar(iHighH, iHighS, iHighV), imgThresholded); //Threshold the image double m01, m10, area; int posX = 0, posY = 0; Moments oMoments = moments(imgThresholded); m01 = oMoments.m01; m10 = oMoments.m10; area = oMoments.m00; // Filter position if (area > 1000000) { // Position posX = m10 / area; posY = m01 / area; } //Remove small objects from the foreground.Morphsize (ms) can be changed to filter out small objects. //The bigger the value of ms (erosion), the bigger an object has to be to get picked up by the camera. int ms = 25; int ds = 5; erode(imgThresholded, imgThresholded, getStructuringElement(MORPH_ELLIPSE, Size(ms, ms)) ); dilate( imgThresholded, imgThresholded, getStructuringElement(MORPH_ELLIPSE, Size(ms, ms)) ); //morphological closing (fill small holes in the foreground) dilate( imgThresholded, imgThresholded, getStructuringElement(MORPH_ELLIPSE, Size(ds, ds)) ); erode(imgThresholded, imgThresholded, getStructuringElement(MORPH_ELLIPSE, Size(ds, ds)) ); imshow("hsv", imgThresholded); //show the thresholded image int largest_area = 0; int largest_contour_index = 0; double width, height; vector< vector<Point> > contours; // Vector for storing contour vector<Vec4i> hierarchy; Rect bounding_rect; // Find all contours in thresholded image findContours(imgThresholded, contours, hierarchy, CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE); // Find the biggest contour and calculate bounding box for(int i = 0; i < contours.size(); i++) { double a = contourArea(contours[i], false); if(a > largest_area) { largest_area = a; largest_contour_index = i; bounding_rect = boundingRect(contours[i]); } } // Calculate width and heigt of bounding box width = bounding_rect.br().x - bounding_rect.tl().x; height = bounding_rect.br().y - bounding_rect.tl().y; // Calculate center.x Point center = Point(((width/2) + bounding_rect.tl().x), ((height/2) + bounding_rect.tl().y)); int depth = ReadDepthData(center.y, center.x, msg_depth); // Print coordinates from the object //ROS_INFO("Center x: %d, center y: %d\n", center.x, center.y); drawContours(cv_ptr->image, contours, largest_contour_index, Scalar(255), 1, 8, hierarchy); // Draw the largest contour using previously stored index. circle(cv_ptr->image, center, 3, Scalar(255,255,0), -1, 8, 0); // Draw dot in center of bb rectangle(cv_ptr->image, bounding_rect.tl(), bounding_rect.br(), Scalar(255,255,0), 2, 8, 0); // Draw bounding box imshow("original", cv_ptr->image); //show the original image camcenter = center.x; //Make a new node ros::NodeHandle nc; ros::Publisher ctr_pub = nc.advertise<std_msgs::Int32>("centerdata", 1); if (camcenter>0) { std_msgs::Int32 ctr; ctr.data = camcenter; ROS_INFO("center: %d", ctr.data); ctr_pub.publish(ctr); } ros::NodeHandle nd; ros::Publisher dpt_pub = nd.advertise<std_msgs::Int32>("depthdata", 1); if (camcenter>0) { std_msgs::Int32 dpt; dpt.data = depth; ROS_INFO("depth: %d", dpt.data); dpt_pub.publish(dpt); } } int main(int argc, char** argv) { ros::init(argc, argv, "opencvnode"); ros::NodeHandle nh; message_filters::Subscriber<CameraInfo> camera_info_sub(nh, "/camera/depth_registered/camera_info", 1); message_filters::Subscriber<Image> depth_image_sub(nh, "/camera/depth/image_raw", 1); message_filters::Subscriber<Image> rgb_image_sub(nh, "/camera/rgb/image_raw", 1); ros::NodeHandle nc; ros::Publisher ctr_pub = nc.advertise<std_msgs::Int32>("centerdata", 1); ros::NodeHandle nd; ros::Publisher dpt_pub = nd.advertise<std_msgs::Int32>("depthdata", 1); //message_filters::Subscriber<std_msgs::String> coordinates_array(nh_, "chatter" , 1); typedef sync_policies::ApproximateTime<Image, Image, CameraInfo> MySyncPolicy; Synchronizer<MySyncPolicy> sync(MySyncPolicy(1), rgb_image_sub, depth_image_sub, camera_info_sub); //TimeSynchronizer<Image, Image, CameraInfo> sync(rgb_image_sub, depth_image_sub, camera_info_sub, 10); sync.registerCallback(boost::bind(&imageCallback, _1, _2, _3)); //cv::namedWindow(OPENCV_WINDOW); namedWindow("original", CV_WINDOW_AUTOSIZE); //create a window called "Control" namedWindow("hsv", CV_WINDOW_AUTOSIZE); // TODO change to hsv values loaded in. For the green card it is: H:42, 90. S:90,255. V:0,255 //Create trackbars in "Control" window cvCreateTrackbar("LowH", "original", &iLowH, 179); //Hue (0 - 179) cvCreateTrackbar("HighH", "original", &iHighH, 179); cvCreateTrackbar("LowS", "original", &iLowS, 255); //Saturation (0 - 255) cvCreateTrackbar("HighS", "original", &iHighS, 255); cvCreateTrackbar("LowV", "original", &iLowV, 255); //Value (0 - 255) cvCreateTrackbar("HighV", "original", &iHighV, 255); cvStartWindowThread(); ros::spin(); return 0; }
Update opencvros.cpp
Update opencvros.cpp
C++
mit
yacob1010/ros
8565c7f2a140769fdd237704ed93ee6a36c20d2e
liboh/plugins/manual_query/ManualObjectQueryProcessor.cpp
liboh/plugins/manual_query/ManualObjectQueryProcessor.cpp
// Copyright (c) 2011 Sirikata 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 "ManualObjectQueryProcessor.hpp" #include <sirikata/core/network/IOStrandImpl.hpp> #define QPLOG(lvl, msg) SILOG(manual-query-processor, lvl, msg) namespace Sirikata { namespace OH { namespace Manual { ManualObjectQueryProcessor* ManualObjectQueryProcessor::create(ObjectHostContext* ctx, const String& args) { return new ManualObjectQueryProcessor(ctx); } ManualObjectQueryProcessor::ManualObjectQueryProcessor(ObjectHostContext* ctx) : ObjectQueryProcessor(ctx), mContext(ctx), mStrand(mContext->ioService->createStrand("ManualObjectQueryProcessor Strand")), mServerQueryHandler(ctx, this, mStrand) { } ManualObjectQueryProcessor::~ManualObjectQueryProcessor() { } void ManualObjectQueryProcessor::start() { mServerQueryHandler.start(); mContext->objectHost->ObjectNodeSessionProvider::addListener(static_cast<ObjectNodeSessionListener*>(this)); } void ManualObjectQueryProcessor::stop() { mServerQueryHandler.stop(); mContext->objectHost->ObjectNodeSessionProvider::removeListener(static_cast<ObjectNodeSessionListener*>(this)); for(QueryHandlerMap::iterator it = mObjectQueryHandlers.begin(); it != mObjectQueryHandlers.end(); it++) it->second->stop(); mObjectQueryHandlers.clear(); mObjectState.clear(); } void ManualObjectQueryProcessor::onObjectNodeSession(const SpaceID& space, const ObjectReference& oref, const OHDP::NodeID& id) { QPLOG(detailed, "New object-space node session: " << oref << " connected to " << space << "-" << id); OHDP::SpaceNodeID snid(space, id); SpaceObjectReference sporef(space, oref); ObjectStateMap::iterator obj_it = mObjectState.find(sporef); // First, clear out old state. This needs to happen before any changes are // made so it can clear out all the old state if (obj_it != mObjectState.end() && obj_it->second.node != OHDP::NodeID::null()) { OHDP::SpaceNodeID old_snid(obj_it->first.space(), obj_it->second.node); mServerQueryHandler.decrementServerQuery(old_snid); if (obj_it->second.registered) unregisterObjectQuery(sporef); } // Update state // Object no longer has a session, it's no longer relevant if (id == OHDP::NodeID::null()) { mObjectState.erase(obj_it); return; } // Otherwise it's new/migrating if (obj_it == mObjectState.end()) obj_it = mObjectState.insert( ObjectStateMap::value_type(sporef, ObjectState()) ).first; obj_it->second.node = id; // Figure out if we need to do anything for registration. At a minimum, // hold onto the server query handler. mServerQueryHandler.incrementServerQuery(snid); // *Don't* try to register. Instead, we need to wait until we're really // fully connected, i.e. until we get an SST stream callback } void ManualObjectQueryProcessor::presenceConnected(HostedObjectPtr ho, const SpaceObjectReference& sporef) { } void ManualObjectQueryProcessor::presenceConnectedStream(HostedObjectPtr ho, const SpaceObjectReference& sporef, SSTStreamPtr strm) { // And possibly register the query ObjectStateMap::iterator obj_it = mObjectState.find(sporef); if (obj_it == mObjectState.end()) return; if (obj_it->second.needsRegistration()) registerOrUpdateObjectQuery(sporef); } void ManualObjectQueryProcessor::presenceDisconnected(HostedObjectPtr ho, const SpaceObjectReference& sporef) { } String ManualObjectQueryProcessor::connectRequest(HostedObjectPtr ho, const SpaceObjectReference& sporef, const String& query) { if (!query.empty()) { ObjectStateMap::iterator obj_it = mObjectState.find(sporef); // Very likely brand new here if (obj_it == mObjectState.end()) obj_it = mObjectState.insert( ObjectStateMap::value_type(sporef, ObjectState()) ).first; obj_it->second.who = ho; obj_it->second.query = query; } // Return an empty query -- we don't want any query passed on to the // serve. We aggregate and register the OH query separately. return ""; } void ManualObjectQueryProcessor::updateQuery(HostedObjectPtr ho, const SpaceObjectReference& sporef, const String& new_query) { ObjectStateMap::iterator it = mObjectState.find(sporef); if (new_query.empty()) { // Cancellation // Fill in the new query, we may still keep this around so we // want an accurate record. it->second.query = new_query; // Clear object state if possible if (it->second.registered) unregisterObjectQuery(sporef); if (it->second.canRemove()) mObjectState.erase(it); } else { // Init or update // Track state it->second.who = ho; it->second.query = new_query; // (New query and can register) or (already registered, needs // update). If we have a new query but can't yet register, it'll be // checked when the connection succeeds if ( (it->second.needsRegistration() && it->second.canRegister()) || (it->second.registered) ) registerOrUpdateObjectQuery(sporef); } } void ManualObjectQueryProcessor::createdServerQuery(const OHDP::SpaceNodeID& snid) { // We get this when the first object session with a space server starts. We // can use this to setup the query processor for objects connected to that // space server. ObjectQueryHandlerPtr obj_query_handler( new ObjectQueryHandler(mContext, this, snid, mStrand) ); mObjectQueryHandlers.insert( QueryHandlerMap::value_type( snid, obj_query_handler ) ); obj_query_handler->start(); } void ManualObjectQueryProcessor::removedServerQuery(const OHDP::SpaceNodeID& snid) { QueryHandlerMap::iterator it = mObjectQueryHandlers.find(snid); assert( it != mObjectQueryHandlers.end() ); ObjectQueryHandlerPtr obj_query_handler = it->second; mObjectQueryHandlers.erase(it); obj_query_handler->stop(); } void ManualObjectQueryProcessor::createdReplicatedIndex(const OHDP::SpaceNodeID& snid, ProxIndexID iid, ReplicatedLocationServiceCachePtr loc_cache, ServerID objects_from_server, bool dynamic_objects) { QueryHandlerMap::iterator it = mObjectQueryHandlers.find(snid); assert( it != mObjectQueryHandlers.end() ); it->second->createdReplicatedIndex(iid, loc_cache, objects_from_server, dynamic_objects); } void ManualObjectQueryProcessor::removedReplicatedIndex(const OHDP::SpaceNodeID& snid, ProxIndexID iid) { QueryHandlerMap::iterator it = mObjectQueryHandlers.find(snid); assert( it != mObjectQueryHandlers.end() ); it->second->removedReplicatedIndex(iid); } void ManualObjectQueryProcessor::queriersAreObserving(const OHDP::SpaceNodeID& snid, const ProxIndexID indexid, const ObjectReference& objid) { mServerQueryHandler.queriersAreObserving(snid, indexid, objid); } void ManualObjectQueryProcessor::queriersStoppedObserving(const OHDP::SpaceNodeID& snid, const ProxIndexID indexid, const ObjectReference& objid) { mServerQueryHandler.queriersStoppedObserving(snid, indexid, objid); } void ManualObjectQueryProcessor::registerOrUpdateObjectQuery(const SpaceObjectReference& sporef) { // Get query info ObjectStateMap::iterator it = mObjectState.find(sporef); assert(it != mObjectState.end()); ObjectState& state = it->second; HostedObjectPtr ho = state.who.lock(); assert( ho && !state.query.empty() && state.node != OHDP::NodeID::null() ); // Get the appropriate handler QueryHandlerMap::iterator handler_it = mObjectQueryHandlers.find(OHDP::SpaceNodeID(sporef.space(), state.node)); assert(handler_it != mObjectQueryHandlers.end()); ObjectQueryHandlerPtr handler = handler_it->second; // And register handler->updateQuery(ho, sporef, state.query); state.registered = true; } void ManualObjectQueryProcessor::unregisterObjectQuery(const SpaceObjectReference& sporef) { // Get query info ObjectStateMap::iterator it = mObjectState.find(sporef); assert(it != mObjectState.end()); ObjectState& state = it->second; HostedObjectPtr ho = state.who.lock(); // unregisterObjectQuery can happen due to disconnection where we // want to preserve the query info, so we can't assert an empty // query like we assert a non-empty one in registerOrUpdateObjectQuery assert( ho && state.node != OHDP::NodeID::null() ); // Get the appropriate handler QueryHandlerMap::iterator handler_it = mObjectQueryHandlers.find(OHDP::SpaceNodeID(sporef.space(), state.node)); assert(handler_it != mObjectQueryHandlers.end()); ObjectQueryHandlerPtr handler = handler_it->second; // And unregister handler->removeQuery(ho, sporef); state.registered = false; } void ManualObjectQueryProcessor::deliverProximityResult(const SpaceObjectReference& sporef, const Sirikata::Protocol::Prox::ProximityUpdate& update) { ObjectStateMap::iterator it = mObjectState.find(sporef); // Object may no longer exist since events cross strands if (it == mObjectState.end()) return; HostedObjectPtr ho = it->second.who.lock(); if (!ho) return; // Should already be in local time, so we can deliver directly deliverProximityUpdate(ho, sporef, update); } void ManualObjectQueryProcessor::deliverLocationResult(const SpaceObjectReference& sporef, const LocUpdate& lu) { ObjectStateMap::iterator it = mObjectState.find(sporef); // Object may no longer exist since events cross strands if (it == mObjectState.end()) return; HostedObjectPtr ho = it->second.who.lock(); if (!ho) return; deliverLocationUpdate(ho, sporef, lu); } void ManualObjectQueryProcessor::commandProperties(const Command::Command& cmd, Command::Commander* cmdr, Command::CommandID cmdid) { Command::Result result = Command::EmptyResult(); result.put("name", "libprox-manual"); result.put("settings.handlers", mObjectQueryHandlers.size()); cmdr->result(cmdid, result); } void ManualObjectQueryProcessor::commandListHandlers(const Command::Command& cmd, Command::Commander* cmdr, Command::CommandID cmdid) { Command::Result result = Command::EmptyResult(); for (QueryHandlerMap::iterator it = mObjectQueryHandlers.begin(); it != mObjectQueryHandlers.end(); it++) { ObjectQueryHandlerPtr hdlr = it->second; hdlr->commandListInfo(it->first, result); } cmdr->result(cmdid, result); } ManualObjectQueryProcessor::ObjectQueryHandlerPtr ManualObjectQueryProcessor::lookupCommandHandler(const Command::Command& cmd, Command::Commander* cmdr, Command::CommandID cmdid) const { ObjectQueryHandlerPtr result; if (cmd.contains("handler")) { String handler_name = cmd.getString("handler"); // Only the first part of the handler name is the SpaceNodeID we need to // look up the ObjectQueryHandler handler_name = handler_name.substr(0, handler_name.find('.')); OHDP::SpaceNodeID snid(handler_name); QueryHandlerMap::const_iterator it = mObjectQueryHandlers.find(snid); if (it != mObjectQueryHandlers.end()) result = it->second; } if (!result) { Command::Result result = Command::EmptyResult(); result.put("error", "Ill-formatted request: handler not specified or invalid."); cmdr->result(cmdid, result); } return result; } void ManualObjectQueryProcessor::commandListNodes(const Command::Command& cmd, Command::Commander* cmdr, Command::CommandID cmdid) { // Look up or trigger error message ObjectQueryHandlerPtr handler = lookupCommandHandler(cmd, cmdr, cmdid); if (!handler) return; handler->commandListNodes(cmd, cmdr, cmdid); } void ManualObjectQueryProcessor::commandForceRebuild(const Command::Command& cmd, Command::Commander* cmdr, Command::CommandID cmdid) { // Look up or trigger error message ObjectQueryHandlerPtr handler = lookupCommandHandler(cmd, cmdr, cmdid); if (!handler) return; handler->commandForceRebuild(cmd, cmdr, cmdid); } } // namespace Manual } // namespace OH } // namespace Sirikata
// Copyright (c) 2011 Sirikata 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 "ManualObjectQueryProcessor.hpp" #include <sirikata/core/network/IOStrandImpl.hpp> #define QPLOG(lvl, msg) SILOG(manual-query-processor, lvl, msg) namespace Sirikata { namespace OH { namespace Manual { ManualObjectQueryProcessor* ManualObjectQueryProcessor::create(ObjectHostContext* ctx, const String& args) { return new ManualObjectQueryProcessor(ctx); } ManualObjectQueryProcessor::ManualObjectQueryProcessor(ObjectHostContext* ctx) : ObjectQueryProcessor(ctx), mContext(ctx), mStrand(mContext->ioService->createStrand("ManualObjectQueryProcessor Strand")), mServerQueryHandler(ctx, this, mStrand) { } ManualObjectQueryProcessor::~ManualObjectQueryProcessor() { } void ManualObjectQueryProcessor::start() { mServerQueryHandler.start(); mContext->objectHost->ObjectNodeSessionProvider::addListener(static_cast<ObjectNodeSessionListener*>(this)); } void ManualObjectQueryProcessor::stop() { mServerQueryHandler.stop(); mContext->objectHost->ObjectNodeSessionProvider::removeListener(static_cast<ObjectNodeSessionListener*>(this)); for(QueryHandlerMap::iterator it = mObjectQueryHandlers.begin(); it != mObjectQueryHandlers.end(); it++) it->second->stop(); mObjectQueryHandlers.clear(); mObjectState.clear(); } void ManualObjectQueryProcessor::onObjectNodeSession(const SpaceID& space, const ObjectReference& oref, const OHDP::NodeID& id) { QPLOG(detailed, "New object-space node session: " << oref << " connected to " << space << "-" << id); OHDP::SpaceNodeID snid(space, id); SpaceObjectReference sporef(space, oref); ObjectStateMap::iterator obj_it = mObjectState.find(sporef); // First, clear out old state. This needs to happen before any changes are // made so it can clear out all the old state if (obj_it != mObjectState.end() && obj_it->second.node != OHDP::NodeID::null()) { OHDP::SpaceNodeID old_snid(obj_it->first.space(), obj_it->second.node); mServerQueryHandler.decrementServerQuery(old_snid); if (obj_it->second.registered) unregisterObjectQuery(sporef); } // Update state // Object no longer has a session, it's no longer relevant if (id == OHDP::NodeID::null()) { if (obj_it != mObjectState.end()) mObjectState.erase(obj_it); return; } // Otherwise it's new/migrating if (obj_it == mObjectState.end()) obj_it = mObjectState.insert( ObjectStateMap::value_type(sporef, ObjectState()) ).first; obj_it->second.node = id; // Figure out if we need to do anything for registration. At a minimum, // hold onto the server query handler. mServerQueryHandler.incrementServerQuery(snid); // *Don't* try to register. Instead, we need to wait until we're really // fully connected, i.e. until we get an SST stream callback } void ManualObjectQueryProcessor::presenceConnected(HostedObjectPtr ho, const SpaceObjectReference& sporef) { } void ManualObjectQueryProcessor::presenceConnectedStream(HostedObjectPtr ho, const SpaceObjectReference& sporef, SSTStreamPtr strm) { // And possibly register the query ObjectStateMap::iterator obj_it = mObjectState.find(sporef); if (obj_it == mObjectState.end()) return; if (obj_it->second.needsRegistration()) registerOrUpdateObjectQuery(sporef); } void ManualObjectQueryProcessor::presenceDisconnected(HostedObjectPtr ho, const SpaceObjectReference& sporef) { } String ManualObjectQueryProcessor::connectRequest(HostedObjectPtr ho, const SpaceObjectReference& sporef, const String& query) { if (!query.empty()) { ObjectStateMap::iterator obj_it = mObjectState.find(sporef); // Very likely brand new here if (obj_it == mObjectState.end()) obj_it = mObjectState.insert( ObjectStateMap::value_type(sporef, ObjectState()) ).first; obj_it->second.who = ho; obj_it->second.query = query; } // Return an empty query -- we don't want any query passed on to the // serve. We aggregate and register the OH query separately. return ""; } void ManualObjectQueryProcessor::updateQuery(HostedObjectPtr ho, const SpaceObjectReference& sporef, const String& new_query) { ObjectStateMap::iterator it = mObjectState.find(sporef); if (new_query.empty()) { // Cancellation // Fill in the new query, we may still keep this around so we // want an accurate record. it->second.query = new_query; // Clear object state if possible if (it->second.registered) unregisterObjectQuery(sporef); if (it->second.canRemove()) mObjectState.erase(it); } else { // Init or update // Track state it->second.who = ho; it->second.query = new_query; // (New query and can register) or (already registered, needs // update). If we have a new query but can't yet register, it'll be // checked when the connection succeeds if ( (it->second.needsRegistration() && it->second.canRegister()) || (it->second.registered) ) registerOrUpdateObjectQuery(sporef); } } void ManualObjectQueryProcessor::createdServerQuery(const OHDP::SpaceNodeID& snid) { // We get this when the first object session with a space server starts. We // can use this to setup the query processor for objects connected to that // space server. ObjectQueryHandlerPtr obj_query_handler( new ObjectQueryHandler(mContext, this, snid, mStrand) ); mObjectQueryHandlers.insert( QueryHandlerMap::value_type( snid, obj_query_handler ) ); obj_query_handler->start(); } void ManualObjectQueryProcessor::removedServerQuery(const OHDP::SpaceNodeID& snid) { QueryHandlerMap::iterator it = mObjectQueryHandlers.find(snid); assert( it != mObjectQueryHandlers.end() ); ObjectQueryHandlerPtr obj_query_handler = it->second; mObjectQueryHandlers.erase(it); obj_query_handler->stop(); } void ManualObjectQueryProcessor::createdReplicatedIndex(const OHDP::SpaceNodeID& snid, ProxIndexID iid, ReplicatedLocationServiceCachePtr loc_cache, ServerID objects_from_server, bool dynamic_objects) { QueryHandlerMap::iterator it = mObjectQueryHandlers.find(snid); assert( it != mObjectQueryHandlers.end() ); it->second->createdReplicatedIndex(iid, loc_cache, objects_from_server, dynamic_objects); } void ManualObjectQueryProcessor::removedReplicatedIndex(const OHDP::SpaceNodeID& snid, ProxIndexID iid) { QueryHandlerMap::iterator it = mObjectQueryHandlers.find(snid); assert( it != mObjectQueryHandlers.end() ); it->second->removedReplicatedIndex(iid); } void ManualObjectQueryProcessor::queriersAreObserving(const OHDP::SpaceNodeID& snid, const ProxIndexID indexid, const ObjectReference& objid) { mServerQueryHandler.queriersAreObserving(snid, indexid, objid); } void ManualObjectQueryProcessor::queriersStoppedObserving(const OHDP::SpaceNodeID& snid, const ProxIndexID indexid, const ObjectReference& objid) { mServerQueryHandler.queriersStoppedObserving(snid, indexid, objid); } void ManualObjectQueryProcessor::registerOrUpdateObjectQuery(const SpaceObjectReference& sporef) { // Get query info ObjectStateMap::iterator it = mObjectState.find(sporef); assert(it != mObjectState.end()); ObjectState& state = it->second; HostedObjectPtr ho = state.who.lock(); assert( ho && !state.query.empty() && state.node != OHDP::NodeID::null() ); // Get the appropriate handler QueryHandlerMap::iterator handler_it = mObjectQueryHandlers.find(OHDP::SpaceNodeID(sporef.space(), state.node)); assert(handler_it != mObjectQueryHandlers.end()); ObjectQueryHandlerPtr handler = handler_it->second; // And register handler->updateQuery(ho, sporef, state.query); state.registered = true; } void ManualObjectQueryProcessor::unregisterObjectQuery(const SpaceObjectReference& sporef) { // Get query info ObjectStateMap::iterator it = mObjectState.find(sporef); assert(it != mObjectState.end()); ObjectState& state = it->second; HostedObjectPtr ho = state.who.lock(); // unregisterObjectQuery can happen due to disconnection where we // want to preserve the query info, so we can't assert an empty // query like we assert a non-empty one in registerOrUpdateObjectQuery assert( ho && state.node != OHDP::NodeID::null() ); // Get the appropriate handler QueryHandlerMap::iterator handler_it = mObjectQueryHandlers.find(OHDP::SpaceNodeID(sporef.space(), state.node)); assert(handler_it != mObjectQueryHandlers.end()); ObjectQueryHandlerPtr handler = handler_it->second; // And unregister handler->removeQuery(ho, sporef); state.registered = false; } void ManualObjectQueryProcessor::deliverProximityResult(const SpaceObjectReference& sporef, const Sirikata::Protocol::Prox::ProximityUpdate& update) { ObjectStateMap::iterator it = mObjectState.find(sporef); // Object may no longer exist since events cross strands if (it == mObjectState.end()) return; HostedObjectPtr ho = it->second.who.lock(); if (!ho) return; // Should already be in local time, so we can deliver directly deliverProximityUpdate(ho, sporef, update); } void ManualObjectQueryProcessor::deliverLocationResult(const SpaceObjectReference& sporef, const LocUpdate& lu) { ObjectStateMap::iterator it = mObjectState.find(sporef); // Object may no longer exist since events cross strands if (it == mObjectState.end()) return; HostedObjectPtr ho = it->second.who.lock(); if (!ho) return; deliverLocationUpdate(ho, sporef, lu); } void ManualObjectQueryProcessor::commandProperties(const Command::Command& cmd, Command::Commander* cmdr, Command::CommandID cmdid) { Command::Result result = Command::EmptyResult(); result.put("name", "libprox-manual"); result.put("settings.handlers", mObjectQueryHandlers.size()); cmdr->result(cmdid, result); } void ManualObjectQueryProcessor::commandListHandlers(const Command::Command& cmd, Command::Commander* cmdr, Command::CommandID cmdid) { Command::Result result = Command::EmptyResult(); for (QueryHandlerMap::iterator it = mObjectQueryHandlers.begin(); it != mObjectQueryHandlers.end(); it++) { ObjectQueryHandlerPtr hdlr = it->second; hdlr->commandListInfo(it->first, result); } cmdr->result(cmdid, result); } ManualObjectQueryProcessor::ObjectQueryHandlerPtr ManualObjectQueryProcessor::lookupCommandHandler(const Command::Command& cmd, Command::Commander* cmdr, Command::CommandID cmdid) const { ObjectQueryHandlerPtr result; if (cmd.contains("handler")) { String handler_name = cmd.getString("handler"); // Only the first part of the handler name is the SpaceNodeID we need to // look up the ObjectQueryHandler handler_name = handler_name.substr(0, handler_name.find('.')); OHDP::SpaceNodeID snid(handler_name); QueryHandlerMap::const_iterator it = mObjectQueryHandlers.find(snid); if (it != mObjectQueryHandlers.end()) result = it->second; } if (!result) { Command::Result result = Command::EmptyResult(); result.put("error", "Ill-formatted request: handler not specified or invalid."); cmdr->result(cmdid, result); } return result; } void ManualObjectQueryProcessor::commandListNodes(const Command::Command& cmd, Command::Commander* cmdr, Command::CommandID cmdid) { // Look up or trigger error message ObjectQueryHandlerPtr handler = lookupCommandHandler(cmd, cmdr, cmdid); if (!handler) return; handler->commandListNodes(cmd, cmdr, cmdid); } void ManualObjectQueryProcessor::commandForceRebuild(const Command::Command& cmd, Command::Commander* cmdr, Command::CommandID cmdid) { // Look up or trigger error message ObjectQueryHandlerPtr handler = lookupCommandHandler(cmd, cmdr, cmdid); if (!handler) return; handler->commandForceRebuild(cmd, cmdr, cmdid); } } // namespace Manual } // namespace OH } // namespace Sirikata
Fix missing check on iterator in ManualObjectQueryProcessor.
Fix missing check on iterator in ManualObjectQueryProcessor.
C++
bsd-3-clause
sirikata/sirikata,sirikata/sirikata,sirikata/sirikata,sirikata/sirikata,sirikata/sirikata,sirikata/sirikata,sirikata/sirikata,sirikata/sirikata
b60cf19fdddbb13380f9e167c1326df8365005c9
Source/core/frame/ConsoleBase.cpp
Source/core/frame/ConsoleBase.cpp
/* * Copyright (C) 2007 Apple 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: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of Apple Computer, Inc. ("Apple") 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 APPLE AND ITS 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 APPLE OR ITS 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 "config.h" #include "core/frame/Console.h" #include "bindings/core/v8/ScriptCallStackFactory.h" #include "core/inspector/InspectorConsoleInstrumentation.h" #include "core/inspector/InspectorTraceEvents.h" #include "core/inspector/ScriptArguments.h" #include "platform/TraceEvent.h" #include "wtf/text/CString.h" #include "wtf/text/WTFString.h" namespace blink { ConsoleBase::~ConsoleBase() { } void ConsoleBase::debug(ScriptState* scriptState, PassRefPtrWillBeRawPtr<ScriptArguments> arguments) { internalAddMessage(LogMessageType, DebugMessageLevel, scriptState, arguments); } void ConsoleBase::error(ScriptState* scriptState, PassRefPtrWillBeRawPtr<ScriptArguments> arguments) { internalAddMessage(LogMessageType, ErrorMessageLevel, scriptState, arguments); } void ConsoleBase::info(ScriptState* scriptState, PassRefPtrWillBeRawPtr<ScriptArguments> arguments) { internalAddMessage(LogMessageType, InfoMessageLevel, scriptState, arguments); } void ConsoleBase::log(ScriptState* scriptState, PassRefPtrWillBeRawPtr<ScriptArguments> arguments) { internalAddMessage(LogMessageType, LogMessageLevel, scriptState, arguments); } void ConsoleBase::warn(ScriptState* scriptState, PassRefPtrWillBeRawPtr<ScriptArguments> arguments) { internalAddMessage(LogMessageType, WarningMessageLevel, scriptState, arguments); } void ConsoleBase::dir(ScriptState* scriptState, PassRefPtrWillBeRawPtr<ScriptArguments> arguments) { internalAddMessage(DirMessageType, LogMessageLevel, scriptState, arguments); } void ConsoleBase::dirxml(ScriptState* scriptState, PassRefPtrWillBeRawPtr<ScriptArguments> arguments) { internalAddMessage(DirXMLMessageType, LogMessageLevel, scriptState, arguments); } void ConsoleBase::table(ScriptState* scriptState, PassRefPtrWillBeRawPtr<ScriptArguments> arguments) { internalAddMessage(TableMessageType, LogMessageLevel, scriptState, arguments); } void ConsoleBase::clear(ScriptState* scriptState, PassRefPtrWillBeRawPtr<ScriptArguments> arguments) { internalAddMessage(ClearMessageType, LogMessageLevel, scriptState, arguments, true); } void ConsoleBase::trace(ScriptState* scriptState, PassRefPtrWillBeRawPtr<ScriptArguments> arguments) { internalAddMessage(TraceMessageType, LogMessageLevel, scriptState, arguments, true, true); } void ConsoleBase::assertCondition(ScriptState* scriptState, PassRefPtrWillBeRawPtr<ScriptArguments> arguments, bool condition) { if (condition) return; internalAddMessage(AssertMessageType, ErrorMessageLevel, scriptState, arguments, true); } void ConsoleBase::count(ScriptState* scriptState, PassRefPtrWillBeRawPtr<ScriptArguments> arguments) { RefPtrWillBeRawPtr<ScriptCallStack> callStack(createScriptCallStackForConsole(1)); const ScriptCallFrame& lastCaller = callStack->at(0); // Follow Firebug's behavior of counting with null and undefined title in // the same bucket as no argument String title; arguments->getFirstArgumentAsString(title); String identifier = title.isEmpty() ? String(lastCaller.sourceURL() + ':' + String::number(lastCaller.lineNumber())) : String(title + '@'); HashCountedSet<String>::AddResult result = m_counts.add(identifier); String message = title + ": " + String::number(result.storedValue->value); RefPtrWillBeRawPtr<ConsoleMessage> consoleMessage = ConsoleMessage::create(ConsoleAPIMessageSource, DebugMessageLevel, message); consoleMessage->setType(CountMessageType); consoleMessage->setScriptState(scriptState); consoleMessage->setCallStack(callStack.release()); reportMessageToConsole(consoleMessage.release()); } void ConsoleBase::markTimeline(const String& title) { timeStamp(title); } void ConsoleBase::profile(const String& title) { InspectorInstrumentation::consoleProfile(context(), title); } void ConsoleBase::profileEnd(const String& title) { InspectorInstrumentation::consoleProfileEnd(context(), title); } void ConsoleBase::time(const String& title) { InspectorInstrumentation::consoleTime(context(), title); TRACE_EVENT_COPY_ASYNC_BEGIN0("blink.console", title.utf8().data(), this); if (title.isNull()) return; m_times.add(title, monotonicallyIncreasingTime()); } void ConsoleBase::timeEnd(ScriptState* scriptState, const String& title) { TRACE_EVENT_COPY_ASYNC_END0("blink.console", title.utf8().data(), this); InspectorInstrumentation::consoleTimeEnd(context(), title, scriptState); // Follow Firebug's behavior of requiring a title that is not null or // undefined for timing functions if (title.isNull()) return; HashMap<String, double>::iterator it = m_times.find(title); if (it == m_times.end()) return; double startTime = it->value; m_times.remove(it); double elapsed = monotonicallyIncreasingTime() - startTime; String message = title + String::format(": %.3fms", elapsed * 1000); RefPtrWillBeRawPtr<ConsoleMessage> consoleMessage = ConsoleMessage::create(ConsoleAPIMessageSource, DebugMessageLevel, message); consoleMessage->setType(TimeEndMessageType); consoleMessage->setScriptState(scriptState); consoleMessage->setCallStack(createScriptCallStackForConsole(1)); reportMessageToConsole(consoleMessage.release()); } void ConsoleBase::timeStamp(const String& title) { TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "TimeStamp", "data", InspectorTimeStampEvent::data(context(), title)); // FIXME(361045): remove InspectorInstrumentation calls once DevTools Timeline migrates to tracing. InspectorInstrumentation::consoleTimeStamp(context(), title); } static String formatTimelineTitle(const String& title) { return String::format("Timeline '%s'", title.utf8().data()); } void ConsoleBase::timeline(ScriptState* scriptState, const String& title) { // FIXME(361045): remove InspectorInstrumentation calls once DevTools Timeline migrates to tracing. InspectorInstrumentation::consoleTimeline(context(), title, scriptState); TRACE_EVENT_COPY_ASYNC_BEGIN0("blink.console", formatTimelineTitle(title).utf8().data(), this); } void ConsoleBase::timelineEnd(ScriptState* scriptState, const String& title) { // FIXME(361045): remove InspectorInstrumentation calls once DevTools Timeline migrates to tracing. InspectorInstrumentation::consoleTimelineEnd(context(), title, scriptState); TRACE_EVENT_COPY_ASYNC_END0("blink.console", formatTimelineTitle(title).utf8().data(), this); } void ConsoleBase::group(ScriptState* scriptState, PassRefPtrWillBeRawPtr<ScriptArguments> arguments) { internalAddMessage(StartGroupMessageType, LogMessageLevel, scriptState, arguments, true); } void ConsoleBase::groupCollapsed(ScriptState* scriptState, PassRefPtrWillBeRawPtr<ScriptArguments> arguments) { internalAddMessage(StartGroupCollapsedMessageType, LogMessageLevel, scriptState, arguments, true); } void ConsoleBase::groupEnd() { internalAddMessage(EndGroupMessageType, LogMessageLevel, nullptr, nullptr, true); } void ConsoleBase::internalAddMessage(MessageType type, MessageLevel level, ScriptState* scriptState, PassRefPtrWillBeRawPtr<ScriptArguments> scriptArguments, bool acceptNoArguments, bool printTrace) { RefPtrWillBeRawPtr<ScriptArguments> arguments = scriptArguments; if (!acceptNoArguments && (!arguments || !arguments->argumentCount())) return; String message; bool gotStringMessage = arguments ? arguments->getFirstArgumentAsString(message) : false; if (gotStringMessage) for (unsigned i = 1; i < arguments->argumentCount(); ++i) { String argAsString; if (arguments->argumentAt(i).getString(arguments->globalState(), argAsString)) { message.append(" "); message.append(argAsString); } } RefPtrWillBeRawPtr<ConsoleMessage> consoleMessage = ConsoleMessage::create(ConsoleAPIMessageSource, level, gotStringMessage? message : String()); consoleMessage->setType(type); consoleMessage->setScriptState(scriptState); consoleMessage->setScriptArguments(arguments); size_t stackSize = printTrace ? ScriptCallStack::maxCallStackSizeToCapture : 1; consoleMessage->setCallStack(createScriptCallStackForConsole(stackSize)); reportMessageToConsole(consoleMessage.release()); } } // namespace blink
/* * Copyright (C) 2007 Apple 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: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of Apple Computer, Inc. ("Apple") 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 APPLE AND ITS 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 APPLE OR ITS 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 "config.h" #include "core/frame/Console.h" #include "bindings/core/v8/ScriptCallStackFactory.h" #include "core/inspector/InspectorConsoleInstrumentation.h" #include "core/inspector/InspectorTraceEvents.h" #include "core/inspector/ScriptArguments.h" #include "platform/TraceEvent.h" #include "wtf/text/CString.h" #include "wtf/text/WTFString.h" namespace blink { ConsoleBase::~ConsoleBase() { } void ConsoleBase::debug(ScriptState* scriptState, PassRefPtrWillBeRawPtr<ScriptArguments> arguments) { internalAddMessage(LogMessageType, DebugMessageLevel, scriptState, arguments); } void ConsoleBase::error(ScriptState* scriptState, PassRefPtrWillBeRawPtr<ScriptArguments> arguments) { internalAddMessage(LogMessageType, ErrorMessageLevel, scriptState, arguments); } void ConsoleBase::info(ScriptState* scriptState, PassRefPtrWillBeRawPtr<ScriptArguments> arguments) { internalAddMessage(LogMessageType, InfoMessageLevel, scriptState, arguments); } void ConsoleBase::log(ScriptState* scriptState, PassRefPtrWillBeRawPtr<ScriptArguments> arguments) { internalAddMessage(LogMessageType, LogMessageLevel, scriptState, arguments); } void ConsoleBase::warn(ScriptState* scriptState, PassRefPtrWillBeRawPtr<ScriptArguments> arguments) { internalAddMessage(LogMessageType, WarningMessageLevel, scriptState, arguments); } void ConsoleBase::dir(ScriptState* scriptState, PassRefPtrWillBeRawPtr<ScriptArguments> arguments) { internalAddMessage(DirMessageType, LogMessageLevel, scriptState, arguments); } void ConsoleBase::dirxml(ScriptState* scriptState, PassRefPtrWillBeRawPtr<ScriptArguments> arguments) { internalAddMessage(DirXMLMessageType, LogMessageLevel, scriptState, arguments); } void ConsoleBase::table(ScriptState* scriptState, PassRefPtrWillBeRawPtr<ScriptArguments> arguments) { internalAddMessage(TableMessageType, LogMessageLevel, scriptState, arguments); } void ConsoleBase::clear(ScriptState* scriptState, PassRefPtrWillBeRawPtr<ScriptArguments> arguments) { internalAddMessage(ClearMessageType, LogMessageLevel, scriptState, arguments, true); } void ConsoleBase::trace(ScriptState* scriptState, PassRefPtrWillBeRawPtr<ScriptArguments> arguments) { internalAddMessage(TraceMessageType, LogMessageLevel, scriptState, arguments, true, true); } void ConsoleBase::assertCondition(ScriptState* scriptState, PassRefPtrWillBeRawPtr<ScriptArguments> arguments, bool condition) { if (condition) return; internalAddMessage(AssertMessageType, ErrorMessageLevel, scriptState, arguments, true); } void ConsoleBase::count(ScriptState* scriptState, PassRefPtrWillBeRawPtr<ScriptArguments> arguments) { RefPtrWillBeRawPtr<ScriptCallStack> callStack(createScriptCallStackForConsole(1)); const ScriptCallFrame& lastCaller = callStack->at(0); // Follow Firebug's behavior of counting with null and undefined title in // the same bucket as no argument String title; arguments->getFirstArgumentAsString(title); String identifier = title.isEmpty() ? String(lastCaller.sourceURL() + ':' + String::number(lastCaller.lineNumber())) : String(title + '@'); HashCountedSet<String>::AddResult result = m_counts.add(identifier); String message = title + ": " + String::number(result.storedValue->value); RefPtrWillBeRawPtr<ConsoleMessage> consoleMessage = ConsoleMessage::create(ConsoleAPIMessageSource, DebugMessageLevel, message); consoleMessage->setType(CountMessageType); consoleMessage->setScriptState(scriptState); consoleMessage->setCallStack(callStack.release()); reportMessageToConsole(consoleMessage.release()); } void ConsoleBase::markTimeline(const String& title) { timeStamp(title); } void ConsoleBase::profile(const String& title) { InspectorInstrumentation::consoleProfile(context(), title); } void ConsoleBase::profileEnd(const String& title) { InspectorInstrumentation::consoleProfileEnd(context(), title); } void ConsoleBase::time(const String& title) { InspectorInstrumentation::consoleTime(context(), title); TRACE_EVENT_COPY_ASYNC_BEGIN0("blink.console", title.utf8().data(), this); if (title.isNull()) return; m_times.add(title, monotonicallyIncreasingTime()); } void ConsoleBase::timeEnd(ScriptState* scriptState, const String& title) { TRACE_EVENT_COPY_ASYNC_END0("blink.console", title.utf8().data(), this); InspectorInstrumentation::consoleTimeEnd(context(), title, scriptState); // Follow Firebug's behavior of requiring a title that is not null or // undefined for timing functions if (title.isNull()) return; HashMap<String, double>::iterator it = m_times.find(title); if (it == m_times.end()) return; double startTime = it->value; m_times.remove(it); double elapsed = monotonicallyIncreasingTime() - startTime; String message = title + String::format(": %.3fms", elapsed * 1000); RefPtrWillBeRawPtr<ConsoleMessage> consoleMessage = ConsoleMessage::create(ConsoleAPIMessageSource, DebugMessageLevel, message); consoleMessage->setType(TimeEndMessageType); consoleMessage->setScriptState(scriptState); consoleMessage->setCallStack(createScriptCallStackForConsole(1)); reportMessageToConsole(consoleMessage.release()); } void ConsoleBase::timeStamp(const String& title) { TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "TimeStamp", "data", InspectorTimeStampEvent::data(context(), title)); // FIXME(361045): remove InspectorInstrumentation calls once DevTools Timeline migrates to tracing. InspectorInstrumentation::consoleTimeStamp(context(), title); } static String formatTimelineTitle(const String& title) { return String::format("Timeline '%s'", title.utf8().data()); } void ConsoleBase::timeline(ScriptState* scriptState, const String& title) { // FIXME(361045): remove InspectorInstrumentation calls once DevTools Timeline migrates to tracing. InspectorInstrumentation::consoleTimeline(context(), title, scriptState); TRACE_EVENT_COPY_ASYNC_BEGIN0("blink.console", formatTimelineTitle(title).utf8().data(), this); } void ConsoleBase::timelineEnd(ScriptState* scriptState, const String& title) { // FIXME(361045): remove InspectorInstrumentation calls once DevTools Timeline migrates to tracing. InspectorInstrumentation::consoleTimelineEnd(context(), title, scriptState); TRACE_EVENT_COPY_ASYNC_END0("blink.console", formatTimelineTitle(title).utf8().data(), this); } void ConsoleBase::group(ScriptState* scriptState, PassRefPtrWillBeRawPtr<ScriptArguments> arguments) { internalAddMessage(StartGroupMessageType, LogMessageLevel, scriptState, arguments, true); } void ConsoleBase::groupCollapsed(ScriptState* scriptState, PassRefPtrWillBeRawPtr<ScriptArguments> arguments) { internalAddMessage(StartGroupCollapsedMessageType, LogMessageLevel, scriptState, arguments, true); } void ConsoleBase::groupEnd() { internalAddMessage(EndGroupMessageType, LogMessageLevel, nullptr, nullptr, true); } void ConsoleBase::internalAddMessage(MessageType type, MessageLevel level, ScriptState* scriptState, PassRefPtrWillBeRawPtr<ScriptArguments> scriptArguments, bool acceptNoArguments, bool printTrace) { RefPtrWillBeRawPtr<ScriptArguments> arguments = scriptArguments; if (!acceptNoArguments && (!arguments || !arguments->argumentCount())) return; String message; bool gotStringMessage = arguments ? arguments->getFirstArgumentAsString(message) : false; if (gotStringMessage) { message = ""; for (unsigned i = 0; i < arguments->argumentCount(); ++i) { String argAsString; if (arguments->argumentAt(i).getString(arguments->globalState(), argAsString)) { RefPtr<JSONValue> value = arguments->argumentAt(i).toJSONValue(scriptState); if (!value) continue; if (i) message.append(" "); message.append(value->toJSONString()); } } } RefPtrWillBeRawPtr<ConsoleMessage> consoleMessage = ConsoleMessage::create(ConsoleAPIMessageSource, level, gotStringMessage? message : String()); consoleMessage->setType(type); consoleMessage->setScriptState(scriptState); consoleMessage->setScriptArguments(arguments); size_t stackSize = printTrace ? ScriptCallStack::maxCallStackSizeToCapture : 1; consoleMessage->setCallStack(createScriptCallStackForConsole(stackSize)); reportMessageToConsole(consoleMessage.release()); } } // namespace blink
fix console.log() output in terminal
fix console.log() output in terminal From: Roger <[email protected]> Conflicts: Source/core/frame/ConsoleBase.cpp
C++
bsd-3-clause
modulexcite/blink,jtg-gg/blink,nwjs/blink,jtg-gg/blink,jtg-gg/blink,jtg-gg/blink,modulexcite/blink,jtg-gg/blink,modulexcite/blink,jtg-gg/blink,modulexcite/blink,nwjs/blink,nwjs/blink,modulexcite/blink,modulexcite/blink,modulexcite/blink,modulexcite/blink,modulexcite/blink,nwjs/blink,nwjs/blink,nwjs/blink,modulexcite/blink,jtg-gg/blink,nwjs/blink,jtg-gg/blink,nwjs/blink,nwjs/blink,jtg-gg/blink,nwjs/blink,jtg-gg/blink
5a24e07617200506d6d2f6fafea9ff18503f0fc6
modules/phase_field/src/auxkernels/FeatureFloodCountAux.C
modules/phase_field/src/auxkernels/FeatureFloodCountAux.C
//* This file is part of the MOOSE framework //* https://www.mooseframework.org //* //* All rights reserved, see COPYRIGHT for full restrictions //* https://github.com/idaholab/moose/blob/master/COPYRIGHT //* //* Licensed under LGPL 2.1, please see LICENSE for details //* https://www.gnu.org/licenses/lgpl-2.1.html #include "FeatureFloodCountAux.h" #include "FeatureFloodCount.h" #include "GrainTrackerInterface.h" #include "MooseEnum.h" #include <algorithm> registerMooseObject("PhaseFieldApp", FeatureFloodCountAux); template <> InputParameters validParams<FeatureFloodCountAux>() { InputParameters params = validParams<AuxKernel>(); params.addClassDescription("Feature detection by connectivity analysis"); params.addDeprecatedParam<UserObjectName>("bubble_object", "The FeatureFloodCount UserObject to get values from.", "Use \"flood_counter\" instead."); params.addRequiredParam<UserObjectName>("flood_counter", "The FeatureFloodCount UserObject to get values from."); params.addParam<unsigned int>("map_index", "The index of which map to retrieve values from when " "using FeatureFloodCount with multiple maps."); MooseEnum field_display( "UNIQUE_REGION VARIABLE_COLORING GHOSTED_ENTITIES HALOS CENTROID ACTIVE_BOUNDS", "UNIQUE_REGION"); params.addParam<MooseEnum>("field_display", field_display, "Determines how the auxilary field should be colored. " "(UNIQUE_REGION and VARIABLE_COLORING are nodal, CENTROID is " "elemental, default: UNIQUE_REGION)"); params.set<ExecFlagEnum>("execute_on") = {EXEC_INITIAL, EXEC_TIMESTEP_END}; return params; } FeatureFloodCountAux::FeatureFloodCountAux(const InputParameters & parameters) : AuxKernel(parameters), _flood_counter(getUserObject<FeatureFloodCount>("flood_counter")), _var_idx(isParamValid("map_index") ? getParam<unsigned int>("map_index") : std::numeric_limits<std::size_t>::max()), _field_display(getParam<MooseEnum>("field_display")), _var_coloring(_field_display == "VARIABLE_COLORING"), _field_type(_field_display.getEnum<FeatureFloodCount::FieldType>()) { if (_flood_counter.isElemental() == isNodal() && (_field_display == "UNIQUE_REGION" || _field_display == "VARIABLE_COLORING" || _field_display == "GHOSTED_ENTITIES" || _field_display == "HALOS")) mooseError("UNIQUE_REGION, VARIABLE_COLORING, GHOSTED_ENTITIES and HALOS must be on variable " "types that match the entity mode of the FeatureFloodCounter"); if (isNodal()) { if (_field_display == "ACTIVE_BOUNDS") mooseError("ACTIVE_BOUNDS is only available for elemental aux variables"); if (_field_display == "CENTROID") mooseError("CENTROID is only available for elemental aux variables"); } } void FeatureFloodCountAux::precalculateValue() { switch (_field_display) { case 0: // UNIQUE_REGION case 1: // VARIABLE_COLORING case 2: // GHOSTED_ENTITIES case 3: // HALOS case 4: // CENTROID _value = _flood_counter.getEntityValue( (isNodal() ? _current_node->id() : _current_elem->id()), _field_type, _var_idx); break; case 5: // ACTIVE_BOUNDS { const auto & var_to_features = _flood_counter.getVarToFeatureVector(_current_elem->id()); _value = std::count_if( var_to_features.begin(), var_to_features.end(), [](unsigned int feature_id) { return feature_id != FeatureFloodCount::invalid_id; }); break; } default: mooseError("Unimplemented \"field_display\" type"); } } Real FeatureFloodCountAux::computeValue() { return _value; }
//* This file is part of the MOOSE framework //* https://www.mooseframework.org //* //* All rights reserved, see COPYRIGHT for full restrictions //* https://github.com/idaholab/moose/blob/master/COPYRIGHT //* //* Licensed under LGPL 2.1, please see LICENSE for details //* https://www.gnu.org/licenses/lgpl-2.1.html #include "FeatureFloodCountAux.h" #include "FeatureFloodCount.h" #include "GrainTrackerInterface.h" #include "MooseEnum.h" #include <algorithm> registerMooseObject("PhaseFieldApp", FeatureFloodCountAux); template <> InputParameters validParams<FeatureFloodCountAux>() { InputParameters params = validParams<AuxKernel>(); params.addClassDescription("Feature detection by connectivity analysis"); params.addDeprecatedParam<UserObjectName>("bubble_object", "The FeatureFloodCount UserObject to get values from.", "Use \"flood_counter\" instead."); params.addRequiredParam<UserObjectName>("flood_counter", "The FeatureFloodCount UserObject to get values from."); params.addParam<unsigned int>("map_index", "The index of which map to retrieve values from when " "using FeatureFloodCount with multiple maps."); MooseEnum field_display( "UNIQUE_REGION VARIABLE_COLORING GHOSTED_ENTITIES HALOS CENTROID ACTIVE_BOUNDS", "UNIQUE_REGION"); params.addParam<MooseEnum>("field_display", field_display, "Determines how the auxilary field should be colored. " "(UNIQUE_REGION and VARIABLE_COLORING are nodal, CENTROID is " "elemental, default: UNIQUE_REGION)"); params.addRelationshipManager("ElementSideNeighborLayers", Moose::RelationshipManagerType::GEOMETRIC | Moose::RelationshipManagerType::ALGEBRAIC); params.set<ExecFlagEnum>("execute_on") = {EXEC_INITIAL, EXEC_TIMESTEP_END}; return params; } FeatureFloodCountAux::FeatureFloodCountAux(const InputParameters & parameters) : AuxKernel(parameters), _flood_counter(getUserObject<FeatureFloodCount>("flood_counter")), _var_idx(isParamValid("map_index") ? getParam<unsigned int>("map_index") : std::numeric_limits<std::size_t>::max()), _field_display(getParam<MooseEnum>("field_display")), _var_coloring(_field_display == "VARIABLE_COLORING"), _field_type(_field_display.getEnum<FeatureFloodCount::FieldType>()) { if (_flood_counter.isElemental() == isNodal() && (_field_display == "UNIQUE_REGION" || _field_display == "VARIABLE_COLORING" || _field_display == "GHOSTED_ENTITIES" || _field_display == "HALOS")) mooseError("UNIQUE_REGION, VARIABLE_COLORING, GHOSTED_ENTITIES and HALOS must be on variable " "types that match the entity mode of the FeatureFloodCounter"); if (isNodal()) { if (_field_display == "ACTIVE_BOUNDS") mooseError("ACTIVE_BOUNDS is only available for elemental aux variables"); if (_field_display == "CENTROID") mooseError("CENTROID is only available for elemental aux variables"); } } void FeatureFloodCountAux::precalculateValue() { switch (_field_display) { case 0: // UNIQUE_REGION case 1: // VARIABLE_COLORING case 2: // GHOSTED_ENTITIES case 3: // HALOS case 4: // CENTROID _value = _flood_counter.getEntityValue( (isNodal() ? _current_node->id() : _current_elem->id()), _field_type, _var_idx); break; case 5: // ACTIVE_BOUNDS { const auto & var_to_features = _flood_counter.getVarToFeatureVector(_current_elem->id()); _value = std::count_if( var_to_features.begin(), var_to_features.end(), [](unsigned int feature_id) { return feature_id != FeatureFloodCount::invalid_id; }); break; } default: mooseError("Unimplemented \"field_display\" type"); } } Real FeatureFloodCountAux::computeValue() { return _value; }
Add some ghosting to FeatureFloodCount refs #12354
Add some ghosting to FeatureFloodCount refs #12354
C++
lgpl-2.1
SudiptaBiswas/moose,sapitts/moose,lindsayad/moose,milljm/moose,bwspenc/moose,harterj/moose,lindsayad/moose,dschwen/moose,laagesen/moose,dschwen/moose,jessecarterMOOSE/moose,milljm/moose,laagesen/moose,andrsd/moose,harterj/moose,SudiptaBiswas/moose,jessecarterMOOSE/moose,jessecarterMOOSE/moose,idaholab/moose,lindsayad/moose,nuclear-wizard/moose,idaholab/moose,milljm/moose,harterj/moose,dschwen/moose,sapitts/moose,andrsd/moose,bwspenc/moose,SudiptaBiswas/moose,bwspenc/moose,nuclear-wizard/moose,nuclear-wizard/moose,laagesen/moose,laagesen/moose,bwspenc/moose,SudiptaBiswas/moose,idaholab/moose,permcody/moose,SudiptaBiswas/moose,andrsd/moose,milljm/moose,YaqiWang/moose,andrsd/moose,andrsd/moose,jessecarterMOOSE/moose,lindsayad/moose,YaqiWang/moose,nuclear-wizard/moose,idaholab/moose,permcody/moose,idaholab/moose,sapitts/moose,sapitts/moose,milljm/moose,permcody/moose,dschwen/moose,laagesen/moose,jessecarterMOOSE/moose,harterj/moose,permcody/moose,sapitts/moose,bwspenc/moose,YaqiWang/moose,dschwen/moose,YaqiWang/moose,harterj/moose,lindsayad/moose
4fe15daac1e672155cfb9253e026939cf6db106d
Sample/LedFlashPulseLighting.cpp
Sample/LedFlashPulseLighting.cpp
// G910_SAMPLE.cpp : Defines the class behaviors for the application. // #pragma comment(lib, "LogitechLEDLib.lib") #include <stdio.h> #include <stdlib.h> #include "LogitechLEDLib.h" #include <iostream> #include "windows.h" using namespace std; int main() { LogiLedInit(); Sleep(500); int red = 100; int green = 0; int blue = 0; int duration = 4000; int interval = 300; //start to flashing LogiLedFlashLighting(red, green, blue, duration, interval); printf("start flashing red=%d, green=%d, blue=%d, duration=%d, interval=%d \n",red,green,blue,duration,interval); Sleep(duration+1000); LogiLedStopEffects(); red=0; green=100; duration = 5000; interval = 300; //start to pulsing LogiLedPulseLighting(red, green, blue, duration, interval); printf("start Pulsing red=%d, green=%d, blue=%d, duration=%d, interval=%d \n",red,green,blue,duration,interval); Sleep(duration+1000); LogiLedStopEffects(); getchar(); LogiLedShutdown(); }
// G910_SAMPLE.cpp : Defines the class behaviors for the application. // #pragma comment(lib, "LogitechLEDLib.lib") #include <stdio.h> #include <stdlib.h> #include "LogitechLEDLib.h" #include <iostream> #include "windows.h" using namespace std; int main() { LogiLedInit(); Sleep(500); int red = 100; int green = 0; int blue = 0; int duration = 4000; int interval = 300; //start to flashing LogiLedFlashLighting(red, green, blue, duration, interval); printf("start flashing red=%d, green=%d, blue=%d, duration=%d, interval=%d \n",red,green,blue,duration,interval); Sleep(duration+1000); LogiLedStopEffects(); red=0; green=100; duration = 5000; interval = 300; //start to pulsing LogiLedPulseLighting(red, green, blue, duration, interval); printf("start Pulsing red=%d, green=%d, blue=%d, duration=%d, interval=%d \n",red,green,blue,duration,interval); Sleep(duration+1000); LogiLedStopEffects(); cout << "Press Enter to exit"; getchar(); LogiLedShutdown(); }
Update LedFlashPulseLighting.cpp
Update LedFlashPulseLighting.cpp
C++
mit
logihackdays/LGS_LED,logihackdays/LGS_LED,logihackdays/LGS_LED
c3c0085e1ae3b848f2b3e434a7466d17b5e45d3d
grit_core/src/CollisionMesh.c++
grit_core/src/CollisionMesh.c++
/* Copyright (c) David Cunningham and the Grit Game Engine project 2010 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <iostream> #include <cstdlib> #include <ctime> #include <OgreException.h> #include <OgreTimer.h> #include <OgreResourceGroupManager.h> #include <LinearMath/btGeometryUtil.h> #include <BulletCollision/Gimpact/btGImpactShape.h> #include <BulletCollision/CollisionDispatch/btInternalEdgeUtility.h> #include <../Extras/GIMPACTUtils/btGImpactConvexDecompositionShape.h> #include "CollisionMesh.h" #include "TColParser.h" #include "CentralisedLog.h" #include "PhysicsWorld.h" #include "path_util.h" #ifndef M_PI #define M_PI 3.1415926535897932385 #endif btCompoundShape *import_compound (btCompoundShape *s, const Compound &c, LooseEnds &les, CollisionMesh::Materials &partMaterials) { les.push_back(new LooseEndImpl<btCollisionShape>(s)); const btVector3 ZV(0,0,0); const btQuaternion ZQ(0,0,0,1); for (size_t i=0 ; i<c.hulls.size() ; ++i) { const Hull &h = c.hulls[i]; btConvexHullShape *s2 = new btConvexHullShape(); les.push_back(new LooseEndImpl<btCollisionShape>(s2)); s2->setMargin(h.margin); for (unsigned j=0 ; j<h.vertexes.size() ; ++j) { const Vector3 &v = h.vertexes[j]; s2->addPoint(v.bullet()); } s->addChildShape(btTransform(ZQ,ZV), s2); partMaterials.push_back(h.material); } for (size_t i=0 ; i<c.boxes.size() ; ++i) { const Box &b = c.boxes[i]; btBoxShape *s2 =new btBoxShape(btVector3(b.dx/2,b.dy/2,b.dz/2)); les.push_back(new LooseEndImpl<btCollisionShape>(s2)); s2->setMargin(b.margin); s->addChildShape(btTransform(btQuaternion(b.qx,b.qy,b.qz,b.qw), btVector3(b.px,b.py,b.pz)), s2); partMaterials.push_back(b.material); } for (size_t i=0 ; i<c.cylinders.size() ; ++i) { const Cylinder &cyl = c.cylinders[i]; btCylinderShape *s2 = new btCylinderShapeZ(btVector3(cyl.dx/2,cyl.dy/2,cyl.dz/2)); les.push_back(new LooseEndImpl<btCollisionShape>(s2)); s2->setMargin(cyl.margin); s->addChildShape( btTransform(btQuaternion(cyl.qx,cyl.qy,cyl.qz,cyl.qw), btVector3(cyl.px,cyl.py,cyl.pz)), s2); partMaterials.push_back(cyl.material); } for (size_t i=0 ; i<c.cones.size() ; ++i) { const Cone &cone = c.cones[i]; btConeShapeZ *s2 = new btConeShapeZ(cone.radius,cone.height); les.push_back(new LooseEndImpl<btCollisionShape>(s2)); s2->setMargin(cone.margin); s->addChildShape( btTransform(btQuaternion(cone.qx,cone.qy,cone.qz,cone.qw), btVector3(cone.px,cone.py,cone.pz)), s2); partMaterials.push_back(cone.material); } for (size_t i=0 ; i<c.planes.size() ; ++i) { const Plane &p = c.planes[i]; btStaticPlaneShape *s2 = new btStaticPlaneShape(btVector3(p.nx,p.ny,p.nz),p.d); les.push_back(new LooseEndImpl<btCollisionShape>(s2)); s->addChildShape(btTransform(ZQ,ZV), s2); partMaterials.push_back(p.material); } for (size_t i=0 ; i<c.spheres.size() ; ++i) { const Sphere &sp = c.spheres[i]; btSphereShape *s2 = new btSphereShape(sp.radius); les.push_back(new LooseEndImpl<btCollisionShape>(s2)); s->addChildShape(btTransform(ZQ, btVector3(sp.px,sp.py,sp.pz)), s2); partMaterials.push_back(sp.material); } return s; } btCollisionShape *import_trimesh (const TriMesh &f, bool is_static, LooseEnds &les, CollisionMesh::Materials &faceMaterials, CollisionMesh::ProcObjFaceDB &faceDB) { Vertexes *vertexes = new Vertexes(); les.push_back(new LooseEndImpl<Vertexes>(vertexes)); int sz = f.vertexes.size(); vertexes->reserve(sz); for (int i=0 ; i<sz ; ++i) { vertexes->push_back(f.vertexes[i]); } Faces *faces = new Faces(f.faces); les.push_back(new LooseEndImpl<Faces>(faces)); faceMaterials.reserve(f.faces.size()); for (Faces::const_iterator i=f.faces.begin(), i_=f.faces.end() ; i!=i_ ; ++i) { int m = i->material; faceMaterials.push_back(m); CollisionMesh::ProcObjFace f; f.A = (*vertexes)[i->v1]; f.AB = (*vertexes)[i->v2] - f.A; f.AC = (*vertexes)[i->v3] - f.A; float area = (f.AB.cross(f.AC)).length(); APP_ASSERT(area>=0); faceDB[m].faces.push_back(f); faceDB[m].areas.push_back(area); faceDB[m].totalArea += area; } btTriangleIndexVertexArray *v = new btTriangleIndexVertexArray( faces->size(), &((*faces)[0].v1), sizeof(Face), vertexes->size(), &((*vertexes)[0].x), sizeof(Vector3)); les.push_back(new LooseEndImpl<btTriangleIndexVertexArray>(v)); btCollisionShape *s; if (is_static) { btBvhTriangleMeshShape *tm = new btBvhTriangleMeshShape(v,true,true); s = tm; s->setMargin(0); btTriangleInfoMap* tri_info_map = new btTriangleInfoMap(); // maybe adjust thresholds in tri_info_map btGenerateInternalEdgeInfo(tm,tri_info_map); les.push_back(new LooseEndImpl<btCollisionShape>(s)); } else { btGImpactShapeInterface *s2 = new btGImpactMeshShape(v); //assume mesh is already shrunk to the given margin s2->setMargin(f.margin); /* this is hopelessly awful in comparison (but faster) btGImpactShapeInterface *s2 = new btGImpactConvexDecompositionShape(v, Vector3(1,1,1), 0.01); */ s2->updateBound(); s = s2; les.push_back(new LooseEndImpl<btCollisionShape>(s)); } return s; } btCompoundShape *import (const TColFile &f, CollisionMesh *cm, LooseEnds &les, CollisionMesh::Materials &partMaterials, CollisionMesh::Materials &faceMaterials, CollisionMesh::ProcObjFaceDB &faceDB) { bool stat = f.mass == 0.0f; // static btCompoundShape *s = new btCompoundShape(); if (f.usingCompound) { import_compound(s, f.compound, les, partMaterials); } if (f.usingTriMesh) { btCollisionShape *s2 = import_trimesh (f.triMesh, stat, les, faceMaterials, faceDB); s->addChildShape(btTransform(btQuaternion(0,0,0,1),btVector3(0,0,0)), s2); } cm->setMass(f.mass); cm->setInertia(Vector3(f.inertia_x,f.inertia_y,f.inertia_z)); cm->setLinearDamping(f.linearDamping); cm->setAngularDamping(f.angularDamping); cm->setLinearSleepThreshold(f.linearSleepThreshold); cm->setAngularSleepThreshold(f.angularSleepThreshold); cm->setCCDMotionThreshold(f.ccdMotionThreshold); cm->setCCDSweptSphereRadius(f.ccdSweptSphereRadius); return s; } class ProxyStreamBuf : public std::streambuf { public: ProxyStreamBuf (const Ogre::DataStreamPtr &file_) : file(file_) { } protected: std::streamsize showmanyc (void) { return 0; } /* int_type uflow (void) { char buf; std::streamsize sz = file->read(&buf,1); if (sz==1) return traits_type::not_eof(buf); else return traits_type::eof(); } */ virtual std::streamsize _Xsgetn_s (char* s, size_t, std::streamsize n) { return xsgetn(s,n); } /* std::streamsize xsgetn (char* s, std::streamsize n) { std::streamsize sz = std::streambuf::xsgetn(s,n); std::cout << "("<<(void*)this<<").xsgetn("<<(void*)s<<","<<n<<") = "<<sz<<std::endl; return sz; } */ pos_type seekpos (pos_type sp, std::ios_base::openmode which) { if (which == std::ios_base::out) { GRIT_EXCEPT("Cannot write to an Ogre::DataStream"); } file->seek(sp); return file->tell(); } pos_type seekoff (off_type off, std::ios_base::seekdir way, std::ios_base::openmode which) { if (which == std::ios_base::out) { GRIT_EXCEPT("Cannot write to an Ogre::DataStream"); } switch (way) { case std::ios_base::beg: file->seek(off); break; case std::ios_base::cur: file->skip(off); break; case std::ios_base::end: GRIT_EXCEPT("Cannot seek to end of an Ogre::DataStream"); default: // compiler is whining at me return -1; } return file->tell(); } std::streamsize xsgetn (char* s, std::streamsize n) { std::streamsize left = n; while (left > 0) { std::streamsize sz = file->read(s,left); if (sz==0) break; left -= sz; s += sz; } return n - left; } std::streamsize xsputn (const char_type*, std::streamsize) { GRIT_EXCEPT("Cannot write to an Ogre::DataStream"); } Ogre::DataStreamPtr file; }; void CollisionMesh::importFromFile (const Ogre::DataStreamPtr &file, const MaterialDB &db) { ProxyStreamBuf proxy(file); { std::istream stream(&proxy); quex::TColLexer qlex(&stream); TColFile tcol; pwd_push_file("/"+file->getName()); parse_tcol_1_0(file->getName(),&qlex,tcol,db); pwd_pop(); Materials m1, m2; ProcObjFaceDB fdb; LooseEnds ls; btCompoundShape *loaded_shape; try { loaded_shape = import(tcol,this,ls,m1,m2,fdb); } catch (GritException& e) { for (LooseEnds::iterator i=ls.begin(), i_=ls.end() ; i!=i_ ; ++i) { delete *i; } throw e; } for (LooseEnds::iterator i=looseEnds.begin(), i_=looseEnds.end() ; i!=i_ ; ++i) { delete *i; } masterShape = loaded_shape; if (mass != 0 && inertia == Vector3(0,0,0)) { btVector3 i; masterShape->calculateLocalInertia(mass,i); inertia = i; } looseEnds = ls; partMaterials = m1; faceMaterials = m2; procObjFaceDB = fdb; } } void CollisionMesh::reload (const MaterialDB &db) { importFromFile(Ogre::ResourceGroupManager::getSingleton().openResource(name,"GRIT"), db); for (Users::iterator i=users.begin(),i_=users.end() ; i!=i_ ; ++i) { (*i)->notifyMeshReloaded(); } } int CollisionMesh::getMaterialFromPart (unsigned int id) { if (id >= partMaterials.size()) return 0; return partMaterials[id]; } int CollisionMesh::getMaterialFromFace (unsigned int id) { if (id >= faceMaterials.size()) return 0; return faceMaterials[id]; } // vim: ts=8:sw=8:et
/* Copyright (c) David Cunningham and the Grit Game Engine project 2010 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <iostream> #include <cstdlib> #include <ctime> #include <OgreException.h> #include <OgreTimer.h> #include <OgreResourceGroupManager.h> #include <LinearMath/btGeometryUtil.h> #include <BulletCollision/Gimpact/btGImpactShape.h> #include <BulletCollision/CollisionDispatch/btInternalEdgeUtility.h> #include <../Extras/GIMPACTUtils/btGImpactConvexDecompositionShape.h> #include "CollisionMesh.h" #include "TColParser.h" #include "CentralisedLog.h" #include "PhysicsWorld.h" #include "path_util.h" #ifndef M_PI #define M_PI 3.1415926535897932385 #endif btCompoundShape *import_compound (btCompoundShape *s, const Compound &c, LooseEnds &les, CollisionMesh::Materials &partMaterials) { les.push_back(new LooseEndImpl<btCollisionShape>(s)); const btVector3 ZV(0,0,0); const btQuaternion ZQ(0,0,0,1); for (size_t i=0 ; i<c.hulls.size() ; ++i) { const Hull &h = c.hulls[i]; btConvexHullShape *s2 = new btConvexHullShape(); les.push_back(new LooseEndImpl<btCollisionShape>(s2)); s2->setMargin(h.margin); for (unsigned j=0 ; j<h.vertexes.size() ; ++j) { const Vector3 &v = h.vertexes[j]; s2->addPoint(v.bullet()); } s->addChildShape(btTransform(ZQ,ZV), s2); partMaterials.push_back(h.material); } for (size_t i=0 ; i<c.boxes.size() ; ++i) { const Box &b = c.boxes[i]; /* implement with hulls btConvexHullShape *s2 = new btConvexHullShape(); s2->addPoint(btVector3(-b.dx/2+b.margin, -b.dy/2+b.margin, -b.dz/2+b.margin)); s2->addPoint(btVector3(-b.dx/2+b.margin, -b.dy/2+b.margin, b.dz/2-b.margin)); s2->addPoint(btVector3(-b.dx/2+b.margin, b.dy/2-b.margin, -b.dz/2+b.margin)); s2->addPoint(btVector3(-b.dx/2+b.margin, b.dy/2-b.margin, b.dz/2-b.margin)); s2->addPoint(btVector3( b.dx/2-b.margin, -b.dy/2+b.margin, -b.dz/2+b.margin)); s2->addPoint(btVector3( b.dx/2-b.margin, -b.dy/2+b.margin, b.dz/2-b.margin)); s2->addPoint(btVector3( b.dx/2-b.margin, b.dy/2-b.margin, -b.dz/2+b.margin)); s2->addPoint(btVector3( b.dx/2-b.margin, b.dy/2-b.margin, b.dz/2-b.margin)); */ btBoxShape *s2 =new btBoxShape(btVector3(b.dx/2,b.dy/2,b.dz/2)); les.push_back(new LooseEndImpl<btCollisionShape>(s2)); s2->setMargin(b.margin); s->addChildShape(btTransform(btQuaternion(b.qx,b.qy,b.qz,b.qw), btVector3(b.px,b.py,b.pz)), s2); partMaterials.push_back(b.material); } for (size_t i=0 ; i<c.cylinders.size() ; ++i) { const Cylinder &cyl = c.cylinders[i]; btCylinderShape *s2 = new btCylinderShapeZ(btVector3(cyl.dx/2,cyl.dy/2,cyl.dz/2)); les.push_back(new LooseEndImpl<btCollisionShape>(s2)); s2->setMargin(cyl.margin); s->addChildShape( btTransform(btQuaternion(cyl.qx,cyl.qy,cyl.qz,cyl.qw), btVector3(cyl.px,cyl.py,cyl.pz)), s2); partMaterials.push_back(cyl.material); } for (size_t i=0 ; i<c.cones.size() ; ++i) { const Cone &cone = c.cones[i]; btConeShapeZ *s2 = new btConeShapeZ(cone.radius,cone.height); les.push_back(new LooseEndImpl<btCollisionShape>(s2)); s2->setMargin(cone.margin); s->addChildShape( btTransform(btQuaternion(cone.qx,cone.qy,cone.qz,cone.qw), btVector3(cone.px,cone.py,cone.pz)), s2); partMaterials.push_back(cone.material); } for (size_t i=0 ; i<c.planes.size() ; ++i) { const Plane &p = c.planes[i]; btStaticPlaneShape *s2 = new btStaticPlaneShape(btVector3(p.nx,p.ny,p.nz),p.d); les.push_back(new LooseEndImpl<btCollisionShape>(s2)); s->addChildShape(btTransform(ZQ,ZV), s2); partMaterials.push_back(p.material); } for (size_t i=0 ; i<c.spheres.size() ; ++i) { const Sphere &sp = c.spheres[i]; btSphereShape *s2 = new btSphereShape(sp.radius); les.push_back(new LooseEndImpl<btCollisionShape>(s2)); s->addChildShape(btTransform(ZQ, btVector3(sp.px,sp.py,sp.pz)), s2); partMaterials.push_back(sp.material); } return s; } btCollisionShape *import_trimesh (const TriMesh &f, bool is_static, LooseEnds &les, CollisionMesh::Materials &faceMaterials, CollisionMesh::ProcObjFaceDB &faceDB) { Vertexes *vertexes = new Vertexes(); les.push_back(new LooseEndImpl<Vertexes>(vertexes)); int sz = f.vertexes.size(); vertexes->reserve(sz); for (int i=0 ; i<sz ; ++i) { vertexes->push_back(f.vertexes[i]); } Faces *faces = new Faces(f.faces); les.push_back(new LooseEndImpl<Faces>(faces)); faceMaterials.reserve(f.faces.size()); for (Faces::const_iterator i=f.faces.begin(), i_=f.faces.end() ; i!=i_ ; ++i) { int m = i->material; faceMaterials.push_back(m); CollisionMesh::ProcObjFace f; f.A = (*vertexes)[i->v1]; f.AB = (*vertexes)[i->v2] - f.A; f.AC = (*vertexes)[i->v3] - f.A; float area = (f.AB.cross(f.AC)).length(); APP_ASSERT(area>=0); faceDB[m].faces.push_back(f); faceDB[m].areas.push_back(area); faceDB[m].totalArea += area; } btTriangleIndexVertexArray *v = new btTriangleIndexVertexArray( faces->size(), &((*faces)[0].v1), sizeof(Face), vertexes->size(), &((*vertexes)[0].x), sizeof(Vector3)); les.push_back(new LooseEndImpl<btTriangleIndexVertexArray>(v)); btCollisionShape *s; if (is_static) { btBvhTriangleMeshShape *tm = new btBvhTriangleMeshShape(v,true,true); s = tm; s->setMargin(0); btTriangleInfoMap* tri_info_map = new btTriangleInfoMap(); tri_info_map->m_edgeDistanceThreshold = 0.01f; btGenerateInternalEdgeInfo(tm,tri_info_map); les.push_back(new LooseEndImpl<btCollisionShape>(s)); } else { btGImpactShapeInterface *s2 = new btGImpactMeshShape(v); //assume mesh is already shrunk to the given margin s2->setMargin(f.margin); /* this is hopelessly awful in comparison (but faster) btGImpactShapeInterface *s2 = new btGImpactConvexDecompositionShape(v, Vector3(1,1,1), 0.01); */ s2->updateBound(); s = s2; les.push_back(new LooseEndImpl<btCollisionShape>(s)); } return s; } btCompoundShape *import (const TColFile &f, CollisionMesh *cm, LooseEnds &les, CollisionMesh::Materials &partMaterials, CollisionMesh::Materials &faceMaterials, CollisionMesh::ProcObjFaceDB &faceDB) { bool stat = f.mass == 0.0f; // static btCompoundShape *s = new btCompoundShape(); if (f.usingCompound) { import_compound(s, f.compound, les, partMaterials); } if (f.usingTriMesh) { btCollisionShape *s2 = import_trimesh (f.triMesh, stat, les, faceMaterials, faceDB); s->addChildShape(btTransform(btQuaternion(0,0,0,1),btVector3(0,0,0)), s2); } cm->setMass(f.mass); cm->setInertia(Vector3(f.inertia_x,f.inertia_y,f.inertia_z)); cm->setLinearDamping(f.linearDamping); cm->setAngularDamping(f.angularDamping); cm->setLinearSleepThreshold(f.linearSleepThreshold); cm->setAngularSleepThreshold(f.angularSleepThreshold); cm->setCCDMotionThreshold(f.ccdMotionThreshold); cm->setCCDSweptSphereRadius(f.ccdSweptSphereRadius); return s; } class ProxyStreamBuf : public std::streambuf { public: ProxyStreamBuf (const Ogre::DataStreamPtr &file_) : file(file_) { } protected: std::streamsize showmanyc (void) { return 0; } /* int_type uflow (void) { char buf; std::streamsize sz = file->read(&buf,1); if (sz==1) return traits_type::not_eof(buf); else return traits_type::eof(); } */ virtual std::streamsize _Xsgetn_s (char* s, size_t, std::streamsize n) { return xsgetn(s,n); } /* std::streamsize xsgetn (char* s, std::streamsize n) { std::streamsize sz = std::streambuf::xsgetn(s,n); std::cout << "("<<(void*)this<<").xsgetn("<<(void*)s<<","<<n<<") = "<<sz<<std::endl; return sz; } */ pos_type seekpos (pos_type sp, std::ios_base::openmode which) { if (which == std::ios_base::out) { GRIT_EXCEPT("Cannot write to an Ogre::DataStream"); } file->seek(sp); return file->tell(); } pos_type seekoff (off_type off, std::ios_base::seekdir way, std::ios_base::openmode which) { if (which == std::ios_base::out) { GRIT_EXCEPT("Cannot write to an Ogre::DataStream"); } switch (way) { case std::ios_base::beg: file->seek(off); break; case std::ios_base::cur: file->skip(off); break; case std::ios_base::end: GRIT_EXCEPT("Cannot seek to end of an Ogre::DataStream"); default: // compiler is whining at me return -1; } return file->tell(); } std::streamsize xsgetn (char* s, std::streamsize n) { std::streamsize left = n; while (left > 0) { std::streamsize sz = file->read(s,left); if (sz==0) break; left -= sz; s += sz; } return n - left; } std::streamsize xsputn (const char_type*, std::streamsize) { GRIT_EXCEPT("Cannot write to an Ogre::DataStream"); } Ogre::DataStreamPtr file; }; void CollisionMesh::importFromFile (const Ogre::DataStreamPtr &file, const MaterialDB &db) { ProxyStreamBuf proxy(file); { std::istream stream(&proxy); quex::TColLexer qlex(&stream); TColFile tcol; pwd_push_file("/"+file->getName()); parse_tcol_1_0(file->getName(),&qlex,tcol,db); pwd_pop(); Materials m1, m2; ProcObjFaceDB fdb; LooseEnds ls; btCompoundShape *loaded_shape; try { loaded_shape = import(tcol,this,ls,m1,m2,fdb); } catch (GritException& e) { for (LooseEnds::iterator i=ls.begin(), i_=ls.end() ; i!=i_ ; ++i) { delete *i; } throw e; } for (LooseEnds::iterator i=looseEnds.begin(), i_=looseEnds.end() ; i!=i_ ; ++i) { delete *i; } masterShape = loaded_shape; if (mass != 0 && inertia == Vector3(0,0,0)) { btVector3 i; masterShape->calculateLocalInertia(mass,i); inertia = i; } looseEnds = ls; partMaterials = m1; faceMaterials = m2; procObjFaceDB = fdb; } } void CollisionMesh::reload (const MaterialDB &db) { importFromFile(Ogre::ResourceGroupManager::getSingleton().openResource(name,"GRIT"), db); for (Users::iterator i=users.begin(),i_=users.end() ; i!=i_ ; ++i) { (*i)->notifyMeshReloaded(); } } int CollisionMesh::getMaterialFromPart (unsigned int id) { if (id >= partMaterials.size()) return 0; return partMaterials[id]; } int CollisionMesh::getMaterialFromFace (unsigned int id) { if (id >= faceMaterials.size()) return 0; return faceMaterials[id]; } // vim: ts=8:sw=8:et
Adjust triangle edge info, doesn't help though
Adjust triangle edge info, doesn't help though
C++
mit
sparkprime/grit-engine,sparkprime/grit-engine,grit-engine/grit-engine,sparkprime/grit-engine,grit-engine/grit-engine,grit-engine/grit-engine,sparkprime/grit-engine,grit-engine/grit-engine
1e16e6c53182500ec3d3d6d9057391fc125760ad
src/ntp-clock.cpp
src/ntp-clock.cpp
/** * 24-hour NTP clock * For use with a 4-digit 7-segment display and an ESP8266 * @copyright 2016 Christopher Hiller <[email protected]> * @license MIT */ #include <ESP8266WiFi.h> #include <NTPClient.h> #include <Adafruit_LEDBackpack.h> #define SSID "YOUR WIFI NETWORK" #define PASS "AND ITS PASSWORD" #define TZ -8 // your time zone offset #define HOST "time.apple.com" // your favorite NTP server NTPClient timeClient(HOST, TZ * 3600); Adafruit_7segment matrix = Adafruit_7segment(); /** * Is the colon supposed to be on or off? */ boolean colon = (boolean) true; /** * Use this to avoid calls to delay() during the loop */ unsigned long prevMillis = 0; /** * Check this in the loop; if it differs from what NTPClient tells us * then it's time to update the time. */ unsigned long prevMin = 0; /** * Toggles the colon state and writes the display. */ void toggleColon() { colon = (boolean) !colon; matrix.drawColon(colon); matrix.writeDisplay(); } /** * Resets 7-segment display. */ void reset() { matrix.clear(); colon = (boolean) false; matrix.writeDisplay(); } /** * Connects to WiFi network. Flashes colon during this phase. */ void connectWiFi() { if (WiFi.status() == WL_CONNECTED) { return; } reset(); WiFi.begin(SSID, PASS); Serial.println("Connecting to " + String(SSID)); while (WiFi.status() != WL_CONNECTED) { Serial.print('.'); toggleColon(); delay(250); } Serial.println("Connected to " + String(SSID)); reset(); } /** * Initializes matrix and connects to WiFi. */ void setup() { Serial.begin(115200); matrix.begin(0x70); connectWiFi(); } /** * Shortcut to turn a char into an int. */ uint8_t charToInt(char c) { return (uint8_t) c - '0'; } /** * Draws the time. This is 24-hour time, but the hour may be one or two * digits; leave the first blank if there's only one digit. */ void drawTime(String hours, String minutes) { if (hours.length() == 1) { matrix.writeDigitRaw(0, 0); matrix.writeDigitNum(1, charToInt(hours.charAt(0))); } else { matrix.writeDigitNum(0, charToInt(hours.charAt(0))); matrix.writeDigitNum(1, charToInt(hours.charAt(1))); } matrix.writeDigitNum(3, charToInt(minutes.charAt(0))); matrix.writeDigitNum(4, charToInt(minutes.charAt(1))); } /** * Flashes colon on/off every second. * Asks the NTP client for an update every second; if the minute has changed, * then update the display. * Keep WiFi connection alive. */ void loop() { unsigned long currentMillis = millis(); unsigned long delta = currentMillis - prevMillis; if (delta >= 500) { if (delta >= 1000) { connectWiFi(); timeClient.update(); unsigned long min = (timeClient.getRawTime() % 3600) / 60; if (min != prevMin) { drawTime(timeClient.getHours(), timeClient.getMinutes()); Serial.println("Updating time to " + timeClient.getFormattedTime()); } prevMin = min; } prevMillis = currentMillis; toggleColon(); } }
/** * 24-hour NTP clock * For use with a 4-digit 7-segment display and an ESP8266 * @copyright 2016 Christopher Hiller <[email protected]> * @license MIT */ #include <ESP8266WiFi.h> #include <NTPClient.h> #include <Adafruit_LEDBackpack.h> #define SSID "YOUR WIFI NETWORK" #define PASS "AND ITS PASSWORD" #define TZ -8 // your time zone offset #define HOST "time.apple.com" // your favorite NTP server NTPClient timeClient(HOST, TZ * 3600); Adafruit_7segment matrix = Adafruit_7segment(); /** * Is the colon supposed to be on or off? */ boolean colon = (boolean) true; /** * Use this to avoid calls to delay() during the loop */ unsigned long prevMillis = 0; /** * Check this in the loop; if it differs from what NTPClient tells us * then it's time to update the time. */ unsigned long prevMin = 0; /** * Toggles the colon state and writes the display. */ void toggleColon() { colon = (boolean) !colon; matrix.drawColon(colon); matrix.writeDisplay(); } /** * Resets 7-segment display. */ void reset() { matrix.clear(); colon = (boolean) false; matrix.writeDisplay(); } /** * Connects to WiFi network. Flashes colon during this phase. */ void connectWiFi() { if (WiFi.status() == WL_CONNECTED) { return; } reset(); WiFi.begin(SSID, PASS); Serial.println("Connecting to " + String(SSID)); while (WiFi.status() != WL_CONNECTED) { Serial.print('.'); toggleColon(); delay(250); } Serial.println("Connected to " + String(SSID)); reset(); } /** * Initializes matrix and connects to WiFi. */ void setup() { Serial.begin(115200); matrix.begin(0x70); connectWiFi(); } /** * Shortcut to turn a char into an int. */ uint8_t charToInt(char c) { return (uint8_t) c - '0'; } /** * Draws the time. This is 24-hour time, but the hour may be one or two * digits; leave the first blank if there's only one digit. */ void drawTime(String hours, String minutes) { if (hours.length() == 1) { matrix.writeDigitRaw(0, 0); matrix.writeDigitNum(1, charToInt(hours.charAt(0))); } else { matrix.writeDigitNum(0, charToInt(hours.charAt(0))); matrix.writeDigitNum(1, charToInt(hours.charAt(1))); } matrix.writeDigitNum(3, charToInt(minutes.charAt(0))); matrix.writeDigitNum(4, charToInt(minutes.charAt(1))); } /** * Flashes colon on/off every second. * Asks the NTP client for an update every second; if the minute has changed, * then update the display. * Keep WiFi connection alive. */ void loop() { unsigned long currentMillis = millis(); unsigned long delta = currentMillis - prevMillis; if (delta >= 500) { if (delta >= 1000) { connectWiFi(); timeClient.update(); unsigned long min = (timeClient.getRawTime() % 3600) / 60; if (min != prevMin) { drawTime(timeClient.getHours(), timeClient.getMinutes()); Serial.println("Updating time to " + timeClient.getFormattedTime()); prevMin = min; } } prevMillis = currentMillis; toggleColon(); } }
fix bug causing clock to not actually update
fix bug causing clock to not actually update
C++
mit
boneskull/ntp-clock
4b98d0f3cab536dac1524b2c48a83fc3be3c5459
remoting/protocol/pepper_stream_channel.cc
remoting/protocol/pepper_stream_channel.cc
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "remoting/protocol/pepper_stream_channel.h" #include "base/bind.h" #include "crypto/hmac.h" #include "jingle/glue/utils.h" #include "net/base/cert_status_flags.h" #include "net/base/cert_verifier.h" #include "net/base/host_port_pair.h" #include "net/base/ssl_config_service.h" #include "net/socket/ssl_client_socket.h" #include "net/socket/client_socket_factory.h" #include "ppapi/c/pp_errors.h" #include "ppapi/cpp/dev/transport_dev.h" #include "ppapi/cpp/var.h" #include "remoting/protocol/channel_authenticator.h" #include "remoting/protocol/pepper_session.h" #include "remoting/protocol/transport_config.h" #include "third_party/libjingle/source/talk/p2p/base/candidate.h" namespace remoting { namespace protocol { namespace { // Value is choosen to balance the extra latency against the reduced // load due to ACK traffic. const int kTcpAckDelayMilliseconds = 10; // Values for the TCP send and receive buffer size. This should be tuned to // accomodate high latency network but not backlog the decoding pipeline. const int kTcpReceiveBufferSize = 256 * 1024; const int kTcpSendBufferSize = kTcpReceiveBufferSize + 30 * 1024; } // namespace PepperStreamChannel::PepperStreamChannel( PepperSession* session, const std::string& name, const Session::StreamChannelCallback& callback) : session_(session), name_(name), callback_(callback), channel_(NULL), connected_(false) { } PepperStreamChannel::~PepperStreamChannel() { session_->OnDeleteChannel(this); // Verify that the |channel_| is ether destroyed or we own it. DCHECK_EQ(channel_, owned_channel_.get()); // Channel should be already destroyed if we were connected. DCHECK(!connected_ || channel_ == NULL); } void PepperStreamChannel::Connect(pp::Instance* pp_instance, const TransportConfig& transport_config, ChannelAuthenticator* authenticator) { DCHECK(CalledOnValidThread()); authenticator_.reset(authenticator); pp::Transport_Dev* transport = new pp::Transport_Dev(pp_instance, name_.c_str(), PP_TRANSPORTTYPE_STREAM); if (transport->SetProperty(PP_TRANSPORTPROPERTY_TCP_RECEIVE_WINDOW, pp::Var(kTcpReceiveBufferSize)) != PP_OK) { LOG(ERROR) << "Failed to set TCP receive window"; } if (transport->SetProperty(PP_TRANSPORTPROPERTY_TCP_SEND_WINDOW, pp::Var(kTcpSendBufferSize)) != PP_OK) { LOG(ERROR) << "Failed to set TCP send window"; } if (transport->SetProperty(PP_TRANSPORTPROPERTY_TCP_NO_DELAY, pp::Var(true)) != PP_OK) { LOG(ERROR) << "Failed to set TCP_NODELAY"; } if (transport->SetProperty(PP_TRANSPORTPROPERTY_TCP_ACK_DELAY, pp::Var(kTcpAckDelayMilliseconds)) != PP_OK) { LOG(ERROR) << "Failed to set TCP ACK delay."; } if (transport_config.nat_traversal) { if (transport->SetProperty( PP_TRANSPORTPROPERTY_STUN_SERVER, pp::Var(transport_config.stun_server)) != PP_OK) { LOG(ERROR) << "Failed to set STUN server."; } if (transport->SetProperty( PP_TRANSPORTPROPERTY_RELAY_SERVER, pp::Var(transport_config.relay_server)) != PP_OK) { LOG(ERROR) << "Failed to set relay server."; } if (transport->SetProperty( PP_TRANSPORTPROPERTY_RELAY_PASSWORD, pp::Var(transport_config.relay_token)) != PP_OK) { LOG(ERROR) << "Failed to set relay token."; } if (transport->SetProperty( PP_TRANSPORTPROPERTY_RELAY_MODE, pp::Var(PP_TRANSPORTRELAYMODE_GOOGLE)) != PP_OK) { LOG(ERROR) << "Failed to set relay mode."; } } if (transport->SetProperty(PP_TRANSPORTPROPERTY_DISABLE_TCP_TRANSPORT, pp::Var(true)) != PP_OK) { LOG(ERROR) << "Failed to set DISABLE_TCP_TRANSPORT flag."; } channel_ = new PepperTransportSocketAdapter(transport, name_, this); owned_channel_.reset(channel_); int result = channel_->Connect(base::Bind(&PepperStreamChannel::OnP2PConnect, base::Unretained(this))); if (result != net::ERR_IO_PENDING) OnP2PConnect(result); } void PepperStreamChannel::AddRemoveCandidate( const cricket::Candidate& candidate) { DCHECK(CalledOnValidThread()); if (channel_) channel_->AddRemoteCandidate(jingle_glue::SerializeP2PCandidate(candidate)); } const std::string& PepperStreamChannel::name() const { DCHECK(CalledOnValidThread()); return name_; } bool PepperStreamChannel::is_connected() const { DCHECK(CalledOnValidThread()); return connected_; } void PepperStreamChannel::OnChannelDeleted() { if (connected_) { channel_ = NULL; // The PepperTransportSocketAdapter is being deleted, so delete // the channel too. delete this; } } void PepperStreamChannel::OnChannelNewLocalCandidate( const std::string& candidate) { DCHECK(CalledOnValidThread()); cricket::Candidate candidate_value; if (!jingle_glue::DeserializeP2PCandidate(candidate, &candidate_value)) { LOG(ERROR) << "Failed to parse candidate " << candidate; } session_->AddLocalCandidate(candidate_value); } void PepperStreamChannel::OnP2PConnect(int result) { DCHECK(CalledOnValidThread()); if (result != net::OK) NotifyConnectFailed(); authenticator_->SecureAndAuthenticate(owned_channel_.release(), base::Bind( &PepperStreamChannel::OnAuthenticationDone, base::Unretained(this))); } void PepperStreamChannel::OnAuthenticationDone( net::Error error, net::StreamSocket* socket) { DCHECK(CalledOnValidThread()); if (error != net::OK) { NotifyConnectFailed(); return; } NotifyConnected(socket); } void PepperStreamChannel::NotifyConnected(net::StreamSocket* socket) { DCHECK(!connected_); callback_.Run(socket); connected_ = true; } void PepperStreamChannel::NotifyConnectFailed() { channel_ = NULL; owned_channel_.reset(); authenticator_.reset(); NotifyConnected(NULL); } } // namespace protocol } // namespace remoting
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "remoting/protocol/pepper_stream_channel.h" #include "base/bind.h" #include "crypto/hmac.h" #include "jingle/glue/utils.h" #include "net/base/cert_status_flags.h" #include "net/base/cert_verifier.h" #include "net/base/host_port_pair.h" #include "net/base/ssl_config_service.h" #include "net/socket/ssl_client_socket.h" #include "net/socket/client_socket_factory.h" #include "ppapi/c/pp_errors.h" #include "ppapi/cpp/dev/transport_dev.h" #include "ppapi/cpp/var.h" #include "remoting/protocol/channel_authenticator.h" #include "remoting/protocol/pepper_session.h" #include "remoting/protocol/transport_config.h" #include "third_party/libjingle/source/talk/p2p/base/candidate.h" namespace remoting { namespace protocol { namespace { // Value is choosen to balance the extra latency against the reduced // load due to ACK traffic. const int kTcpAckDelayMilliseconds = 10; // Values for the TCP send and receive buffer size. This should be tuned to // accomodate high latency network but not backlog the decoding pipeline. const int kTcpReceiveBufferSize = 256 * 1024; const int kTcpSendBufferSize = kTcpReceiveBufferSize + 30 * 1024; } // namespace PepperStreamChannel::PepperStreamChannel( PepperSession* session, const std::string& name, const Session::StreamChannelCallback& callback) : session_(session), name_(name), callback_(callback), channel_(NULL), connected_(false) { } PepperStreamChannel::~PepperStreamChannel() { session_->OnDeleteChannel(this); // Channel should be already destroyed if we were connected. DCHECK(!connected_ || channel_ == NULL); } void PepperStreamChannel::Connect(pp::Instance* pp_instance, const TransportConfig& transport_config, ChannelAuthenticator* authenticator) { DCHECK(CalledOnValidThread()); authenticator_.reset(authenticator); pp::Transport_Dev* transport = new pp::Transport_Dev(pp_instance, name_.c_str(), PP_TRANSPORTTYPE_STREAM); if (transport->SetProperty(PP_TRANSPORTPROPERTY_TCP_RECEIVE_WINDOW, pp::Var(kTcpReceiveBufferSize)) != PP_OK) { LOG(ERROR) << "Failed to set TCP receive window"; } if (transport->SetProperty(PP_TRANSPORTPROPERTY_TCP_SEND_WINDOW, pp::Var(kTcpSendBufferSize)) != PP_OK) { LOG(ERROR) << "Failed to set TCP send window"; } if (transport->SetProperty(PP_TRANSPORTPROPERTY_TCP_NO_DELAY, pp::Var(true)) != PP_OK) { LOG(ERROR) << "Failed to set TCP_NODELAY"; } if (transport->SetProperty(PP_TRANSPORTPROPERTY_TCP_ACK_DELAY, pp::Var(kTcpAckDelayMilliseconds)) != PP_OK) { LOG(ERROR) << "Failed to set TCP ACK delay."; } if (transport_config.nat_traversal) { if (transport->SetProperty( PP_TRANSPORTPROPERTY_STUN_SERVER, pp::Var(transport_config.stun_server)) != PP_OK) { LOG(ERROR) << "Failed to set STUN server."; } if (transport->SetProperty( PP_TRANSPORTPROPERTY_RELAY_SERVER, pp::Var(transport_config.relay_server)) != PP_OK) { LOG(ERROR) << "Failed to set relay server."; } if (transport->SetProperty( PP_TRANSPORTPROPERTY_RELAY_PASSWORD, pp::Var(transport_config.relay_token)) != PP_OK) { LOG(ERROR) << "Failed to set relay token."; } if (transport->SetProperty( PP_TRANSPORTPROPERTY_RELAY_MODE, pp::Var(PP_TRANSPORTRELAYMODE_GOOGLE)) != PP_OK) { LOG(ERROR) << "Failed to set relay mode."; } } if (transport->SetProperty(PP_TRANSPORTPROPERTY_DISABLE_TCP_TRANSPORT, pp::Var(true)) != PP_OK) { LOG(ERROR) << "Failed to set DISABLE_TCP_TRANSPORT flag."; } channel_ = new PepperTransportSocketAdapter(transport, name_, this); owned_channel_.reset(channel_); int result = channel_->Connect(base::Bind(&PepperStreamChannel::OnP2PConnect, base::Unretained(this))); if (result != net::ERR_IO_PENDING) OnP2PConnect(result); } void PepperStreamChannel::AddRemoveCandidate( const cricket::Candidate& candidate) { DCHECK(CalledOnValidThread()); if (channel_) channel_->AddRemoteCandidate(jingle_glue::SerializeP2PCandidate(candidate)); } const std::string& PepperStreamChannel::name() const { DCHECK(CalledOnValidThread()); return name_; } bool PepperStreamChannel::is_connected() const { DCHECK(CalledOnValidThread()); return connected_; } void PepperStreamChannel::OnChannelDeleted() { if (connected_) { channel_ = NULL; // The PepperTransportSocketAdapter is being deleted, so delete // the channel too. delete this; } } void PepperStreamChannel::OnChannelNewLocalCandidate( const std::string& candidate) { DCHECK(CalledOnValidThread()); cricket::Candidate candidate_value; if (!jingle_glue::DeserializeP2PCandidate(candidate, &candidate_value)) { LOG(ERROR) << "Failed to parse candidate " << candidate; } session_->AddLocalCandidate(candidate_value); } void PepperStreamChannel::OnP2PConnect(int result) { DCHECK(CalledOnValidThread()); if (result != net::OK) NotifyConnectFailed(); authenticator_->SecureAndAuthenticate(owned_channel_.release(), base::Bind( &PepperStreamChannel::OnAuthenticationDone, base::Unretained(this))); } void PepperStreamChannel::OnAuthenticationDone( net::Error error, net::StreamSocket* socket) { DCHECK(CalledOnValidThread()); if (error != net::OK) { NotifyConnectFailed(); return; } NotifyConnected(socket); } void PepperStreamChannel::NotifyConnected(net::StreamSocket* socket) { DCHECK(!connected_); callback_.Run(socket); connected_ = true; } void PepperStreamChannel::NotifyConnectFailed() { channel_ = NULL; owned_channel_.reset(); authenticator_.reset(); NotifyConnected(NULL); } } // namespace protocol } // namespace remoting
Remove old DCHECK from ~PepperStreamChannel().
Remove old DCHECK from ~PepperStreamChannel(). Now channel_ can be owned by the ChannelAuthenticator, so the assumption verified by this DCHECK is not valid anymore. BUG=105214 Review URL: http://codereview.chromium.org/8989068 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@116105 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
gavinp/chromium,yitian134/chromium,gavinp/chromium,adobe/chromium,adobe/chromium,adobe/chromium,gavinp/chromium,yitian134/chromium,ropik/chromium,adobe/chromium,gavinp/chromium,gavinp/chromium,adobe/chromium,gavinp/chromium,ropik/chromium,ropik/chromium,yitian134/chromium,ropik/chromium,yitian134/chromium,adobe/chromium,gavinp/chromium,yitian134/chromium,adobe/chromium,yitian134/chromium,yitian134/chromium,ropik/chromium,gavinp/chromium,yitian134/chromium,adobe/chromium,gavinp/chromium,gavinp/chromium,ropik/chromium,ropik/chromium,adobe/chromium,yitian134/chromium,yitian134/chromium,adobe/chromium,ropik/chromium,ropik/chromium,adobe/chromium
02a962207bca0c9719a5e28d10881ecb16a9ca9e
src/Gui/MDIView.cpp
src/Gui/MDIView.cpp
/*************************************************************************** * Copyright (c) 2007 Werner Mayer <wmayer[at]users.sourceforge.net> * * * * This file is part of the FreeCAD CAx development system. * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Library General Public * * License as published by the Free Software Foundation; either * * version 2 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU Library General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this library; see the file COPYING.LIB. If not, * * write to the Free Software Foundation, Inc., 59 Temple Place, * * Suite 330, Boston, MA 02111-1307, USA * * * ***************************************************************************/ #include "PreCompiled.h" #ifndef _PreComp_ # include <qapplication.h> # include <qregexp.h> # include <QEvent> # include <QCloseEvent> # include <QMdiSubWindow> #endif #include "MDIView.h" #include "Command.h" #include "Document.h" #include "Application.h" #include "MainWindow.h" using namespace Gui; TYPESYSTEM_SOURCE_ABSTRACT(Gui::MDIView,Gui::BaseView); MDIView::MDIView(Gui::Document* pcDocument,QWidget* parent, Qt::WFlags wflags) : QMainWindow(parent, wflags), BaseView(pcDocument),currentMode(Child), wstate(Qt::WindowNoState) { setAttribute(Qt::WA_DeleteOnClose); } MDIView::~MDIView() { //This view might be the focus widget of the main window. In this case we must //clear the focus and e.g. set the focus directly to the main window, otherwise //the application crashes when accessing this deleted view. //This effect only occurs if this widget is not in Child mode, because otherwise //the focus stuff is done correctly. QWidget* foc = getMainWindow()->focusWidget(); if (foc) { QWidget* par = foc; while (par) { if (par == this) { getMainWindow()->setFocus(); break; } par = par->parentWidget(); } } } void MDIView::deleteSelf() { // When using QMdiArea make sure to remove the QMdiSubWindow // this view is associated with. #if !defined (NO_USE_QT_MDI_AREA) QWidget* parent = this->parentWidget(); if (qobject_cast<QMdiSubWindow*>(parent)) delete parent; else #endif delete this; } void MDIView::onRelabel(Gui::Document *pDoc) { if (!bIsPassive) { // Try to separate document name and view number if there is one QString cap = windowTitle(); // Either with dirty flag ... QRegExp rx(QLatin1String("(\\s\\:\\s\\d+\\[\\*\\])$")); int pos = rx.lastIndexIn(cap); if (pos == -1) { // ... or not rx.setPattern(QLatin1String("(\\s\\:\\s\\d+)$")); pos = rx.lastIndexIn(cap); } if (pos != -1) { cap = QString::fromUtf8(pDoc->getDocument()->Label.getValue()); cap += rx.cap(); setWindowTitle(cap); } else { cap = QString::fromUtf8(pDoc->getDocument()->Label.getValue()); cap = QString::fromAscii("%1[*]").arg(cap); setWindowTitle(cap); } } } void MDIView::viewAll() { } /// receive a message bool MDIView::onMsg(const char* pMsg,const char** ppReturn) { return false; } bool MDIView::onHasMsg(const char* pMsg) const { return false; } bool MDIView::canClose(void) { if (!bIsPassive && getGuiDocument() && getGuiDocument()->isLastView()) { this->setFocus(); // raises the view to front return (getGuiDocument()->canClose()); } return true; } void MDIView::closeEvent(QCloseEvent *e) { if (canClose()) { e->accept(); if (!bIsPassive) { // must be detached so that the last view can get asked Document* doc = this->getGuiDocument(); if (doc && !doc->isLastView()) doc->detachView(this); } // Note: When using QMdiArea we must not use removeWindow() // because otherwise the QMdiSubWindow will loose its parent // and thus the notification in QMdiSubWindow::closeEvent of // other mdi windows to get maximized if this window // is maximized will fail. // This odd behaviour is caused by the invocation of // d->mdiArea->removeSubWindow(parent) which we must let there // because otherwise other parts don't work as they should. #if defined (NO_USE_QT_MDI_AREA) // avoid flickering getMainWindow()->removeWindow(this); #endif QMainWindow::closeEvent(e); } else e->ignore(); } void MDIView::windowStateChanged( MDIView* ) { } void MDIView::print() { // print command specified but print method not overriden! assert(0); } void MDIView::printPdf() { // print command specified but print method not overriden! assert(0); } void MDIView::printPreview() { // print command specified but print method not overriden! assert(0); } QSize MDIView::minimumSizeHint () const { return QSize(400, 300); } void MDIView::changeEvent(QEvent *e) { switch (e->type()) { case QEvent::ActivationChange: { // Forces this top-level window to be the active view of the main window if (isActiveWindow()) { if (getMainWindow()->activeWindow() != this) getMainWindow()->setActiveWindow(this); } } break; case QEvent::WindowTitleChange: case QEvent::ModifiedChange: { // sets the appropriate tab of the tabbar getMainWindow()->tabChanged(this); } break; default: { QMainWindow::changeEvent(e); } break; } } #if defined(Q_WS_X11) // To fix bug #0000345 move function declaration to here extern void qt_x11_wait_for_window_manager( QWidget* w ); // defined in qwidget_x11.cpp #endif void MDIView::setCurrentViewMode(ViewMode mode) { switch (mode) { // go to normal mode case Child: { if (this->currentMode == FullScreen) { showNormal(); setWindowFlags(windowFlags() & ~Qt::Window); } else if (this->currentMode == TopLevel) { this->wstate = windowState(); setWindowFlags( windowFlags() & ~Qt::Window ); } if (this->currentMode != Child) { this->currentMode = Child; getMainWindow()->addWindow(this); getMainWindow()->activateWindow(); update(); } } break; // go to top-level mode case TopLevel: { if (this->currentMode == Child) { #if !defined (NO_USE_QT_MDI_AREA) if (qobject_cast<QMdiSubWindow*>(this->parentWidget())) #endif getMainWindow()->removeWindow(this); setWindowFlags(windowFlags() | Qt::Window); setParent(0, Qt::Window | Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowMinMaxButtonsHint); if (this->wstate & Qt::WindowMaximized) showMaximized(); else showNormal(); #if defined(Q_WS_X11) //extern void qt_x11_wait_for_window_manager( QWidget* w ); // defined in qwidget_x11.cpp qt_x11_wait_for_window_manager(this); #endif activateWindow(); } else if (this->currentMode == FullScreen) { if (this->wstate & Qt::WindowMaximized) showMaximized(); else showNormal(); } this->currentMode = TopLevel; update(); } break; // go to fullscreen mode case FullScreen: { if (this->currentMode == Child) { #if !defined (NO_USE_QT_MDI_AREA) if (qobject_cast<QMdiSubWindow*>(this->parentWidget())) #endif getMainWindow()->removeWindow(this); setWindowFlags(windowFlags() | Qt::Window); setParent(0, Qt::Window); showFullScreen(); } else if (this->currentMode == TopLevel) { this->wstate = windowState(); showFullScreen(); } this->currentMode = FullScreen; update(); } break; } } #include "moc_MDIView.cpp"
/*************************************************************************** * Copyright (c) 2007 Werner Mayer <wmayer[at]users.sourceforge.net> * * * * This file is part of the FreeCAD CAx development system. * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Library General Public * * License as published by the Free Software Foundation; either * * version 2 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU Library General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this library; see the file COPYING.LIB. If not, * * write to the Free Software Foundation, Inc., 59 Temple Place, * * Suite 330, Boston, MA 02111-1307, USA * * * ***************************************************************************/ #include "PreCompiled.h" #ifndef _PreComp_ # include <qapplication.h> # include <qregexp.h> # include <QEvent> # include <QCloseEvent> # include <QMdiSubWindow> #endif #include "MDIView.h" #include "Command.h" #include "Document.h" #include "Application.h" #include "MainWindow.h" using namespace Gui; TYPESYSTEM_SOURCE_ABSTRACT(Gui::MDIView,Gui::BaseView); MDIView::MDIView(Gui::Document* pcDocument,QWidget* parent, Qt::WFlags wflags) : QMainWindow(parent, wflags), BaseView(pcDocument),currentMode(Child), wstate(Qt::WindowNoState) { setAttribute(Qt::WA_DeleteOnClose); } MDIView::~MDIView() { //This view might be the focus widget of the main window. In this case we must //clear the focus and e.g. set the focus directly to the main window, otherwise //the application crashes when accessing this deleted view. //This effect only occurs if this widget is not in Child mode, because otherwise //the focus stuff is done correctly. if (getMainWindow()) { QWidget* foc = getMainWindow()->focusWidget(); if (foc) { QWidget* par = foc; while (par) { if (par == this) { getMainWindow()->setFocus(); break; } par = par->parentWidget(); } } } } void MDIView::deleteSelf() { // When using QMdiArea make sure to remove the QMdiSubWindow // this view is associated with. #if !defined (NO_USE_QT_MDI_AREA) QWidget* parent = this->parentWidget(); if (qobject_cast<QMdiSubWindow*>(parent)) delete parent; else #endif delete this; } void MDIView::onRelabel(Gui::Document *pDoc) { if (!bIsPassive) { // Try to separate document name and view number if there is one QString cap = windowTitle(); // Either with dirty flag ... QRegExp rx(QLatin1String("(\\s\\:\\s\\d+\\[\\*\\])$")); int pos = rx.lastIndexIn(cap); if (pos == -1) { // ... or not rx.setPattern(QLatin1String("(\\s\\:\\s\\d+)$")); pos = rx.lastIndexIn(cap); } if (pos != -1) { cap = QString::fromUtf8(pDoc->getDocument()->Label.getValue()); cap += rx.cap(); setWindowTitle(cap); } else { cap = QString::fromUtf8(pDoc->getDocument()->Label.getValue()); cap = QString::fromAscii("%1[*]").arg(cap); setWindowTitle(cap); } } } void MDIView::viewAll() { } /// receive a message bool MDIView::onMsg(const char* pMsg,const char** ppReturn) { return false; } bool MDIView::onHasMsg(const char* pMsg) const { return false; } bool MDIView::canClose(void) { if (!bIsPassive && getGuiDocument() && getGuiDocument()->isLastView()) { this->setFocus(); // raises the view to front return (getGuiDocument()->canClose()); } return true; } void MDIView::closeEvent(QCloseEvent *e) { if (canClose()) { e->accept(); if (!bIsPassive) { // must be detached so that the last view can get asked Document* doc = this->getGuiDocument(); if (doc && !doc->isLastView()) doc->detachView(this); } // Note: When using QMdiArea we must not use removeWindow() // because otherwise the QMdiSubWindow will loose its parent // and thus the notification in QMdiSubWindow::closeEvent of // other mdi windows to get maximized if this window // is maximized will fail. // This odd behaviour is caused by the invocation of // d->mdiArea->removeSubWindow(parent) which we must let there // because otherwise other parts don't work as they should. #if defined (NO_USE_QT_MDI_AREA) // avoid flickering getMainWindow()->removeWindow(this); #endif QMainWindow::closeEvent(e); } else e->ignore(); } void MDIView::windowStateChanged( MDIView* ) { } void MDIView::print() { // print command specified but print method not overriden! assert(0); } void MDIView::printPdf() { // print command specified but print method not overriden! assert(0); } void MDIView::printPreview() { // print command specified but print method not overriden! assert(0); } QSize MDIView::minimumSizeHint () const { return QSize(400, 300); } void MDIView::changeEvent(QEvent *e) { switch (e->type()) { case QEvent::ActivationChange: { // Forces this top-level window to be the active view of the main window if (isActiveWindow()) { if (getMainWindow()->activeWindow() != this) getMainWindow()->setActiveWindow(this); } } break; case QEvent::WindowTitleChange: case QEvent::ModifiedChange: { // sets the appropriate tab of the tabbar getMainWindow()->tabChanged(this); } break; default: { QMainWindow::changeEvent(e); } break; } } #if defined(Q_WS_X11) // To fix bug #0000345 move function declaration to here extern void qt_x11_wait_for_window_manager( QWidget* w ); // defined in qwidget_x11.cpp #endif void MDIView::setCurrentViewMode(ViewMode mode) { switch (mode) { // go to normal mode case Child: { if (this->currentMode == FullScreen) { showNormal(); setWindowFlags(windowFlags() & ~Qt::Window); } else if (this->currentMode == TopLevel) { this->wstate = windowState(); setWindowFlags( windowFlags() & ~Qt::Window ); } if (this->currentMode != Child) { this->currentMode = Child; getMainWindow()->addWindow(this); getMainWindow()->activateWindow(); update(); } } break; // go to top-level mode case TopLevel: { if (this->currentMode == Child) { #if !defined (NO_USE_QT_MDI_AREA) if (qobject_cast<QMdiSubWindow*>(this->parentWidget())) #endif getMainWindow()->removeWindow(this); setWindowFlags(windowFlags() | Qt::Window); setParent(0, Qt::Window | Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowMinMaxButtonsHint); if (this->wstate & Qt::WindowMaximized) showMaximized(); else showNormal(); #if defined(Q_WS_X11) //extern void qt_x11_wait_for_window_manager( QWidget* w ); // defined in qwidget_x11.cpp qt_x11_wait_for_window_manager(this); #endif activateWindow(); } else if (this->currentMode == FullScreen) { if (this->wstate & Qt::WindowMaximized) showMaximized(); else showNormal(); } this->currentMode = TopLevel; update(); } break; // go to fullscreen mode case FullScreen: { if (this->currentMode == Child) { #if !defined (NO_USE_QT_MDI_AREA) if (qobject_cast<QMdiSubWindow*>(this->parentWidget())) #endif getMainWindow()->removeWindow(this); setWindowFlags(windowFlags() | Qt::Window); setParent(0, Qt::Window); showFullScreen(); } else if (this->currentMode == TopLevel) { this->wstate = windowState(); showFullScreen(); } this->currentMode = FullScreen; update(); } break; } } #include "moc_MDIView.cpp"
Fix possible crash when cleaning up MDI views
Fix possible crash when cleaning up MDI views
C++
lgpl-2.1
usakhelo/FreeCAD,marcoitur/FreeCAD,YuanYouYuan/FreeCAD,Creworker/FreeCAD,marcoitur/FreeCAD,cpollard1001/FreeCAD_sf_master,wood-galaxy/FreeCAD,usakhelo/FreeCAD,bblacey/FreeCAD-MacOS-CI,marcoitur/Freecad_test,marcoitur/Freecad_test,usakhelo/FreeCAD,chrisjaquet/FreeCAD,elgambitero/FreeCAD_sf_master,cpollard1001/FreeCAD_sf_master,JonasThomas/free-cad,mickele77/FreeCAD,maurerpe/FreeCAD,cypsun/FreeCAD,Fat-Zer/FreeCAD_sf_master,wood-galaxy/FreeCAD,balazs-bamer/FreeCAD-Surface,Fat-Zer/FreeCAD_sf_master,JonasThomas/free-cad,usakhelo/FreeCAD,jonnor/FreeCAD,marcoitur/FreeCAD,dsbrown/FreeCAD,kkoksvik/FreeCAD,Alpistinho/FreeCAD,thdtjsdn/FreeCAD,wood-galaxy/FreeCAD,cpollard1001/FreeCAD_sf_master,timthelion/FreeCAD_sf_master,elgambitero/FreeCAD_sf_master,JonasThomas/free-cad,timthelion/FreeCAD_sf_master,jriegel/FreeCAD,YuanYouYuan/FreeCAD,marcoitur/Freecad_test,usakhelo/FreeCAD,chrisjaquet/FreeCAD,kkoksvik/FreeCAD,balazs-bamer/FreeCAD-Surface,wood-galaxy/FreeCAD,timthelion/FreeCAD,maurerpe/FreeCAD,Fat-Zer/FreeCAD_sf_master,timthelion/FreeCAD_sf_master,bblacey/FreeCAD-MacOS-CI,chrisjaquet/FreeCAD,wood-galaxy/FreeCAD,chrisjaquet/FreeCAD,timthelion/FreeCAD,jonnor/FreeCAD,bblacey/FreeCAD-MacOS-CI,timthelion/FreeCAD_sf_master,usakhelo/FreeCAD,cypsun/FreeCAD,maurerpe/FreeCAD,balazs-bamer/FreeCAD-Surface,Creworker/FreeCAD,elgambitero/FreeCAD_sf_master,timthelion/FreeCAD,cypsun/FreeCAD,mickele77/FreeCAD,mickele77/FreeCAD,thdtjsdn/FreeCAD,dsbrown/FreeCAD,chrisjaquet/FreeCAD,dsbrown/FreeCAD,jriegel/FreeCAD,cpollard1001/FreeCAD_sf_master,Alpistinho/FreeCAD,JonasThomas/free-cad,YuanYouYuan/FreeCAD,maurerpe/FreeCAD,thdtjsdn/FreeCAD,jonnor/FreeCAD,Creworker/FreeCAD,kkoksvik/FreeCAD,elgambitero/FreeCAD_sf_master,usakhelo/FreeCAD,balazs-bamer/FreeCAD-Surface,Alpistinho/FreeCAD,Fat-Zer/FreeCAD_sf_master,YuanYouYuan/FreeCAD,jriegel/FreeCAD,Fat-Zer/FreeCAD_sf_master,dsbrown/FreeCAD,yantrabuddhi/FreeCAD,yantrabuddhi/FreeCAD,Alpistinho/FreeCAD,jriegel/FreeCAD,mickele77/FreeCAD,marcoitur/FreeCAD,thdtjsdn/FreeCAD,balazs-bamer/FreeCAD-Surface,maurerpe/FreeCAD,wood-galaxy/FreeCAD,chrisjaquet/FreeCAD,elgambitero/FreeCAD_sf_master,bblacey/FreeCAD-MacOS-CI,cypsun/FreeCAD,kkoksvik/FreeCAD,bblacey/FreeCAD-MacOS-CI,bblacey/FreeCAD-MacOS-CI,timthelion/FreeCAD,timthelion/FreeCAD,Alpistinho/FreeCAD,bblacey/FreeCAD-MacOS-CI,yantrabuddhi/FreeCAD,dsbrown/FreeCAD,chrisjaquet/FreeCAD,jonnor/FreeCAD,timthelion/FreeCAD,timthelion/FreeCAD_sf_master,mickele77/FreeCAD,Creworker/FreeCAD,marcoitur/FreeCAD,YuanYouYuan/FreeCAD,marcoitur/Freecad_test,thdtjsdn/FreeCAD,kkoksvik/FreeCAD,yantrabuddhi/FreeCAD,marcoitur/Freecad_test,yantrabuddhi/FreeCAD,jriegel/FreeCAD,cpollard1001/FreeCAD_sf_master,cypsun/FreeCAD,Creworker/FreeCAD,jonnor/FreeCAD
d13bcdb3a9f9b43010fe8cbb4efbfe7eec0b705b
src/mesa/drivers/dri/i965/brw_fs_peephole_predicated_break.cpp
src/mesa/drivers/dri/i965/brw_fs_peephole_predicated_break.cpp
/* * Copyright © 2013 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #include "brw_fs.h" #include "brw_cfg.h" /** @file brw_fs_peephole_predicated_break.cpp * * Loops are often structured as * * loop: * CMP.f0 * (+f0) IF * BREAK * ENDIF * ... * WHILE loop * * This peephole pass removes the IF and ENDIF instructions and predicates the * BREAK, dropping two instructions from the loop body. */ bool fs_visitor::opt_peephole_predicated_break() { bool progress = false; foreach_block (block, cfg) { if (block->start_ip != block->end_ip) continue; /* BREAK and CONTINUE instructions, by definition, can only be found at * the ends of basic blocks. */ fs_inst *jump_inst = (fs_inst *)block->end(); if (jump_inst->opcode != BRW_OPCODE_BREAK && jump_inst->opcode != BRW_OPCODE_CONTINUE) continue; fs_inst *if_inst = (fs_inst *)block->prev()->end(); if (if_inst->opcode != BRW_OPCODE_IF) continue; fs_inst *endif_inst = (fs_inst *)block->next()->start(); if (endif_inst->opcode != BRW_OPCODE_ENDIF) continue; bblock_t *jump_block = block; bblock_t *if_block = jump_block->prev(); bblock_t *endif_block = jump_block->next(); /* For Sandybridge with IF with embedded comparison we need to emit an * instruction to set the flag register. */ if (brw->gen == 6 && if_inst->conditional_mod) { fs_inst *cmp_inst = CMP(reg_null_d, if_inst->src[0], if_inst->src[1], if_inst->conditional_mod); if_inst->insert_before(if_block, cmp_inst); jump_inst->predicate = BRW_PREDICATE_NORMAL; } else { jump_inst->predicate = if_inst->predicate; jump_inst->predicate_inverse = if_inst->predicate_inverse; } bblock_t *earlier_block = if_block; if (if_block->start_ip == if_block->end_ip) { earlier_block = if_block->prev(); } if_inst->remove(if_block); bblock_t *later_block = endif_block; if (endif_block->start_ip == endif_block->end_ip) { later_block = endif_block->next(); } endif_inst->remove(endif_block); earlier_block->children.make_empty(); later_block->parents.make_empty(); earlier_block->add_successor(cfg->mem_ctx, jump_block); jump_block->add_successor(cfg->mem_ctx, later_block); if (earlier_block->can_combine_with(jump_block)) { earlier_block->combine_with(jump_block); block = earlier_block; } progress = true; } if (progress) invalidate_live_intervals(); return progress; }
/* * Copyright © 2013 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #include "brw_fs.h" #include "brw_cfg.h" /** @file brw_fs_peephole_predicated_break.cpp * * Loops are often structured as * * loop: * CMP.f0 * (+f0) IF * BREAK * ENDIF * ... * WHILE loop * * This peephole pass removes the IF and ENDIF instructions and predicates the * BREAK, dropping two instructions from the loop body. * * If the loop was a DO { ... } WHILE loop, it looks like * * loop: * ... * CMP.f0 * (+f0) IF * BREAK * ENDIF * WHILE loop * * and we can remove the BREAK instruction and predicate the WHILE. */ bool fs_visitor::opt_peephole_predicated_break() { bool progress = false; foreach_block (block, cfg) { if (block->start_ip != block->end_ip) continue; /* BREAK and CONTINUE instructions, by definition, can only be found at * the ends of basic blocks. */ fs_inst *jump_inst = (fs_inst *)block->end(); if (jump_inst->opcode != BRW_OPCODE_BREAK && jump_inst->opcode != BRW_OPCODE_CONTINUE) continue; fs_inst *if_inst = (fs_inst *)block->prev()->end(); if (if_inst->opcode != BRW_OPCODE_IF) continue; fs_inst *endif_inst = (fs_inst *)block->next()->start(); if (endif_inst->opcode != BRW_OPCODE_ENDIF) continue; bblock_t *jump_block = block; bblock_t *if_block = jump_block->prev(); bblock_t *endif_block = jump_block->next(); /* For Sandybridge with IF with embedded comparison we need to emit an * instruction to set the flag register. */ if (brw->gen == 6 && if_inst->conditional_mod) { fs_inst *cmp_inst = CMP(reg_null_d, if_inst->src[0], if_inst->src[1], if_inst->conditional_mod); if_inst->insert_before(if_block, cmp_inst); jump_inst->predicate = BRW_PREDICATE_NORMAL; } else { jump_inst->predicate = if_inst->predicate; jump_inst->predicate_inverse = if_inst->predicate_inverse; } bblock_t *earlier_block = if_block; if (if_block->start_ip == if_block->end_ip) { earlier_block = if_block->prev(); } if_inst->remove(if_block); bblock_t *later_block = endif_block; if (endif_block->start_ip == endif_block->end_ip) { later_block = endif_block->next(); } endif_inst->remove(endif_block); earlier_block->children.make_empty(); later_block->parents.make_empty(); earlier_block->add_successor(cfg->mem_ctx, jump_block); jump_block->add_successor(cfg->mem_ctx, later_block); if (earlier_block->can_combine_with(jump_block)) { earlier_block->combine_with(jump_block); block = earlier_block; } /* Now look at the first instruction of the block following the BREAK. If * it's a WHILE, we can delete the break, predicate the WHILE, and join * the two basic blocks. */ bblock_t *while_block = earlier_block->next(); fs_inst *while_inst = (fs_inst *)while_block->start(); if (jump_inst->opcode == BRW_OPCODE_BREAK && while_inst->opcode == BRW_OPCODE_WHILE && while_inst->predicate == BRW_PREDICATE_NONE) { jump_inst->remove(earlier_block); while_inst->predicate = jump_inst->predicate; while_inst->predicate_inverse = !jump_inst->predicate_inverse; earlier_block->children.make_empty(); earlier_block->add_successor(cfg->mem_ctx, while_block); assert(earlier_block->can_combine_with(while_block)); earlier_block->combine_with(while_block); earlier_block->next()->parents.make_empty(); earlier_block->add_successor(cfg->mem_ctx, earlier_block->next()); } progress = true; } if (progress) invalidate_live_intervals(); return progress; }
Extend predicated break pass to predicate WHILE.
i965/fs: Extend predicated break pass to predicate WHILE. Helps a handful of programs in Serious Sam 3 that use do-while loops. instructions in affected programs: 16114 -> 16075 (-0.24%) Reviewed-by: Ian Romanick <[email protected]>
C++
mit
bkaradzic/glsl-optimizer,tokyovigilante/glsl-optimizer,mcanthony/glsl-optimizer,benaadams/glsl-optimizer,jbarczak/glsl-optimizer,tokyovigilante/glsl-optimizer,djreep81/glsl-optimizer,zz85/glsl-optimizer,tokyovigilante/glsl-optimizer,jbarczak/glsl-optimizer,zz85/glsl-optimizer,zz85/glsl-optimizer,dellis1972/glsl-optimizer,zz85/glsl-optimizer,benaadams/glsl-optimizer,benaadams/glsl-optimizer,metora/MesaGLSLCompiler,zeux/glsl-optimizer,zz85/glsl-optimizer,mcanthony/glsl-optimizer,wolf96/glsl-optimizer,djreep81/glsl-optimizer,tokyovigilante/glsl-optimizer,bkaradzic/glsl-optimizer,zeux/glsl-optimizer,wolf96/glsl-optimizer,zz85/glsl-optimizer,dellis1972/glsl-optimizer,djreep81/glsl-optimizer,zeux/glsl-optimizer,bkaradzic/glsl-optimizer,dellis1972/glsl-optimizer,metora/MesaGLSLCompiler,zeux/glsl-optimizer,wolf96/glsl-optimizer,dellis1972/glsl-optimizer,jbarczak/glsl-optimizer,djreep81/glsl-optimizer,bkaradzic/glsl-optimizer,metora/MesaGLSLCompiler,wolf96/glsl-optimizer,tokyovigilante/glsl-optimizer,jbarczak/glsl-optimizer,benaadams/glsl-optimizer,jbarczak/glsl-optimizer,zeux/glsl-optimizer,wolf96/glsl-optimizer,djreep81/glsl-optimizer,mcanthony/glsl-optimizer,bkaradzic/glsl-optimizer,mcanthony/glsl-optimizer,dellis1972/glsl-optimizer,mcanthony/glsl-optimizer,benaadams/glsl-optimizer,benaadams/glsl-optimizer
ff6a8a6d579a76bfd6338ca8fbc12273af336d32
src/nanoFramework.System.Collections/nf_system_collections.cpp
src/nanoFramework.System.Collections/nf_system_collections.cpp
#include "nf_system_collections.h" static const CLR_RT_MethodHandler method_lookup[] = { NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, Library_nf_system_collections_System_Collections_Queue::Clear___VOID, Library_nf_system_collections_System_Collections_Queue::CopyTo___VOID__SystemArray__I4, Library_nf_system_collections_System_Collections_Queue::Enqueue___VOID__OBJECT, NULL, Library_nf_system_collections_System_Collections_Queue::Dequeue___OBJECT, Library_nf_system_collections_System_Collections_Queue::Peek___OBJECT, NULL, NULL, NULL, NULL, NULL, NULL, Library_nf_system_collections_System_Collections_Stack::Clear___VOID, NULL, NULL, NULL, NULL, Library_nf_system_collections_System_Collections_Stack::Peek___OBJECT, Library_nf_system_collections_System_Collections_Stack::Pop___OBJECT, Library_nf_system_collections_System_Collections_Stack::Push___VOID__OBJECT, NULL, NULL, }; const CLR_RT_NativeAssemblyData g_CLR_AssemblyNative_nanoFramework_System_Collections = { "nanoFramework.System.Collections", 0x3D26C4A9, method_lookup, { 100, 0, 0, 1 } };
#include "nf_system_collections.h" static const CLR_RT_MethodHandler method_lookup[] = { NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, Library_nf_system_collections_System_Collections_Queue::Clear___VOID, Library_nf_system_collections_System_Collections_Queue::CopyTo___VOID__SystemArray__I4, Library_nf_system_collections_System_Collections_Queue::Enqueue___VOID__OBJECT, NULL, Library_nf_system_collections_System_Collections_Queue::Dequeue___OBJECT, Library_nf_system_collections_System_Collections_Queue::Peek___OBJECT, NULL, NULL, NULL, NULL, NULL, NULL, Library_nf_system_collections_System_Collections_Stack::Clear___VOID, NULL, NULL, NULL, NULL, Library_nf_system_collections_System_Collections_Stack::Peek___OBJECT, Library_nf_system_collections_System_Collections_Stack::Pop___OBJECT, Library_nf_system_collections_System_Collections_Stack::Push___VOID__OBJECT, NULL, NULL, }; const CLR_RT_NativeAssemblyData g_CLR_AssemblyNative_nanoFramework_System_Collections = { "nanoFramework.System.Collections", 0x5A31313D, method_lookup, { 100, 0, 0, 1 } };
Update declaration of System.Collections (#1594)
Update declaration of System.Collections (#1594)
C++
mit
nanoframework/nf-interpreter,Eclo/nf-interpreter,Eclo/nf-interpreter,Eclo/nf-interpreter,nanoframework/nf-interpreter,Eclo/nf-interpreter,nanoframework/nf-interpreter,nanoframework/nf-interpreter
3404edfcd59258dc1a218a8fe6c8331f5c365a8a
engine/utils/Log.cpp
engine/utils/Log.cpp
// Copyright 2015-2020 Elviss Strazdins. All rights reserved. #if defined(__APPLE__) # include <TargetConditionals.h> #endif #if defined(__ANDROID__) # include <android/log.h> #elif TARGET_OS_IOS || TARGET_OS_TV # include <sys/syslog.h> #elif TARGET_OS_MAC || defined(__linux__) # include <unistd.h> #elif defined(_WIN32) # pragma push_macro("WIN32_LEAN_AND_MEAN") # pragma push_macro("NOMINMAX") # ifndef WIN32_LEAN_AND_MEAN # define WIN32_LEAN_AND_MEAN # endif # ifndef NOMINMAX # define NOMINMAX # endif # include <Windows.h> # pragma pop_macro("WIN32_LEAN_AND_MEAN") # pragma pop_macro("NOMINMAX") # include <strsafe.h> #elif defined(__EMSCRIPTEN__) # include <emscripten.h> #endif #include "Log.hpp" namespace ouzel { Log::~Log() { if (!s.empty()) logger.log(s, level); } void Logger::logString(const std::string& str, Log::Level level) { #if defined(__ANDROID__) int priority = 0; switch (level) { case Log::Level::error: priority = ANDROID_LOG_ERROR; break; case Log::Level::warning: priority = ANDROID_LOG_WARN; break; case Log::Level::info: priority = ANDROID_LOG_INFO; break; case Log::Level::all: priority = ANDROID_LOG_DEBUG; break; default: return; } __android_log_print(priority, "Ouzel", "%s", str.c_str()); #elif TARGET_OS_IOS || TARGET_OS_TV int priority = 0; switch (level) { case Log::Level::error: priority = LOG_ERR; break; case Log::Level::warning: priority = LOG_WARNING; break; case Log::Level::info: priority = LOG_INFO; break; case Log::Level::all: priority = LOG_DEBUG; break; default: return; } syslog(priority, "%s", str.c_str()); #elif TARGET_OS_MAC || defined(__linux__) int fd = 0; switch (level) { case Log::Level::error: case Log::Level::warning: fd = STDERR_FILENO; break; case Log::Level::info: case Log::Level::all: fd = STDOUT_FILENO; break; default: return; } std::vector<char> output(str.begin(), str.end()); output.push_back('\n'); std::size_t offset = 0; while (offset < output.size()) { ssize_t written = write(fd, output.data() + offset, output.size() - offset); while (written == -1 && errno == EINTR) written = write(fd, output.data() + offset, output.size() - offset); if (written == -1) return; offset += static_cast<std::size_t>(written); } #elif defined(_WIN32) const int bufferSize = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, nullptr, 0); if (bufferSize == 0) return; auto buffer = std::make_unique<WCHAR[]>(bufferSize + 1); // +1 for the newline if (MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, buffer.get(), bufferSize) == 0) return; if (FAILED(StringCchCatW(buffer.get(), static_cast<size_t>(bufferSize), L"\n"))) return; OutputDebugStringW(buffer.get()); # if DEBUG HANDLE handle; switch (level) { case Log::Level::error: case Log::Level::warning: handle = GetStdHandle(STD_ERROR_HANDLE); break; case Log::Level::info: case Log::Level::all: handle = GetStdHandle(STD_OUTPUT_HANDLE); break; default: return; } WriteConsoleW(handle, buffer.get(), static_cast<DWORD>(wcslen(buffer.get())), nullptr, nullptr); # endif #elif defined(__EMSCRIPTEN__) int flags = EM_LOG_CONSOLE; switch (level) { case Log::Level::error: flags |= EM_LOG_ERROR; break; case Log::Level::warning: flags |= EM_LOG_WARN; break; case Log::Level::info: case Log::Level::all: break; default: return; } emscripten_log(flags, "%s", str.c_str()); #endif } }
// Copyright 2015-2020 Elviss Strazdins. All rights reserved. #if defined(__APPLE__) # include <TargetConditionals.h> #endif #if defined(__ANDROID__) # include <android/log.h> #elif TARGET_OS_IOS || TARGET_OS_TV # include <sys/syslog.h> #elif TARGET_OS_MAC || defined(__linux__) # include <unistd.h> #elif defined(_WIN32) # pragma push_macro("WIN32_LEAN_AND_MEAN") # pragma push_macro("NOMINMAX") # ifndef WIN32_LEAN_AND_MEAN # define WIN32_LEAN_AND_MEAN # endif # ifndef NOMINMAX # define NOMINMAX # endif # include <Windows.h> # pragma pop_macro("WIN32_LEAN_AND_MEAN") # pragma pop_macro("NOMINMAX") # include <strsafe.h> #elif defined(__EMSCRIPTEN__) # include <emscripten.h> #endif #include "Log.hpp" namespace ouzel { Log::~Log() { if (!s.empty()) logger.log(s, level); } void Logger::logString(const std::string& str, Log::Level level) { #if defined(__ANDROID__) int priority = 0; switch (level) { case Log::Level::error: priority = ANDROID_LOG_ERROR; break; case Log::Level::warning: priority = ANDROID_LOG_WARN; break; case Log::Level::info: priority = ANDROID_LOG_INFO; break; case Log::Level::all: priority = ANDROID_LOG_DEBUG; break; default: return; } __android_log_print(priority, "Ouzel", "%s", str.c_str()); #elif TARGET_OS_IOS || TARGET_OS_TV int priority = 0; switch (level) { case Log::Level::error: priority = LOG_ERR; break; case Log::Level::warning: priority = LOG_WARNING; break; case Log::Level::info: priority = LOG_INFO; break; case Log::Level::all: priority = LOG_DEBUG; break; default: return; } syslog(priority, "%s", str.c_str()); #elif TARGET_OS_MAC || defined(__linux__) int fd = 0; switch (level) { case Log::Level::error: case Log::Level::warning: fd = STDERR_FILENO; break; case Log::Level::info: case Log::Level::all: fd = STDOUT_FILENO; break; default: return; } std::vector<char> output(str.begin(), str.end()); output.push_back('\n'); std::size_t offset = 0; while (offset < output.size()) { ssize_t written = write(fd, output.data() + offset, output.size() - offset); while (written == -1 && errno == EINTR) written = write(fd, output.data() + offset, output.size() - offset); if (written == -1) return; offset += static_cast<std::size_t>(written); } #elif defined(_WIN32) const int bufferSize = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, nullptr, 0); if (bufferSize == 0) return; auto buffer = std::make_unique<WCHAR[]>(bufferSize + 1); // +1 for the newline if (MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, buffer.get(), bufferSize) == 0) return; if (FAILED(StringCchCatW(buffer.get(), static_cast<size_t>(bufferSize + 1), L"\n"))) return; OutputDebugStringW(buffer.get()); # if DEBUG HANDLE handle; switch (level) { case Log::Level::error: case Log::Level::warning: handle = GetStdHandle(STD_ERROR_HANDLE); break; case Log::Level::info: case Log::Level::all: handle = GetStdHandle(STD_OUTPUT_HANDLE); break; default: return; } WriteConsoleW(handle, buffer.get(), static_cast<DWORD>(wcslen(buffer.get())), nullptr, nullptr); # endif #elif defined(__EMSCRIPTEN__) int flags = EM_LOG_CONSOLE; switch (level) { case Log::Level::error: flags |= EM_LOG_ERROR; break; case Log::Level::warning: flags |= EM_LOG_WARN; break; case Log::Level::info: case Log::Level::all: break; default: return; } emscripten_log(flags, "%s", str.c_str()); #endif } }
Fix logging on Windows
Fix logging on Windows
C++
unlicense
elnormous/ouzel,elnormous/ouzel,elnormous/ouzel
b24240187257d4cfda5ee5571726f4145ba2475c
opencog/embodiment/Control/MessagingSystem/SpawnerExecutable.cc
opencog/embodiment/Control/MessagingSystem/SpawnerExecutable.cc
/* * opencog/embodiment/Control/MessagingSystem/SpawnerExecutable.cc * * Copyright (C) 2002-2009 Novamente LLC * All Rights Reserved * Author(s): Andre Senna * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License v3 as * published by the Free Software Foundation and including the exceptions * at http://opencog.org/wiki/Licenses * * 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 Affero General Public License * along with this program; if not, write to: * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <opencog/embodiment/Control/EmbodimentConfig.h> #include <exception> #include <opencog/util/exceptions.h> #include <opencog/util/files.h> #include <opencog/util/macros.h> #include "Spawner.h" using namespace opencog::messaging; using namespace opencog; using namespace opencog::control; void spawner_unexpected_handler() { throw; } int main(int argc, char *argv[]) { Spawner *spawner = NULL; config(EmbodimentConfig::embodimentCreateInstance, true); // if exists load file with configuration parameters // IMPORTANT: this file should be the same for all executables that create // a systemParameter object. if (fileExists(config().get("CONFIG_FILE").c_str())) { config().load(config().get("CONFIG_FILE").c_str()); } // setting unexpected handler in case a different exception from // the specified ones is thrown in the code std::set_unexpected(spawner_unexpected_handler); int i; i = system("./router &"); sleep(5); i = system("./learningServer &"); //i = system("./pvpSimulator &"); // proxy OC_UNUSED( i ); try { server(Spawner::createInstance); spawner = &(static_cast<Spawner&>(server())); spawner->init(config().get("SPAWNER_ID"), config().get("SPAWNER_IP"), config().get_int("SPAWNER_PORT")); spawner->serverLoop(); } catch (opencog::InvalidParamException& ipe) { logger().error( "SpawnerExec - Error creating spawner object."); } catch (std::bad_alloc) { logger().error( "SpawnerExec - Spawner raised a bad_alloc exception."); } catch (...) { logger().error( "Spawner executable - An exceptional situation occured. Check log for more information."); } // if spawner criated, delete it if (spawner) { delete spawner; } return (0); }
/* * opencog/embodiment/Control/MessagingSystem/SpawnerExecutable.cc * * Copyright (C) 2002-2009 Novamente LLC * All Rights Reserved * Author(s): Andre Senna * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License v3 as * published by the Free Software Foundation and including the exceptions * at http://opencog.org/wiki/Licenses * * 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 Affero General Public License * along with this program; if not, write to: * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <opencog/embodiment/Control/EmbodimentConfig.h> #include <exception> #include <opencog/util/exceptions.h> #include <opencog/util/files.h> #include <opencog/util/macros.h> #include "Spawner.h" using namespace opencog::messaging; using namespace opencog; using namespace opencog::control; void spawner_unexpected_handler() { throw; } int main(int argc, char *argv[]) { Spawner *spawner = NULL; config(EmbodimentConfig::embodimentCreateInstance, true); // if exists load file with configuration parameters // IMPORTANT: this file should be the same for all executables that create // a systemParameter object. if (fileExists(config().get("CONFIG_FILE").c_str())) { config().load(config().get("CONFIG_FILE").c_str()); } // setting unexpected handler in case a different exception from // the specified ones is thrown in the code std::set_unexpected(spawner_unexpected_handler); int i; i = system("./router &"); sleep(5); // i = system("./learningServer &"); //i = system("./pvpSimulator &"); // proxy OC_UNUSED( i ); try { server(Spawner::createInstance); spawner = &(static_cast<Spawner&>(server())); spawner->init(config().get("SPAWNER_ID"), config().get("SPAWNER_IP"), config().get_int("SPAWNER_PORT")); spawner->serverLoop(); } catch (opencog::InvalidParamException& ipe) { logger().error( "SpawnerExec - Error creating spawner object."); } catch (std::bad_alloc) { logger().error( "SpawnerExec - Spawner raised a bad_alloc exception."); } catch (...) { logger().error( "Spawner executable - An exceptional situation occured. Check log for more information."); } // if spawner criated, delete it if (spawner) { delete spawner; } return (0); }
Disable LearningServer which is not currently used
Disable LearningServer which is not currently used That is just to avoid useless log in the ROUTER log file which is already hard enouhg to comprehend.
C++
agpl-3.0
kinoc/opencog,anitzkin/opencog,kinoc/opencog,AmeBel/atomspace,yantrabuddhi/opencog,ArvinPan/opencog,shujingke/opencog,virneo/opencog,kinoc/opencog,eddiemonroe/atomspace,tim777z/opencog,sumitsourabh/opencog,MarcosPividori/atomspace,Allend575/opencog,Allend575/opencog,Tiggels/opencog,rodsol/atomspace,rTreutlein/atomspace,iAMr00t/opencog,rohit12/opencog,williampma/atomspace,inflector/atomspace,roselleebarle04/opencog,inflector/opencog,shujingke/opencog,williampma/atomspace,iAMr00t/opencog,AmeBel/opencog,sumitsourabh/opencog,roselleebarle04/opencog,roselleebarle04/opencog,andre-senna/opencog,rTreutlein/atomspace,AmeBel/atomspace,gavrieltal/opencog,rohit12/opencog,virneo/opencog,gavrieltal/opencog,cosmoharrigan/opencog,tim777z/opencog,yantrabuddhi/opencog,ruiting/opencog,rodsol/atomspace,jlegendary/opencog,eddiemonroe/atomspace,jlegendary/opencog,roselleebarle04/opencog,ruiting/opencog,andre-senna/opencog,TheNameIsNigel/opencog,misgeatgit/opencog,gaapt/opencog,kim135797531/opencog,Selameab/opencog,TheNameIsNigel/opencog,prateeksaxena2809/opencog,rohit12/opencog,rohit12/atomspace,misgeatgit/atomspace,Selameab/opencog,iAMr00t/opencog,ruiting/opencog,ceefour/atomspace,gaapt/opencog,printedheart/opencog,inflector/opencog,AmeBel/opencog,printedheart/opencog,eddiemonroe/atomspace,misgeatgit/atomspace,sanuj/opencog,iAMr00t/opencog,virneo/opencog,kim135797531/opencog,jlegendary/opencog,eddiemonroe/opencog,eddiemonroe/opencog,tim777z/opencog,cosmoharrigan/opencog,AmeBel/atomspace,ArvinPan/opencog,shujingke/opencog,yantrabuddhi/opencog,ArvinPan/opencog,rodsol/opencog,cosmoharrigan/opencog,printedheart/opencog,rohit12/atomspace,williampma/opencog,inflector/atomspace,shujingke/opencog,printedheart/atomspace,andre-senna/opencog,andre-senna/opencog,AmeBel/opencog,virneo/opencog,jswiergo/atomspace,printedheart/opencog,ArvinPan/atomspace,prateeksaxena2809/opencog,UIKit0/atomspace,jswiergo/atomspace,williampma/opencog,Selameab/atomspace,roselleebarle04/opencog,yantrabuddhi/atomspace,gaapt/opencog,Allend575/opencog,jlegendary/opencog,printedheart/atomspace,virneo/opencog,ceefour/opencog,misgeatgit/opencog,misgeatgit/atomspace,ruiting/opencog,virneo/atomspace,Tiggels/opencog,anitzkin/opencog,Selameab/opencog,yantrabuddhi/opencog,eddiemonroe/opencog,AmeBel/atomspace,tim777z/opencog,prateeksaxena2809/opencog,ceefour/opencog,anitzkin/opencog,andre-senna/opencog,gavrieltal/opencog,kim135797531/opencog,ceefour/opencog,rodsol/opencog,yantrabuddhi/opencog,eddiemonroe/atomspace,cosmoharrigan/atomspace,jlegendary/opencog,sanuj/opencog,ceefour/opencog,rohit12/opencog,cosmoharrigan/opencog,UIKit0/atomspace,jswiergo/atomspace,Selameab/atomspace,ceefour/atomspace,kinoc/opencog,Allend575/opencog,gavrieltal/opencog,printedheart/opencog,williampma/opencog,eddiemonroe/opencog,cosmoharrigan/atomspace,virneo/atomspace,sumitsourabh/opencog,misgeatgit/atomspace,misgeatgit/opencog,cosmoharrigan/atomspace,misgeatgit/opencog,printedheart/atomspace,AmeBel/opencog,Allend575/opencog,williampma/opencog,inflector/atomspace,Selameab/opencog,rodsol/opencog,ceefour/opencog,rohit12/atomspace,shujingke/opencog,TheNameIsNigel/opencog,ArvinPan/atomspace,Tiggels/opencog,kim135797531/opencog,jlegendary/opencog,printedheart/atomspace,MarcosPividori/atomspace,tim777z/opencog,Tiggels/opencog,Selameab/atomspace,AmeBel/opencog,rodsol/opencog,ruiting/opencog,sumitsourabh/opencog,gavrieltal/opencog,gaapt/opencog,Tiggels/opencog,virneo/atomspace,jswiergo/atomspace,jlegendary/opencog,misgeatgit/opencog,kinoc/opencog,MarcosPividori/atomspace,inflector/opencog,misgeatgit/opencog,TheNameIsNigel/opencog,williampma/atomspace,rohit12/opencog,yantrabuddhi/atomspace,yantrabuddhi/opencog,ceefour/opencog,rTreutlein/atomspace,gavrieltal/opencog,gavrieltal/opencog,sumitsourabh/opencog,Selameab/atomspace,yantrabuddhi/atomspace,cosmoharrigan/opencog,ruiting/opencog,UIKit0/atomspace,eddiemonroe/opencog,rodsol/opencog,yantrabuddhi/atomspace,sanuj/opencog,ceefour/opencog,roselleebarle04/opencog,anitzkin/opencog,rTreutlein/atomspace,misgeatgit/opencog,inflector/opencog,ArvinPan/atomspace,inflector/opencog,kim135797531/opencog,virneo/opencog,Selameab/opencog,rTreutlein/atomspace,anitzkin/opencog,printedheart/opencog,inflector/opencog,Tiggels/opencog,sanuj/opencog,ArvinPan/opencog,eddiemonroe/atomspace,sumitsourabh/opencog,ceefour/atomspace,andre-senna/opencog,yantrabuddhi/atomspace,kim135797531/opencog,prateeksaxena2809/opencog,kinoc/opencog,sanuj/opencog,kinoc/opencog,kim135797531/opencog,gaapt/opencog,sanuj/opencog,virneo/atomspace,Allend575/opencog,inflector/atomspace,inflector/opencog,Selameab/opencog,inflector/atomspace,iAMr00t/opencog,prateeksaxena2809/opencog,rohit12/opencog,AmeBel/atomspace,misgeatgit/opencog,eddiemonroe/opencog,gaapt/opencog,sumitsourabh/opencog,shujingke/opencog,andre-senna/opencog,cosmoharrigan/atomspace,anitzkin/opencog,roselleebarle04/opencog,gaapt/opencog,shujingke/opencog,AmeBel/opencog,rohit12/atomspace,inflector/opencog,tim777z/opencog,williampma/opencog,ArvinPan/atomspace,eddiemonroe/opencog,TheNameIsNigel/opencog,MarcosPividori/atomspace,ruiting/opencog,rodsol/atomspace,UIKit0/atomspace,TheNameIsNigel/opencog,rodsol/opencog,iAMr00t/opencog,Allend575/opencog,ArvinPan/opencog,ArvinPan/opencog,prateeksaxena2809/opencog,virneo/opencog,williampma/opencog,yantrabuddhi/opencog,prateeksaxena2809/opencog,cosmoharrigan/opencog,AmeBel/opencog,anitzkin/opencog,rodsol/atomspace,williampma/atomspace,misgeatgit/atomspace,misgeatgit/opencog,ceefour/atomspace
ca31fcb4c315a2f22d8593add2a12ce38869b248
tensorflow/compiler/xla/service/all_reduce_reassociate_test.cc
tensorflow/compiler/xla/service/all_reduce_reassociate_test.cc
/* Copyright 2021 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/compiler/xla/service/all_reduce_reassociate.h" #include "tensorflow/compiler/xla/service/hlo_matchers.h" #include "tensorflow/compiler/xla/service/hlo_module.h" #include "tensorflow/compiler/xla/service/hlo_opcode.h" #include "tensorflow/compiler/xla/tests/hlo_test_base.h" namespace xla { namespace { namespace m = xla::testing::opcode_matchers; class AllReduceSimplifierTest : public HloTestBase { public: StatusOr<std::unique_ptr<HloModule>> RunPass(absl::string_view hlo_module, bool expect_change) { TF_ASSIGN_OR_RETURN(auto module, ParseAndReturnVerifiedModule(hlo_module)); AllReduceReassociate pass; auto changed = AllReduceReassociate().Run(module.get()); if (!changed.ok()) { return changed.status(); } EXPECT_EQ(changed.ValueOrDie(), expect_change); return StatusOr<std::unique_ptr<HloModule>>(std::move(module)); } size_t AllReduceCount(std::unique_ptr<HloModule>& module) { return absl::c_count_if(module->entry_computation()->instructions(), [](const HloInstruction* inst) { return inst->opcode() == HloOpcode::kAllReduce; }); } }; TEST_F(AllReduceSimplifierTest, Simple) { absl::string_view hlo_string = R"( HloModule m sum { a = f32[] parameter(0) b = f32[] parameter(1) ROOT add.2 = f32[] add(a, b) } ENTRY main { p0 = f32[8] parameter(0) p1 = f32[8] parameter(1) ar0 = f32[8] all-reduce(p0), replica_groups={}, to_apply=sum ar1 = f32[8] all-reduce(p1), replica_groups={}, to_apply=sum ROOT add = f32[8] add(ar0, ar1) } )"; TF_ASSERT_OK_AND_ASSIGN(auto module, RunPass(hlo_string, /*expect_change=*/true)); EXPECT_THAT(module->entry_computation()->root_instruction(), m::AllReduce(m::Add(m::Parameter(0), m::Parameter(1)))); EXPECT_EQ(AllReduceCount(module), 1); } TEST_F(AllReduceSimplifierTest, SimpleWithChannelId) { absl::string_view hlo_string = R"( HloModule m sum { a = f32[] parameter(0) b = f32[] parameter(1) ROOT add.2 = f32[] add(a, b) } ENTRY main { p0 = f32[8] parameter(0) p1 = f32[8] parameter(1) ar0 = f32[8] all-reduce(p0), channel_id=1, replica_groups={}, to_apply=sum ar1 = f32[8] all-reduce(p1), channel_id=1, replica_groups={}, to_apply=sum ROOT add = f32[8] add(ar0, ar1) } )"; TF_ASSERT_OK_AND_ASSIGN(auto module, RunPass(hlo_string, /*expect_change=*/true)); EXPECT_THAT(module->entry_computation()->root_instruction(), m::AllReduce(m::Add(m::Parameter(0), m::Parameter(1)))); EXPECT_EQ(AllReduceCount(module), 1); } // Checks whether a linear chain of adds of ARs is reassociated iin a single // pass. TEST_F(AllReduceSimplifierTest, SimpleChain) { absl::string_view hlo_string = R"( HloModule m sum { a = f32[] parameter(0) b = f32[] parameter(1) ROOT add.2 = f32[] add(a, b) } ENTRY main { p0 = f32[8] parameter(0) p1 = f32[8] parameter(1) p2 = f32[8] parameter(2) p3 = f32[8] parameter(3) ar0 = f32[8] all-reduce(p0), replica_groups={}, to_apply=sum ar1 = f32[8] all-reduce(p1), replica_groups={}, to_apply=sum ar2 = f32[8] all-reduce(p2), replica_groups={}, to_apply=sum ar3 = f32[8] all-reduce(p3), replica_groups={}, to_apply=sum add0 = f32[8] add(ar0, ar1) add1 = f32[8] add(add0, ar2) ROOT add2 = f32[8] add(add1, ar3) } )"; TF_ASSERT_OK_AND_ASSIGN(auto module, RunPass(hlo_string, /*expect_change=*/true)); EXPECT_THAT( module->entry_computation()->root_instruction(), m::AllReduce(m::Add( m::Add(m::Add(m::Parameter(0), m::Parameter(1)), m::Parameter(2)), m::Parameter(3)))); EXPECT_EQ(AllReduceCount(module), 1); } // Checks whether a tree of add of ARs is reassociated in a single pass. TEST_F(AllReduceSimplifierTest, SimpleTree) { absl::string_view hlo_string = R"( HloModule m sum { a = f32[] parameter(0) b = f32[] parameter(1) ROOT add.2 = f32[] add(a, b) } ENTRY main { p0 = f32[8] parameter(0) p1 = f32[8] parameter(1) p2 = f32[8] parameter(2) p3 = f32[8] parameter(3) ar0 = f32[8] all-reduce(p0), replica_groups={}, to_apply=sum ar1 = f32[8] all-reduce(p1), replica_groups={}, to_apply=sum ar2 = f32[8] all-reduce(p2), replica_groups={}, to_apply=sum ar3 = f32[8] all-reduce(p3), replica_groups={}, to_apply=sum add0 = f32[8] add(ar0, ar1) add1 = f32[8] add(ar2, ar3) ROOT add2 = f32[8] add(add0, add1) } )"; TF_ASSERT_OK_AND_ASSIGN(auto module, RunPass(hlo_string, /*expect_change=*/true)); EXPECT_THAT(module->entry_computation()->root_instruction(), m::AllReduce(m::Add(m::Add(m::Parameter(0), m::Parameter(1)), m::Add(m::Parameter(2), m::Parameter(3))))); EXPECT_EQ(AllReduceCount(module), 1); } TEST_F(AllReduceSimplifierTest, MismatchOp0) { absl::string_view hlo_string = R"( HloModule m sum { a = f32[] parameter(0) b = f32[] parameter(1) ROOT add.2 = f32[] add(a, b) } max { a = f32[] parameter(0) b = f32[] parameter(1) ROOT r = f32[] maximum(a, b) } ENTRY main { p0 = f32[8] parameter(0) p1 = f32[8] parameter(1) ar0 = f32[8] all-reduce(p0), replica_groups={}, to_apply=sum ar1 = f32[8] all-reduce(p1), replica_groups={}, to_apply=max ROOT add = f32[8] add(ar0, ar1) } )"; TF_ASSERT_OK_AND_ASSIGN(auto module, RunPass(hlo_string, /*expect_change=*/false)); } TEST_F(AllReduceSimplifierTest, MismatchOp1) { absl::string_view hlo_string = R"( HloModule m sum { a = f32[] parameter(0) b = f32[] parameter(1) ROOT add.2 = f32[] add(a, b) } max { a = f32[] parameter(0) b = f32[] parameter(1) ROOT r = f32[] maximum(a, b) } ENTRY main { p0 = f32[8] parameter(0) p1 = f32[8] parameter(1) ar0 = f32[8] all-reduce(p0), replica_groups={}, to_apply=max ar1 = f32[8] all-reduce(p1), replica_groups={}, to_apply=max ROOT add = f32[8] add(ar0, ar1) } )"; TF_ASSERT_OK_AND_ASSIGN(auto module, RunPass(hlo_string, /*expect_change=*/false)); } TEST_F(AllReduceSimplifierTest, MismatchReplicaGroups) { absl::string_view hlo_string = R"( HloModule m sum { a = f32[] parameter(0) b = f32[] parameter(1) ROOT add.2 = f32[] add(a, b) } ENTRY main { p0 = f32[8] parameter(0) p1 = f32[8] parameter(1) ar0 = f32[8] all-reduce(p0), replica_groups={{0}}, to_apply=sum ar1 = f32[8] all-reduce(p1), replica_groups={}, to_apply=sum ROOT add = f32[8] add(ar0, ar1) } )"; TF_ASSERT_OK_AND_ASSIGN(auto module, RunPass(hlo_string, /*expect_change=*/false)); } TEST_F(AllReduceSimplifierTest, MismatchHasChannelId) { absl::string_view hlo_string = R"( HloModule m sum { a = f32[] parameter(0) b = f32[] parameter(1) ROOT add.2 = f32[] add(a, b) } ENTRY main { p0 = f32[8] parameter(0) p1 = f32[8] parameter(1) ar0 = f32[8] all-reduce(p0), replica_groups={}, channel_id=3, to_apply=sum ar1 = f32[8] all-reduce(p1), replica_groups={}, to_apply=sum ROOT add = f32[8] add(ar0, ar1) } )"; TF_ASSERT_OK_AND_ASSIGN(auto module, RunPass(hlo_string, /*expect_change=*/false)); } TEST_F(AllReduceSimplifierTest, MismatchUseGlobalDeviceId) { absl::string_view hlo_string = R"( HloModule m sum { a = f32[] parameter(0) b = f32[] parameter(1) ROOT add.2 = f32[] add(a, b) } ENTRY main { p0 = f32[8] parameter(0) p1 = f32[8] parameter(1) ar0 = f32[8] all-reduce(p0), replica_groups={{0, 1}}, channel_id=3, use_global_device_ids=true, to_apply=sum ar1 = f32[8] all-reduce(p1), replica_groups={{0, 1}}, channel_id=4, to_apply=sum ROOT add = f32[8] add(ar0, ar1) } )"; TF_ASSERT_OK_AND_ASSIGN(auto module, RunPass(hlo_string, /*expect_change=*/false)); } TEST_F(AllReduceSimplifierTest, NotSingleUser) { absl::string_view hlo_string = R"( HloModule m sum { a = f32[] parameter(0) b = f32[] parameter(1) ROOT add.2 = f32[] add(a, b) } ENTRY main { p0 = f32[8] parameter(0) p1 = f32[8] parameter(1) ar0 = f32[8] all-reduce(p0), replica_groups={}, to_apply=sum ar1 = f32[8] all-reduce(p1), replica_groups={}, to_apply=sum add = f32[8] add(ar0, ar1) ROOT t = (f32[8], f32[8]) tuple(ar0, add) } )"; TF_ASSERT_OK_AND_ASSIGN(auto module, RunPass(hlo_string, /*expect_change=*/false)); } } // namespace } // namespace xla
/* Copyright 2021 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/compiler/xla/service/all_reduce_reassociate.h" #include "tensorflow/compiler/xla/service/hlo_matchers.h" #include "tensorflow/compiler/xla/service/hlo_module.h" #include "tensorflow/compiler/xla/service/hlo_opcode.h" #include "tensorflow/compiler/xla/tests/hlo_test_base.h" namespace xla { namespace { namespace m = xla::testing::opcode_matchers; class AllReduceSimplifierTest : public HloTestBase { public: StatusOr<std::unique_ptr<HloModule>> RunPass(absl::string_view hlo_module, bool expect_change) { TF_ASSIGN_OR_RETURN(auto module, ParseAndReturnVerifiedModule(hlo_module)); auto changed = AllReduceReassociate().Run(module.get()); if (!changed.ok()) { return changed.status(); } EXPECT_EQ(changed.ValueOrDie(), expect_change); return StatusOr<std::unique_ptr<HloModule>>(std::move(module)); } size_t AllReduceCount(std::unique_ptr<HloModule>& module) { return absl::c_count_if(module->entry_computation()->instructions(), [](const HloInstruction* inst) { return inst->opcode() == HloOpcode::kAllReduce; }); } }; TEST_F(AllReduceSimplifierTest, Simple) { absl::string_view hlo_string = R"( HloModule m sum { a = f32[] parameter(0) b = f32[] parameter(1) ROOT add.2 = f32[] add(a, b) } ENTRY main { p0 = f32[8] parameter(0) p1 = f32[8] parameter(1) ar0 = f32[8] all-reduce(p0), replica_groups={}, to_apply=sum ar1 = f32[8] all-reduce(p1), replica_groups={}, to_apply=sum ROOT add = f32[8] add(ar0, ar1) } )"; TF_ASSERT_OK_AND_ASSIGN(auto module, RunPass(hlo_string, /*expect_change=*/true)); EXPECT_THAT(module->entry_computation()->root_instruction(), m::AllReduce(m::Add(m::Parameter(0), m::Parameter(1)))); EXPECT_EQ(AllReduceCount(module), 1); } TEST_F(AllReduceSimplifierTest, SimpleWithChannelId) { absl::string_view hlo_string = R"( HloModule m sum { a = f32[] parameter(0) b = f32[] parameter(1) ROOT add.2 = f32[] add(a, b) } ENTRY main { p0 = f32[8] parameter(0) p1 = f32[8] parameter(1) ar0 = f32[8] all-reduce(p0), channel_id=1, replica_groups={}, to_apply=sum ar1 = f32[8] all-reduce(p1), channel_id=1, replica_groups={}, to_apply=sum ROOT add = f32[8] add(ar0, ar1) } )"; TF_ASSERT_OK_AND_ASSIGN(auto module, RunPass(hlo_string, /*expect_change=*/true)); EXPECT_THAT(module->entry_computation()->root_instruction(), m::AllReduce(m::Add(m::Parameter(0), m::Parameter(1)))); EXPECT_EQ(AllReduceCount(module), 1); } // Checks whether a linear chain of adds of ARs is reassociated iin a single // pass. TEST_F(AllReduceSimplifierTest, SimpleChain) { absl::string_view hlo_string = R"( HloModule m sum { a = f32[] parameter(0) b = f32[] parameter(1) ROOT add.2 = f32[] add(a, b) } ENTRY main { p0 = f32[8] parameter(0) p1 = f32[8] parameter(1) p2 = f32[8] parameter(2) p3 = f32[8] parameter(3) ar0 = f32[8] all-reduce(p0), replica_groups={}, to_apply=sum ar1 = f32[8] all-reduce(p1), replica_groups={}, to_apply=sum ar2 = f32[8] all-reduce(p2), replica_groups={}, to_apply=sum ar3 = f32[8] all-reduce(p3), replica_groups={}, to_apply=sum add0 = f32[8] add(ar0, ar1) add1 = f32[8] add(add0, ar2) ROOT add2 = f32[8] add(add1, ar3) } )"; TF_ASSERT_OK_AND_ASSIGN(auto module, RunPass(hlo_string, /*expect_change=*/true)); EXPECT_THAT( module->entry_computation()->root_instruction(), m::AllReduce(m::Add( m::Add(m::Add(m::Parameter(0), m::Parameter(1)), m::Parameter(2)), m::Parameter(3)))); EXPECT_EQ(AllReduceCount(module), 1); } // Checks whether a tree of add of ARs is reassociated in a single pass. TEST_F(AllReduceSimplifierTest, SimpleTree) { absl::string_view hlo_string = R"( HloModule m sum { a = f32[] parameter(0) b = f32[] parameter(1) ROOT add.2 = f32[] add(a, b) } ENTRY main { p0 = f32[8] parameter(0) p1 = f32[8] parameter(1) p2 = f32[8] parameter(2) p3 = f32[8] parameter(3) ar0 = f32[8] all-reduce(p0), replica_groups={}, to_apply=sum ar1 = f32[8] all-reduce(p1), replica_groups={}, to_apply=sum ar2 = f32[8] all-reduce(p2), replica_groups={}, to_apply=sum ar3 = f32[8] all-reduce(p3), replica_groups={}, to_apply=sum add0 = f32[8] add(ar0, ar1) add1 = f32[8] add(ar2, ar3) ROOT add2 = f32[8] add(add0, add1) } )"; TF_ASSERT_OK_AND_ASSIGN(auto module, RunPass(hlo_string, /*expect_change=*/true)); EXPECT_THAT(module->entry_computation()->root_instruction(), m::AllReduce(m::Add(m::Add(m::Parameter(0), m::Parameter(1)), m::Add(m::Parameter(2), m::Parameter(3))))); EXPECT_EQ(AllReduceCount(module), 1); } TEST_F(AllReduceSimplifierTest, MismatchOp0) { absl::string_view hlo_string = R"( HloModule m sum { a = f32[] parameter(0) b = f32[] parameter(1) ROOT add.2 = f32[] add(a, b) } max { a = f32[] parameter(0) b = f32[] parameter(1) ROOT r = f32[] maximum(a, b) } ENTRY main { p0 = f32[8] parameter(0) p1 = f32[8] parameter(1) ar0 = f32[8] all-reduce(p0), replica_groups={}, to_apply=sum ar1 = f32[8] all-reduce(p1), replica_groups={}, to_apply=max ROOT add = f32[8] add(ar0, ar1) } )"; TF_ASSERT_OK_AND_ASSIGN(auto module, RunPass(hlo_string, /*expect_change=*/false)); } TEST_F(AllReduceSimplifierTest, MismatchOp1) { absl::string_view hlo_string = R"( HloModule m sum { a = f32[] parameter(0) b = f32[] parameter(1) ROOT add.2 = f32[] add(a, b) } max { a = f32[] parameter(0) b = f32[] parameter(1) ROOT r = f32[] maximum(a, b) } ENTRY main { p0 = f32[8] parameter(0) p1 = f32[8] parameter(1) ar0 = f32[8] all-reduce(p0), replica_groups={}, to_apply=max ar1 = f32[8] all-reduce(p1), replica_groups={}, to_apply=max ROOT add = f32[8] add(ar0, ar1) } )"; TF_ASSERT_OK_AND_ASSIGN(auto module, RunPass(hlo_string, /*expect_change=*/false)); } TEST_F(AllReduceSimplifierTest, MismatchReplicaGroups) { absl::string_view hlo_string = R"( HloModule m sum { a = f32[] parameter(0) b = f32[] parameter(1) ROOT add.2 = f32[] add(a, b) } ENTRY main { p0 = f32[8] parameter(0) p1 = f32[8] parameter(1) ar0 = f32[8] all-reduce(p0), replica_groups={{0}}, to_apply=sum ar1 = f32[8] all-reduce(p1), replica_groups={}, to_apply=sum ROOT add = f32[8] add(ar0, ar1) } )"; TF_ASSERT_OK_AND_ASSIGN(auto module, RunPass(hlo_string, /*expect_change=*/false)); } TEST_F(AllReduceSimplifierTest, MismatchHasChannelId) { absl::string_view hlo_string = R"( HloModule m sum { a = f32[] parameter(0) b = f32[] parameter(1) ROOT add.2 = f32[] add(a, b) } ENTRY main { p0 = f32[8] parameter(0) p1 = f32[8] parameter(1) ar0 = f32[8] all-reduce(p0), replica_groups={}, channel_id=3, to_apply=sum ar1 = f32[8] all-reduce(p1), replica_groups={}, to_apply=sum ROOT add = f32[8] add(ar0, ar1) } )"; TF_ASSERT_OK_AND_ASSIGN(auto module, RunPass(hlo_string, /*expect_change=*/false)); } TEST_F(AllReduceSimplifierTest, MismatchUseGlobalDeviceId) { absl::string_view hlo_string = R"( HloModule m sum { a = f32[] parameter(0) b = f32[] parameter(1) ROOT add.2 = f32[] add(a, b) } ENTRY main { p0 = f32[8] parameter(0) p1 = f32[8] parameter(1) ar0 = f32[8] all-reduce(p0), replica_groups={{0, 1}}, channel_id=3, use_global_device_ids=true, to_apply=sum ar1 = f32[8] all-reduce(p1), replica_groups={{0, 1}}, channel_id=4, to_apply=sum ROOT add = f32[8] add(ar0, ar1) } )"; TF_ASSERT_OK_AND_ASSIGN(auto module, RunPass(hlo_string, /*expect_change=*/false)); } TEST_F(AllReduceSimplifierTest, NotSingleUser) { absl::string_view hlo_string = R"( HloModule m sum { a = f32[] parameter(0) b = f32[] parameter(1) ROOT add.2 = f32[] add(a, b) } ENTRY main { p0 = f32[8] parameter(0) p1 = f32[8] parameter(1) ar0 = f32[8] all-reduce(p0), replica_groups={}, to_apply=sum ar1 = f32[8] all-reduce(p1), replica_groups={}, to_apply=sum add = f32[8] add(ar0, ar1) ROOT t = (f32[8], f32[8]) tuple(ar0, add) } )"; TF_ASSERT_OK_AND_ASSIGN(auto module, RunPass(hlo_string, /*expect_change=*/false)); } } // namespace } // namespace xla
Delete unused `pass`
[NFC] Delete unused `pass` PiperOrigin-RevId: 393383495 Change-Id: I5c956264d5c0909940bf97aabed01f53d38c2dd1
C++
apache-2.0
tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow-pywrap_saved_model,karllessard/tensorflow,Intel-Corporation/tensorflow,yongtang/tensorflow,gautam1858/tensorflow,karllessard/tensorflow,yongtang/tensorflow,paolodedios/tensorflow,paolodedios/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow-pywrap_saved_model,karllessard/tensorflow,Intel-tensorflow/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,karllessard/tensorflow,gautam1858/tensorflow,yongtang/tensorflow,paolodedios/tensorflow,gautam1858/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,Intel-tensorflow/tensorflow,tensorflow/tensorflow,tensorflow/tensorflow-pywrap_saved_model,karllessard/tensorflow,tensorflow/tensorflow-pywrap_saved_model,Intel-Corporation/tensorflow,karllessard/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow,paolodedios/tensorflow,Intel-Corporation/tensorflow,paolodedios/tensorflow,Intel-tensorflow/tensorflow,Intel-tensorflow/tensorflow,yongtang/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow-experimental_link_static_libraries_once,karllessard/tensorflow,yongtang/tensorflow,tensorflow/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,Intel-tensorflow/tensorflow,Intel-Corporation/tensorflow,Intel-tensorflow/tensorflow,Intel-tensorflow/tensorflow,yongtang/tensorflow,yongtang/tensorflow,karllessard/tensorflow,yongtang/tensorflow,Intel-Corporation/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow-pywrap_saved_model,karllessard/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,paolodedios/tensorflow,yongtang/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow-experimental_link_static_libraries_once,yongtang/tensorflow,gautam1858/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,yongtang/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow-pywrap_tf_optimizer,karllessard/tensorflow,tensorflow/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow,Intel-tensorflow/tensorflow,paolodedios/tensorflow,gautam1858/tensorflow,paolodedios/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,Intel-tensorflow/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,Intel-Corporation/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow,Intel-Corporation/tensorflow,tensorflow/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,Intel-Corporation/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,karllessard/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,gautam1858/tensorflow
5ca0a403f6f573dbbfd20a1807bf70f64c7c9ab6
tensorflow/compiler/xla/service/while_loop_constant_sinking.cc
tensorflow/compiler/xla/service/while_loop_constant_sinking.cc
/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/compiler/xla/service/while_loop_constant_sinking.h" #include "absl/algorithm/container.h" #include "absl/container/inlined_vector.h" #include "tensorflow/compiler/xla/service/while_util.h" #include "tensorflow/compiler/xla/util.h" namespace xla { // Replaces all uses of old_instr with new_instr except the use at // `while_body_root` (which must be a tuple instruction) at index `tuple_index`. // This utility helps us replace an instruction in the while body with a // constant while still keeping it trivially loop invariant. static Status ReplaceUsesWhileKeepingLoopInvariance( HloInstruction* old_instr, HloInstruction* new_instr, HloInstruction* while_body_root, int64 tuple_index) { CHECK_EQ(while_body_root->opcode(), HloOpcode::kTuple); std::vector<HloInstruction*> users; users.reserve(old_instr->user_count()); absl::c_copy(old_instr->users(), std::back_inserter(users)); for (auto* user : users) { for (int64 i = 0, e = user->operand_count(); i < e; i++) { if (user->operand(i) == old_instr && !(user == while_body_root && i == tuple_index)) { TF_RETURN_IF_ERROR(user->ReplaceOperandWith(i, new_instr)); } } } return Status::OK(); } StatusOr<bool> WhileLoopConstantSinking::TrySinkingConstantsIntoWhileLoop( HloInstruction* while_instr) { HloComputation* while_cond = while_instr->while_condition(); HloComputation* while_body = while_instr->while_body(); const HloInstruction& init_value = *while_instr->operand(0); if (init_value.opcode() != HloOpcode::kTuple) { return false; } bool changed = false; absl::flat_hash_map<int64, absl::InlinedVector<HloInstruction*, 1>> invariant_conditional_gte_index_to_inst = WhileUtil::GetGTEsMapForWhileConditional(*while_cond); std::vector<HloInstruction*> invariant_body_gtes = WhileUtil::GetInvariantGTEsForWhileBody(*while_body); for (HloInstruction* invariant_body_gte : invariant_body_gtes) { int64 index = invariant_body_gte->tuple_index(); const HloInstruction& invariant_value = *init_value.operand(index); // Original value should be a constant if (invariant_value.opcode() != HloOpcode::kConstant) { continue; } // Sink into the while_body // Should have at least one user that's not while_body_root. if (invariant_body_gte->user_count() > 1) { HloInstruction* constant_instr = while_body->AddInstruction(invariant_value.Clone(/*suffix=*/".sunk")); TF_RETURN_IF_ERROR(ReplaceUsesWhileKeepingLoopInvariance( invariant_body_gte, constant_instr, while_body->root_instruction(), index)); changed = true; } // Check if there is a corresponding GTE in while_conditional. absl::flat_hash_map<int64, absl::InlinedVector<HloInstruction*, 1>>::iterator it = invariant_conditional_gte_index_to_inst.find(index); if (it == invariant_conditional_gte_index_to_inst.end()) { continue; } for (HloInstruction* invariant_cond_gte : it->second) { // Should have at least one user. if (invariant_cond_gte->user_count() > 0) { HloInstruction* constant_instr = while_cond->AddInstruction( invariant_value.Clone(/*suffix=*/".sunk")); TF_RETURN_IF_ERROR( invariant_cond_gte->ReplaceAllUsesWith(constant_instr)); changed = true; } } } return changed; } StatusOr<bool> WhileLoopConstantSinking::Run(HloModule* module) { VLOG(2) << "HLO module before WhileLoopConstantSinking:"; XLA_VLOG_LINES(2, module->ToString()); bool changed = false; std::vector<HloInstruction*> while_instrs; for (auto* comp : module->MakeNonfusionComputations()) { // Right now we don't particulary care about optimizing while-of-while // patterns. If/When we do, we'll want to visit the outer while (while_0) // before we visit the inner while (while_1): // // while_1_body(state) { // val = gte(state, 0) // Loop invariant // use(val) // } // // while_0_body(state) { // val = gte(state, 0) // Loop invariant // while_1 = while(init=tuple(val, ...), body=while_1_body, ...) // ... // } // // main { // while_0 = while(init=(constant, ...), body=while_0_body, ...) // } // // This will let us sink the constant into the outer while first and then // into the inner while in a single run of this pass. absl::c_copy_if(comp->instructions(), std::back_inserter(while_instrs), [](const HloInstruction* instr) { return instr->opcode() == HloOpcode::kWhile; }); } for (HloInstruction* while_instr : while_instrs) { TF_ASSIGN_OR_RETURN(bool result, TrySinkingConstantsIntoWhileLoop(while_instr)); changed |= result; } if (changed) { VLOG(2) << "HLO module after WhileLoopConstantSinking:"; XLA_VLOG_LINES(2, module->ToString()); } else { VLOG(2) << "HLO module unchanged after WhileLoopConstantSinking"; } return changed; } } // namespace xla
/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/compiler/xla/service/while_loop_constant_sinking.h" #include "absl/algorithm/container.h" #include "absl/container/inlined_vector.h" #include "tensorflow/compiler/xla/service/while_util.h" #include "tensorflow/compiler/xla/util.h" namespace xla { // Replaces all uses of old_instr with new_instr except the use at // `while_body_root` (which must be a tuple instruction) at index `tuple_index`. // This utility helps us replace an instruction in the while body with a // constant while still keeping it trivially loop invariant. static Status ReplaceUsesWhileKeepingLoopInvariance( HloInstruction* old_instr, HloInstruction* new_instr, HloInstruction* while_body_root, int64 tuple_index) { CHECK_EQ(while_body_root->opcode(), HloOpcode::kTuple); std::vector<HloInstruction*> users; users.reserve(old_instr->user_count()); absl::c_copy(old_instr->users(), std::back_inserter(users)); for (auto* user : users) { for (int64 i = 0, e = user->operand_count(); i < e; i++) { if (user->operand(i) == old_instr && !(user == while_body_root && i == tuple_index)) { TF_RETURN_IF_ERROR(user->ReplaceOperandWith(i, new_instr)); } } } return Status::OK(); } StatusOr<bool> WhileLoopConstantSinking::TrySinkingConstantsIntoWhileLoop( HloInstruction* while_instr) { HloComputation* while_cond = while_instr->while_condition(); HloComputation* while_body = while_instr->while_body(); const HloInstruction& init_value = *while_instr->operand(0); if (init_value.opcode() != HloOpcode::kTuple) { return false; } bool changed = false; absl::flat_hash_map<int64, absl::InlinedVector<HloInstruction*, 1>> invariant_conditional_gte_index_to_inst = WhileUtil::GetGTEsMapForWhileConditional(*while_cond); std::vector<HloInstruction*> invariant_body_gtes = WhileUtil::GetInvariantGTEsForWhileBody(*while_body); for (HloInstruction* invariant_body_gte : invariant_body_gtes) { int64 index = invariant_body_gte->tuple_index(); const HloInstruction& invariant_value = *init_value.operand(index); // Original value should be a constant. if (invariant_value.opcode() != HloOpcode::kConstant) { continue; } // Sink into the while_body. // Should have at least one user that's not while_body_root. if (invariant_body_gte->user_count() > 1) { HloInstruction* constant_instr = while_body->AddInstruction(invariant_value.Clone(/*suffix=*/".sunk")); TF_RETURN_IF_ERROR(ReplaceUsesWhileKeepingLoopInvariance( invariant_body_gte, constant_instr, while_body->root_instruction(), index)); changed = true; } // Check if there is a corresponding GTE in while_conditional. absl::flat_hash_map<int64, absl::InlinedVector<HloInstruction*, 1>>::iterator it = invariant_conditional_gte_index_to_inst.find(index); if (it == invariant_conditional_gte_index_to_inst.end()) { continue; } for (HloInstruction* invariant_cond_gte : it->second) { // Should have at least one user. if (invariant_cond_gte->user_count() > 0) { HloInstruction* constant_instr = while_cond->AddInstruction( invariant_value.Clone(/*suffix=*/".sunk")); TF_RETURN_IF_ERROR( invariant_cond_gte->ReplaceAllUsesWith(constant_instr)); changed = true; } } } return changed; } StatusOr<bool> WhileLoopConstantSinking::Run(HloModule* module) { VLOG(2) << "HLO module before WhileLoopConstantSinking:"; XLA_VLOG_LINES(2, module->ToString()); bool changed = false; std::vector<HloInstruction*> while_instrs; for (auto* comp : module->MakeNonfusionComputations()) { // Right now we don't particulary care about optimizing while-of-while // patterns. If/When we do, we'll want to visit the outer while (while_0) // before we visit the inner while (while_1): // // while_1_body(state) { // val = gte(state, 0) // Loop invariant // use(val) // } // // while_0_body(state) { // val = gte(state, 0) // Loop invariant // while_1 = while(init=tuple(val, ...), body=while_1_body, ...) // ... // } // // main { // while_0 = while(init=(constant, ...), body=while_0_body, ...) // } // // This will let us sink the constant into the outer while first and then // into the inner while in a single run of this pass. absl::c_copy_if(comp->instructions(), std::back_inserter(while_instrs), [](const HloInstruction* instr) { return instr->opcode() == HloOpcode::kWhile; }); } for (HloInstruction* while_instr : while_instrs) { TF_ASSIGN_OR_RETURN(bool result, TrySinkingConstantsIntoWhileLoop(while_instr)); changed |= result; } if (changed) { VLOG(2) << "HLO module after WhileLoopConstantSinking:"; XLA_VLOG_LINES(2, module->ToString()); } else { VLOG(2) << "HLO module unchanged after WhileLoopConstantSinking"; } return changed; } } // namespace xla
Address review comments
Address review comments
C++
apache-2.0
Bismarrck/tensorflow,jendap/tensorflow,chemelnucfin/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow,DavidNorman/tensorflow,aldian/tensorflow,asimshankar/tensorflow,jbedorf/tensorflow,petewarden/tensorflow,ghchinoy/tensorflow,petewarden/tensorflow,renyi533/tensorflow,frreiss/tensorflow-fred,ppwwyyxx/tensorflow,jbedorf/tensorflow,ppwwyyxx/tensorflow,apark263/tensorflow,freedomtan/tensorflow,annarev/tensorflow,annarev/tensorflow,brchiu/tensorflow,kevin-coder/tensorflow-fork,annarev/tensorflow,renyi533/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,chemelnucfin/tensorflow,asimshankar/tensorflow,tensorflow/tensorflow-pywrap_saved_model,ageron/tensorflow,gunan/tensorflow,karllessard/tensorflow,frreiss/tensorflow-fred,sarvex/tensorflow,gautam1858/tensorflow,gunan/tensorflow,Intel-tensorflow/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow,jbedorf/tensorflow,aam-at/tensorflow,Bismarrck/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,xzturn/tensorflow,frreiss/tensorflow-fred,theflofly/tensorflow,asimshankar/tensorflow,adit-chandra/tensorflow,ppwwyyxx/tensorflow,yongtang/tensorflow,theflofly/tensorflow,hehongliang/tensorflow,kevin-coder/tensorflow-fork,ppwwyyxx/tensorflow,chemelnucfin/tensorflow,alsrgv/tensorflow,apark263/tensorflow,hfp/tensorflow-xsmm,aam-at/tensorflow,freedomtan/tensorflow,DavidNorman/tensorflow,apark263/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,hehongliang/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,karllessard/tensorflow,petewarden/tensorflow,brchiu/tensorflow,alsrgv/tensorflow,jbedorf/tensorflow,xzturn/tensorflow,Intel-Corporation/tensorflow,davidzchen/tensorflow,aam-at/tensorflow,brchiu/tensorflow,ageron/tensorflow,apark263/tensorflow,kevin-coder/tensorflow-fork,renyi533/tensorflow,DavidNorman/tensorflow,DavidNorman/tensorflow,ageron/tensorflow,petewarden/tensorflow,yongtang/tensorflow,petewarden/tensorflow,aldian/tensorflow,ppwwyyxx/tensorflow,ghchinoy/tensorflow,ghchinoy/tensorflow,aldian/tensorflow,Intel-Corporation/tensorflow,Intel-tensorflow/tensorflow,Intel-tensorflow/tensorflow,gunan/tensorflow,jendap/tensorflow,Intel-tensorflow/tensorflow,Intel-tensorflow/tensorflow,arborh/tensorflow,aam-at/tensorflow,kevin-coder/tensorflow-fork,apark263/tensorflow,jendap/tensorflow,yongtang/tensorflow,kevin-coder/tensorflow-fork,hfp/tensorflow-xsmm,hfp/tensorflow-xsmm,alsrgv/tensorflow,brchiu/tensorflow,asimshankar/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,gunan/tensorflow,DavidNorman/tensorflow,apark263/tensorflow,davidzchen/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,arborh/tensorflow,gautam1858/tensorflow,Bismarrck/tensorflow,cxxgtxy/tensorflow,chemelnucfin/tensorflow,davidzchen/tensorflow,gautam1858/tensorflow,freedomtan/tensorflow,ageron/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,davidzchen/tensorflow,jhseu/tensorflow,chemelnucfin/tensorflow,gautam1858/tensorflow,kevin-coder/tensorflow-fork,kevin-coder/tensorflow-fork,aldian/tensorflow,hfp/tensorflow-xsmm,gautam1858/tensorflow,adit-chandra/tensorflow,jbedorf/tensorflow,sarvex/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,arborh/tensorflow,alsrgv/tensorflow,ghchinoy/tensorflow,tensorflow/tensorflow-pywrap_saved_model,paolodedios/tensorflow,Bismarrck/tensorflow,tensorflow/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,apark263/tensorflow,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow,brchiu/tensorflow,kevin-coder/tensorflow-fork,sarvex/tensorflow,tensorflow/tensorflow-pywrap_saved_model,aam-at/tensorflow,ageron/tensorflow,paolodedios/tensorflow,alsrgv/tensorflow,jhseu/tensorflow,Intel-tensorflow/tensorflow,ppwwyyxx/tensorflow,Intel-tensorflow/tensorflow,chemelnucfin/tensorflow,freedomtan/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,hehongliang/tensorflow,jhseu/tensorflow,aldian/tensorflow,ppwwyyxx/tensorflow,karllessard/tensorflow,jhseu/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,hfp/tensorflow-xsmm,davidzchen/tensorflow,chemelnucfin/tensorflow,hehongliang/tensorflow,xzturn/tensorflow,DavidNorman/tensorflow,frreiss/tensorflow-fred,aldian/tensorflow,theflofly/tensorflow,frreiss/tensorflow-fred,tensorflow/tensorflow,xzturn/tensorflow,ageron/tensorflow,asimshankar/tensorflow,karllessard/tensorflow,asimshankar/tensorflow,adit-chandra/tensorflow,sarvex/tensorflow,alsrgv/tensorflow,ghchinoy/tensorflow,gautam1858/tensorflow,DavidNorman/tensorflow,cxxgtxy/tensorflow,yongtang/tensorflow,Bismarrck/tensorflow,jendap/tensorflow,tensorflow/tensorflow,DavidNorman/tensorflow,jendap/tensorflow,karllessard/tensorflow,karllessard/tensorflow,yongtang/tensorflow,ghchinoy/tensorflow,apark263/tensorflow,gunan/tensorflow,xzturn/tensorflow,renyi533/tensorflow,davidzchen/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,Intel-Corporation/tensorflow,gunan/tensorflow,hehongliang/tensorflow,aam-at/tensorflow,hfp/tensorflow-xsmm,cxxgtxy/tensorflow,renyi533/tensorflow,chemelnucfin/tensorflow,paolodedios/tensorflow,jbedorf/tensorflow,arborh/tensorflow,tensorflow/tensorflow,ppwwyyxx/tensorflow,karllessard/tensorflow,Bismarrck/tensorflow,arborh/tensorflow,Intel-Corporation/tensorflow,jhseu/tensorflow,jendap/tensorflow,yongtang/tensorflow,hfp/tensorflow-xsmm,jendap/tensorflow,brchiu/tensorflow,jhseu/tensorflow,jbedorf/tensorflow,Bismarrck/tensorflow,aam-at/tensorflow,theflofly/tensorflow,sarvex/tensorflow,DavidNorman/tensorflow,asimshankar/tensorflow,gautam1858/tensorflow,cxxgtxy/tensorflow,annarev/tensorflow,asimshankar/tensorflow,Intel-Corporation/tensorflow,frreiss/tensorflow-fred,tensorflow/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,petewarden/tensorflow,Intel-tensorflow/tensorflow,annarev/tensorflow,yongtang/tensorflow,Bismarrck/tensorflow,tensorflow/tensorflow-pywrap_saved_model,theflofly/tensorflow,karllessard/tensorflow,apark263/tensorflow,adit-chandra/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,yongtang/tensorflow,ageron/tensorflow,paolodedios/tensorflow,gautam1858/tensorflow,asimshankar/tensorflow,ppwwyyxx/tensorflow,theflofly/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,adit-chandra/tensorflow,karllessard/tensorflow,freedomtan/tensorflow,ghchinoy/tensorflow,arborh/tensorflow,adit-chandra/tensorflow,gautam1858/tensorflow,aldian/tensorflow,davidzchen/tensorflow,theflofly/tensorflow,xzturn/tensorflow,jhseu/tensorflow,hfp/tensorflow-xsmm,DavidNorman/tensorflow,davidzchen/tensorflow,tensorflow/tensorflow,jbedorf/tensorflow,jendap/tensorflow,ageron/tensorflow,frreiss/tensorflow-fred,jhseu/tensorflow,freedomtan/tensorflow,tensorflow/tensorflow-pywrap_saved_model,Intel-Corporation/tensorflow,paolodedios/tensorflow,davidzchen/tensorflow,karllessard/tensorflow,tensorflow/tensorflow-pywrap_saved_model,annarev/tensorflow,paolodedios/tensorflow,yongtang/tensorflow,theflofly/tensorflow,cxxgtxy/tensorflow,theflofly/tensorflow,arborh/tensorflow,xzturn/tensorflow,brchiu/tensorflow,aam-at/tensorflow,aam-at/tensorflow,renyi533/tensorflow,adit-chandra/tensorflow,theflofly/tensorflow,jbedorf/tensorflow,Intel-tensorflow/tensorflow,asimshankar/tensorflow,renyi533/tensorflow,brchiu/tensorflow,petewarden/tensorflow,renyi533/tensorflow,chemelnucfin/tensorflow,aam-at/tensorflow,apark263/tensorflow,apark263/tensorflow,jendap/tensorflow,paolodedios/tensorflow,jhseu/tensorflow,jendap/tensorflow,aldian/tensorflow,gunan/tensorflow,gunan/tensorflow,annarev/tensorflow,sarvex/tensorflow,annarev/tensorflow,jendap/tensorflow,xzturn/tensorflow,brchiu/tensorflow,hfp/tensorflow-xsmm,tensorflow/tensorflow-pywrap_saved_model,petewarden/tensorflow,ageron/tensorflow,annarev/tensorflow,annarev/tensorflow,hehongliang/tensorflow,brchiu/tensorflow,adit-chandra/tensorflow,tensorflow/tensorflow-pywrap_saved_model,jbedorf/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,alsrgv/tensorflow,aam-at/tensorflow,tensorflow/tensorflow-pywrap_saved_model,alsrgv/tensorflow,freedomtan/tensorflow,ppwwyyxx/tensorflow,arborh/tensorflow,renyi533/tensorflow,Bismarrck/tensorflow,yongtang/tensorflow,freedomtan/tensorflow,hehongliang/tensorflow,alsrgv/tensorflow,adit-chandra/tensorflow,brchiu/tensorflow,freedomtan/tensorflow,ppwwyyxx/tensorflow,hfp/tensorflow-xsmm,ghchinoy/tensorflow,adit-chandra/tensorflow,chemelnucfin/tensorflow,hfp/tensorflow-xsmm,petewarden/tensorflow,alsrgv/tensorflow,frreiss/tensorflow-fred,petewarden/tensorflow,ppwwyyxx/tensorflow,cxxgtxy/tensorflow,paolodedios/tensorflow,cxxgtxy/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,gautam1858/tensorflow,asimshankar/tensorflow,gunan/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,kevin-coder/tensorflow-fork,ghchinoy/tensorflow,xzturn/tensorflow,freedomtan/tensorflow,chemelnucfin/tensorflow,ageron/tensorflow,arborh/tensorflow,ghchinoy/tensorflow,annarev/tensorflow,renyi533/tensorflow,Intel-Corporation/tensorflow,davidzchen/tensorflow,sarvex/tensorflow,xzturn/tensorflow,jhseu/tensorflow,Bismarrck/tensorflow,gunan/tensorflow,ageron/tensorflow,theflofly/tensorflow,ghchinoy/tensorflow,alsrgv/tensorflow,DavidNorman/tensorflow,davidzchen/tensorflow,yongtang/tensorflow,theflofly/tensorflow,jbedorf/tensorflow,davidzchen/tensorflow,Intel-tensorflow/tensorflow,frreiss/tensorflow-fred,gautam1858/tensorflow,gautam1858/tensorflow,freedomtan/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,DavidNorman/tensorflow,cxxgtxy/tensorflow,adit-chandra/tensorflow,frreiss/tensorflow-fred,petewarden/tensorflow,jhseu/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,Intel-Corporation/tensorflow,adit-chandra/tensorflow,alsrgv/tensorflow,arborh/tensorflow,paolodedios/tensorflow,petewarden/tensorflow,karllessard/tensorflow,sarvex/tensorflow,gunan/tensorflow,xzturn/tensorflow,tensorflow/tensorflow,xzturn/tensorflow,aam-at/tensorflow,renyi533/tensorflow,tensorflow/tensorflow-pywrap_saved_model,kevin-coder/tensorflow-fork,jbedorf/tensorflow,paolodedios/tensorflow,arborh/tensorflow,renyi533/tensorflow,gunan/tensorflow,chemelnucfin/tensorflow,ageron/tensorflow,tensorflow/tensorflow,arborh/tensorflow,Bismarrck/tensorflow,frreiss/tensorflow-fred,freedomtan/tensorflow,ghchinoy/tensorflow,jhseu/tensorflow,kevin-coder/tensorflow-fork,frreiss/tensorflow-fred
6aea4b20a9383586a9bf9d845b2bb6580a2e8aed
external/vulkancts/modules/vulkan/api/vktApiDeviceDrmPropertiesTests.cpp
external/vulkancts/modules/vulkan/api/vktApiDeviceDrmPropertiesTests.cpp
/*------------------------------------------------------------------------- * Vulkan Conformance Tests * ------------------------ * * Copyright (c) 2021 NVIDIA, Inc. * Copyright (c) 2021 The Khronos Group Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *//*! * \file * \brief VK_EXT_device_drm_properties tests *//*--------------------------------------------------------------------*/ #include "vktApiDeviceDrmPropertiesTests.hpp" #include "vktTestGroupUtil.hpp" #include "vktTestCaseUtil.hpp" #include "deFilePath.hpp" #include "deDirectoryIterator.hpp" #include "deDynamicLibrary.hpp" #if DEQP_SUPPORT_DRM #include <sys/sysmacros.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <xf86drm.h> #endif using namespace vk; namespace vkt { namespace api { namespace { enum TestType { TEST_FILES_EXIST = 0, }; void checkSupport (Context& context, const TestType config) { DE_UNREF(config); context.requireDeviceFunctionality("VK_EXT_physical_device_drm"); } #if DEQP_SUPPORT_DRM class LibDrm : protected de::DynamicLibrary { static const char* libDrmFiles[]; typedef int (*PFNDRMGETDEVICES2PROC)(deUint32, drmDevicePtr[], int); typedef int (*PFNDRMGETDEVICESPROC)(drmDevicePtr[], int); typedef void (*PFNDRMFREEDEVICESPROC)(drmDevicePtr[], int); PFNDRMGETDEVICES2PROC pGetDevices2; PFNDRMGETDEVICESPROC pGetDevices; PFNDRMFREEDEVICESPROC pFreeDevices; int intGetDevices(drmDevicePtr devices[], int maxDevices) const { if (pGetDevices2) return pGetDevices2(0, devices, maxDevices); else return pGetDevices(devices, maxDevices); } public: LibDrm() : DynamicLibrary(libDrmFiles) { pGetDevices2 = (PFNDRMGETDEVICES2PROC)getFunction("drmGetDevices2"); pGetDevices = (PFNDRMGETDEVICESPROC)getFunction("drmGetDevices"); pFreeDevices = (PFNDRMFREEDEVICESPROC)getFunction("drmFreeDevices"); if (!pGetDevices2 && !pGetDevices) TCU_FAIL("Could not load a valid drmGetDevices() variant from libdrm"); if (!pFreeDevices) TCU_FAIL("Could not load drmFreeDevices() from libdrm"); } drmDevicePtr *getDevices(int *pNumDevices) const { *pNumDevices = intGetDevices(DE_NULL, 0); if (*pNumDevices < 0) TCU_FAIL("Failed to query number of DRM devices in system"); if (*pNumDevices == 0) return DE_NULL; drmDevicePtr *devs = new drmDevicePtr[*pNumDevices]; *pNumDevices = intGetDevices(devs, *pNumDevices); if (*pNumDevices < 0) { delete[] devs; TCU_FAIL("Failed to query list of DRM devices in system"); } return devs; } void freeDevices(drmDevicePtr *devices, int count) const { pFreeDevices(devices, count); delete[] devices; } ~LibDrm() { } }; const char* LibDrm::libDrmFiles[] = { "libdrm.so.2", "libdrm.so", DE_NULL }; #endif // DEQP_SUPPORT_DRM void testFilesExist (const VkPhysicalDeviceDrmPropertiesEXT& deviceDrmProperties) { bool primaryFound = !deviceDrmProperties.hasPrimary; bool renderFound = !deviceDrmProperties.hasRender; #if DEQP_SUPPORT_DRM static const LibDrm libDrm; int numDrmDevices; drmDevicePtr* drmDevices = libDrm.getDevices(&numDrmDevices); for (int i = 0; i < numDrmDevices; i++) { for (int j = 0; j < DRM_NODE_MAX; j++) { if (!(drmDevices[i]->available_nodes & (1 << j))) continue; struct stat statBuf; deMemset(&statBuf, 0, sizeof(statBuf)); int res = stat(drmDevices[i]->nodes[j], &statBuf); if (res || !(statBuf.st_mode & S_IFCHR)) continue; if (deviceDrmProperties.primaryMajor == major(statBuf.st_rdev) && deviceDrmProperties.primaryMinor == minor(statBuf.st_rdev)) { primaryFound = true; continue; } if (deviceDrmProperties.renderMajor == major(statBuf.st_rdev) && deviceDrmProperties.renderMinor == minor(statBuf.st_rdev)) { renderFound = true; continue; } } } libDrm.freeDevices(drmDevices, numDrmDevices); #endif // DEQP_SUPPORT_DRM if (!primaryFound) TCU_FAIL("DRM primary device file not found"); if (!renderFound) TCU_FAIL("DRM render device file not found"); } static tcu::TestStatus testDeviceDrmProperties (Context& context, const TestType testType) { const VkPhysicalDevice physDevice = context.getPhysicalDevice(); VkPhysicalDeviceProperties2 deviceProperties2; const int memsetPattern = 0xaa; VkPhysicalDeviceDrmPropertiesEXT deviceDrmProperties; deMemset(&deviceDrmProperties, 0, sizeof(deviceDrmProperties)); deviceDrmProperties.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRM_PROPERTIES_EXT; deviceDrmProperties.pNext = DE_NULL; deMemset(&deviceProperties2, memsetPattern, sizeof(deviceProperties2)); deviceProperties2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2; deviceProperties2.pNext = &deviceDrmProperties; context.getInstanceInterface().getPhysicalDeviceProperties2(physDevice, &deviceProperties2); switch (testType) { case TEST_FILES_EXIST: testFilesExist (deviceDrmProperties); break; default: TCU_THROW(InternalError, "Unknown test type specified"); } return tcu::TestStatus::pass("Pass"); } static void createTestCases (tcu::TestCaseGroup* group) { addFunctionCase(group, "drm_files_exist", "Verify device files for major/minor nodes exist", checkSupport, testDeviceDrmProperties, TEST_FILES_EXIST); } } // anonymous tcu::TestCaseGroup* createDeviceDrmPropertiesTests(tcu::TestContext& testCtx) { return createTestGroup(testCtx, "device_drm_properties", "VK_EXT_device_drm_properties tests", createTestCases); } } // api } // vkt
/*------------------------------------------------------------------------- * Vulkan Conformance Tests * ------------------------ * * Copyright (c) 2021 NVIDIA, Inc. * Copyright (c) 2021 The Khronos Group Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *//*! * \file * \brief VK_EXT_device_drm_properties tests *//*--------------------------------------------------------------------*/ #include "vktApiDeviceDrmPropertiesTests.hpp" #include "vktTestGroupUtil.hpp" #include "vktTestCaseUtil.hpp" #include "deFilePath.hpp" #include "deDirectoryIterator.hpp" #include "deDynamicLibrary.hpp" #if DEQP_SUPPORT_DRM #if !defined(__FreeBSD__) // major() and minor() are defined in sys/types.h on FreeBSD, and in // sys/sysmacros.h on Linux and Solaris. #include <sys/sysmacros.h> #endif // !defined(__FreeBSD__) #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <xf86drm.h> #endif // DEQP_SUPPORT_DRM using namespace vk; namespace vkt { namespace api { namespace { enum TestType { TEST_FILES_EXIST = 0, }; void checkSupport (Context& context, const TestType config) { DE_UNREF(config); context.requireDeviceFunctionality("VK_EXT_physical_device_drm"); } #if DEQP_SUPPORT_DRM class LibDrm : protected de::DynamicLibrary { static const char* libDrmFiles[]; typedef int (*PFNDRMGETDEVICES2PROC)(deUint32, drmDevicePtr[], int); typedef int (*PFNDRMGETDEVICESPROC)(drmDevicePtr[], int); typedef void (*PFNDRMFREEDEVICESPROC)(drmDevicePtr[], int); PFNDRMGETDEVICES2PROC pGetDevices2; PFNDRMGETDEVICESPROC pGetDevices; PFNDRMFREEDEVICESPROC pFreeDevices; int intGetDevices(drmDevicePtr devices[], int maxDevices) const { if (pGetDevices2) return pGetDevices2(0, devices, maxDevices); else return pGetDevices(devices, maxDevices); } public: LibDrm() : DynamicLibrary(libDrmFiles) { pGetDevices2 = (PFNDRMGETDEVICES2PROC)getFunction("drmGetDevices2"); pGetDevices = (PFNDRMGETDEVICESPROC)getFunction("drmGetDevices"); pFreeDevices = (PFNDRMFREEDEVICESPROC)getFunction("drmFreeDevices"); if (!pGetDevices2 && !pGetDevices) TCU_FAIL("Could not load a valid drmGetDevices() variant from libdrm"); if (!pFreeDevices) TCU_FAIL("Could not load drmFreeDevices() from libdrm"); } drmDevicePtr *getDevices(int *pNumDevices) const { *pNumDevices = intGetDevices(DE_NULL, 0); if (*pNumDevices < 0) TCU_FAIL("Failed to query number of DRM devices in system"); if (*pNumDevices == 0) return DE_NULL; drmDevicePtr *devs = new drmDevicePtr[*pNumDevices]; *pNumDevices = intGetDevices(devs, *pNumDevices); if (*pNumDevices < 0) { delete[] devs; TCU_FAIL("Failed to query list of DRM devices in system"); } return devs; } void freeDevices(drmDevicePtr *devices, int count) const { pFreeDevices(devices, count); delete[] devices; } ~LibDrm() { } }; const char* LibDrm::libDrmFiles[] = { "libdrm.so.2", "libdrm.so", DE_NULL }; #endif // DEQP_SUPPORT_DRM void testFilesExist (const VkPhysicalDeviceDrmPropertiesEXT& deviceDrmProperties) { bool primaryFound = !deviceDrmProperties.hasPrimary; bool renderFound = !deviceDrmProperties.hasRender; #if DEQP_SUPPORT_DRM static const LibDrm libDrm; int numDrmDevices; drmDevicePtr* drmDevices = libDrm.getDevices(&numDrmDevices); for (int i = 0; i < numDrmDevices; i++) { for (int j = 0; j < DRM_NODE_MAX; j++) { if (!(drmDevices[i]->available_nodes & (1 << j))) continue; struct stat statBuf; deMemset(&statBuf, 0, sizeof(statBuf)); int res = stat(drmDevices[i]->nodes[j], &statBuf); if (res || !(statBuf.st_mode & S_IFCHR)) continue; if (deviceDrmProperties.primaryMajor == major(statBuf.st_rdev) && deviceDrmProperties.primaryMinor == minor(statBuf.st_rdev)) { primaryFound = true; continue; } if (deviceDrmProperties.renderMajor == major(statBuf.st_rdev) && deviceDrmProperties.renderMinor == minor(statBuf.st_rdev)) { renderFound = true; continue; } } } libDrm.freeDevices(drmDevices, numDrmDevices); #endif // DEQP_SUPPORT_DRM if (!primaryFound) TCU_FAIL("DRM primary device file not found"); if (!renderFound) TCU_FAIL("DRM render device file not found"); } static tcu::TestStatus testDeviceDrmProperties (Context& context, const TestType testType) { const VkPhysicalDevice physDevice = context.getPhysicalDevice(); VkPhysicalDeviceProperties2 deviceProperties2; const int memsetPattern = 0xaa; VkPhysicalDeviceDrmPropertiesEXT deviceDrmProperties; deMemset(&deviceDrmProperties, 0, sizeof(deviceDrmProperties)); deviceDrmProperties.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRM_PROPERTIES_EXT; deviceDrmProperties.pNext = DE_NULL; deMemset(&deviceProperties2, memsetPattern, sizeof(deviceProperties2)); deviceProperties2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2; deviceProperties2.pNext = &deviceDrmProperties; context.getInstanceInterface().getPhysicalDeviceProperties2(physDevice, &deviceProperties2); switch (testType) { case TEST_FILES_EXIST: testFilesExist (deviceDrmProperties); break; default: TCU_THROW(InternalError, "Unknown test type specified"); } return tcu::TestStatus::pass("Pass"); } static void createTestCases (tcu::TestCaseGroup* group) { addFunctionCase(group, "drm_files_exist", "Verify device files for major/minor nodes exist", checkSupport, testDeviceDrmProperties, TEST_FILES_EXIST); } } // anonymous tcu::TestCaseGroup* createDeviceDrmPropertiesTests(tcu::TestContext& testCtx) { return createTestGroup(testCtx, "device_drm_properties", "VK_EXT_device_drm_properties tests", createTestCases); } } // api } // vkt
Fix FreeBSD build of VK_EXT_physical_device_drm tests
Fix FreeBSD build of VK_EXT_physical_device_drm tests Linux defines the major() and minor() macros in the sys/sysmacros.h header, but FreeBSD does not have this header and instead defines them in sys/types.h. Components: Vulkan Affects: dEQP-VK.api.device_drm_properties.* Change-Id: I0bed149d24241e152437f530f5eb137738c46122
C++
apache-2.0
KhronosGroup/Vulkan-CTS,KhronosGroup/Vulkan-CTS,KhronosGroup/Vulkan-CTS,KhronosGroup/Vulkan-CTS,KhronosGroup/VK-GL-CTS,KhronosGroup/VK-GL-CTS,KhronosGroup/VK-GL-CTS,KhronosGroup/VK-GL-CTS,KhronosGroup/Vulkan-CTS,KhronosGroup/VK-GL-CTS,KhronosGroup/VK-GL-CTS,KhronosGroup/Vulkan-CTS
bf269d67b3d1e8d88797022e4ea542f34c06df47
paddle/platform/place.cc
paddle/platform/place.cc
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve. 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 "paddle/platform/place.h" namespace paddle { namespace platform { namespace detail { class PlacePrinter : public boost::static_visitor<> { public: explicit PlacePrinter(std::ostream &os) : os_(os) {} void operator()(const CPUPlace &) { os_ << "CPUPlace"; } void operator()(const MKLDNNPlace &) { os_ << "MKLDNNPlace"; } void operator()(const GPUPlace &p) { os_ << "GPUPlace(" << p.device << ")"; } private: std::ostream &os_; }; } // namespace detail static Place the_default_place; void set_place(const Place &place) { the_default_place = place; } const Place &get_place() { return the_default_place; } const GPUPlace default_gpu() { return GPUPlace(0); } const CPUPlace default_cpu() { return CPUPlace(); } const MKLDNNPlace default_mkldnn() { return MKLDNNPlace(); } bool is_gpu_place(const Place &p) { return boost::apply_visitor(IsGPUPlace(), p); } bool is_cpu_place(const Place &p) { return !boost::apply_visitor(IsGPUPlace(), p); } bool is_mkldnn_place(const Place &p) { return boost::apply_visitor(IsMKLDNNPlace(), p); } bool places_are_same_class(const Place &p1, const Place &p2) { return p1.which() == p2.which(); } std::ostream &operator<<(std::ostream &os, const Place &p) { detail::PlacePrinter printer(os); boost::apply_visitor(printer, p); return os; } } // namespace platform } // namespace paddle
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve. 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 "paddle/platform/place.h" namespace paddle { namespace platform { namespace detail { class PlacePrinter : public boost::static_visitor<> { public: explicit PlacePrinter(std::ostream &os) : os_(os) {} void operator()(const CPUPlace &) { os_ << "CPUPlace"; } void operator()(const MKLDNNPlace &) { os_ << "MKLDNNPlace"; } void operator()(const GPUPlace &p) { os_ << "GPUPlace(" << p.device << ")"; } private: std::ostream &os_; }; } // namespace detail static Place the_default_place; void set_place(const Place &place) { the_default_place = place; } const Place &get_place() { return the_default_place; } const GPUPlace default_gpu() { return GPUPlace(0); } const CPUPlace default_cpu() { return CPUPlace(); } const MKLDNNPlace default_mkldnn() { return MKLDNNPlace(); } bool is_gpu_place(const Place &p) { return boost::apply_visitor(IsGPUPlace(), p); } bool is_cpu_place(const Place &p) { return !is_gpu_place(p) && !is_mkldnn_place(p); } bool is_mkldnn_place(const Place &p) { return boost::apply_visitor(IsMKLDNNPlace(), p); } bool places_are_same_class(const Place &p1, const Place &p2) { return p1.which() == p2.which(); } std::ostream &operator<<(std::ostream &os, const Place &p) { detail::PlacePrinter printer(os); boost::apply_visitor(printer, p); return os; } } // namespace platform } // namespace paddle
fix place_test on MKLDNNPlace
fix place_test on MKLDNNPlace
C++
apache-2.0
Canpio/Paddle,PaddlePaddle/Paddle,putcn/Paddle,jacquesqiao/Paddle,Canpio/Paddle,pkuyym/Paddle,jacquesqiao/Paddle,putcn/Paddle,PaddlePaddle/Paddle,QiJune/Paddle,jacquesqiao/Paddle,pkuyym/Paddle,chengduoZH/Paddle,pkuyym/Paddle,putcn/Paddle,reyoung/Paddle,tensor-tang/Paddle,pkuyym/Paddle,reyoung/Paddle,lcy-seso/Paddle,QiJune/Paddle,chengduoZH/Paddle,QiJune/Paddle,Canpio/Paddle,chengduoZH/Paddle,luotao1/Paddle,jacquesqiao/Paddle,PaddlePaddle/Paddle,baidu/Paddle,lcy-seso/Paddle,luotao1/Paddle,PaddlePaddle/Paddle,baidu/Paddle,reyoung/Paddle,lcy-seso/Paddle,luotao1/Paddle,Canpio/Paddle,jacquesqiao/Paddle,Canpio/Paddle,chengduoZH/Paddle,lcy-seso/Paddle,pkuyym/Paddle,baidu/Paddle,tensor-tang/Paddle,luotao1/Paddle,reyoung/Paddle,tensor-tang/Paddle,PaddlePaddle/Paddle,QiJune/Paddle,lcy-seso/Paddle,Canpio/Paddle,reyoung/Paddle,putcn/Paddle,luotao1/Paddle,Canpio/Paddle,putcn/Paddle,baidu/Paddle,luotao1/Paddle,putcn/Paddle,tensor-tang/Paddle,jacquesqiao/Paddle,tensor-tang/Paddle,baidu/Paddle,chengduoZH/Paddle,QiJune/Paddle,QiJune/Paddle,Canpio/Paddle,lcy-seso/Paddle,PaddlePaddle/Paddle,reyoung/Paddle,pkuyym/Paddle,PaddlePaddle/Paddle,luotao1/Paddle
f0367a8826080fda393e313e58894130c6909b8a
slideshow/source/engine/animationnodes/animationcommandnode.cxx
slideshow/source/engine/animationnodes/animationcommandnode.cxx
/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: animationcommandnode.cxx,v $ * $Revision: 1.9.18.1 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_slideshow.hxx" // must be first #include <canvas/debug.hxx> #include <canvas/verbosetrace.hxx> #include <com/sun/star/presentation/EffectCommands.hpp> #include <com/sun/star/animations/XAnimate.hpp> #include <com/sun/star/beans/PropertyValue.hpp> #include "animationcommandnode.hxx" #include "delayevent.hxx" #include "tools.hxx" #include "nodetools.hxx" #include <boost/bind.hpp> using namespace com::sun::star; namespace slideshow { namespace internal { namespace EffectCommands = com::sun::star::presentation::EffectCommands; AnimationCommandNode::AnimationCommandNode( uno::Reference<animations::XAnimationNode> const& xNode, ::boost::shared_ptr<BaseContainerNode> const& pParent, NodeContext const& rContext ) : BaseNode( xNode, pParent, rContext ), mpShape(), mxCommandNode( xNode, ::com::sun::star::uno::UNO_QUERY_THROW ) { uno::Reference< drawing::XShape > xShape( mxCommandNode->getTarget(), uno::UNO_QUERY ); ShapeSharedPtr pShape( getContext().mpSubsettableShapeManager->lookupShape( xShape ) ); mpShape = ::boost::dynamic_pointer_cast< ExternalMediaShape >( pShape ); } void AnimationCommandNode::dispose() { mxCommandNode.clear(); mpShape.reset(); BaseNode::dispose(); } void AnimationCommandNode::activate_st() { switch( mxCommandNode->getCommand() ) { // the command is user defined case EffectCommands::CUSTOM: break; // the command is an ole verb. case EffectCommands::VERB: break; // the command starts playing on a media object case EffectCommands::PLAY: { double fMediaTime=0.0; beans::PropertyValue aMediaTime; if( (mxCommandNode->getParameter() >>= aMediaTime) && aMediaTime.Name.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM("MediaTime") )) { aMediaTime.Value >>= fMediaTime; } if( mpShape ) { mpShape->setMediaTime(fMediaTime/1000.0); mpShape->play(); } break; } // the command toggles the pause status on a media object case EffectCommands::TOGGLEPAUSE: { if( mpShape ) if( mpShape->isPlaying() ) mpShape->pause(); else mpShape->play(); break; } // the command stops the animation on a media object case EffectCommands::STOP: { if( mpShape ) mpShape->stop(); break; } // the command stops all currently running sound effects case EffectCommands::STOPAUDIO: getContext().mrEventMultiplexer.notifyCommandStopAudio( getSelf() ); break; } // deactivate ASAP: scheduleDeactivationEvent( makeEvent( boost::bind( &AnimationNode::deactivate, getSelf() ) ) ); } bool AnimationCommandNode::hasPendingAnimation() const { return mxCommandNode->getCommand() == EffectCommands::STOPAUDIO || mpShape; } } // namespace internal } // namespace slideshow
/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: animationcommandnode.cxx,v $ * $Revision: 1.9.18.1 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_slideshow.hxx" // must be first #include <canvas/debug.hxx> #include <canvas/verbosetrace.hxx> #include <com/sun/star/presentation/EffectCommands.hpp> #include <com/sun/star/animations/XAnimate.hpp> #include <com/sun/star/beans/PropertyValue.hpp> #include "animationcommandnode.hxx" #include "delayevent.hxx" #include "tools.hxx" #include "nodetools.hxx" #include <boost/bind.hpp> using namespace com::sun::star; namespace slideshow { namespace internal { namespace EffectCommands = com::sun::star::presentation::EffectCommands; AnimationCommandNode::AnimationCommandNode( uno::Reference<animations::XAnimationNode> const& xNode, ::boost::shared_ptr<BaseContainerNode> const& pParent, NodeContext const& rContext ) : BaseNode( xNode, pParent, rContext ), mpShape(), mxCommandNode( xNode, ::com::sun::star::uno::UNO_QUERY_THROW ) { uno::Reference< drawing::XShape > xShape( mxCommandNode->getTarget(), uno::UNO_QUERY ); ShapeSharedPtr pShape( getContext().mpSubsettableShapeManager->lookupShape( xShape ) ); mpShape = ::boost::dynamic_pointer_cast< ExternalMediaShape >( pShape ); } void AnimationCommandNode::dispose() { mxCommandNode.clear(); mpShape.reset(); BaseNode::dispose(); } void AnimationCommandNode::activate_st() { switch( mxCommandNode->getCommand() ) { // the command is user defined case EffectCommands::CUSTOM: break; // the command is an ole verb. case EffectCommands::VERB: break; // the command starts playing on a media object case EffectCommands::PLAY: { double fMediaTime=0.0; beans::PropertyValue aMediaTime; if( (mxCommandNode->getParameter() >>= aMediaTime) && aMediaTime.Name.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM("MediaTime") )) { aMediaTime.Value >>= fMediaTime; } if( mpShape ) { mpShape->setMediaTime(fMediaTime/1000.0); mpShape->play(); } break; } // the command toggles the pause status on a media object case EffectCommands::TOGGLEPAUSE: { if( mpShape ) { if( mpShape->isPlaying() ) mpShape->pause(); else mpShape->play(); } break; } // the command stops the animation on a media object case EffectCommands::STOP: { if( mpShape ) mpShape->stop(); break; } // the command stops all currently running sound effects case EffectCommands::STOPAUDIO: getContext().mrEventMultiplexer.notifyCommandStopAudio( getSelf() ); break; } // deactivate ASAP: scheduleDeactivationEvent( makeEvent( boost::bind( &AnimationNode::deactivate, getSelf() ) ) ); } bool AnimationCommandNode::hasPendingAnimation() const { return mxCommandNode->getCommand() == EffectCommands::STOPAUDIO || mpShape; } } // namespace internal } // namespace slideshow
integrate CWS cmcfixes54 2009-02-19 17:39:12 +0100 cmc r268301 : revert meant-to-be local-only changes in configure 2009-02-19 17:33:52 +0100 cmc r268300 : revert meant-to-be local-only change in readlicense_oo 2009-02-19 17:31:48 +0100 cmc r268299 : remove config_office dir from workspace, hopefully this doesn't screw things up 2009-02-05 17:38:47 +0100 cmc r267431 : #i98367# snprintf needs stdio.h on gcc4.4 2009-01-27 10:51:54 +0100 cmc r266964 : CWS-TOOLING: rebase CWS cmcfixes54 to trunk@266944 (milestone: DEV300:m40) 2009-01-23 10:05:33 +0100 cmc r266774 : #i98389# fix t602 filter warnings 2009-01-22 16:37:57 +0100 cmc r266740 : #i98367# revert limits.h as its going in elsewhere 2009-01-22 16:36:45 +0100 cmc r266739 : #i98367# remove easy warnings 2009-01-22 16:31:49 +0100 cmc r266738 : #i98366# merge in basic fix of #i96087# to bf_basic 2009-01-22 14:50:24 +0100 cmc r266716 : #i98288# some versions of neon report DAV:Collection instead of Collection
CWS-TOOLING: integrate CWS cmcfixes54 2009-02-19 17:39:12 +0100 cmc r268301 : revert meant-to-be local-only changes in configure 2009-02-19 17:33:52 +0100 cmc r268300 : revert meant-to-be local-only change in readlicense_oo 2009-02-19 17:31:48 +0100 cmc r268299 : remove config_office dir from workspace, hopefully this doesn't screw things up 2009-02-05 17:38:47 +0100 cmc r267431 : #i98367# snprintf needs stdio.h on gcc4.4 2009-01-27 10:51:54 +0100 cmc r266964 : CWS-TOOLING: rebase CWS cmcfixes54 to trunk@266944 (milestone: DEV300:m40) 2009-01-23 10:05:33 +0100 cmc r266774 : #i98389# fix t602 filter warnings 2009-01-22 16:37:57 +0100 cmc r266740 : #i98367# revert limits.h as its going in elsewhere 2009-01-22 16:36:45 +0100 cmc r266739 : #i98367# remove easy warnings 2009-01-22 16:31:49 +0100 cmc r266738 : #i98366# merge in basic fix of #i96087# to bf_basic 2009-01-22 14:50:24 +0100 cmc r266716 : #i98288# some versions of neon report DAV:Collection instead of Collection
C++
mpl-2.0
JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core
4a8d62eb9b4bd523fefc5c6ab3bb3195f07d7df2
source/Plugins/ExpressionParser/Swift/SwiftREPLMaterializer.cpp
source/Plugins/ExpressionParser/Swift/SwiftREPLMaterializer.cpp
//===-- SwiftREPLMaterializer.cpp -------------------------------*- C++ -*-===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #include "SwiftREPLMaterializer.h" #include "SwiftASTManipulator.h" #include "lldb/Core/Log.h" #include "lldb/Core/ValueObjectConstResult.h" #include "lldb/Expression/IRExecutionUnit.h" #include "lldb/Expression/IRMemoryMap.h" #include "lldb/Target/Target.h" #include "swift/Demangling/Demangle.h" using namespace lldb_private; class EntityREPLResultVariable : public Materializer::Entity { public: EntityREPLResultVariable(const CompilerType &type, swift::ValueDecl *swift_decl, SwiftREPLMaterializer *parent, Materializer::PersistentVariableDelegate *delegate) : Entity(), m_type(type), m_parent(parent), m_swift_decl(swift_decl), m_temporary_allocation(LLDB_INVALID_ADDRESS), m_temporary_allocation_size(0), m_delegate(delegate) { // Hard-coding to maximum size of a pointer since all results are // materialized by reference m_size = 8; m_alignment = 8; } void Materialize(lldb::StackFrameSP &frame_sp, IRMemoryMap &map, lldb::addr_t process_address, Error &err) { // no action required } void MakeREPLResult(IRExecutionUnit &execution_unit, Error &err, const IRExecutionUnit::JittedGlobalVariable *variable) { err.Clear(); ExecutionContextScope *exe_scope = execution_unit.GetBestExecutionContextScope(); if (!exe_scope) { err.SetErrorString("Couldn't dematerialize a result variable: invalid " "execution context scope"); return; } lldb::TargetSP target_sp = exe_scope->CalculateTarget(); if (!target_sp) { err.SetErrorString("Couldn't dematerialize a result variable: no target"); return; } lldb::LanguageType lang = (m_type.GetMinimumLanguage() == lldb::eLanguageTypeSwift) ? lldb::eLanguageTypeSwift : lldb::eLanguageTypeObjC_plus_plus; PersistentExpressionState *persistent_state = target_sp->GetPersistentExpressionStateForLanguage(lang); if (!persistent_state) { err.SetErrorString("Couldn't dematerialize a result variable: language " "doesn't have persistent state"); } ConstString name = m_delegate ? m_delegate->GetName() : persistent_state->GetNextPersistentVariableName(false); lldb::ExpressionVariableSP ret; ret = persistent_state ->CreatePersistentVariable(exe_scope, name, m_type, execution_unit.GetByteOrder(), execution_unit.GetAddressByteSize()) ->shared_from_this(); if (!ret) { err.SetErrorStringWithFormat("couldn't dematerialize a result variable: " "failed to make persistent variable %s", name.AsCString()); return; } lldb::ProcessSP process_sp = execution_unit.GetBestExecutionContextScope()->CalculateProcess(); ret->m_live_sp = ValueObjectConstResult::Create( exe_scope, m_type, name, variable ? variable->m_remote_addr : LLDB_INVALID_ADDRESS, eAddressTypeLoad, execution_unit.GetAddressByteSize()); ret->ValueUpdated(); if (variable) { const size_t pvar_byte_size = ret->GetByteSize(); uint8_t *pvar_data = ret->GetValueBytes(); Error read_error; execution_unit.ReadMemory(pvar_data, variable->m_remote_addr, pvar_byte_size, read_error); if (!read_error.Success()) { err.SetErrorString("Couldn't dematerialize a result variable: couldn't " "read its memory"); return; } } if (m_delegate) { m_delegate->DidDematerialize(ret); } // Register the variable with the persistent decls under the assumed, // just-generated name so it can be reused. if (m_swift_decl) { llvm::cast<SwiftPersistentExpressionState>(persistent_state) ->RegisterSwiftPersistentDeclAlias(m_swift_decl, name); } return; } void Dematerialize(lldb::StackFrameSP &frame_sp, IRMemoryMap &map, lldb::addr_t process_address, lldb::addr_t frame_top, lldb::addr_t frame_bottom, Error &err) { IRExecutionUnit *execution_unit = llvm::cast<SwiftREPLMaterializer>(m_parent)->GetExecutionUnit(); if (!execution_unit) { return; } for (const IRExecutionUnit::JittedGlobalVariable &variable : execution_unit->GetJittedGlobalVariables()) { if (strstr(variable.m_name.GetCString(), SwiftASTManipulator::GetResultName())) { MakeREPLResult(*execution_unit, err, &variable); return; } } if (SwiftASTContext::IsPossibleZeroSizeType(m_type)) { MakeREPLResult(*execution_unit, err, nullptr); return; } err.SetErrorToGenericError(); err.SetErrorStringWithFormat( "Couldn't dematerialize result: corresponding symbol wasn't found"); } void DumpToLog(IRMemoryMap &map, lldb::addr_t process_address, Log *log) { StreamString dump_stream; const lldb::addr_t load_addr = process_address + m_offset; dump_stream.Printf("0x%" PRIx64 ": EntityResultVariable\n", load_addr); Error err; lldb::addr_t ptr = LLDB_INVALID_ADDRESS; { dump_stream.Printf("Pointer:\n"); DataBufferHeap data(m_size, 0); map.ReadMemory(data.GetBytes(), load_addr, m_size, err); if (!err.Success()) { dump_stream.Printf(" <could not be read>\n"); } else { DataExtractor extractor(data.GetBytes(), data.GetByteSize(), map.GetByteOrder(), map.GetAddressByteSize()); extractor.DumpHexBytes(&dump_stream, data.GetBytes(), data.GetByteSize(), 16, load_addr); lldb::offset_t offset; ptr = extractor.GetPointer(&offset); dump_stream.PutChar('\n'); } } if (m_temporary_allocation == LLDB_INVALID_ADDRESS) { dump_stream.Printf("Points to process memory:\n"); } else { dump_stream.Printf("Temporary allocation:\n"); } if (ptr == LLDB_INVALID_ADDRESS) { dump_stream.Printf(" <could not be be found>\n"); } else { DataBufferHeap data(m_temporary_allocation_size, 0); map.ReadMemory(data.GetBytes(), m_temporary_allocation, m_temporary_allocation_size, err); if (!err.Success()) { dump_stream.Printf(" <could not be read>\n"); } else { DataExtractor extractor(data.GetBytes(), data.GetByteSize(), map.GetByteOrder(), map.GetAddressByteSize()); extractor.DumpHexBytes(&dump_stream, data.GetBytes(), data.GetByteSize(), 16, m_temporary_allocation); dump_stream.PutChar('\n'); } } log->PutCString(dump_stream.GetData()); } void Wipe(IRMemoryMap &map, lldb::addr_t process_address) { m_temporary_allocation = LLDB_INVALID_ADDRESS; m_temporary_allocation_size = 0; } private: CompilerType m_type; SwiftREPLMaterializer *m_parent; swift::ValueDecl *m_swift_decl; // only used for the REPL; nullptr otherwise lldb::addr_t m_temporary_allocation; size_t m_temporary_allocation_size; Materializer::PersistentVariableDelegate *m_delegate; }; uint32_t SwiftREPLMaterializer::AddREPLResultVariable( const CompilerType &type, swift::ValueDecl *decl, PersistentVariableDelegate *delegate, Error &err) { EntityVector::iterator iter = m_entities.insert(m_entities.end(), EntityUP()); iter->reset(new EntityREPLResultVariable(type, decl, this, delegate)); uint32_t ret = AddStructMember(**iter); (*iter)->SetOffset(ret); return ret; } class EntityREPLPersistentVariable : public Materializer::Entity { public: EntityREPLPersistentVariable( lldb::ExpressionVariableSP &persistent_variable_sp, SwiftREPLMaterializer *parent, Materializer::PersistentVariableDelegate *delegate) : Entity(), m_persistent_variable_sp(persistent_variable_sp), m_parent(parent), m_delegate(delegate) { // Hard-coding to maximum size of a pointer since persistent variables are // materialized by reference m_size = 8; m_alignment = 8; } void Materialize(lldb::StackFrameSP &frame_sp, IRMemoryMap &map, lldb::addr_t process_address, Error &err) { // no action required } void Dematerialize(lldb::StackFrameSP &frame_sp, IRMemoryMap &map, lldb::addr_t process_address, lldb::addr_t frame_top, lldb::addr_t frame_bottom, Error &err) { if (llvm::cast<SwiftExpressionVariable>(m_persistent_variable_sp.get()) ->GetIsComputed()) return; IRExecutionUnit *execution_unit = m_parent->GetExecutionUnit(); if (!execution_unit) { return; } swift::Demangle::Context demangle_ctx; for (const IRExecutionUnit::JittedGlobalVariable &variable : execution_unit->GetJittedGlobalVariables()) { // e.g. // kind=Global // kind=Variable // kind=Module, text="lldb_expr_0" // kind=Identifier, text="a" swift::Demangle::NodePointer node_pointer = demangle_ctx.demangleSymbolAsNode(variable.m_name.GetStringRef()); if (!node_pointer || node_pointer->getKind() != swift::Demangle::Node::Kind::Global) continue; swift::Demangle::NodePointer variable_pointer = node_pointer->getFirstChild(); if (!variable_pointer || variable_pointer->getKind() != swift::Demangle::Node::Kind::Variable) continue; llvm::StringRef last_component; for (swift::Demangle::NodePointer child : *variable_pointer) { if (child && child->getKind() == swift::Demangle::Node::Kind::Identifier && child->hasText()) { last_component = child->getText(); break; } } if (last_component.empty()) continue; if (m_persistent_variable_sp->GetName().GetStringRef().equals( last_component)) { ExecutionContextScope *exe_scope = execution_unit->GetBestExecutionContextScope(); if (!exe_scope) { err.SetErrorString("Couldn't dematerialize a persistent variable: " "invalid execution context scope"); return; } m_persistent_variable_sp->m_live_sp = ValueObjectConstResult::Create( exe_scope, m_persistent_variable_sp->GetCompilerType(), m_persistent_variable_sp->GetName(), variable.m_remote_addr, eAddressTypeLoad, execution_unit->GetAddressByteSize()); // Read the contents of the spare memory area m_persistent_variable_sp->ValueUpdated(); Error read_error; execution_unit->ReadMemory( m_persistent_variable_sp->GetValueBytes(), variable.m_remote_addr, m_persistent_variable_sp->GetByteSize(), read_error); if (!read_error.Success()) { err.SetErrorStringWithFormat( "couldn't read the contents of %s from memory: %s", m_persistent_variable_sp->GetName().GetCString(), read_error.AsCString()); return; } m_persistent_variable_sp->m_flags &= ~ExpressionVariable::EVNeedsFreezeDry; return; } demangle_ctx.clear(); } err.SetErrorToGenericError(); err.SetErrorStringWithFormat( "Couldn't dematerialize %s: corresponding symbol wasn't found", m_persistent_variable_sp->GetName().GetCString()); } void DumpToLog(IRMemoryMap &map, lldb::addr_t process_address, Log *log) { StreamString dump_stream; Error err; const lldb::addr_t load_addr = process_address + m_offset; dump_stream.Printf("0x%" PRIx64 ": EntityPersistentVariable (%s)\n", load_addr, m_persistent_variable_sp->GetName().AsCString()); { dump_stream.Printf("Pointer:\n"); DataBufferHeap data(m_size, 0); map.ReadMemory(data.GetBytes(), load_addr, m_size, err); if (!err.Success()) { dump_stream.Printf(" <could not be read>\n"); } else { DataExtractor extractor(data.GetBytes(), data.GetByteSize(), map.GetByteOrder(), map.GetAddressByteSize()); extractor.DumpHexBytes(&dump_stream, data.GetBytes(), data.GetByteSize(), 16, load_addr); dump_stream.PutChar('\n'); } } { dump_stream.Printf("Target:\n"); lldb::addr_t target_address; map.ReadPointerFromMemory(&target_address, load_addr, err); if (!err.Success()) { dump_stream.Printf(" <could not be read>\n"); } else { DataBufferHeap data(m_persistent_variable_sp->GetByteSize(), 0); map.ReadMemory(data.GetBytes(), target_address, m_persistent_variable_sp->GetByteSize(), err); if (!err.Success()) { dump_stream.Printf(" <could not be read>\n"); } else { DataExtractor extractor(data.GetBytes(), data.GetByteSize(), map.GetByteOrder(), map.GetAddressByteSize()); extractor.DumpHexBytes(&dump_stream, data.GetBytes(), data.GetByteSize(), 16, target_address); dump_stream.PutChar('\n'); } } } log->PutCString(dump_stream.GetData()); } void Wipe(IRMemoryMap &map, lldb::addr_t process_address) {} private: lldb::ExpressionVariableSP m_persistent_variable_sp; SwiftREPLMaterializer *m_parent; Materializer::PersistentVariableDelegate *m_delegate; }; uint32_t SwiftREPLMaterializer::AddPersistentVariable( lldb::ExpressionVariableSP &persistent_variable_sp, PersistentVariableDelegate *delegate, Error &err) { EntityVector::iterator iter = m_entities.insert(m_entities.end(), EntityUP()); iter->reset( new EntityREPLPersistentVariable(persistent_variable_sp, this, delegate)); uint32_t ret = AddStructMember(**iter); (*iter)->SetOffset(ret); return ret; }
//===-- SwiftREPLMaterializer.cpp -------------------------------*- C++ -*-===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #include "SwiftREPLMaterializer.h" #include "SwiftASTManipulator.h" #include "lldb/Core/Log.h" #include "lldb/Core/ValueObjectConstResult.h" #include "lldb/Expression/IRExecutionUnit.h" #include "lldb/Expression/IRMemoryMap.h" #include "lldb/Target/Target.h" #include "swift/Demangling/Demangle.h" using namespace lldb_private; static llvm::StringRef GetNameOfDemangledVariable(swift::Demangle::NodePointer node_pointer) { if (!node_pointer || node_pointer->getKind() != swift::Demangle::Node::Kind::Global) return llvm::StringRef(); swift::Demangle::NodePointer variable_pointer = node_pointer->getFirstChild(); if (!variable_pointer || variable_pointer->getKind() != swift::Demangle::Node::Kind::Variable) return llvm::StringRef(); for (swift::Demangle::NodePointer child : *variable_pointer) { if (child && child->getKind() == swift::Demangle::Node::Kind::Identifier && child->hasText()) { return child->getText(); } } return llvm::StringRef(); } class EntityREPLResultVariable : public Materializer::Entity { public: EntityREPLResultVariable(const CompilerType &type, swift::ValueDecl *swift_decl, SwiftREPLMaterializer *parent, Materializer::PersistentVariableDelegate *delegate) : Entity(), m_type(type), m_parent(parent), m_swift_decl(swift_decl), m_temporary_allocation(LLDB_INVALID_ADDRESS), m_temporary_allocation_size(0), m_delegate(delegate) { // Hard-coding to maximum size of a pointer since all results are // materialized by reference m_size = 8; m_alignment = 8; } void Materialize(lldb::StackFrameSP &frame_sp, IRMemoryMap &map, lldb::addr_t process_address, Error &err) { // no action required } void MakeREPLResult(IRExecutionUnit &execution_unit, Error &err, const IRExecutionUnit::JittedGlobalVariable *variable) { err.Clear(); ExecutionContextScope *exe_scope = execution_unit.GetBestExecutionContextScope(); if (!exe_scope) { err.SetErrorString("Couldn't dematerialize a result variable: invalid " "execution context scope"); return; } lldb::TargetSP target_sp = exe_scope->CalculateTarget(); if (!target_sp) { err.SetErrorString("Couldn't dematerialize a result variable: no target"); return; } lldb::LanguageType lang = (m_type.GetMinimumLanguage() == lldb::eLanguageTypeSwift) ? lldb::eLanguageTypeSwift : lldb::eLanguageTypeObjC_plus_plus; PersistentExpressionState *persistent_state = target_sp->GetPersistentExpressionStateForLanguage(lang); if (!persistent_state) { err.SetErrorString("Couldn't dematerialize a result variable: language " "doesn't have persistent state"); } ConstString name = m_delegate ? m_delegate->GetName() : persistent_state->GetNextPersistentVariableName(false); lldb::ExpressionVariableSP ret; ret = persistent_state ->CreatePersistentVariable(exe_scope, name, m_type, execution_unit.GetByteOrder(), execution_unit.GetAddressByteSize()) ->shared_from_this(); if (!ret) { err.SetErrorStringWithFormat("couldn't dematerialize a result variable: " "failed to make persistent variable %s", name.AsCString()); return; } lldb::ProcessSP process_sp = execution_unit.GetBestExecutionContextScope()->CalculateProcess(); ret->m_live_sp = ValueObjectConstResult::Create( exe_scope, m_type, name, variable ? variable->m_remote_addr : LLDB_INVALID_ADDRESS, eAddressTypeLoad, execution_unit.GetAddressByteSize()); ret->ValueUpdated(); if (variable) { const size_t pvar_byte_size = ret->GetByteSize(); uint8_t *pvar_data = ret->GetValueBytes(); Error read_error; execution_unit.ReadMemory(pvar_data, variable->m_remote_addr, pvar_byte_size, read_error); if (!read_error.Success()) { err.SetErrorString("Couldn't dematerialize a result variable: couldn't " "read its memory"); return; } } if (m_delegate) { m_delegate->DidDematerialize(ret); } // Register the variable with the persistent decls under the assumed, // just-generated name so it can be reused. if (m_swift_decl) { llvm::cast<SwiftPersistentExpressionState>(persistent_state) ->RegisterSwiftPersistentDeclAlias(m_swift_decl, name); } return; } void Dematerialize(lldb::StackFrameSP &frame_sp, IRMemoryMap &map, lldb::addr_t process_address, lldb::addr_t frame_top, lldb::addr_t frame_bottom, Error &err) { IRExecutionUnit *execution_unit = llvm::cast<SwiftREPLMaterializer>(m_parent)->GetExecutionUnit(); if (!execution_unit) { return; } swift::Demangle::Context demangle_ctx; llvm::StringRef result_name = SwiftASTManipulator::GetResultName(); for (const IRExecutionUnit::JittedGlobalVariable &variable : execution_unit->GetJittedGlobalVariables()) { swift::Demangle::NodePointer node_pointer = demangle_ctx.demangleSymbolAsNode(variable.m_name.GetStringRef()); llvm::StringRef variable_name = GetNameOfDemangledVariable(node_pointer); if (variable_name == result_name) { MakeREPLResult(*execution_unit, err, &variable); return; } demangle_ctx.clear(); } if (SwiftASTContext::IsPossibleZeroSizeType(m_type)) { MakeREPLResult(*execution_unit, err, nullptr); return; } err.SetErrorToGenericError(); err.SetErrorStringWithFormat( "Couldn't dematerialize result: corresponding symbol wasn't found"); } void DumpToLog(IRMemoryMap &map, lldb::addr_t process_address, Log *log) { StreamString dump_stream; const lldb::addr_t load_addr = process_address + m_offset; dump_stream.Printf("0x%" PRIx64 ": EntityResultVariable\n", load_addr); Error err; lldb::addr_t ptr = LLDB_INVALID_ADDRESS; { dump_stream.Printf("Pointer:\n"); DataBufferHeap data(m_size, 0); map.ReadMemory(data.GetBytes(), load_addr, m_size, err); if (!err.Success()) { dump_stream.Printf(" <could not be read>\n"); } else { DataExtractor extractor(data.GetBytes(), data.GetByteSize(), map.GetByteOrder(), map.GetAddressByteSize()); extractor.DumpHexBytes(&dump_stream, data.GetBytes(), data.GetByteSize(), 16, load_addr); lldb::offset_t offset; ptr = extractor.GetPointer(&offset); dump_stream.PutChar('\n'); } } if (m_temporary_allocation == LLDB_INVALID_ADDRESS) { dump_stream.Printf("Points to process memory:\n"); } else { dump_stream.Printf("Temporary allocation:\n"); } if (ptr == LLDB_INVALID_ADDRESS) { dump_stream.Printf(" <could not be be found>\n"); } else { DataBufferHeap data(m_temporary_allocation_size, 0); map.ReadMemory(data.GetBytes(), m_temporary_allocation, m_temporary_allocation_size, err); if (!err.Success()) { dump_stream.Printf(" <could not be read>\n"); } else { DataExtractor extractor(data.GetBytes(), data.GetByteSize(), map.GetByteOrder(), map.GetAddressByteSize()); extractor.DumpHexBytes(&dump_stream, data.GetBytes(), data.GetByteSize(), 16, m_temporary_allocation); dump_stream.PutChar('\n'); } } log->PutCString(dump_stream.GetData()); } void Wipe(IRMemoryMap &map, lldb::addr_t process_address) { m_temporary_allocation = LLDB_INVALID_ADDRESS; m_temporary_allocation_size = 0; } private: CompilerType m_type; SwiftREPLMaterializer *m_parent; swift::ValueDecl *m_swift_decl; // only used for the REPL; nullptr otherwise lldb::addr_t m_temporary_allocation; size_t m_temporary_allocation_size; Materializer::PersistentVariableDelegate *m_delegate; }; uint32_t SwiftREPLMaterializer::AddREPLResultVariable( const CompilerType &type, swift::ValueDecl *decl, PersistentVariableDelegate *delegate, Error &err) { EntityVector::iterator iter = m_entities.insert(m_entities.end(), EntityUP()); iter->reset(new EntityREPLResultVariable(type, decl, this, delegate)); uint32_t ret = AddStructMember(**iter); (*iter)->SetOffset(ret); return ret; } class EntityREPLPersistentVariable : public Materializer::Entity { public: EntityREPLPersistentVariable( lldb::ExpressionVariableSP &persistent_variable_sp, SwiftREPLMaterializer *parent, Materializer::PersistentVariableDelegate *delegate) : Entity(), m_persistent_variable_sp(persistent_variable_sp), m_parent(parent), m_delegate(delegate) { // Hard-coding to maximum size of a pointer since persistent variables are // materialized by reference m_size = 8; m_alignment = 8; } void Materialize(lldb::StackFrameSP &frame_sp, IRMemoryMap &map, lldb::addr_t process_address, Error &err) { // no action required } void Dematerialize(lldb::StackFrameSP &frame_sp, IRMemoryMap &map, lldb::addr_t process_address, lldb::addr_t frame_top, lldb::addr_t frame_bottom, Error &err) { if (llvm::cast<SwiftExpressionVariable>(m_persistent_variable_sp.get()) ->GetIsComputed()) return; IRExecutionUnit *execution_unit = m_parent->GetExecutionUnit(); if (!execution_unit) { return; } swift::Demangle::Context demangle_ctx; for (const IRExecutionUnit::JittedGlobalVariable &variable : execution_unit->GetJittedGlobalVariables()) { // e.g. // kind=Global // kind=Variable // kind=Module, text="lldb_expr_0" // kind=Identifier, text="a" swift::Demangle::NodePointer node_pointer = demangle_ctx.demangleSymbolAsNode(variable.m_name.GetStringRef()); llvm::StringRef last_component = GetNameOfDemangledVariable(node_pointer); if (last_component.empty()) continue; if (m_persistent_variable_sp->GetName().GetStringRef().equals( last_component)) { ExecutionContextScope *exe_scope = execution_unit->GetBestExecutionContextScope(); if (!exe_scope) { err.SetErrorString("Couldn't dematerialize a persistent variable: " "invalid execution context scope"); return; } m_persistent_variable_sp->m_live_sp = ValueObjectConstResult::Create( exe_scope, m_persistent_variable_sp->GetCompilerType(), m_persistent_variable_sp->GetName(), variable.m_remote_addr, eAddressTypeLoad, execution_unit->GetAddressByteSize()); // Read the contents of the spare memory area m_persistent_variable_sp->ValueUpdated(); Error read_error; execution_unit->ReadMemory( m_persistent_variable_sp->GetValueBytes(), variable.m_remote_addr, m_persistent_variable_sp->GetByteSize(), read_error); if (!read_error.Success()) { err.SetErrorStringWithFormat( "couldn't read the contents of %s from memory: %s", m_persistent_variable_sp->GetName().GetCString(), read_error.AsCString()); return; } m_persistent_variable_sp->m_flags &= ~ExpressionVariable::EVNeedsFreezeDry; return; } demangle_ctx.clear(); } err.SetErrorToGenericError(); err.SetErrorStringWithFormat( "Couldn't dematerialize %s: corresponding symbol wasn't found", m_persistent_variable_sp->GetName().GetCString()); } void DumpToLog(IRMemoryMap &map, lldb::addr_t process_address, Log *log) { StreamString dump_stream; Error err; const lldb::addr_t load_addr = process_address + m_offset; dump_stream.Printf("0x%" PRIx64 ": EntityPersistentVariable (%s)\n", load_addr, m_persistent_variable_sp->GetName().AsCString()); { dump_stream.Printf("Pointer:\n"); DataBufferHeap data(m_size, 0); map.ReadMemory(data.GetBytes(), load_addr, m_size, err); if (!err.Success()) { dump_stream.Printf(" <could not be read>\n"); } else { DataExtractor extractor(data.GetBytes(), data.GetByteSize(), map.GetByteOrder(), map.GetAddressByteSize()); extractor.DumpHexBytes(&dump_stream, data.GetBytes(), data.GetByteSize(), 16, load_addr); dump_stream.PutChar('\n'); } } { dump_stream.Printf("Target:\n"); lldb::addr_t target_address; map.ReadPointerFromMemory(&target_address, load_addr, err); if (!err.Success()) { dump_stream.Printf(" <could not be read>\n"); } else { DataBufferHeap data(m_persistent_variable_sp->GetByteSize(), 0); map.ReadMemory(data.GetBytes(), target_address, m_persistent_variable_sp->GetByteSize(), err); if (!err.Success()) { dump_stream.Printf(" <could not be read>\n"); } else { DataExtractor extractor(data.GetBytes(), data.GetByteSize(), map.GetByteOrder(), map.GetAddressByteSize()); extractor.DumpHexBytes(&dump_stream, data.GetBytes(), data.GetByteSize(), 16, target_address); dump_stream.PutChar('\n'); } } } log->PutCString(dump_stream.GetData()); } void Wipe(IRMemoryMap &map, lldb::addr_t process_address) {} private: lldb::ExpressionVariableSP m_persistent_variable_sp; SwiftREPLMaterializer *m_parent; Materializer::PersistentVariableDelegate *m_delegate; }; uint32_t SwiftREPLMaterializer::AddPersistentVariable( lldb::ExpressionVariableSP &persistent_variable_sp, PersistentVariableDelegate *delegate, Error &err) { EntityVector::iterator iter = m_entities.insert(m_entities.end(), EntityUP()); iter->reset( new EntityREPLPersistentVariable(persistent_variable_sp, this, delegate)); uint32_t ret = AddStructMember(**iter); (*iter)->SetOffset(ret); return ret; }
Fix a problem with new symbol mangling in the repl.
Fix a problem with new symbol mangling in the repl. It's not sufficient to grep for the "lldb_result" variable in a mangled name, because in the new mangling scheme parts of the name may be substituted. Instead the name has to be de-mangled.
C++
apache-2.0
apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb
254866bf00d10b9d81fed228f4a1cc2833bacbaa
src/BabylonImGui/src/babylon_imgui/run_scene_with_inspector.cpp
src/BabylonImGui/src/babylon_imgui/run_scene_with_inspector.cpp
#include <imgui_utils/icons_font_awesome_5.h> #include <babylon/babylon_imgui/run_scene_with_inspector.h> #include <babylon/babylon_imgui/babylon_logs_window.h> #include <imgui_utils/app_runner/imgui_runner.h> #include <babylon/GL/framebuffer_canvas.h> #include <babylon/core/filesystem.h> #include <babylon/core/system.h> #include <babylon/core/logging.h> #include <babylon/samples/samples_index.h> #ifdef _WIN32 #include <windows.h> #endif namespace { template<typename EnumType> bool ShowTabBarEnum(const std::map<EnumType, std::string> & enumNames, EnumType * value) { bool changed = false; for (const auto & kv : enumNames) { bool selected = (*value == kv.first); if (selected) ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.3f, 0.3f, 0.6f, 1.f)); if (ImGui::Button(kv.second.c_str())) { if (*value != kv.first) { *value = kv.first; changed = true; } } if (selected) ImGui::PopStyleColor(); ImGui::SameLine(); } //ImGui::NewLine(); //ImGui::Separator(); return changed; } } #include <iostream> namespace BABYLON { namespace impl { const int INSPECTOR_WIDTH = 400; class BabylonInspectorApp { public: BabylonInspectorApp() { std::string exePath = BABYLON::System::getExecutablePath(); std::string exeFolder = BABYLON::Filesystem::baseDir(exePath); std::string sandboxPath = exeFolder + "/../../../src/SamplesRunner/sandbox.cpp"; sandboxPath = BABYLON::Filesystem::absolutePath(sandboxPath); _sandboxCodeEditor.setFiles({ sandboxPath }); } void RunApp( std::shared_ptr<BABYLON::IRenderableScene> initialScene, const SceneWithInspectorOptions & options ) { _appContext._options = options; std::function<bool(void)> showGuiLambda = [this]() -> bool { bool r = this->render(); for (auto f : _appContext._options._heartbeatCallbacks) f(); if (_appContext._options._sandboxCompilerCallback) { SandboxCompilerStatus sandboxCompilerStatus = _appContext._options._sandboxCompilerCallback(); if (sandboxCompilerStatus._renderableScene) setRenderableScene(sandboxCompilerStatus._renderableScene); _appContext._isCompiling = sandboxCompilerStatus._isCompiling; } return r; }; auto initSceneLambda = [&]() { this->initScene(); this->setRenderableScene(initialScene); }; ImGuiUtils::ImGuiRunner::RunGui(showGuiLambda, _appContext._options._appWindowParams, initSceneLambda); } private: enum class ViewState { Scene3d, SamplesCodeViewer, SampleBrowser, #ifdef BABYLON_BUILD_SANDBOX SandboxEditor, #endif }; static std::map<BabylonInspectorApp::ViewState, std::string> ViewStateLabels; void initScene() { _appContext._sampleListComponent.OnNewRenderableScene = [&](std::shared_ptr<IRenderableScene> scene) { this->setRenderableScene(scene); }; _appContext._sampleListComponent.OnEditFiles = [&](const std::vector<std::string> & files) { _samplesCodeEditor.setFiles(files); _appContext._viewState = ViewState::SamplesCodeViewer; }; _appContext._sampleListComponent.OnLoopSamples = [&](const std::vector<std::string> & samples) { _appContext._loopSamples.flagLoop = true; _appContext._loopSamples.samplesToLoop = samples; _appContext._loopSamples.currentIdx = 0; _appContext._viewState = ViewState::Scene3d; }; _appContext._sceneWidget = std::make_unique<BABYLON::ImGuiSceneWidget>(getSceneSize()); _appContext._sceneWidget->OnBeforeResize.push_back( [this]() { _appContext._inspector.release(); } ); } ImVec2 getSceneSize() { ImVec2 sceneSize = ImGui::GetIO().DisplaySize; sceneSize.x -= INSPECTOR_WIDTH; sceneSize.y -= 60; return sceneSize; } ImVec2 getSceneSizeSmall() { ImVec2 sceneSize = getSceneSize(); sceneSize.x /= 3.f; sceneSize.y /= 3.f; return sceneSize; } void createInspectorIfNeeded() { auto currentScene = _appContext._sceneWidget->getScene(); if ((! _appContext._inspector) || (_appContext._inspector->scene() != currentScene)) { _appContext._inspector = std::make_unique<BABYLON::Inspector>(nullptr, _appContext._sceneWidget->getScene()); _appContext._inspector->setScene(currentScene); } } bool render() // renders the GUI. Returns true when exit required { bool shallExit = false; createInspectorIfNeeded(); _appContext._inspector->render(false, INSPECTOR_WIDTH); ImGui::SameLine(); ImGui::BeginGroup(); ImGui::Text("%s", _appContext._sceneWidget->getRenderableScene()->getName()); ImGui::SameLine(0., 100.); ShowTabBarEnum(ViewStateLabels, &_appContext._viewState); ImGui::SameLine(0.f, 80.f); BABYLON::BabylonLogsWindow::instance().render(); ImGui::SameLine(); if (ImGui::Button(ICON_FA_DOOR_OPEN " Exit")) shallExit = true; ImGui::Separator(); if (_appContext._viewState == ViewState::Scene3d) _appContext._sceneWidget->render(getSceneSize()); if (_appContext._viewState == ViewState::SamplesCodeViewer) _samplesCodeEditor.render(); else if (_appContext._viewState == ViewState::SampleBrowser) _appContext._sampleListComponent.render(); #ifdef BABYLON_BUILD_SANDBOX if (_appContext._viewState == ViewState::SandboxEditor) renderSandbox(); #endif ImGui::EndGroup(); handleLoopSamples(); if (_appContext._options._flagScreenshotOneSampleAndExit) return saveScreenshot(); else return shallExit; } void setRenderableScene(std::shared_ptr<BABYLON::IRenderableScene> scene) { if (_appContext._inspector) _appContext._inspector->setScene(nullptr); _appContext._sceneWidget->setRenderableScene(scene); if (_appContext._inspector) _appContext._inspector->setScene(_appContext._sceneWidget->getScene()); if (_appContext._viewState == ViewState::SampleBrowser) _appContext._viewState = ViewState::Scene3d; } // Saves a screenshot after few frames (eeturns true when done) bool saveScreenshot() { _appContext._frameCounter++; if (_appContext._frameCounter < 30) return false; int imageWidth = 200; int jpgQuality = 75; this->_appContext._sceneWidget->getCanvas()->saveScreenshotJpg((_appContext._options._sceneName + ".jpg").c_str(), jpgQuality, imageWidth); return true; } void renderSandbox() { //ImGui::ShowDemoWindow(); ImGui::BeginGroup(); ImGui::Text("Sandbox : you can edit the code below!"); ImGui::Text("As soon as you save it, the code will be compiled and the 3D scene will be updated"); _appContext._sceneWidget->render(getSceneSizeSmall()); ImGui::EndGroup(); if (_appContext._isCompiling) { ImGui::TextColored(ImVec4(1., 0., 0., 1.), "Compiling"); BabylonLogsWindow::instance().setVisible(true); } _sandboxCodeEditor.render(); } private: void handleLoopSamples() { static BABYLON::Samples::SamplesIndex samplesIndex; if (!_appContext._loopSamples.flagLoop) return; static int frame_counter = 0; const int max_frames = 60; if (frame_counter > max_frames) { std::string sampleName = _appContext._loopSamples.samplesToLoop[_appContext._loopSamples.currentIdx]; BABYLON_LOG_ERROR("LoopSample", sampleName); auto scene = samplesIndex.createRenderableScene(sampleName, nullptr); this->setRenderableScene(scene); if (_appContext._loopSamples.currentIdx < _appContext._loopSamples.samplesToLoop.size() - 2) _appContext._loopSamples.currentIdx++; else _appContext._loopSamples.flagLoop = false; frame_counter = 0; } else frame_counter++; } struct AppContext { std::unique_ptr<BABYLON::ImGuiSceneWidget> _sceneWidget; std::unique_ptr< BABYLON::Inspector> _inspector; BABYLON::SamplesBrowser _sampleListComponent; ViewState _viewState = ViewState::Scene3d; int _frameCounter = 0; SceneWithInspectorOptions _options; bool _isCompiling = false; struct { bool flagLoop = false; size_t currentIdx = 0; std::vector<std::string> samplesToLoop; } _loopSamples; }; AppContext _appContext; ImGuiUtils::CodeEditor _samplesCodeEditor = ImGuiUtils::CodeEditor(true); // true <-> showCheckboxReadOnly ImGuiUtils::CodeEditor _sandboxCodeEditor; }; // end of class BabylonInspectorApp std::map<BabylonInspectorApp::ViewState, std::string> BabylonInspectorApp::ViewStateLabels = { { BabylonInspectorApp::ViewState::Scene3d, ICON_FA_CUBE " 3D Scene"}, { BabylonInspectorApp::ViewState::SampleBrowser, ICON_FA_PALETTE " Browse samples"}, { BabylonInspectorApp::ViewState::SamplesCodeViewer, ICON_FA_EDIT " Samples Code Viewer"}, #ifdef BABYLON_BUILD_SANDBOX { BabylonInspectorApp::ViewState::SandboxEditor, ICON_FA_FLASK " Sandbox"}, #endif }; } // namespace impl // public API void runSceneWithInspector( std::shared_ptr<BABYLON::IRenderableScene> scene, SceneWithInspectorOptions options /* = SceneWithInspectorOptions() */ ) { BABYLON::impl::BabylonInspectorApp app; app.RunApp(scene, options); } } // namespace BABYLON
#include <imgui_utils/icons_font_awesome_5.h> #include <babylon/babylon_imgui/run_scene_with_inspector.h> #include <babylon/babylon_imgui/babylon_logs_window.h> #include <imgui_utils/app_runner/imgui_runner.h> #include <babylon/GL/framebuffer_canvas.h> #include <babylon/core/filesystem.h> #include <babylon/core/system.h> #include <babylon/core/logging.h> #include <babylon/samples/samples_index.h> #ifdef _WIN32 #include <windows.h> #endif namespace { template<typename EnumType> bool ShowTabBarEnum(const std::map<EnumType, std::string> & enumNames, EnumType * value) { bool changed = false; for (const auto & kv : enumNames) { bool selected = (*value == kv.first); if (selected) ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.3f, 0.3f, 0.6f, 1.f)); if (ImGui::Button(kv.second.c_str())) { if (*value != kv.first) { *value = kv.first; changed = true; } } if (selected) ImGui::PopStyleColor(); ImGui::SameLine(); } //ImGui::NewLine(); //ImGui::Separator(); return changed; } } // namespace #include <iostream> namespace BABYLON { namespace impl { const int INSPECTOR_WIDTH = 400; class BabylonInspectorApp { public: BabylonInspectorApp() { std::string exePath = BABYLON::System::getExecutablePath(); std::string exeFolder = BABYLON::Filesystem::baseDir(exePath); std::string sandboxPath = exeFolder + "/../../../src/SamplesRunner/sandbox.cpp"; sandboxPath = BABYLON::Filesystem::absolutePath(sandboxPath); _sandboxCodeEditor.setFiles({ sandboxPath }); } void RunApp( std::shared_ptr<BABYLON::IRenderableScene> initialScene, const SceneWithInspectorOptions & options ) { _appContext._options = options; std::function<bool(void)> showGuiLambda = [this]() -> bool { bool r = this->render(); for (auto f : _appContext._options._heartbeatCallbacks) f(); if (_appContext._options._sandboxCompilerCallback) { SandboxCompilerStatus sandboxCompilerStatus = _appContext._options._sandboxCompilerCallback(); if (sandboxCompilerStatus._renderableScene) setRenderableScene(sandboxCompilerStatus._renderableScene); _appContext._isCompiling = sandboxCompilerStatus._isCompiling; } return r; }; auto initSceneLambda = [&]() { this->initScene(); this->setRenderableScene(initialScene); }; ImGuiUtils::ImGuiRunner::RunGui(showGuiLambda, _appContext._options._appWindowParams, initSceneLambda); } private: enum class ViewState { Scene3d, SamplesCodeViewer, SampleBrowser, #ifdef BABYLON_BUILD_SANDBOX SandboxEditor, #endif }; static std::map<BabylonInspectorApp::ViewState, std::string> ViewStateLabels; void initScene() { _appContext._sampleListComponent.OnNewRenderableScene = [&](std::shared_ptr<IRenderableScene> scene) { this->setRenderableScene(scene); }; _appContext._sampleListComponent.OnEditFiles = [&](const std::vector<std::string> & files) { _samplesCodeEditor.setFiles(files); _appContext._viewState = ViewState::SamplesCodeViewer; }; _appContext._sampleListComponent.OnLoopSamples = [&](const std::vector<std::string> & samples) { _appContext._loopSamples.flagLoop = true; _appContext._loopSamples.samplesToLoop = samples; _appContext._loopSamples.currentIdx = 0; _appContext._viewState = ViewState::Scene3d; }; _appContext._sceneWidget = std::make_unique<BABYLON::ImGuiSceneWidget>(getSceneSize()); _appContext._sceneWidget->OnBeforeResize.push_back( [this]() { _appContext._inspector.release(); } ); } ImVec2 getSceneSize() { ImVec2 sceneSize = ImGui::GetIO().DisplaySize; sceneSize.x -= INSPECTOR_WIDTH; sceneSize.y -= 60; return sceneSize; } ImVec2 getSceneSizeSmall() { ImVec2 sceneSize = getSceneSize(); sceneSize.x /= 3.f; sceneSize.y /= 3.f; return sceneSize; } void createInspectorIfNeeded() { auto currentScene = _appContext._sceneWidget->getScene(); if ((! _appContext._inspector) || (_appContext._inspector->scene() != currentScene)) { _appContext._inspector = std::make_unique<BABYLON::Inspector>(nullptr, _appContext._sceneWidget->getScene()); _appContext._inspector->setScene(currentScene); } } bool render() // renders the GUI. Returns true when exit required { bool shallExit = false; createInspectorIfNeeded(); _appContext._inspector->render(false, INSPECTOR_WIDTH); ImGui::SameLine(); ImGui::BeginGroup(); ImGui::Text("%s", _appContext._sceneWidget->getRenderableScene()->getName()); ImGui::SameLine(0., 100.); ShowTabBarEnum(ViewStateLabels, &_appContext._viewState); ImGui::SameLine(0.f, 80.f); BABYLON::BabylonLogsWindow::instance().render(); ImGui::SameLine(); if (ImGui::Button(ICON_FA_DOOR_OPEN " Exit")) shallExit = true; ImGui::Separator(); if (_appContext._viewState == ViewState::Scene3d) _appContext._sceneWidget->render(getSceneSize()); if (_appContext._viewState == ViewState::SamplesCodeViewer) _samplesCodeEditor.render(); else if (_appContext._viewState == ViewState::SampleBrowser) _appContext._sampleListComponent.render(); #ifdef BABYLON_BUILD_SANDBOX if (_appContext._viewState == ViewState::SandboxEditor) renderSandbox(); #endif ImGui::EndGroup(); handleLoopSamples(); if (_appContext._options._flagScreenshotOneSampleAndExit) return saveScreenshot(); else return shallExit; } void setRenderableScene(std::shared_ptr<BABYLON::IRenderableScene> scene) { if (_appContext._inspector) _appContext._inspector->setScene(nullptr); _appContext._sceneWidget->setRenderableScene(scene); if (_appContext._inspector) _appContext._inspector->setScene(_appContext._sceneWidget->getScene()); if (_appContext._viewState == ViewState::SampleBrowser) _appContext._viewState = ViewState::Scene3d; } // Saves a screenshot after few frames (eeturns true when done) bool saveScreenshot() { _appContext._frameCounter++; if (_appContext._frameCounter < 30) return false; int imageWidth = 200; int jpgQuality = 75; this->_appContext._sceneWidget->getCanvas()->saveScreenshotJpg((_appContext._options._sceneName + ".jpg").c_str(), jpgQuality, imageWidth); return true; } void renderSandbox() { ImGui::BeginGroup(); ImGui::Text("Sandbox : you can edit the code below!"); ImGui::Text("As soon as you save it, the code will be compiled and the 3D scene will be updated"); _appContext._sceneWidget->render(getSceneSizeSmall()); ImGui::EndGroup(); if (_appContext._isCompiling) { ImGui::TextColored(ImVec4(1., 0., 0., 1.), "Compiling"); BabylonLogsWindow::instance().setVisible(true); } if (ImGui::Button(ICON_FA_PLAY " Run")) _sandboxCodeEditor.saveAll(); _sandboxCodeEditor.render(); } private: void handleLoopSamples() { static BABYLON::Samples::SamplesIndex samplesIndex; if (!_appContext._loopSamples.flagLoop) return; static int frame_counter = 0; const int max_frames = 60; if (frame_counter > max_frames) { std::string sampleName = _appContext._loopSamples.samplesToLoop[_appContext._loopSamples.currentIdx]; BABYLON_LOG_ERROR("LoopSample", sampleName); auto scene = samplesIndex.createRenderableScene(sampleName, nullptr); this->setRenderableScene(scene); if (_appContext._loopSamples.currentIdx < _appContext._loopSamples.samplesToLoop.size() - 2) _appContext._loopSamples.currentIdx++; else _appContext._loopSamples.flagLoop = false; frame_counter = 0; } else frame_counter++; } struct AppContext { std::unique_ptr<BABYLON::ImGuiSceneWidget> _sceneWidget; std::unique_ptr< BABYLON::Inspector> _inspector; BABYLON::SamplesBrowser _sampleListComponent; ViewState _viewState = ViewState::Scene3d; int _frameCounter = 0; SceneWithInspectorOptions _options; bool _isCompiling = false; struct { bool flagLoop = false; size_t currentIdx = 0; std::vector<std::string> samplesToLoop; } _loopSamples; }; AppContext _appContext; ImGuiUtils::CodeEditor _samplesCodeEditor = ImGuiUtils::CodeEditor(true); // true <-> showCheckboxReadOnly ImGuiUtils::CodeEditor _sandboxCodeEditor; }; // end of class BabylonInspectorApp std::map<BabylonInspectorApp::ViewState, std::string> BabylonInspectorApp::ViewStateLabels = { { BabylonInspectorApp::ViewState::Scene3d, ICON_FA_CUBE " 3D Scene"}, { BabylonInspectorApp::ViewState::SampleBrowser, ICON_FA_PALETTE " Browse samples"}, { BabylonInspectorApp::ViewState::SamplesCodeViewer, ICON_FA_EDIT " Samples Code Viewer"}, #ifdef BABYLON_BUILD_SANDBOX { BabylonInspectorApp::ViewState::SandboxEditor, ICON_FA_FLASK " Sandbox"}, #endif }; } // namespace impl // public API void runSceneWithInspector( std::shared_ptr<BABYLON::IRenderableScene> scene, SceneWithInspectorOptions options /* = SceneWithInspectorOptions() */ ) { BABYLON::impl::BabylonInspectorApp app; app.RunApp(scene, options); } } // namespace BABYLON
add "Run" button in the sandbox tab
run_scene_with_inspector: add "Run" button in the sandbox tab
C++
apache-2.0
samdauwe/BabylonCpp,samdauwe/BabylonCpp,samdauwe/BabylonCpp,samdauwe/BabylonCpp
465f4c69ac34a592b2d6526e44b6248a183dd257
Library/Sources/Stroika/Foundation/DataExchange/7z/ArchiveReader.cpp
Library/Sources/Stroika/Foundation/DataExchange/7z/ArchiveReader.cpp
/* * Copyright(c) Sophist Solutions, Inc. 1990-2015. All rights reserved */ #include "../../StroikaPreComp.h" #include "../../Characters/Format.h" #include "../../Execution/Finally.h" #include "../../Streams/iostream/InputStreamFromStdIStream.h" #include "ArchiveReader.h" #if qHasFeature_LZMA extern "C" { #include <lzma/7z.h> #include <lzma/7zCrc.h> } #endif #if qHasFeature_LZMA && defined (_MSC_VER) // Use #pragma comment lib instead of explicit entry in the lib entry of the project file #pragma comment (lib, "lzma.lib") #endif using namespace Stroika::Foundation; using namespace Stroika::Foundation::DataExchange; using Streams::iostream::InputStreamFromStdIStream; #if qHasFeature_LZMA namespace { struct InitOnce_ { InitOnce_ () { ::CrcGenerateTable (); } } sInitOnce_; } class _7z::ArchiveReader::Rep_ : public ArchiveReader::_IRep { private: // could do smarter/block allocation or arena allocation, but KISS for now static void* Alloc_ (void* p, size_t size) { Require (size > 0); return new Byte [size]; } static void Free_ (void* p, void* address) { delete[] reinterpret_cast<Byte*> (address); } private: mutable ISzAlloc fAllocImp_ { }; mutable ISzAlloc fAllocTempImp_ { }; CSzArEx fDB_ { }; struct MyISeekInStream : ISeekInStream { Streams::InputStream<Memory::Byte> fInStream_; MyISeekInStream (const Streams::InputStream<Memory::Byte>& in) : fInStream_ (in) { Read = Stream_Read_; Seek = Stream_Seek_; } static SRes Stream_Read_ (void* pp, void* buf, size_t* size) { MyISeekInStream* pThis = (MyISeekInStream*)pp; size_t sz = pThis->fInStream_.Read (reinterpret_cast<Byte*> (buf), reinterpret_cast<Byte*> (buf) + *size); Assert (sz <= *size); *size = sz; return SZ_OK; // not sure on EOF/underflow?SZ_ERROR_READ } static SRes Stream_Seek_ (void* pp, Int64* pos, ESzSeek origin) { MyISeekInStream* pThis = (MyISeekInStream*)pp; switch (origin) { case SZ_SEEK_SET: *pos = pThis->fInStream_.Seek (*pos); break; case SZ_SEEK_CUR: *pos = pThis->fInStream_.Seek (Streams::Whence::eFromCurrent, *pos); break; case SZ_SEEK_END: *pos = pThis->fInStream_.Seek (Streams::Whence::eFromEnd, *pos); break; default: AssertNotReached (); return SZ_ERROR_UNSUPPORTED; } return SZ_OK; } }; MyISeekInStream fInSeekStream_; mutable CLookToRead fLookStream_ { }; public: Rep_ (const Streams::InputStream<Memory::Byte>& in) : fInSeekStream_ (in) { fAllocImp_ = ISzAlloc { Alloc_, Free_ }; fAllocTempImp_ = ISzAlloc { Alloc_, Free_ }; ::SzArEx_Init (&fDB_); ::LookToRead_CreateVTable (&fLookStream_, false); fLookStream_.realStream = &fInSeekStream_; SRes ret {}; if ((ret = ::SzArEx_Open (&fDB_, &fLookStream_.s, &fAllocImp_, &fAllocTempImp_)) != SZ_OK) { // throw } } ~Rep_ () { ::SzArEx_Free (&fDB_, &fAllocImp_); } virtual Set<String> GetContainedFiles () const override { Set<String> result; for (unsigned int i = 0; i < fDB_.NumFiles; i++) { if (not SzArEx_IsDir (&fDB_, i)) { size_t nameLen = ::SzArEx_GetFileNameUtf16 (&fDB_, i, nullptr); if (nameLen < 1) { break; } Memory::SmallStackBuffer<char16_t> fileName (nameLen); size_t z = ::SzArEx_GetFileNameUtf16 (&fDB_, i, reinterpret_cast<UInt16*> (&fileName[0])); result.Add (String (&fileName[0])); } } return result; } virtual Memory::BLOB GetData (const String& fileName) const { UInt32 idx = GetIdx_ (fileName); if (idx == -1) { throw "bad"; //filenotfound } Byte* outBuffer = 0; // it must be 0 before first call for each new archive UInt32 blockIndex = 0xFFFFFFFF; // can have any value if outBuffer = 0 size_t outBufferSize = 0; // can have any value if outBuffer = 0 size_t offset {}; size_t outSizeProcessed {}; Execution::Finally cleanup { [&outBuffer, this] { IAlloc_Free (&fAllocImp_, outBuffer); } }; SRes ret; if ((ret = ::SzArEx_Extract (&fDB_, &fLookStream_.s, idx, &blockIndex, &outBuffer, &outBufferSize, &offset, &outSizeProcessed, &fAllocImp_, &fAllocTempImp_)) != SZ_OK) { throw "bad"; } return Memory::BLOB (outBuffer + offset, outBuffer + offset + outSizeProcessed); } UInt32 GetIdx_ (const String& fn) const { // could create map to lookup once and maintain for (UInt32 i = 0; i < fDB_.NumFiles; i++) { if (not SzArEx_IsDir (&fDB_, i)) { size_t nameLen = SzArEx_GetFileNameUtf16 (&fDB_, i, nullptr); if (nameLen < 1) { break; } Memory::SmallStackBuffer<char16_t> fileName (nameLen); size_t z = ::SzArEx_GetFileNameUtf16 (&fDB_, i, reinterpret_cast<UInt16*> (&fileName[0])); if (String (&fileName[0]) == fn) { return i; } } } return static_cast<UInt32> (-1); } }; _7z::ArchiveReader::ArchiveReader (const Streams::InputStream<Memory::Byte>& in) : DataExchange::ArchiveReader (make_shared<Rep_> (in)) { } #endif
/* * Copyright(c) Sophist Solutions, Inc. 1990-2015. All rights reserved */ #include "../../StroikaPreComp.h" #include "../../Characters/Format.h" #include "../../Execution/Finally.h" #include "../../Streams/iostream/InputStreamFromStdIStream.h" #include "ArchiveReader.h" #if qHasFeature_LZMA extern "C" { #include <lzma/7z.h> #include <lzma/7zCrc.h> } #endif #if qHasFeature_LZMA && defined (_MSC_VER) // Use #pragma comment lib instead of explicit entry in the lib entry of the project file #pragma comment (lib, "lzma.lib") #endif using namespace Stroika::Foundation; using namespace Stroika::Foundation::DataExchange; using Streams::iostream::InputStreamFromStdIStream; #if qHasFeature_LZMA namespace { struct InitOnce_ { InitOnce_ () { ::CrcGenerateTable (); } } sInitOnce_; } class _7z::ArchiveReader::Rep_ : public ArchiveReader::_IRep { private: // could do smarter/block allocation or arena allocation, but KISS for now static void* Alloc_ (void* p, size_t size) { Require (size > 0); return new Byte [size]; } static void Free_ (void* p, void* address) { delete[] reinterpret_cast<Byte*> (address); } private: mutable ISzAlloc fAllocImp_ { }; mutable ISzAlloc fAllocTempImp_ { }; CSzArEx fDB_ { }; struct MyISeekInStream : ISeekInStream { Streams::InputStream<Memory::Byte> fInStream_; MyISeekInStream (const Streams::InputStream<Memory::Byte>& in) : fInStream_ (in) { Read = Stream_Read_; Seek = Stream_Seek_; } static SRes Stream_Read_ (void* pp, void* buf, size_t* size) { MyISeekInStream* pThis = (MyISeekInStream*)pp; size_t sz = pThis->fInStream_.Read (reinterpret_cast<Byte*> (buf), reinterpret_cast<Byte*> (buf) + *size); Assert (sz <= *size); *size = sz; return SZ_OK; // not sure on EOF/underflow?SZ_ERROR_READ } static SRes Stream_Seek_ (void* pp, Int64* pos, ESzSeek origin) { MyISeekInStream* pThis = (MyISeekInStream*)pp; switch (origin) { case SZ_SEEK_SET: *pos = pThis->fInStream_.Seek (*pos); break; case SZ_SEEK_CUR: *pos = pThis->fInStream_.Seek (Streams::Whence::eFromCurrent, *pos); break; case SZ_SEEK_END: *pos = pThis->fInStream_.Seek (Streams::Whence::eFromEnd, *pos); break; default: AssertNotReached (); return SZ_ERROR_UNSUPPORTED; } return SZ_OK; } }; MyISeekInStream fInSeekStream_; mutable CLookToRead fLookStream_ { }; public: Rep_ (const Streams::InputStream<Memory::Byte>& in) : fInSeekStream_ (in) { fAllocImp_ = ISzAlloc { Alloc_, Free_ }; fAllocTempImp_ = ISzAlloc { Alloc_, Free_ }; ::SzArEx_Init (&fDB_); ::LookToRead_CreateVTable (&fLookStream_, false); fLookStream_.realStream = &fInSeekStream_; SRes ret {}; if ((ret = ::SzArEx_Open (&fDB_, &fLookStream_.s, &fAllocImp_, &fAllocTempImp_)) != SZ_OK) { // throw throw "bad"; } } ~Rep_ () { ::SzArEx_Free (&fDB_, &fAllocImp_); } virtual Set<String> GetContainedFiles () const override { Set<String> result; for (unsigned int i = 0; i < fDB_.NumFiles; i++) { if (not SzArEx_IsDir (&fDB_, i)) { size_t nameLen = ::SzArEx_GetFileNameUtf16 (&fDB_, i, nullptr); if (nameLen < 1) { break; } Memory::SmallStackBuffer<char16_t> fileName (nameLen); size_t z = ::SzArEx_GetFileNameUtf16 (&fDB_, i, reinterpret_cast<UInt16*> (&fileName[0])); result.Add (String (&fileName[0])); } } return result; } virtual Memory::BLOB GetData (const String& fileName) const { UInt32 idx = GetIdx_ (fileName); if (idx == -1) { throw "bad"; //filenotfound } Byte* outBuffer = 0; // it must be 0 before first call for each new archive UInt32 blockIndex = 0xFFFFFFFF; // can have any value if outBuffer = 0 size_t outBufferSize = 0; // can have any value if outBuffer = 0 size_t offset {}; size_t outSizeProcessed {}; Execution::Finally cleanup { [&outBuffer, this] { IAlloc_Free (&fAllocImp_, outBuffer); } }; SRes ret; if ((ret = ::SzArEx_Extract (&fDB_, &fLookStream_.s, idx, &blockIndex, &outBuffer, &outBufferSize, &offset, &outSizeProcessed, &fAllocImp_, &fAllocTempImp_)) != SZ_OK) { throw "bad"; } return Memory::BLOB (outBuffer + offset, outBuffer + offset + outSizeProcessed); } UInt32 GetIdx_ (const String& fn) const { // could create map to lookup once and maintain for (UInt32 i = 0; i < fDB_.NumFiles; i++) { if (not SzArEx_IsDir (&fDB_, i)) { size_t nameLen = SzArEx_GetFileNameUtf16 (&fDB_, i, nullptr); if (nameLen < 1) { break; } Memory::SmallStackBuffer<char16_t> fileName (nameLen); size_t z = ::SzArEx_GetFileNameUtf16 (&fDB_, i, reinterpret_cast<UInt16*> (&fileName[0])); if (String (&fileName[0]) == fn) { return i; } } } return static_cast<UInt32> (-1); } }; _7z::ArchiveReader::ArchiveReader (const Streams::InputStream<Memory::Byte>& in) : DataExchange::ArchiveReader (make_shared<Rep_> (in)) { } #endif
tweak DataExchange/7z/ArchiveReader
tweak DataExchange/7z/ArchiveReader
C++
mit
SophistSolutions/Stroika,SophistSolutions/Stroika,SophistSolutions/Stroika,SophistSolutions/Stroika,SophistSolutions/Stroika
ec8b7ed57f45cf972b5d6d6435db7d8d22751620
src/opencvros.cpp
src/opencvros.cpp
#include <ros/ros.h> #include "std_msgs/Int32.h" #include <sstream> #include <geometry_msgs/Twist.h> #include <stdlib.h> #include <image_transport/image_transport.h> #include <image_transport/subscriber_filter.h> #include <cv_bridge/cv_bridge.h> #include <sensor_msgs/image_encodings.h> #include <sensor_msgs/LaserScan.h> #include "std_msgs/String.h" #include <message_filters/sync_policies/approximate_time.h> #include <sensor_msgs/Image.h> #include <message_filters/time_synchronizer.h> #include <message_filters/subscriber.h> #include <sensor_msgs/CameraInfo.h> #include <message_filters/sync_policies/exact_time.h> #include <boost/bind/protect.hpp> #include <boost/bind.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/highgui/highgui.hpp> static const std::string OPENCV_WINDOW = "Image window"; using namespace cv; using namespace std; using namespace message_filters; using namespace sensor_msgs; int drivestate = 1; static int camcenter; static int funcscan = 0; static int mainscan = 0; /* Groen flesje int iLowH = 30; int iHighH = 69; int iLowS = 152; int iHighS = 255; int iLowV = 41; int iHighV = 166; */ /*Blauw Flesje int iLowH = 94; int iHighH = 134; int iLowS = 65; int iHighS = 180; int iLowV = 29; int iHighV = 127; */ /*Rood Cola int iLowH = 0; int iHighH = 29; int iLowS = 211; int iHighS = 255; int iLowV = 11; int iHighV = 190; */ //Groen Arizona int iLowH = 19; int iHighH = 98; int iLowS = 155; int iHighS = 255; int iLowV = 47; int iHighV = 255; typedef union U_FloatParse { float float_data; unsigned char byte_data[4]; } U_FloatConvert; int ReadDepthData(unsigned int height_pos, unsigned int width_pos, sensor_msgs::ImageConstPtr depth_image) { //credits opencv math and tutorial to Kyle Hounslaw // If position is invalid if ((height_pos >= depth_image->height) || (width_pos >= depth_image->width)) return -1; int index = (height_pos*depth_image->step) + (width_pos*(depth_image->step/depth_image->width)); // If data is 4 byte floats (rectified depth image) if ((depth_image->step/depth_image->width) == 4) { U_FloatConvert depth_data; int i, endian_check = 1; // If big endian if ((depth_image->is_bigendian && (*(char*)&endian_check != 1)) || // Both big endian ((!depth_image->is_bigendian) && (*(char*)&endian_check == 1))) // Both lil endian { for (i = 0; i < 4; i++) depth_data.byte_data[i] = depth_image->data[index + i]; // Make sure data is valid (check if NaN) if (depth_data.float_data == depth_data.float_data) return int(depth_data.float_data*1000); return -1; // If depth data invalid } // else, one little endian, one big endian for (i = 0; i < 4; i++) depth_data.byte_data[i] = depth_image->data[3 + index - i]; // Make sure data is valid (check if NaN) if (depth_data.float_data == depth_data.float_data) return int(depth_data.float_data*1000); return -1; // If depth data invalid } // Otherwise, data is 2 byte integers (raw depth image) int temp_val; // If big endian if (depth_image->is_bigendian) temp_val = (depth_image->data[index] << 8) + depth_image->data[index + 1]; // If little endian else temp_val = depth_image->data[index] + (depth_image->data[index + 1] << 8); // Make sure data is valid (check if NaN) if (temp_val == temp_val) return temp_val; return -1; // If depth data invalid } //imagecallback takes the camera sensor values, extracts the wanted HSV values from them and then finds the biggest part of the image which has this given value. //After this a bounding box is put around that part of the image, and from the center of this box the depth value and position on the screen is calculated. void imageCallback(const sensor_msgs::ImageConstPtr& msg, const sensor_msgs::ImageConstPtr& msg_depth, const sensor_msgs::CameraInfoConstPtr& right_camera) { //CVBridge is used to convert the image from ROS to OpenCV format in order to use OpenCV's functions. cv_bridge::CvImagePtr cv_ptr; try { cv_ptr = cv_bridge::toCvCopy(msg, sensor_msgs::image_encodings::BGR8); } catch (cv_bridge::Exception& e) { ROS_ERROR("cv_bridge exception: %s", e.what()); return; } Mat imgOriginal; Mat imgHSV; cv::cvtColor(cv_ptr->image, imgHSV, cv::COLOR_BGR2HSV); //Convert the captured frame from RGB to HSV Mat imgThresholded; inRange(imgHSV, Scalar(iLowH, iLowS, iLowV), Scalar(iHighH, iHighS, iHighV), imgThresholded); //Threshold the image double m01, m10, area; int posX = 0, posY = 0; Moments oMoments = moments(imgThresholded); m01 = oMoments.m01; m10 = oMoments.m10; area = oMoments.m00; // Filter position if (area > 1000000) { // Position posX = m10 / area; posY = m01 / area; } //Remove small objects from the foreground.Morphsize (ms) can be changed to filter out small objects. //The bigger the value of ms (erosion), the bigger an object has to be to get picked up by the camera. int ms = 25; int ds = 5; erode(imgThresholded, imgThresholded, getStructuringElement(MORPH_ELLIPSE, Size(ms, ms)) ); dilate( imgThresholded, imgThresholded, getStructuringElement(MORPH_ELLIPSE, Size(ms, ms)) ); //morphological closing (fill small holes in the foreground) dilate( imgThresholded, imgThresholded, getStructuringElement(MORPH_ELLIPSE, Size(ds, ds)) ); erode(imgThresholded, imgThresholded, getStructuringElement(MORPH_ELLIPSE, Size(ds, ds)) ); imshow("hsv", imgThresholded); //show the thresholded image int largest_area = 0; int largest_contour_index = 0; double width, height; vector< vector<Point> > contours; // Vector for storing contour vector<Vec4i> hierarchy; Rect bounding_rect; // Find all contours in thresholded image findContours(imgThresholded, contours, hierarchy, CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE); // Find the biggest contour and calculate bounding box for(int i = 0; i < contours.size(); i++) { double a = contourArea(contours[i], false); if(a > largest_area) { largest_area = a; largest_contour_index = i; bounding_rect = boundingRect(contours[i]); } } // Calculate width and heigt of bounding box width = bounding_rect.br().x - bounding_rect.tl().x; height = bounding_rect.br().y - bounding_rect.tl().y; // Calculate center.x Point center = Point(((width/2) + bounding_rect.tl().x), ((height/2) + bounding_rect.tl().y)); int depth = ReadDepthData(center.y, center.x, msg_depth); // Print coordinates from the object //ROS_INFO("Center x: %d, center y: %d\n", center.x, center.y); drawContours(cv_ptr->image, contours, largest_contour_index, Scalar(255), 1, 8, hierarchy); // Draw the largest contour using previously stored index. circle(cv_ptr->image, center, 3, Scalar(255,255,0), -1, 8, 0); // Draw dot in center of bb rectangle(cv_ptr->image, bounding_rect.tl(), bounding_rect.br(), Scalar(255,255,0), 2, 8, 0); // Draw bounding box imshow("original", cv_ptr->image); //show the original image camcenter = center.x; //Make a new node ros::NodeHandle nc; ros::Publisher ctr_pub = nc.advertise<std_msgs::Int32>("centerdata", 1); if (camcenter>0) { std_msgs::Int32 ctr; ctr.data = camcenter; ROS_INFO("center: %d", ctr.data); ctr_pub.publish(ctr); } ros::NodeHandle nd; ros::Publisher dpt_pub = nd.advertise<std_msgs::Int32>("depthdata", 1); if (camcenter>0) { std_msgs::Int32 dpt; dpt.data = depth; ROS_INFO("depth: %d", dpt.data); dpt_pub.publish(dpt); } } int main(int argc, char** argv) { ros::init(argc, argv, "opencvnode"); ros::NodeHandle nh; message_filters::Subscriber<CameraInfo> camera_info_sub(nh, "/camera/depth_registered/camera_info", 1); message_filters::Subscriber<Image> depth_image_sub(nh, "/camera/depth/image_raw", 1); message_filters::Subscriber<Image> rgb_image_sub(nh, "/camera/rgb/image_raw", 1); ros::NodeHandle nc; ros::Publisher ctr_pub = nc.advertise<std_msgs::Int32>("centerdata", 1); ros::NodeHandle nd; ros::Publisher dpt_pub = nd.advertise<std_msgs::Int32>("depthdata", 1); //message_filters::Subscriber<std_msgs::String> coordinates_array(nh_, "chatter" , 1); typedef sync_policies::ApproximateTime<Image, Image, CameraInfo> MySyncPolicy; Synchronizer<MySyncPolicy> sync(MySyncPolicy(1), rgb_image_sub, depth_image_sub, camera_info_sub); //TimeSynchronizer<Image, Image, CameraInfo> sync(rgb_image_sub, depth_image_sub, camera_info_sub, 10); sync.registerCallback(boost::bind(&imageCallback, _1, _2, _3)); //cv::namedWindow(OPENCV_WINDOW); namedWindow("original", CV_WINDOW_AUTOSIZE); //create a window called "Control" namedWindow("hsv", CV_WINDOW_AUTOSIZE); // TODO change to hsv values loaded in. For the green card it is: H:42, 90. S:90,255. V:0,255 //Create trackbars in "Control" window cvCreateTrackbar("LowH", "original", &iLowH, 179); //Hue (0 - 179) cvCreateTrackbar("HighH", "original", &iHighH, 179); cvCreateTrackbar("LowS", "original", &iLowS, 255); //Saturation (0 - 255) cvCreateTrackbar("HighS", "original", &iHighS, 255); cvCreateTrackbar("LowV", "original", &iLowV, 255); //Value (0 - 255) cvCreateTrackbar("HighV", "original", &iHighV, 255); cvStartWindowThread(); ros::spin(); return 0; }
#include <ros/ros.h> #include "std_msgs/Int32.h" #include <sstream> #include <geometry_msgs/Twist.h> #include <stdlib.h> #include <image_transport/image_transport.h> #include <image_transport/subscriber_filter.h> #include <cv_bridge/cv_bridge.h> #include <sensor_msgs/image_encodings.h> #include <sensor_msgs/LaserScan.h> #include "std_msgs/String.h" #include <message_filters/sync_policies/approximate_time.h> #include <sensor_msgs/Image.h> #include <message_filters/time_synchronizer.h> #include <message_filters/subscriber.h> #include <sensor_msgs/CameraInfo.h> #include <message_filters/sync_policies/exact_time.h> #include <boost/bind/protect.hpp> #include <boost/bind.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/highgui/highgui.hpp> static const std::string OPENCV_WINDOW = "Image window"; using namespace cv; using namespace std; using namespace message_filters; using namespace sensor_msgs; int drivestate = 1; static int camcenter; static int funcscan = 0; static int mainscan = 0; /* Groen flesje int iLowH = 30; int iHighH = 69; int iLowS = 152; int iHighS = 255; int iLowV = 41; int iHighV = 166; */ /*Blauw Flesje int iLowH = 94; int iHighH = 134; int iLowS = 65; int iHighS = 180; int iLowV = 29; int iHighV = 127; */ /*Rood Cola int iLowH = 0; int iHighH = 29; int iLowS = 211; int iHighS = 255; int iLowV = 11; int iHighV = 190; */ //Groen Arizona int iLowH = 19; int iHighH = 98; int iLowS = 155; int iHighS = 255; int iLowV = 47; int iHighV = 255; //A typedef creates an alias which simplifies the use of multiple identifiers. typedef union U_FloatParse { float float_data; unsigned char byte_data[4]; } U_FloatConvert; //ReadDepthData finds out what the depth of the object is. int ReadDepthData(unsigned int height_pos, unsigned int width_pos, sensor_msgs::ImageConstPtr depth_image) { // If position is invalid if ((height_pos >= depth_image->height) || (width_pos >= depth_image->width)) return -1; int index = (height_pos*depth_image->step) + (width_pos*(depth_image->step/depth_image->width)); // If data is 4 byte floats (rectified depth image) if ((depth_image->step/depth_image->width) == 4) { U_FloatConvert depth_data; int i, endian_check = 1; // If big endian if ((depth_image->is_bigendian && (*(char*)&endian_check != 1)) || // Both big endian ((!depth_image->is_bigendian) && (*(char*)&endian_check == 1))) // Both lil endian { for (i = 0; i < 4; i++) depth_data.byte_data[i] = depth_image->data[index + i]; // Make sure data is valid (check if NaN) if (depth_data.float_data == depth_data.float_data) return int(depth_data.float_data*1000); return -1; // If depth data invalid } // else, one little endian, one big endian for (i = 0; i < 4; i++) depth_data.byte_data[i] = depth_image->data[3 + index - i]; // Make sure data is valid (check if NaN) if (depth_data.float_data == depth_data.float_data) return int(depth_data.float_data*1000); return -1; // If depth data invalid } // Otherwise, data is 2 byte integers (raw depth image) int temp_val; // If big endian if (depth_image->is_bigendian) temp_val = (depth_image->data[index] << 8) + depth_image->data[index + 1]; // If little endian else temp_val = depth_image->data[index] + (depth_image->data[index + 1] << 8); // Make sure data is valid (check if NaN) if (temp_val == temp_val) return temp_val; return -1; // If depth data invalid } //imagecallback takes the camera sensor values, extracts the wanted HSV values from them and then finds the biggest part of the image which has this given value. //After this a bounding box is put around that part of the image, and from the center of this box the depth value and position on the screen is calculated. void imageCallback(const sensor_msgs::ImageConstPtr& msg, const sensor_msgs::ImageConstPtr& msg_depth, const sensor_msgs::CameraInfoConstPtr& right_camera) { //CVBridge is used to convert the image from ROS to OpenCV format in order to use OpenCV's functions. cv_bridge::CvImagePtr cv_ptr; try { cv_ptr = cv_bridge::toCvCopy(msg, sensor_msgs::image_encodings::BGR8); } catch (cv_bridge::Exception& e) { ROS_ERROR("cv_bridge exception: %s", e.what()); return; } //source opencv tutorial: Kyle Hounslaw Mat imgOriginal; Mat imgHSV; cv::cvtColor(cv_ptr->image, imgHSV, cv::COLOR_BGR2HSV); //Convert the captured frame from RGB to HSV Mat imgThresholded; inRange(imgHSV, Scalar(iLowH, iLowS, iLowV), Scalar(iHighH, iHighS, iHighV), imgThresholded); //Threshold the image double m01, m10, area; int posX = 0, posY = 0; Moments oMoments = moments(imgThresholded); m01 = oMoments.m01; m10 = oMoments.m10; area = oMoments.m00; // Filter position if (area > 1000000) { // Position posX = m10 / area; posY = m01 / area; } //Remove small objects from the foreground.Morphsize (ms) can be changed to filter out small objects. //The bigger the value of ms (erosion), the bigger an object has to be to get picked up by the camera. int ms = 25; int ds = 5; erode(imgThresholded, imgThresholded, getStructuringElement(MORPH_ELLIPSE, Size(ms, ms)) ); dilate( imgThresholded, imgThresholded, getStructuringElement(MORPH_ELLIPSE, Size(ms, ms)) ); //morphological closing (fill small holes in the foreground) dilate( imgThresholded, imgThresholded, getStructuringElement(MORPH_ELLIPSE, Size(ds, ds)) ); erode(imgThresholded, imgThresholded, getStructuringElement(MORPH_ELLIPSE, Size(ds, ds)) ); imshow("hsv", imgThresholded); //show the thresholded image int largest_area = 0; int largest_contour_index = 0; double width, height; vector< vector<Point> > contours; // Vector for storing contour vector<Vec4i> hierarchy; Rect bounding_rect; // Find all contours in thresholded image findContours(imgThresholded, contours, hierarchy, CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE); // Find the biggest contour and calculate bounding box for(int i = 0; i < contours.size(); i++) { double a = contourArea(contours[i], false); if(a > largest_area) { largest_area = a; largest_contour_index = i; bounding_rect = boundingRect(contours[i]); } } // Calculate width and heigt of bounding box width = bounding_rect.br().x - bounding_rect.tl().x; height = bounding_rect.br().y - bounding_rect.tl().y; // Calculate center.x Point center = Point(((width/2) + bounding_rect.tl().x), ((height/2) + bounding_rect.tl().y)); int depth = ReadDepthData(center.y, center.x, msg_depth); // Print coordinates from the object //ROS_INFO("Center x: %d, center y: %d\n", center.x, center.y); drawContours(cv_ptr->image, contours, largest_contour_index, Scalar(255), 1, 8, hierarchy); // Draw the largest contour using previously stored index. circle(cv_ptr->image, center, 3, Scalar(255,255,0), -1, 8, 0); // Draw dot in center of bb rectangle(cv_ptr->image, bounding_rect.tl(), bounding_rect.br(), Scalar(255,255,0), 2, 8, 0); // Draw bounding box imshow("original", cv_ptr->image); //show the original image camcenter = center.x; //Make a new node ros::NodeHandle nc; ros::Publisher ctr_pub = nc.advertise<std_msgs::Int32>("centerdata", 1); if (camcenter>0) { std_msgs::Int32 ctr; ctr.data = camcenter; ROS_INFO("center: %d", ctr.data); ctr_pub.publish(ctr); } ros::NodeHandle nd; ros::Publisher dpt_pub = nd.advertise<std_msgs::Int32>("depthdata", 1); if (camcenter>0) { std_msgs::Int32 dpt; dpt.data = depth; ROS_INFO("depth: %d", dpt.data); dpt_pub.publish(dpt); } } //Main function subscribes to the camera topics and enters them into the imageCallback function int main(int argc, char** argv) { ros::init(argc, argv, "opencvnode"); ros::NodeHandle nh; message_filters::Subscriber<CameraInfo> camera_info_sub(nh, "/camera/depth_registered/camera_info", 1); message_filters::Subscriber<Image> depth_image_sub(nh, "/camera/depth/image_raw", 1); message_filters::Subscriber<Image> rgb_image_sub(nh, "/camera/rgb/image_raw", 1); ros::NodeHandle nc; ros::Publisher ctr_pub = nc.advertise<std_msgs::Int32>("centerdata", 1); ros::NodeHandle nd; ros::Publisher dpt_pub = nd.advertise<std_msgs::Int32>("depthdata", 1); typedef sync_policies::ApproximateTime<Image, Image, CameraInfo> MySyncPolicy; Synchronizer<MySyncPolicy> sync(MySyncPolicy(1), rgb_image_sub, depth_image_sub, camera_info_sub); sync.registerCallback(boost::bind(&imageCallback, _1, _2, _3)); //cv::namedWindow(OPENCV_WINDOW); namedWindow("original", CV_WINDOW_AUTOSIZE); //create a window called "Control" namedWindow("hsv", CV_WINDOW_AUTOSIZE); //HSV Trackbar creation, these are bound to the colored image output window. cvCreateTrackbar("LowH", "original", &iLowH, 179); //Hue (0 - 179) cvCreateTrackbar("HighH", "original", &iHighH, 179); cvCreateTrackbar("LowS", "original", &iLowS, 255); //Saturation (0 - 255) cvCreateTrackbar("HighS", "original", &iHighS, 255); cvCreateTrackbar("LowV", "original", &iLowV, 255); //Value (0 - 255) cvCreateTrackbar("HighV", "original", &iHighV, 255); cvStartWindowThread(); ros::spin(); return 0; }
Update opencvros.cpp
Update opencvros.cpp
C++
mit
yacob1010/ros
b3d76c3426d65bfca4ca700d0c9be38b01ee5c17
gui/qtgsi/src/TQApplication.cxx
gui/qtgsi/src/TQApplication.cxx
// @(#)root/qtgsi:$Id$ // Author: Denis Bertini, M. Al-Turany 01/11/2000 /************************************************************************* * Copyright (C) 1995-2006, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TQApplication // // // // This class create the ROOT native GUI version of the ROOT // // application environment. This in contrast to the Win32 version. // // Once the native widgets work on Win32 this class can be folded into // // the TApplication class (since all graphic will go via TVirtualX). // // // ////////////////////////////////////////////////////////////////////////// #include "TROOT.h" #include "TQApplication.h" #include "TQRootGuiFactory.h" ClassImp(TQApplication) //______________________________________________________________________________ TQApplication::TQApplication() :TApplication() { // Used by Dictionary() } //______________________________________________________________________________ TQApplication::TQApplication(const char *appClassName, Int_t *argc, char **argv, void *options, Int_t numOptions) : TApplication(appClassName,argc,argv,options,numOptions) { // Create the root application and load the graphic libraries fCustomized=kFALSE; LoadGraphicsLibs(); } //______________________________________________________________________________ TQApplication::~TQApplication() { // Delete ROOT application environment. if (gApplication) gApplication->Terminate(0); } //______________________________________________________________________________ void TQApplication::LoadGraphicsLibs() { // Here we overload the LoadGraphicsLibs() function. // This function now just instantiates a QRootGuiFactory // object and redirect the global pointer gGuiFactory to point // to it. if (gROOT->IsBatch()) return; gROOT->LoadClass("TCanvas", "Gpad"); gGuiFactory = new TQRootGuiFactory(); } //______________________________________________________________________________ void TQApplication::SetCustomized() { // Set the custom flag fCustomized = kTRUE; if (fCustomized) ((TQRootGuiFactory*) gGuiFactory)->SetCustomFlag(kTRUE); }
// @(#)root/qtgsi:$Id$ // Author: Denis Bertini, M. Al-Turany 01/11/2000 /************************************************************************* * Copyright (C) 1995-2006, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TQApplication // // // // This class create the ROOT native GUI version of the ROOT // // application environment. This in contrast to the Win32 version. // // Once the native widgets work on Win32 this class can be folded into // // the TApplication class (since all graphic will go via TVirtualX). // // // ////////////////////////////////////////////////////////////////////////// #include "TROOT.h" #include "TQApplication.h" #include "TQRootGuiFactory.h" ClassImp(TQApplication) //______________________________________________________________________________ TQApplication::TQApplication() :TApplication() { // Used by Dictionary() fCustomized=kFALSE; } //______________________________________________________________________________ TQApplication::TQApplication(const char *appClassName, Int_t *argc, char **argv, void *options, Int_t numOptions) : TApplication(appClassName,argc,argv,options,numOptions) { // Create the root application and load the graphic libraries fCustomized=kFALSE; LoadGraphicsLibs(); } //______________________________________________________________________________ TQApplication::~TQApplication() { // Delete ROOT application environment. if (gApplication) gApplication->Terminate(0); } //______________________________________________________________________________ void TQApplication::LoadGraphicsLibs() { // Here we overload the LoadGraphicsLibs() function. // This function now just instantiates a QRootGuiFactory // object and redirect the global pointer gGuiFactory to point // to it. if (gROOT->IsBatch()) return; gROOT->LoadClass("TCanvas", "Gpad"); gGuiFactory = new TQRootGuiFactory(); } //______________________________________________________________________________ void TQApplication::SetCustomized() { // Set the custom flag fCustomized = kTRUE; if (fCustomized) ((TQRootGuiFactory*) gGuiFactory)->SetCustomFlag(kTRUE); }
Fix uninitialized variable (coverity)
Fix uninitialized variable (coverity) git-svn-id: acec3fd5b7ea1eb9e79d6329d318e8118ee2e14f@38438 27541ba8-7e3a-0410-8455-c3a389f83636
C++
lgpl-2.1
root-mirror/root,gbitzes/root,thomaskeck/root,root-mirror/root,buuck/root,gganis/root,omazapa/root,smarinac/root,sbinet/cxx-root,ffurano/root5,veprbl/root,jrtomps/root,gganis/root,esakellari/my_root_for_test,mkret2/root,esakellari/root,esakellari/my_root_for_test,esakellari/root,cxx-hep/root-cern,root-mirror/root,jrtomps/root,jrtomps/root,olifre/root,zzxuanyuan/root,beniz/root,lgiommi/root,olifre/root,gbitzes/root,tc3t/qoot,satyarth934/root,krafczyk/root,veprbl/root,perovic/root,BerserkerTroll/root,Duraznos/root,smarinac/root,veprbl/root,mkret2/root,evgeny-boger/root,krafczyk/root,arch1tect0r/root,kirbyherm/root-r-tools,veprbl/root,gbitzes/root,perovic/root,evgeny-boger/root,abhinavmoudgil95/root,sawenzel/root,pspe/root,mkret2/root,gbitzes/root,jrtomps/root,nilqed/root,omazapa/root,CristinaCristescu/root,karies/root,zzxuanyuan/root-compressor-dummy,tc3t/qoot,georgtroska/root,0x0all/ROOT,BerserkerTroll/root,sawenzel/root,agarciamontoro/root,zzxuanyuan/root,mkret2/root,mkret2/root,abhinavmoudgil95/root,georgtroska/root,vukasinmilosevic/root,root-mirror/root,CristinaCristescu/root,mhuwiler/rootauto,0x0all/ROOT,strykejern/TTreeReader,tc3t/qoot,0x0all/ROOT,zzxuanyuan/root,BerserkerTroll/root,agarciamontoro/root,georgtroska/root,mattkretz/root,karies/root,strykejern/TTreeReader,vukasinmilosevic/root,satyarth934/root,dfunke/root,thomaskeck/root,veprbl/root,mhuwiler/rootauto,beniz/root,cxx-hep/root-cern,zzxuanyuan/root-compressor-dummy,nilqed/root,buuck/root,thomaskeck/root,gbitzes/root,BerserkerTroll/root,smarinac/root,vukasinmilosevic/root,buuck/root,Dr15Jones/root,dfunke/root,zzxuanyuan/root,CristinaCristescu/root,esakellari/root,alexschlueter/cern-root,krafczyk/root,satyarth934/root,jrtomps/root,olifre/root,tc3t/qoot,esakellari/my_root_for_test,jrtomps/root,lgiommi/root,gganis/root,buuck/root,arch1tect0r/root,CristinaCristescu/root,mhuwiler/rootauto,strykejern/TTreeReader,thomaskeck/root,lgiommi/root,0x0all/ROOT,karies/root,zzxuanyuan/root-compressor-dummy,smarinac/root,beniz/root,sirinath/root,pspe/root,arch1tect0r/root,0x0all/ROOT,zzxuanyuan/root-compressor-dummy,buuck/root,cxx-hep/root-cern,abhinavmoudgil95/root,0x0all/ROOT,jrtomps/root,dfunke/root,strykejern/TTreeReader,agarciamontoro/root,gganis/root,krafczyk/root,evgeny-boger/root,zzxuanyuan/root-compressor-dummy,gbitzes/root,nilqed/root,0x0all/ROOT,root-mirror/root,arch1tect0r/root,pspe/root,alexschlueter/cern-root,pspe/root,omazapa/root,zzxuanyuan/root-compressor-dummy,krafczyk/root,beniz/root,kirbyherm/root-r-tools,sirinath/root,esakellari/my_root_for_test,evgeny-boger/root,simonpf/root,davidlt/root,agarciamontoro/root,gbitzes/root,mkret2/root,perovic/root,omazapa/root-old,abhinavmoudgil95/root,karies/root,satyarth934/root,perovic/root,0x0all/ROOT,nilqed/root,buuck/root,agarciamontoro/root,sbinet/cxx-root,simonpf/root,Y--/root,omazapa/root-old,alexschlueter/cern-root,dfunke/root,agarciamontoro/root,gganis/root,simonpf/root,davidlt/root,krafczyk/root,Y--/root,Duraznos/root,CristinaCristescu/root,mhuwiler/rootauto,jrtomps/root,CristinaCristescu/root,olifre/root,olifre/root,esakellari/my_root_for_test,bbockelm/root,agarciamontoro/root,davidlt/root,vukasinmilosevic/root,mhuwiler/rootauto,root-mirror/root,beniz/root,georgtroska/root,sawenzel/root,dfunke/root,olifre/root,olifre/root,thomaskeck/root,abhinavmoudgil95/root,smarinac/root,arch1tect0r/root,zzxuanyuan/root,mhuwiler/rootauto,arch1tect0r/root,Duraznos/root,sirinath/root,bbockelm/root,vukasinmilosevic/root,esakellari/root,cxx-hep/root-cern,esakellari/root,pspe/root,gbitzes/root,vukasinmilosevic/root,BerserkerTroll/root,smarinac/root,omazapa/root-old,sawenzel/root,gbitzes/root,davidlt/root,root-mirror/root,beniz/root,root-mirror/root,lgiommi/root,perovic/root,sirinath/root,mkret2/root,sbinet/cxx-root,Y--/root,vukasinmilosevic/root,davidlt/root,lgiommi/root,CristinaCristescu/root,davidlt/root,lgiommi/root,tc3t/qoot,thomaskeck/root,BerserkerTroll/root,perovic/root,georgtroska/root,abhinavmoudgil95/root,evgeny-boger/root,Duraznos/root,mattkretz/root,sirinath/root,lgiommi/root,mhuwiler/rootauto,mattkretz/root,thomaskeck/root,Duraznos/root,ffurano/root5,sirinath/root,Y--/root,simonpf/root,vukasinmilosevic/root,kirbyherm/root-r-tools,vukasinmilosevic/root,zzxuanyuan/root,omazapa/root,omazapa/root-old,cxx-hep/root-cern,olifre/root,satyarth934/root,abhinavmoudgil95/root,gganis/root,omazapa/root-old,alexschlueter/cern-root,olifre/root,pspe/root,pspe/root,mkret2/root,perovic/root,sawenzel/root,alexschlueter/cern-root,olifre/root,strykejern/TTreeReader,beniz/root,BerserkerTroll/root,simonpf/root,cxx-hep/root-cern,sirinath/root,simonpf/root,sbinet/cxx-root,Duraznos/root,sbinet/cxx-root,Y--/root,zzxuanyuan/root,karies/root,perovic/root,sawenzel/root,evgeny-boger/root,thomaskeck/root,arch1tect0r/root,kirbyherm/root-r-tools,dfunke/root,omazapa/root-old,mhuwiler/rootauto,krafczyk/root,smarinac/root,veprbl/root,ffurano/root5,krafczyk/root,Dr15Jones/root,Y--/root,omazapa/root,evgeny-boger/root,vukasinmilosevic/root,arch1tect0r/root,BerserkerTroll/root,gbitzes/root,0x0all/ROOT,arch1tect0r/root,georgtroska/root,mkret2/root,jrtomps/root,sawenzel/root,pspe/root,sirinath/root,nilqed/root,esakellari/my_root_for_test,veprbl/root,nilqed/root,simonpf/root,ffurano/root5,tc3t/qoot,beniz/root,agarciamontoro/root,abhinavmoudgil95/root,evgeny-boger/root,gganis/root,omazapa/root-old,dfunke/root,ffurano/root5,ffurano/root5,Duraznos/root,sbinet/cxx-root,zzxuanyuan/root,smarinac/root,lgiommi/root,Duraznos/root,zzxuanyuan/root,Y--/root,cxx-hep/root-cern,omazapa/root,thomaskeck/root,abhinavmoudgil95/root,mattkretz/root,esakellari/root,zzxuanyuan/root-compressor-dummy,nilqed/root,mhuwiler/rootauto,karies/root,gbitzes/root,buuck/root,sbinet/cxx-root,jrtomps/root,omazapa/root,root-mirror/root,zzxuanyuan/root-compressor-dummy,veprbl/root,simonpf/root,Dr15Jones/root,mattkretz/root,zzxuanyuan/root,omazapa/root-old,buuck/root,mattkretz/root,georgtroska/root,esakellari/my_root_for_test,bbockelm/root,omazapa/root-old,lgiommi/root,esakellari/root,zzxuanyuan/root-compressor-dummy,agarciamontoro/root,karies/root,beniz/root,esakellari/root,gganis/root,satyarth934/root,CristinaCristescu/root,root-mirror/root,krafczyk/root,arch1tect0r/root,sbinet/cxx-root,krafczyk/root,strykejern/TTreeReader,davidlt/root,buuck/root,mkret2/root,abhinavmoudgil95/root,nilqed/root,karies/root,zzxuanyuan/root,mattkretz/root,dfunke/root,bbockelm/root,sbinet/cxx-root,satyarth934/root,tc3t/qoot,gganis/root,mkret2/root,mhuwiler/rootauto,bbockelm/root,satyarth934/root,agarciamontoro/root,vukasinmilosevic/root,Dr15Jones/root,esakellari/my_root_for_test,esakellari/root,BerserkerTroll/root,sirinath/root,bbockelm/root,bbockelm/root,sbinet/cxx-root,krafczyk/root,sawenzel/root,dfunke/root,davidlt/root,Duraznos/root,gganis/root,veprbl/root,tc3t/qoot,arch1tect0r/root,veprbl/root,beniz/root,zzxuanyuan/root-compressor-dummy,smarinac/root,smarinac/root,bbockelm/root,nilqed/root,cxx-hep/root-cern,buuck/root,pspe/root,CristinaCristescu/root,omazapa/root,zzxuanyuan/root-compressor-dummy,thomaskeck/root,tc3t/qoot,alexschlueter/cern-root,mattkretz/root,sawenzel/root,strykejern/TTreeReader,satyarth934/root,BerserkerTroll/root,Y--/root,buuck/root,esakellari/my_root_for_test,esakellari/my_root_for_test,simonpf/root,davidlt/root,karies/root,beniz/root,perovic/root,omazapa/root-old,perovic/root,kirbyherm/root-r-tools,karies/root,davidlt/root,davidlt/root,bbockelm/root,bbockelm/root,jrtomps/root,simonpf/root,satyarth934/root,veprbl/root,Dr15Jones/root,evgeny-boger/root,Y--/root,omazapa/root-old,omazapa/root,sbinet/cxx-root,georgtroska/root,lgiommi/root,Y--/root,esakellari/root,zzxuanyuan/root,CristinaCristescu/root,tc3t/qoot,karies/root,dfunke/root,bbockelm/root,pspe/root,georgtroska/root,gganis/root,Y--/root,georgtroska/root,satyarth934/root,kirbyherm/root-r-tools,sawenzel/root,sirinath/root,simonpf/root,mattkretz/root,kirbyherm/root-r-tools,evgeny-boger/root,abhinavmoudgil95/root,dfunke/root,mhuwiler/rootauto,georgtroska/root,alexschlueter/cern-root,perovic/root,esakellari/root,CristinaCristescu/root,Dr15Jones/root,sirinath/root,BerserkerTroll/root,agarciamontoro/root,lgiommi/root,root-mirror/root,evgeny-boger/root,Duraznos/root,mattkretz/root,omazapa/root,nilqed/root,olifre/root,mattkretz/root,ffurano/root5,Duraznos/root,omazapa/root,pspe/root,sawenzel/root,nilqed/root,Dr15Jones/root
b6e505dd9b7bfe8c89c393de6c070c2db0c9b190
src/MCJITHelper.hpp
src/MCJITHelper.hpp
#ifndef MCJITHELPER_HPP #define MCJITHELPER_HPP #include <string> #include <vector> #include <memory> #include <llvm/Analysis/Passes.h> #include <llvm/IR/LLVMContext.h> #include <llvm/IR/Module.h> #include <llvm/IR/Function.h> #include <llvm/IR/LegacyPassManager.h> #include <llvm/Transforms/Scalar.h> #include <llvm/ExecutionEngine/MCJIT.h> #include <llvm/ExecutionEngine/SectionMemoryManager.h> class MCJITHelper { public: MCJITHelper(llvm::LLVMContext& C) : Context(C), OpenModule(NULL) {} ~MCJITHelper(); llvm::Function *getFunction(const std::string FnName); llvm::Module *getModuleForNewFunction(std::string &FnName); void *getPointerToFunction(llvm::Function *F); void *getPointerToNamedFunction(const std::string &Name); llvm::ExecutionEngine *compileModule(llvm::Module *M); void closeCurrentModule(); void dump(); private: typedef std::vector<llvm::Module*> ModuleVector; llvm::LLVMContext &Context; llvm::Module *OpenModule; ModuleVector Modules; std::map<llvm::Module*, llvm::ExecutionEngine*> EngineMap; }; class HelpingMemoryManager : public llvm::SectionMemoryManager { HelpingMemoryManager(const HelpingMemoryManager&) = delete; void operator=(const HelpingMemoryManager&) = delete; public: HelpingMemoryManager(MCJITHelper *Helper) : MasterHelper(Helper) {} virtual ~HelpingMemoryManager() {} /// This method returns the address of the specified function. /// Our implementation will attempt to find functions in other /// modules associated with the MCJITHelper to cross link functions /// from one generated module to another. /// /// If \p AbortOnFailure is false and no function with the given name is /// found, this function returns a null pointer. Otherwise, it prints a /// message to stderr and aborts. virtual void *getPointerToNamedFunction(const std::string &Name, bool AbortOnFailure = true); private: MCJITHelper *MasterHelper; }; void *HelpingMemoryManager::getPointerToNamedFunction(const std::string &Name, bool AbortOnFailure) { // Try the standard symbol resolution first, but ask it not to abort. void *pfn = SectionMemoryManager::getPointerToNamedFunction(Name, false); if (pfn) return pfn; pfn = MasterHelper->getPointerToNamedFunction(Name); if (!pfn && AbortOnFailure) llvm::report_fatal_error("Program used external function '" + Name + "' which could not be resolved!"); return pfn; } MCJITHelper::~MCJITHelper() { // Walk the vector of modules. ModuleVector::iterator it, end; for (it = Modules.begin(), end = Modules.end(); it != end; ++it) { // See if we have an execution engine for this module. auto mapIt = EngineMap.find(*it); // If we have an EE, the EE owns the module so just delete the EE. if (mapIt != EngineMap.end()) { delete mapIt->second; } else { // Otherwise, we still own the module. Delete it now. delete *it; } } } llvm::Function* MCJITHelper::getFunction(const std::string FnName) { ModuleVector::iterator begin = Modules.begin(); ModuleVector::iterator end = Modules.end(); ModuleVector::iterator it; for (it = begin; it != end; ++it) { llvm::Function *F = (*it)->getFunction(FnName); if (F) { if (*it == OpenModule) return F; assert(OpenModule != NULL); // This function is in a module that has already been JITed. // We need to generate a new prototype for external linkage. llvm::Function *PF = OpenModule->getFunction(FnName); if (PF && !PF->empty()) { PRINTERR("redefinition of function across modules"); return 0; } // If we don't have a prototype yet, create one. if (!PF) PF = llvm::Function::Create(F->getFunctionType(), llvm::Function::ExternalLinkage, FnName, OpenModule); return PF; } } return NULL; } llvm::Module* MCJITHelper::getModuleForNewFunction(std::string &FnName) { // If we have a Module that hasn't been JITed, use that. if (OpenModule) return OpenModule; // Otherwise create a new Module. std::string ModName("module_" + FnName); llvm::Module *M = new llvm::Module(ModName, Context); Modules.push_back(M); OpenModule = M; return M; } void* MCJITHelper::getPointerToFunction(llvm::Function* F) { // Look for this function in an existing module ModuleVector::iterator begin = Modules.begin(); ModuleVector::iterator end = Modules.end(); ModuleVector::iterator it; std::string FnName = F->getName(); for (it = begin; it != end; ++it) { llvm::Function *MF = (*it)->getFunction(FnName); if (MF == F) { auto eeIt = EngineMap.find(*it); if (eeIt != EngineMap.end()) { void *P = eeIt->second->getPointerToFunction(F); if (P) return P; } else { llvm::ExecutionEngine *EE = compileModule(*it); void *P = EE->getPointerToFunction(F); if (P) return P; } } } return NULL; } void MCJITHelper::closeCurrentModule() { OpenModule = NULL; } llvm::ExecutionEngine* MCJITHelper::compileModule(llvm::Module *M) { if (M == OpenModule) closeCurrentModule(); std::string ErrStr; llvm::ExecutionEngine *NewEngine = llvm::EngineBuilder(std::unique_ptr<llvm::Module>(M)) .setErrorStr(&ErrStr) .setMCJITMemoryManager(llvm::make_unique<HelpingMemoryManager>(this)) .create(); if (!NewEngine) { PRINTERR("Could not create ExecutionEngine: %s\n", ErrStr.c_str()); exit(1); } // Create a function pass manager for this engine llvm::legacy::FunctionPassManager *FPM = new llvm::legacy::FunctionPassManager(M); // Set up the optimizer pipeline. Start with registering info about how the // target lays out data structures. M->setDataLayout(NewEngine->getDataLayout()); //FPM->add(new llvm::DataLayout(*NewEngine->getDataLayout())); // Provide basic AliasAnalysis support for GVN. FPM->add(llvm::createBasicAliasAnalysisPass()); // Promote allocas to registers. FPM->add(llvm::createPromoteMemoryToRegisterPass()); // Do simple "peephole" optimizations and bit-twiddling optzns. FPM->add(llvm::createInstructionCombiningPass()); // Reassociate expressions. FPM->add(llvm::createReassociatePass()); // Eliminate Common SubExpressions. FPM->add(llvm::createGVNPass()); // Simplify the control flow graph (deleting unreachable blocks, etc). FPM->add(llvm::createCFGSimplificationPass()); FPM->doInitialization(); // For each function in the module llvm::Module::iterator it; llvm::Module::iterator end = M->end(); for (it = M->begin(); it != end; ++it) { // Run the FPM on this function FPM->run(*it); } // We don't need this anymore delete FPM; // Store this engine EngineMap[M] = NewEngine; NewEngine->finalizeObject(); return NewEngine; } void *MCJITHelper::getPointerToNamedFunction(const std::string &Name) { // Look for the functions in our modules, compiling only as necessary ModuleVector::iterator begin = Modules.begin(); ModuleVector::iterator end = Modules.end(); ModuleVector::iterator it; for (it = begin; it != end; ++it) { llvm::Function *F = (*it)->getFunction(Name); if (F && !F->empty()) { auto eeIt = EngineMap.find(*it); if (eeIt != EngineMap.end()) { void *P = eeIt->second->getPointerToFunction(F); if (P) return P; } else { llvm::ExecutionEngine *EE = compileModule(*it); void *P = EE->getPointerToFunction(F); if (P) return P; } } } return NULL; } void MCJITHelper::dump() { ModuleVector::iterator begin = Modules.begin(); ModuleVector::iterator end = Modules.end(); ModuleVector::iterator it; for (it = begin; it != end; ++it) (*it)->dump(); } #endif // MCJITHELPER_HPP
#ifndef MCJITHELPER_HPP #define MCJITHELPER_HPP #include <string> #include <vector> #include <memory> #include <llvm/Analysis/Passes.h> #include <llvm/IR/LLVMContext.h> #include <llvm/IR/Module.h> #include <llvm/IR/Function.h> #include <llvm/IR/LegacyPassManager.h> #include <llvm/Transforms/Scalar.h> #include <llvm/ExecutionEngine/MCJIT.h> #include <llvm/ExecutionEngine/SectionMemoryManager.h> class MCJITHelper { public: MCJITHelper(llvm::LLVMContext& C) : Context(C), OpenModule(NULL) {} ~MCJITHelper(); llvm::Function *getFunction(const std::string FnName); llvm::Module *getModuleForNewFunction(std::string &FnName); void *getPointerToFunction(llvm::Function *F); void *getPointerToNamedFunction(const std::string &Name); llvm::ExecutionEngine *compileModule(llvm::Module *M); void closeCurrentModule(); void dump(); private: typedef std::vector<llvm::Module*> ModuleVector; llvm::LLVMContext &Context; llvm::Module *OpenModule; ModuleVector Modules; std::map<llvm::Module*, llvm::ExecutionEngine*> EngineMap; }; class HelpingMemoryManager : public llvm::SectionMemoryManager { HelpingMemoryManager(const HelpingMemoryManager&) = delete; void operator=(const HelpingMemoryManager&) = delete; public: HelpingMemoryManager(MCJITHelper *Helper) : MasterHelper(Helper) {} virtual ~HelpingMemoryManager() {} /// This method returns the address of the specified function. /// Our implementation will attempt to find functions in other /// modules associated with the MCJITHelper to cross link functions /// from one generated module to another. /// /// If \p AbortOnFailure is false and no function with the given name is /// found, this function returns a null pointer. Otherwise, it prints a /// message to stderr and aborts. virtual void *getPointerToNamedFunction(const std::string &Name, bool AbortOnFailure = true); private: MCJITHelper *MasterHelper; }; void *HelpingMemoryManager::getPointerToNamedFunction(const std::string &Name, bool AbortOnFailure) { // Try the standard symbol resolution first, but ask it not to abort. void *pfn = SectionMemoryManager::getPointerToNamedFunction(Name, false); if (pfn) return pfn; pfn = MasterHelper->getPointerToNamedFunction(Name); if (!pfn && AbortOnFailure) llvm::report_fatal_error("Program used external function '" + Name + "' which could not be resolved!"); return pfn; } MCJITHelper::~MCJITHelper() { // Walk the vector of modules. ModuleVector::iterator it, end; for (it = Modules.begin(), end = Modules.end(); it != end; ++it) { // See if we have an execution engine for this module. auto mapIt = EngineMap.find(*it); // If we have an EE, the EE owns the module so just delete the EE. if (mapIt != EngineMap.end()) { delete mapIt->second; } else { // Otherwise, we still own the module. Delete it now. delete *it; } } } llvm::Function* MCJITHelper::getFunction(const std::string FnName) { ModuleVector::iterator begin = Modules.begin(); ModuleVector::iterator end = Modules.end(); ModuleVector::iterator it; for (it = begin; it != end; ++it) { llvm::Function *F = (*it)->getFunction(FnName); if (F) { if (*it == OpenModule) return F; assert(OpenModule != NULL); // This function is in a module that has already been JITed. // We need to generate a new prototype for external linkage. llvm::Function *PF = OpenModule->getFunction(FnName); if (PF && !PF->empty()) { PRINTERR("redefinition of function across modules"); return 0; } // If we don't have a prototype yet, create one. if (!PF) PF = llvm::Function::Create(F->getFunctionType(), llvm::Function::ExternalLinkage, FnName, OpenModule); return PF; } } return NULL; } llvm::Module* MCJITHelper::getModuleForNewFunction(std::string &FnName) { // If we have a Module that hasn't been JITed, use that. if (OpenModule) return OpenModule; // Otherwise create a new Module. std::string ModName("module_" + FnName); llvm::Module *M = new llvm::Module(ModName, Context); Modules.push_back(M); OpenModule = M; return M; } void* MCJITHelper::getPointerToFunction(llvm::Function* F) { // Look for this function in an existing module ModuleVector::iterator begin = Modules.begin(); ModuleVector::iterator end = Modules.end(); ModuleVector::iterator it; std::string FnName = F->getName(); for (it = begin; it != end; ++it) { llvm::Function *MF = (*it)->getFunction(FnName); if (MF == F) { auto eeIt = EngineMap.find(*it); if (eeIt != EngineMap.end()) { void *P = eeIt->second->getPointerToFunction(F); if (P) return P; } else { llvm::ExecutionEngine *EE = compileModule(*it); void *P = EE->getPointerToFunction(F); if (P) return P; } } } return NULL; } void MCJITHelper::closeCurrentModule() { OpenModule = NULL; } llvm::ExecutionEngine* MCJITHelper::compileModule(llvm::Module *M) { if (M == OpenModule) closeCurrentModule(); std::string ErrStr; llvm::ExecutionEngine *NewEngine = llvm::EngineBuilder(std::unique_ptr<llvm::Module>(M)) .setErrorStr(&ErrStr) .setMCJITMemoryManager(llvm::make_unique<HelpingMemoryManager>(this)) .create(); if (!NewEngine) { PRINTERR("Could not create ExecutionEngine: %s\n", ErrStr.c_str()); exit(1); } // Create a function pass manager for this engine llvm::legacy::FunctionPassManager *FPM = new llvm::legacy::FunctionPassManager(M); // Set up the optimizer pipeline. Start with registering info about how the // target lays out data structures. #if LLVM_VERSION_MINOR >= 7 M->setDataLayout(*NewEngine->getDataLayout()); #else M->setDataLayout(NewEngine->getDataLayout()); #endif // LLVM_VERSION_MINOR >= 7 //FPM->add(new llvm::DataLayout(*NewEngine->getDataLayout())); // Provide basic AliasAnalysis support for GVN. FPM->add(llvm::createBasicAliasAnalysisPass()); // Promote allocas to registers. FPM->add(llvm::createPromoteMemoryToRegisterPass()); // Do simple "peephole" optimizations and bit-twiddling optzns. FPM->add(llvm::createInstructionCombiningPass()); // Reassociate expressions. FPM->add(llvm::createReassociatePass()); // Eliminate Common SubExpressions. FPM->add(llvm::createGVNPass()); // Simplify the control flow graph (deleting unreachable blocks, etc). FPM->add(llvm::createCFGSimplificationPass()); FPM->doInitialization(); // For each function in the module llvm::Module::iterator it; llvm::Module::iterator end = M->end(); for (it = M->begin(); it != end; ++it) { // Run the FPM on this function FPM->run(*it); } // We don't need this anymore delete FPM; // Store this engine EngineMap[M] = NewEngine; NewEngine->finalizeObject(); return NewEngine; } void *MCJITHelper::getPointerToNamedFunction(const std::string &Name) { // Look for the functions in our modules, compiling only as necessary ModuleVector::iterator begin = Modules.begin(); ModuleVector::iterator end = Modules.end(); ModuleVector::iterator it; for (it = begin; it != end; ++it) { llvm::Function *F = (*it)->getFunction(Name); if (F && !F->empty()) { auto eeIt = EngineMap.find(*it); if (eeIt != EngineMap.end()) { void *P = eeIt->second->getPointerToFunction(F); if (P) return P; } else { llvm::ExecutionEngine *EE = compileModule(*it); void *P = EE->getPointerToFunction(F); if (P) return P; } } } return NULL; } void MCJITHelper::dump() { ModuleVector::iterator begin = Modules.begin(); ModuleVector::iterator end = Modules.end(); ModuleVector::iterator it; for (it = begin; it != end; ++it) (*it)->dump(); } #endif // MCJITHELPER_HPP
fix for LLVM 3.7
fix for LLVM 3.7
C++
bsd-3-clause
ytakano/tsukuyomi,ytakano/tsukuyomi
9fdf16201e1332f1c02c5592c54ad5c9c3440427
roofit/roostats/src/SequentialProposal.cxx
roofit/roostats/src/SequentialProposal.cxx
// @(#)root/roostats:$Id$ // Authors: Giovanni Petrucciani 4/21/2011 /************************************************************************* * Copyright (C) 1995-2008, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #include "RooStats/SequentialProposal.h" #include <RooArgSet.h> #include <iostream> #include <memory> #include <TIterator.h> #include <RooRandom.h> #include <RooStats/RooStatsUtils.h> ClassImp(RooStats::SequentialProposal) namespace RooStats { SequentialProposal::SequentialProposal(double divisor) : ProposalFunction(), fDivisor(1./divisor) { } // Populate xPrime with a new proposed point void SequentialProposal::Propose(RooArgSet& xPrime, RooArgSet& x ) { RooStats::SetParameters(&x, &xPrime); std::auto_ptr<TIterator> it(xPrime.createIterator()); RooRealVar* var; int n = xPrime.getSize(), j = floor(RooRandom::uniform()*n); for (int i = 0; (var = (RooRealVar*)it->Next()) != NULL; ++i) { if (i == j) { double val = var->getVal(), max = var->getMax(), min = var->getMin(), len = max - min; val += RooRandom::gaussian() * len * fDivisor; while (val > max) val -= len; while (val < min) val += len; var->setVal(val); //std::cout << "Proposing a step along " << var->GetName() << std::endl; } } } Bool_t SequentialProposal::IsSymmetric(RooArgSet& , RooArgSet& ) { return true; } // Return the probability of proposing the point x1 given the starting // point x2 Double_t SequentialProposal::GetProposalDensity(RooArgSet& , RooArgSet& ) { return 1.0; // should not be needed } }
// @(#)root/roostats:$Id$ // Authors: Giovanni Petrucciani 4/21/2011 /************************************************************************* * Copyright (C) 1995-2008, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #include "RooStats/SequentialProposal.h" #include <RooArgSet.h> #include <iostream> #include <memory> #include <TIterator.h> #include <RooRandom.h> #include <RooStats/RooStatsUtils.h> ClassImp(RooStats::SequentialProposal) namespace RooStats { SequentialProposal::SequentialProposal(double divisor) : ProposalFunction(), fDivisor(1./divisor) { } // Populate xPrime with a new proposed point void SequentialProposal::Propose(RooArgSet& xPrime, RooArgSet& x ) { RooStats::SetParameters(&x, &xPrime); std::auto_ptr<TIterator> it(xPrime.createIterator()); RooRealVar* var; int n = xPrime.getSize(); int j = int( floor(RooRandom::uniform()*n) ); for (int i = 0; (var = (RooRealVar*)it->Next()) != NULL; ++i) { if (i == j) { double val = var->getVal(), max = var->getMax(), min = var->getMin(), len = max - min; val += RooRandom::gaussian() * len * fDivisor; while (val > max) val -= len; while (val < min) val += len; var->setVal(val); //std::cout << "Proposing a step along " << var->GetName() << std::endl; } } } Bool_t SequentialProposal::IsSymmetric(RooArgSet& , RooArgSet& ) { return true; } // Return the probability of proposing the point x1 given the starting // point x2 Double_t SequentialProposal::GetProposalDensity(RooArgSet& , RooArgSet& ) { return 1.0; // should not be needed } }
fix a compilation warning
fix a compilation warning git-svn-id: acec3fd5b7ea1eb9e79d6329d318e8118ee2e14f@39005 27541ba8-7e3a-0410-8455-c3a389f83636
C++
lgpl-2.1
root-mirror/root,jrtomps/root,buuck/root,CristinaCristescu/root,esakellari/my_root_for_test,tc3t/qoot,ffurano/root5,omazapa/root,thomaskeck/root,ffurano/root5,georgtroska/root,strykejern/TTreeReader,abhinavmoudgil95/root,georgtroska/root,sawenzel/root,tc3t/qoot,kirbyherm/root-r-tools,mkret2/root,sirinath/root,tc3t/qoot,tc3t/qoot,pspe/root,esakellari/root,tc3t/qoot,evgeny-boger/root,arch1tect0r/root,BerserkerTroll/root,tc3t/qoot,tc3t/qoot,beniz/root,simonpf/root,nilqed/root,bbockelm/root,karies/root,agarciamontoro/root,sawenzel/root,mhuwiler/rootauto,Duraznos/root,mattkretz/root,buuck/root,Y--/root,evgeny-boger/root,alexschlueter/cern-root,kirbyherm/root-r-tools,olifre/root,zzxuanyuan/root-compressor-dummy,perovic/root,dfunke/root,esakellari/my_root_for_test,karies/root,strykejern/TTreeReader,mkret2/root,satyarth934/root,satyarth934/root,kirbyherm/root-r-tools,gbitzes/root,vukasinmilosevic/root,mkret2/root,esakellari/my_root_for_test,omazapa/root,vukasinmilosevic/root,Dr15Jones/root,gbitzes/root,pspe/root,zzxuanyuan/root-compressor-dummy,zzxuanyuan/root-compressor-dummy,mhuwiler/rootauto,agarciamontoro/root,thomaskeck/root,bbockelm/root,satyarth934/root,zzxuanyuan/root,gganis/root,vukasinmilosevic/root,georgtroska/root,agarciamontoro/root,Duraznos/root,Y--/root,dfunke/root,krafczyk/root,vukasinmilosevic/root,bbockelm/root,Y--/root,jrtomps/root,nilqed/root,vukasinmilosevic/root,gbitzes/root,sirinath/root,zzxuanyuan/root,omazapa/root-old,veprbl/root,ffurano/root5,lgiommi/root,Duraznos/root,olifre/root,Duraznos/root,Duraznos/root,karies/root,esakellari/root,Dr15Jones/root,davidlt/root,agarciamontoro/root,zzxuanyuan/root-compressor-dummy,veprbl/root,zzxuanyuan/root,veprbl/root,smarinac/root,gbitzes/root,simonpf/root,satyarth934/root,bbockelm/root,veprbl/root,thomaskeck/root,gbitzes/root,pspe/root,alexschlueter/cern-root,perovic/root,buuck/root,simonpf/root,jrtomps/root,Dr15Jones/root,abhinavmoudgil95/root,sirinath/root,buuck/root,CristinaCristescu/root,olifre/root,CristinaCristescu/root,esakellari/root,simonpf/root,pspe/root,sirinath/root,beniz/root,beniz/root,beniz/root,davidlt/root,davidlt/root,perovic/root,satyarth934/root,mattkretz/root,abhinavmoudgil95/root,CristinaCristescu/root,abhinavmoudgil95/root,mattkretz/root,cxx-hep/root-cern,davidlt/root,root-mirror/root,kirbyherm/root-r-tools,omazapa/root,mhuwiler/rootauto,mhuwiler/rootauto,sbinet/cxx-root,esakellari/my_root_for_test,arch1tect0r/root,georgtroska/root,cxx-hep/root-cern,sawenzel/root,mhuwiler/rootauto,mattkretz/root,Duraznos/root,abhinavmoudgil95/root,sbinet/cxx-root,zzxuanyuan/root,zzxuanyuan/root-compressor-dummy,zzxuanyuan/root,Y--/root,esakellari/my_root_for_test,mattkretz/root,dfunke/root,nilqed/root,evgeny-boger/root,krafczyk/root,gbitzes/root,zzxuanyuan/root-compressor-dummy,smarinac/root,bbockelm/root,CristinaCristescu/root,mkret2/root,0x0all/ROOT,nilqed/root,CristinaCristescu/root,jrtomps/root,zzxuanyuan/root-compressor-dummy,CristinaCristescu/root,0x0all/ROOT,buuck/root,omazapa/root,omazapa/root-old,simonpf/root,arch1tect0r/root,davidlt/root,esakellari/root,perovic/root,sbinet/cxx-root,pspe/root,evgeny-boger/root,Dr15Jones/root,sawenzel/root,smarinac/root,0x0all/ROOT,omazapa/root-old,evgeny-boger/root,dfunke/root,sirinath/root,karies/root,thomaskeck/root,olifre/root,evgeny-boger/root,satyarth934/root,ffurano/root5,abhinavmoudgil95/root,bbockelm/root,strykejern/TTreeReader,thomaskeck/root,0x0all/ROOT,pspe/root,buuck/root,Y--/root,veprbl/root,thomaskeck/root,krafczyk/root,veprbl/root,buuck/root,simonpf/root,veprbl/root,lgiommi/root,bbockelm/root,esakellari/root,krafczyk/root,agarciamontoro/root,nilqed/root,Y--/root,mhuwiler/rootauto,jrtomps/root,abhinavmoudgil95/root,karies/root,buuck/root,strykejern/TTreeReader,pspe/root,krafczyk/root,gganis/root,esakellari/my_root_for_test,veprbl/root,sbinet/cxx-root,nilqed/root,perovic/root,omazapa/root,zzxuanyuan/root,Y--/root,satyarth934/root,tc3t/qoot,nilqed/root,olifre/root,gganis/root,davidlt/root,abhinavmoudgil95/root,jrtomps/root,esakellari/root,beniz/root,zzxuanyuan/root-compressor-dummy,0x0all/ROOT,CristinaCristescu/root,Dr15Jones/root,alexschlueter/cern-root,mkret2/root,lgiommi/root,simonpf/root,krafczyk/root,smarinac/root,karies/root,satyarth934/root,Duraznos/root,vukasinmilosevic/root,jrtomps/root,root-mirror/root,alexschlueter/cern-root,agarciamontoro/root,BerserkerTroll/root,BerserkerTroll/root,sawenzel/root,zzxuanyuan/root-compressor-dummy,davidlt/root,Duraznos/root,cxx-hep/root-cern,esakellari/my_root_for_test,sirinath/root,arch1tect0r/root,agarciamontoro/root,davidlt/root,veprbl/root,omazapa/root,omazapa/root-old,cxx-hep/root-cern,agarciamontoro/root,zzxuanyuan/root,mkret2/root,omazapa/root,dfunke/root,simonpf/root,esakellari/root,agarciamontoro/root,gganis/root,ffurano/root5,mattkretz/root,zzxuanyuan/root-compressor-dummy,veprbl/root,zzxuanyuan/root,vukasinmilosevic/root,evgeny-boger/root,satyarth934/root,mhuwiler/rootauto,perovic/root,jrtomps/root,buuck/root,perovic/root,buuck/root,arch1tect0r/root,ffurano/root5,CristinaCristescu/root,alexschlueter/cern-root,gbitzes/root,olifre/root,mhuwiler/rootauto,root-mirror/root,BerserkerTroll/root,sirinath/root,omazapa/root,smarinac/root,gganis/root,CristinaCristescu/root,kirbyherm/root-r-tools,gbitzes/root,beniz/root,pspe/root,krafczyk/root,cxx-hep/root-cern,root-mirror/root,pspe/root,esakellari/root,gganis/root,esakellari/root,gganis/root,alexschlueter/cern-root,dfunke/root,abhinavmoudgil95/root,root-mirror/root,mattkretz/root,smarinac/root,zzxuanyuan/root,beniz/root,CristinaCristescu/root,arch1tect0r/root,lgiommi/root,sbinet/cxx-root,root-mirror/root,sawenzel/root,nilqed/root,mhuwiler/rootauto,georgtroska/root,sbinet/cxx-root,sirinath/root,arch1tect0r/root,perovic/root,satyarth934/root,zzxuanyuan/root,arch1tect0r/root,georgtroska/root,Duraznos/root,karies/root,buuck/root,olifre/root,krafczyk/root,olifre/root,Duraznos/root,vukasinmilosevic/root,simonpf/root,arch1tect0r/root,beniz/root,mattkretz/root,thomaskeck/root,nilqed/root,jrtomps/root,omazapa/root,Dr15Jones/root,BerserkerTroll/root,evgeny-boger/root,dfunke/root,root-mirror/root,georgtroska/root,lgiommi/root,georgtroska/root,bbockelm/root,smarinac/root,simonpf/root,omazapa/root-old,strykejern/TTreeReader,tc3t/qoot,bbockelm/root,olifre/root,omazapa/root-old,esakellari/root,lgiommi/root,0x0all/ROOT,thomaskeck/root,BerserkerTroll/root,georgtroska/root,karies/root,Y--/root,esakellari/my_root_for_test,zzxuanyuan/root-compressor-dummy,mkret2/root,georgtroska/root,arch1tect0r/root,lgiommi/root,Dr15Jones/root,esakellari/my_root_for_test,mattkretz/root,strykejern/TTreeReader,BerserkerTroll/root,BerserkerTroll/root,cxx-hep/root-cern,krafczyk/root,sirinath/root,georgtroska/root,lgiommi/root,root-mirror/root,mkret2/root,sbinet/cxx-root,sbinet/cxx-root,bbockelm/root,zzxuanyuan/root,bbockelm/root,omazapa/root,dfunke/root,sirinath/root,mhuwiler/rootauto,kirbyherm/root-r-tools,evgeny-boger/root,root-mirror/root,cxx-hep/root-cern,agarciamontoro/root,nilqed/root,karies/root,Y--/root,BerserkerTroll/root,mkret2/root,smarinac/root,mkret2/root,jrtomps/root,0x0all/ROOT,omazapa/root,simonpf/root,lgiommi/root,0x0all/ROOT,ffurano/root5,perovic/root,lgiommi/root,krafczyk/root,Y--/root,dfunke/root,cxx-hep/root-cern,Duraznos/root,omazapa/root-old,dfunke/root,thomaskeck/root,vukasinmilosevic/root,thomaskeck/root,sbinet/cxx-root,omazapa/root-old,perovic/root,evgeny-boger/root,vukasinmilosevic/root,evgeny-boger/root,perovic/root,beniz/root,sawenzel/root,lgiommi/root,esakellari/root,BerserkerTroll/root,davidlt/root,olifre/root,gganis/root,olifre/root,sawenzel/root,omazapa/root-old,strykejern/TTreeReader,sawenzel/root,alexschlueter/cern-root,gbitzes/root,davidlt/root,esakellari/my_root_for_test,vukasinmilosevic/root,sirinath/root,omazapa/root-old,gbitzes/root,beniz/root,mattkretz/root,arch1tect0r/root,smarinac/root,sbinet/cxx-root,sbinet/cxx-root,karies/root,Y--/root,root-mirror/root,jrtomps/root,veprbl/root,krafczyk/root,davidlt/root,mhuwiler/rootauto,abhinavmoudgil95/root,dfunke/root,pspe/root,abhinavmoudgil95/root,zzxuanyuan/root,pspe/root,tc3t/qoot,gganis/root,kirbyherm/root-r-tools,sawenzel/root,0x0all/ROOT,gbitzes/root,satyarth934/root,beniz/root,agarciamontoro/root,BerserkerTroll/root,gganis/root,nilqed/root,karies/root,mkret2/root,omazapa/root-old,gganis/root,smarinac/root,sawenzel/root,mattkretz/root
fca52a2d5bc438099d7fe49ce01a33782d2acd4a
examples/graphics/lights.cpp
examples/graphics/lights.cpp
/* Allocore Example: Lighting Description: This example demonstrates how to use lighting within a scene. Author: Lance Putnam, 12/2010 (putnam.lance at gmail dot com) */ #include "allocore/al_Allocore.hpp" using namespace al; struct MyWindow : Window{ MyWindow(){ phase = 0.5; surface.primitive(Graphics::TRIANGLE_STRIP); surface.color(1,1,1); const int Nx=30, Ny=30; for(int j=0; j<Ny; ++j){ float y=float(j)/(Ny-1); for(int i=0; i<Nx; ++i){ float x=float(i)/(Nx-1); surface.vertex(x*4-2, y*4-2); surface.normal(0,0,1); }} for(int j=0; j<Ny-1; ++j){ surface.index(j*Nx); for(int i=0; i<Nx ; ++i){ int idx = j*Nx + i; surface.index(idx); surface.index(idx+Nx); }} } bool onFrame(){ gl.clearColor(0,0,0,0); gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); gl.viewport(0,0, width(), height()); gl.matrixMode(gl.PROJECTION); gl.loadMatrix(Matrix4d::perspective(45, aspect(), 0.1, 100)); gl.matrixMode(gl.MODELVIEW); gl.loadMatrix(Matrix4d::lookAt(Vec3d(0,0,5), Vec3d(0,0,0), Vec3d(0,1,0))); gl.depthTesting(1); gl.blending(0); // Set light position phase += 1./1800; if(phase > 1) phase -= 1; float x = cos(7*phase*2*M_PI); float y = sin(11*phase*2*M_PI); float z = cos(phase*2*M_PI)*0.5 + 0.5; light.pos(x,y,z); light.diffuse(Color(1,0,0)); gl.mesh().reset(); gl.mesh().primitive(gl.TRIANGLES); gl.mesh().color(1,1,1); addSphere(gl.mesh(),0.1); gl.mesh().translate(x,y,z); gl.draw(); material(); light(); gl.draw(surface); return true; } Graphics gl; Light light; Material material; Mesh surface; double phase; }; MyWindow win; int main(){ win.append(*new StandardWindowKeyControls); win.create(); MainLoop::start(); return 0; }
/* Allocore Example: Lighting Description: This example demonstrates how to use lighting within a scene. Author: Lance Putnam, 12/2010 (putnam.lance at gmail dot com) */ #include "allocore/al_Allocore.hpp" using namespace al; struct MyWindow : Window{ MyWindow(){ phase = 0.5; surface.primitive(Graphics::TRIANGLE_STRIP); surface.color(1,1,1); const int Nx=30, Ny=30; for(int j=0; j<Ny; ++j){ float y=float(j)/(Ny-1); for(int i=0; i<Nx; ++i){ float x=float(i)/(Nx-1); surface.vertex(x*4-2, y*4-2); surface.normal(0,0,1); }} for(int j=0; j<Ny-1; ++j){ for(int i=0; i<Nx ; ++i){ int idx = j*Nx + i; surface.index(idx); surface.index(idx+Nx); } int idx = surface.indices().last(); surface.index(idx); surface.index(idx - Nx + 1); } } bool onFrame(){ gl.clearColor(0,0,0,0); gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); gl.viewport(0,0, width(), height()); gl.matrixMode(gl.PROJECTION); gl.loadMatrix(Matrix4d::perspective(45, aspect(), 0.1, 100)); gl.matrixMode(gl.MODELVIEW); gl.loadMatrix(Matrix4d::lookAt(Vec3d(0,0,5), Vec3d(0,0,0), Vec3d(0,1,0))); gl.depthTesting(1); gl.blending(0); // Set light position phase += 1./1800; if(phase > 1) phase -= 1; float x = cos(7*phase*2*M_PI); float y = sin(11*phase*2*M_PI); float z = cos(phase*2*M_PI)*0.5 + 0.5; light.pos(x,y,z); light.diffuse(Color(1,0,0)); gl.mesh().reset(); gl.mesh().primitive(gl.TRIANGLES); gl.mesh().color(1,1,1); addSphere(gl.mesh(),0.1); gl.mesh().translate(x,y,z); gl.draw(); material(); light(); gl.draw(surface); return true; } Graphics gl; Light light; Material material; Mesh surface; double phase; }; MyWindow win; int main(){ win.append(*new StandardWindowKeyControls); win.create(); MainLoop::start(); return 0; }
fix light example mesh
fix light example mesh
C++
bsd-3-clause
AlloSphere-Research-Group/AlloSystem,AlloSphere-Research-Group/AlloSystem,AlloSphere-Research-Group/AlloSystem,AlloSphere-Research-Group/AlloSystem,AlloSphere-Research-Group/AlloSystem
3d724c00606b6d98f7d7ed4a1b4ce78293746177
src/interpolated-path.cc
src/interpolated-path.cc
// Copyright (c) 2015, Joseph Mirabel // Authors: Joseph Mirabel ([email protected]) // // This file is part of hpp-core. // hpp-core is free software: you can redistribute it // and/or modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation, either version // 3 of the License, or (at your option) any later version. // // hpp-core 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 Lesser Public License for more details. You should have // received a copy of the GNU Lesser General Public License along with // hpp-core. If not, see <http://www.gnu.org/licenses/>. #include <hpp/core/interpolated-path.hh> #include <hpp/util/debug.hh> #include <hpp/pinocchio/device.hh> #include <hpp/pinocchio/liegroup.hh> #include <hpp/pinocchio/configuration.hh> #include <hpp/core/config-projector.hh> #include <hpp/core/projection-error.hh> namespace hpp { namespace core { InterpolatedPath::InterpolatedPath (const DevicePtr_t& device, ConfigurationIn_t init, ConfigurationIn_t end, value_type length) : parent_t (interval_t (0, length), device->configSize (), device->numberDof ()), device_ (device) { assert (init.size() == device_->configSize ()); insert (0, init); insert (length, end); assert (device); assert (length >= 0); assert (!constraints ()); } InterpolatedPath::InterpolatedPath (const DevicePtr_t& device, ConfigurationIn_t init, ConfigurationIn_t end, value_type length, ConstraintSetPtr_t constraints) : parent_t (interval_t (0, length), device->configSize (), device->numberDof (), constraints), device_ (device) { assert (init.size() == device_->configSize ()); insert (0, init); insert (length, end); assert (device); assert (length >= 0); } InterpolatedPath::InterpolatedPath (const InterpolatedPath& path) : parent_t (path), device_ (path.device_), configs_ (path.configs_) { assert (initial().size() == device_->configSize ()); } InterpolatedPath::InterpolatedPath (const InterpolatedPath& path, const ConstraintSetPtr_t& constraints) : parent_t (path, constraints), device_ (path.device_), configs_ (path.configs_) { } InterpolatedPathPtr_t InterpolatedPath::create (const PathPtr_t& path, const DevicePtr_t& device, const std::size_t& nbSamples) { // TODO: If it is a path vector, should we get the waypoints and build // a interpolated path from those waypoints ? InterpolatedPath* ptr = new InterpolatedPath (device, path->initial (), path->end(), path->length(), path->constraints ()); InterpolatedPathPtr_t shPtr (ptr); ptr->init (shPtr); const value_type dl = path->length () / (value_type) (nbSamples + 1); Configuration_t q (device->configSize ()); for (std::size_t iS = 0; iS < nbSamples; ++iS) { const value_type u = dl * (value_type) (iS + 1); if (!(*path) (q, u)) throw projection_error ("could not build InterpolatedPath"); ptr->insert (u, q); } return shPtr; } void InterpolatedPath::init (InterpolatedPathPtr_t self) { parent_t::init (self); weak_ = self; checkPath (); } void InterpolatedPath::initCopy (InterpolatedPathPtr_t self) { parent_t::init (self); weak_ = self; checkPath (); } bool InterpolatedPath::impl_compute (ConfigurationOut_t result, value_type param) const { assert (param >= paramRange().first); if (param == paramRange ().first || paramLength() == 0) { result.noalias () = initial(); return true; } if (param >= paramRange ().second) { result.noalias () = end(); return true; } InterpolationPoints_t::const_iterator itA = configs_.lower_bound (param); InterpolationPoints_t::const_iterator itB = itA; --itB; const value_type T = itA->first - itB->first; const value_type u = (param - itB->first) / T; pinocchio::interpolate<hpp::pinocchio::LieGroupTpl> (device_, itB->second, itA->second, u, result); return true; } void InterpolatedPath::impl_derivative (vectorOut_t result, const value_type& s, size_type order) const { value_type param (s); assert (param >= paramRange().first); if (paramRange ().first == paramRange ().second) { result.setZero (); return; } InterpolationPoints_t::const_iterator itA; InterpolationPoints_t::const_iterator itB; if (param >= paramRange ().second) { param = paramRange ().second; itA = configs_.end(); --itA; itB = itA; --itB; } else { itA = configs_.upper_bound (param); itB = configs_.lower_bound (param); if (itB == itA) { if (itB == configs_.begin ()) { ++itA; } else { --itB; } } } assert (itA != configs_.end ()); const value_type T = itA->first - itB->first; if (order > 1) { result.setZero (); return; } if (order == 1) { pinocchio::difference <hpp::pinocchio::LieGroupTpl> (device_, itA->second, itB->second, result); result = (1/T) * result; } } void InterpolatedPath::impl_velocityBound (vectorOut_t result, const value_type& t0, const value_type& t1) const { InterpolationPoints_t::const_iterator next = configs_.lower_bound (t0); InterpolationPoints_t::const_iterator current = next; ++next; result.setZero(); vector_t tmp (result.size()); while (t1 > current->first) { pinocchio::difference <hpp::pinocchio::LieGroupTpl> (device_, next->second, current->second, tmp); const value_type T = next->first - current->first; result.noalias() = result.cwiseMax(tmp.cwiseAbs() / T); ++current; ++next; } } PathPtr_t InterpolatedPath::impl_extract (const interval_t& subInterval) const throw (projection_error) { // Length is assumed to be proportional to interval range const bool reverse = (subInterval.first > subInterval.second); const value_type tmin = (reverse)?subInterval.second:subInterval.first ; const value_type tmax = (reverse)?subInterval.first :subInterval.second; const value_type l = tmax - tmin; bool success; Configuration_t q1 (configAtParam (subInterval.first, success)); if (!success) throw projection_error ("Failed to apply constraints in InterpolatedPath::extract"); Configuration_t q2 (configAtParam (subInterval.second, success)); if (!success) throw projection_error ("Failed to apply constraints in InterpolatedPath::extract"); InterpolatedPathPtr_t result = InterpolatedPath::create (device_, q1, q2, l, constraints ()); InterpolationPoints_t::const_iterator it = configs_.upper_bound (tmin); if (reverse) for (; it->first < tmax; ++it) result->insert (l - (it->first - tmin), it->second); else for (; it->first < tmax; ++it) result->insert (it->first - tmin, it->second); return result; } PathPtr_t InterpolatedPath::reverse () const { const value_type& l = paramLength(); InterpolatedPathPtr_t result = InterpolatedPath::create (device_, end(), initial(), l, constraints ()); if (configs_.size () > 2) { InterpolationPoints_t::const_reverse_iterator it = configs_.rbegin(); ++it; InterpolationPoints_t::const_reverse_iterator itEnd = configs_.rend(); --itEnd; for (; it != itEnd; ++it) result->insert (l - it->first, it->second); } return result; } DevicePtr_t InterpolatedPath::device () const { return device_; } } // namespace core } // namespace hpp
// Copyright (c) 2015, Joseph Mirabel // Authors: Joseph Mirabel ([email protected]) // // This file is part of hpp-core. // hpp-core is free software: you can redistribute it // and/or modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation, either version // 3 of the License, or (at your option) any later version. // // hpp-core 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 Lesser Public License for more details. You should have // received a copy of the GNU Lesser General Public License along with // hpp-core. If not, see <http://www.gnu.org/licenses/>. #include <hpp/core/interpolated-path.hh> #include <hpp/util/debug.hh> #include <hpp/pinocchio/device.hh> #include <hpp/pinocchio/liegroup.hh> #include <hpp/pinocchio/configuration.hh> #include <hpp/core/config-projector.hh> #include <hpp/core/projection-error.hh> namespace hpp { namespace core { InterpolatedPath::InterpolatedPath (const DevicePtr_t& device, ConfigurationIn_t init, ConfigurationIn_t end, value_type length) : parent_t (interval_t (0, length), device->configSize (), device->numberDof ()), device_ (device) { assert (init.size() == device_->configSize ()); insert (0, init); insert (length, end); assert (device); assert (length >= 0); assert (!constraints ()); } InterpolatedPath::InterpolatedPath (const DevicePtr_t& device, ConfigurationIn_t init, ConfigurationIn_t end, value_type length, ConstraintSetPtr_t constraints) : parent_t (interval_t (0, length), device->configSize (), device->numberDof (), constraints), device_ (device) { assert (init.size() == device_->configSize ()); insert (0, init); insert (length, end); assert (device); assert (length >= 0); } InterpolatedPath::InterpolatedPath (const InterpolatedPath& path) : parent_t (path), device_ (path.device_), configs_ (path.configs_) { assert (initial().size() == device_->configSize ()); } InterpolatedPath::InterpolatedPath (const InterpolatedPath& path, const ConstraintSetPtr_t& constraints) : parent_t (path, constraints), device_ (path.device_), configs_ (path.configs_) { } InterpolatedPathPtr_t InterpolatedPath::create (const PathPtr_t& path, const DevicePtr_t& device, const std::size_t& nbSamples) { // TODO: If it is a path vector, should we get the waypoints and build // a interpolated path from those waypoints ? InterpolatedPath* ptr = new InterpolatedPath (device, path->initial (), path->end(), path->length(), path->constraints ()); InterpolatedPathPtr_t shPtr (ptr); ptr->init (shPtr); const value_type dl = path->length () / (value_type) (nbSamples + 1); Configuration_t q (device->configSize ()); for (std::size_t iS = 0; iS < nbSamples; ++iS) { const value_type u = dl * (value_type) (iS + 1); if (!(*path) (q, u)) throw projection_error ("could not build InterpolatedPath"); ptr->insert (u, q); } return shPtr; } void InterpolatedPath::init (InterpolatedPathPtr_t self) { parent_t::init (self); weak_ = self; checkPath (); } void InterpolatedPath::initCopy (InterpolatedPathPtr_t self) { parent_t::init (self); weak_ = self; checkPath (); } bool InterpolatedPath::impl_compute (ConfigurationOut_t result, value_type param) const { assert (param >= paramRange().first); if (param == paramRange ().first || paramLength() == 0) { result.noalias () = initial(); return true; } if (param >= paramRange ().second) { result.noalias () = end(); return true; } InterpolationPoints_t::const_iterator itA = configs_.lower_bound (param); InterpolationPoints_t::const_iterator itB = itA; --itB; const value_type T = itA->first - itB->first; const value_type u = (param - itB->first) / T; pinocchio::interpolate<hpp::pinocchio::LieGroupTpl> (device_, itB->second, itA->second, u, result); return true; } void InterpolatedPath::impl_derivative (vectorOut_t result, const value_type& s, size_type order) const { value_type param (s); assert (param >= paramRange().first); if (paramRange ().first == paramRange ().second) { result.setZero (); return; } InterpolationPoints_t::const_iterator itA; InterpolationPoints_t::const_iterator itB; if (param >= configs_.rbegin()->first) { param = configs_.rbegin()->first; itA = configs_.end(); --itA; itB = itA; --itB; } else { itA = configs_.upper_bound (param); itB = configs_.lower_bound (param); if (itB == itA) { if (itB == configs_.begin ()) { ++itA; } else { --itB; } } } assert (itA != configs_.end ()); const value_type T = itA->first - itB->first; if (order > 1) { result.setZero (); return; } if (order == 1) { pinocchio::difference <hpp::pinocchio::LieGroupTpl> (device_, itA->second, itB->second, result); result = (1/T) * result; } } void InterpolatedPath::impl_velocityBound (vectorOut_t result, const value_type& t0, const value_type& t1) const { InterpolationPoints_t::const_iterator next = configs_.lower_bound (t0); InterpolationPoints_t::const_iterator current = next; ++next; result.setZero(); vector_t tmp (result.size()); while (t1 > current->first) { pinocchio::difference <hpp::pinocchio::LieGroupTpl> (device_, next->second, current->second, tmp); const value_type T = next->first - current->first; result.noalias() = result.cwiseMax(tmp.cwiseAbs() / T); ++current; ++next; } } PathPtr_t InterpolatedPath::impl_extract (const interval_t& subInterval) const throw (projection_error) { // Length is assumed to be proportional to interval range const bool reverse = (subInterval.first > subInterval.second); const value_type tmin = (reverse)?subInterval.second:subInterval.first ; const value_type tmax = (reverse)?subInterval.first :subInterval.second; const value_type l = tmax - tmin; bool success; Configuration_t q1 (configAtParam (subInterval.first, success)); if (!success) throw projection_error ("Failed to apply constraints in InterpolatedPath::extract"); Configuration_t q2 (configAtParam (subInterval.second, success)); if (!success) throw projection_error ("Failed to apply constraints in InterpolatedPath::extract"); InterpolatedPathPtr_t result = InterpolatedPath::create (device_, q1, q2, l, constraints ()); InterpolationPoints_t::const_iterator it = configs_.upper_bound (tmin); if (reverse) for (; it->first < tmax; ++it) result->insert (l - (it->first - tmin), it->second); else for (; it->first < tmax; ++it) result->insert (it->first - tmin, it->second); return result; } PathPtr_t InterpolatedPath::reverse () const { const value_type& l = paramLength(); InterpolatedPathPtr_t result = InterpolatedPath::create (device_, end(), initial(), l, constraints ()); if (configs_.size () > 2) { InterpolationPoints_t::const_reverse_iterator it = configs_.rbegin(); ++it; InterpolationPoints_t::const_reverse_iterator itEnd = configs_.rend(); --itEnd; for (; it != itEnd; ++it) result->insert (l - it->first, it->second); } return result; } DevicePtr_t InterpolatedPath::device () const { return device_; } } // namespace core } // namespace hpp
Fix bug in InterpolatedPath::impl_derivative
Fix bug in InterpolatedPath::impl_derivative
C++
bsd-2-clause
humanoid-path-planner/hpp-core
fb31d22b5fd6d7f516758d68b8b0fae0f5a7629e
src/sail/game.cpp
src/sail/game.cpp
/* * Copyright (C) 2015 Luke San Antonio * All rights reserved. */ #include "game.h" #include <thread> #include "../common/log.h" #include "../net/protocol.h" #include "../tasks/render.h" namespace redc { namespace sail { po::options_description command_options_desc() noexcept { po::options_description general_opt("General"); general_opt.add_options() ("help", "display help") ("out-log-level", po::value<unsigned int>()->default_value(2), "set minimum log level to stdout") ("log-file", po::value<std::string>(), "set log file") ("file-log-level", po::value<unsigned int>()->default_value(0), "set minimum log level to file") ; po::options_description boat_opt("Boat"); boat_opt.add_options() ("hull", po::value<unsigned int>()->default_value(0), "set boat hull") ("sail", po::value<unsigned int>()->default_value(0), "set boat sail") ("rudder", po::value<unsigned int>()->default_value(0), "set boat rudder") ("gun", po::value<unsigned int>()->default_value(0), "set boat gun") ; po::options_description server_opt("Networking"); server_opt.add_options() ("name", po::value<std::string>(), "client name") ("port", po::value<uint16_t>()->default_value(28222), "set port number") ("max-peers", po::value<uint16_t>()->default_value(12), "set max number of connections") ("local-server", "start local server with a client gui") ("dedicated-server", "start a dedicated server without a client gui") ("advertise-server", "advertise the server to other clients") ("connect", po::value<std::string>(), "connect to a server") ; po::options_description desc("Allowed Options"); desc.add(general_opt).add(boat_opt).add(server_opt); return desc; } po::variables_map parse_command_options(int argc, char** argv) noexcept { po::variables_map vm; po::store(po::parse_command_line(argc, argv, command_options_desc()), vm); po::notify(vm); return vm; } Server_Mode pick_server_mode(po::variables_map const& vm) noexcept { bool dedicated = vm.count("dedicated-server"); bool local = vm.count("local-server"); bool connect = vm.count("connect"); int total = dedicated + local + connect; if(total > 1) { return Server_Mode::Bad; } if(dedicated) return Server_Mode::Dedicated; if(connect) return Server_Mode::Connect; // By default, start a local server. else return Server_Mode::Local; } //using namespace redc::literals; int start_game(po::variables_map const& vm) noexcept { Game game; Render_Task render(game, vm, "Sail", Vec<int>{1000,1000}, false, false); while(!render.should_close()) { render.step(); } return EXIT_SUCCESS; } int start_connect(po::variables_map const& vm) noexcept { // Get details auto port = vm["port"].as<uint16_t>(); auto addr = vm["connect"].as<std::string>(); // Negotiate connection // Just wait for now auto client = net::wait_for_connection(addr, port); // Wait for information Game game; net::wait_for_game_info(client, game); // Set name net::set_name(client, vm["name"].as<std::string>()); //Input_Task input_task; Render_Task render_task(game, vm, "Sail", {1000, 1000}, false, false); while(!render_task.should_close()) { //input_task.step(); //client.step(); render_task.step(); } net::close_connection(client); return EXIT_SUCCESS; } int start_dedicated(po::variables_map const& vm) noexcept { // Get details //auto port = vm["port"].as<uint16_t>(); //auto max_peers = vm["max-peers"].as<uint16_t>(); //auto server = net::make_server(port, max_peers); //Game game; return EXIT_SUCCESS; } } }
/* * Copyright (C) 2015 Luke San Antonio * All rights reserved. */ #include "game.h" #include <thread> #include "../common/log.h" #include "../net/protocol.h" #include "../tasks/render.h" #include <boost/program_options.hpp> #include <boost/program_options/parsers.hpp> namespace redc { namespace sail { po::options_description command_options_desc() noexcept { po::options_description general_opt("General"); general_opt.add_options() ("help", "display help") ("out-log-level", po::value<unsigned int>()->default_value(2), "set minimum log level to stdout") ("log-file", po::value<std::string>(), "set log file") ("file-log-level", po::value<unsigned int>()->default_value(0), "set minimum log level to file") ; po::options_description boat_opt("Boat"); boat_opt.add_options() ("hull", po::value<unsigned int>()->default_value(0), "set boat hull") ("sail", po::value<unsigned int>()->default_value(0), "set boat sail") ("rudder", po::value<unsigned int>()->default_value(0), "set boat rudder") ("gun", po::value<unsigned int>()->default_value(0), "set boat gun") ; po::options_description server_opt("Networking"); server_opt.add_options() ("name", po::value<std::string>(), "client name") ("port", po::value<uint16_t>()->default_value(28222), "set port number") ("max-peers", po::value<uint16_t>()->default_value(12), "set max number of connections") ("local-server", "start local server with a client gui") ("dedicated-server", "start a dedicated server without a client gui") ("advertise-server", "advertise the server to other clients") ("connect", po::value<std::string>(), "connect to a server") ; po::options_description config_opt("Config"); config_opt.add_options()("render.fov", po::value<float>(), "FOV"); po::options_description desc("Allowed Options"); desc.add(general_opt).add(boat_opt).add(server_opt).add(config_opt); return desc; } po::variables_map parse_command_options(int argc, char** argv) noexcept { po::variables_map vm; po::store(po::parse_command_line(argc, argv, command_options_desc()), vm); po::store(po::parse_config_file<char>("assets/cfg.ini", command_options_desc()), vm); po::notify(vm); return vm; } Server_Mode pick_server_mode(po::variables_map const& vm) noexcept { bool dedicated = vm.count("dedicated-server"); bool local = vm.count("local-server"); bool connect = vm.count("connect"); int total = dedicated + local + connect; if(total > 1) { return Server_Mode::Bad; } if(dedicated) return Server_Mode::Dedicated; if(connect) return Server_Mode::Connect; // By default, start a local server. else return Server_Mode::Local; } //using namespace redc::literals; int start_game(po::variables_map const& vm) noexcept { Game game; Render_Task render(game, vm, "Sail", Vec<int>{1000,1000}, false, false); while(!render.should_close()) { render.step(); } return EXIT_SUCCESS; } int start_connect(po::variables_map const& vm) noexcept { // Get details auto port = vm["port"].as<uint16_t>(); auto addr = vm["connect"].as<std::string>(); // Negotiate connection // Just wait for now auto client = net::wait_for_connection(addr, port); // Wait for information Game game; net::wait_for_game_info(client, game); // Set name net::set_name(client, vm["name"].as<std::string>()); //Input_Task input_task; Render_Task render_task(game, vm, "Sail", {1000, 1000}, false, false); while(!render_task.should_close()) { //input_task.step(); //client.step(); render_task.step(); } net::close_connection(client); return EXIT_SUCCESS; } int start_dedicated(po::variables_map const& vm) noexcept { // Get details //auto port = vm["port"].as<uint16_t>(); //auto max_peers = vm["max-peers"].as<uint16_t>(); //auto server = net::make_server(port, max_peers); //Game game; return EXIT_SUCCESS; } } }
Add field of view config option!
Add field of view config option!
C++
bsd-3-clause
RedCraneStudio/redcrane-engine,RedCraneStudio/redcrane-engine,RedCraneStudio/redcrane-engine,RedCraneStudio/redcrane-engine
4a8f63fcd263c649534d121e25430675b6cb701a
src/SegmentBase.hpp
src/SegmentBase.hpp
#ifndef CPPJIEBA_SEGMENTBASE_H #define CPPJIEBA_SEGMENTBASE_H #include "TransCode.hpp" #include "Limonp/Logger.hpp" #include "Limonp/InitOnOff.hpp" #include "ISegment.hpp" #include <cassert> namespace CppJieba { using namespace Limonp; //const char* const SPECIAL_CHARS = " \t\n"; #ifndef CPPJIEBA_GBK const UnicodeValueType SPECIAL_SYMBOL[] = {32u, 9u, 10u, 12290u, 65292u}; #else const UnicodeValueType SPECIAL_SYMBOL[] = {32u, 9u, 10u}; #endif class SegmentBase: public ISegment, public InitOnOff { public: SegmentBase(){_loadSpecialSymbols();}; virtual ~SegmentBase(){}; private: unordered_set<UnicodeValueType> _specialSymbols; private: void _loadSpecialSymbols() { size_t size = sizeof(SPECIAL_SYMBOL)/sizeof(*SPECIAL_SYMBOL); for(size_t i = 0; i < size; i ++) { _specialSymbols.insert(SPECIAL_SYMBOL[i]); } assert(_specialSymbols.size()); } public: virtual bool cut(Unicode::const_iterator begin, Unicode::const_iterator end, vector<string>& res) const = 0; virtual bool cut(const string& str, vector<string>& res) const { assert(_getInitFlag()); res.clear(); Unicode unicode; unicode.reserve(str.size()); TransCode::decode(str, unicode); Unicode::const_iterator left = unicode.begin(); Unicode::const_iterator right; for(right = unicode.begin(); right != unicode.end(); right++) { if(isIn(_specialSymbols, *right)) { if(left != right) { cut(left, right, res); } res.resize(res.size() + 1); TransCode::encode(right, right + 1, res.back()); left = right + 1; } } if(left != right) { cut(left, right, res); } return true; } }; } #endif
#ifndef CPPJIEBA_SEGMENTBASE_H #define CPPJIEBA_SEGMENTBASE_H #include "TransCode.hpp" #include "Limonp/Logger.hpp" #include "Limonp/InitOnOff.hpp" #include "Limonp/NonCopyable.hpp" #include "ISegment.hpp" #include <cassert> namespace CppJieba { using namespace Limonp; //const char* const SPECIAL_CHARS = " \t\n"; #ifndef CPPJIEBA_GBK const UnicodeValueType SPECIAL_SYMBOL[] = {32u, 9u, 10u, 12290u, 65292u}; #else const UnicodeValueType SPECIAL_SYMBOL[] = {32u, 9u, 10u}; #endif class SegmentBase: public ISegment, public InitOnOff, public NonCopyable { public: SegmentBase(){_loadSpecialSymbols();}; virtual ~SegmentBase(){}; private: unordered_set<UnicodeValueType> _specialSymbols; private: void _loadSpecialSymbols() { size_t size = sizeof(SPECIAL_SYMBOL)/sizeof(*SPECIAL_SYMBOL); for(size_t i = 0; i < size; i ++) { _specialSymbols.insert(SPECIAL_SYMBOL[i]); } assert(_specialSymbols.size()); } public: virtual bool cut(Unicode::const_iterator begin, Unicode::const_iterator end, vector<string>& res) const = 0; virtual bool cut(const string& str, vector<string>& res) const { assert(_getInitFlag()); res.clear(); Unicode unicode; unicode.reserve(str.size()); TransCode::decode(str, unicode); Unicode::const_iterator left = unicode.begin(); Unicode::const_iterator right; for(right = unicode.begin(); right != unicode.end(); right++) { if(isIn(_specialSymbols, *right)) { if(left != right) { cut(left, right, res); } res.resize(res.size() + 1); TransCode::encode(right, right + 1, res.back()); left = right + 1; } } if(left != right) { cut(left, right, res); } return true; } }; } #endif
make segments NonCopyable
make segments NonCopyable
C++
mit
fortranlee/cppjieba,songinfo/cppjieba,fortranlee/cppjieba,songinfo/cppjieba,fortranlee/cppjieba,songinfo/cppjieba
c7bb83e1d06176100eb759507d670fc1321799ac
src/Bull/Core/Hardware/Unix/CPUImpl.hpp
src/Bull/Core/Hardware/Unix/CPUImpl.hpp
#ifndef BULL_CORE_HARDWARE_CPU_HPP #define BULL_CORE_HARDWARE_CPU_HPP #include <Bull/Core/Hardware/CPU.hpp> namespace Bull { namespace prv { struct CPUImpl { /*! \brief Get the number of CPU * * \return Return the number of CPU * */ static unsigned int getCount(); /*! \brief Get the CPU architecture * * \return Return the CPU architecture * */ static CPU::Architecture getArchitecture(); }; } } #endif // BULL_CORE_HARDWARE_CPU_HPP
#ifndef BULL_CORE_HARDWARE_CPUIMPL_HPP #define BULL_CORE_HARDWARE_CPUIMPL_HPP #include <Bull/Core/Hardware/CPU.hpp> namespace Bull { namespace prv { struct CPUImpl { /*! \brief Get the number of CPU * * \return Return the number of CPU * */ static unsigned int getCount(); /*! \brief Get the CPU architecture * * \return Return the CPU architecture * */ static CPU::Architecture getArchitecture(); }; } } #endif // BULL_CORE_HARDWARE_CPUIMPL_HPP
Fix build on Linux
[Core/CPU] Fix build on Linux
C++
mit
siliace/Bull
b32e2bd548964c6349bc299f2d9f68b8253a3aa6
benchmarks/pt_mcomponentdata/pt_mcomponentdata.cpp
benchmarks/pt_mcomponentdata/pt_mcomponentdata.cpp
/*************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of libmeegotouch. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** 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 ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ #include "pt_mcomponentdata.h" #include <MComponentData> #include <MApplication> void Pt_MComponentData::constructor() { int argc = 1; char *argv[argc]; char appName[] = "./widgetsgallery"; argv[0] = appName; MComponentData *componentData; QBENCHMARK_ONCE { componentData = new MComponentData(argc, argv, appName); } delete componentData; } QTEST_MAIN(Pt_MComponentData)
/*************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of libmeegotouch. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** 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 ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ #include "pt_mcomponentdata.h" #include <MComponentData> #include <MApplication> void Pt_MComponentData::constructor() { int argc = 1; char *argv[argc]; char appName[] = "./widgetsgallery"; argv[0] = appName; MComponentData *componentData = 0; QBENCHMARK_ONCE { componentData = new MComponentData(argc, argv, appName); } delete componentData; } QTEST_MAIN(Pt_MComponentData)
Fix coverity issue 90
Changes: Fix coverity issue 90 RevBy: Mike
C++
lgpl-2.1
nemomobile-graveyard/libmeegotouch,nemomobile-graveyard/libmeegotouch,nemomobile-graveyard/libmeegotouch,nemomobile-graveyard/libmeegotouch,nemomobile-graveyard/libmeegotouch,nemomobile-graveyard/libmeegotouch