text
stringlengths
54
60.6k
<commit_before>/* * Copyright (C) 2008, Morgan Quigley and Willow Garage, Inc. * * 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 names of Stanford University or Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "ros/ros.h" #include <transitbuddy_robot_publisher/robot_publisher_node.h> int main(int argc, char **argv) { ros::init ( argc, argv, "robot_publisher" ); ros::NodeHandle n; RobotPublisherNode bridge ( n ); ros::Rate rate ( bridge.frequency() ); while ( ros::ok() ) { bridge.publishRobotPose(); ros::spinOnce(); rate.sleep(); } return 0; } RobotPublisherNode::RobotPublisherNode(ros::NodeHandle & n) : n_ ( n ), n_param_ ( "~" ), frequency_ ( DEFAUTL_FRQ), publish_(false), frame_id_(DEFAULT_FRAME_ID) { n_param_.getParam ( "frequency", frequency_ ); ROS_INFO ( "frequency: %5.2f", frequency_ ); n_param_.getParam ( "publish", publish_ ); ROS_INFO ( "publish: %s", (publish_?"true":"false") ); n_param_.getParam ( "frame_id", frame_id_ ); ROS_INFO ( "frame_id: %s", frame_id_.c_str() ); sub_ = n_.subscribe( NAME_SUB, 1, &RobotPublisherNode::callbackHumanPose, this ); pub_ = n_param_.advertise<transitbuddy_msgs::PoseWithIDArray> ( NAME_PUB, 1 ); } RobotPublisherNode::~RobotPublisherNode(){ } void RobotPublisherNode::callbackHumanPose(const transitbuddy_msgs::PoseWithIDArray::ConstPtr& msg){ ROS_INFO ( "robotPoseCallback"); } void RobotPublisherNode::publishRobotPose(){ if(publish_ == false) return; ROS_INFO ( "publishHumanPose"); transitbuddy_msgs::PoseWithIDArray poses; poses.header.stamp = ros::Time::now(); poses.header.frame_id = frame_id_; poses.poses.resize(2); poses.poses[0].id = 10; poses.poses[0].valid = true; poses.poses[0].pose.position.x = -12.0; poses.poses[1].id = 12; poses.poses[1].valid = false; poses.poses[1].pose.position.x = 24.0; pub_.publish(poses); } <commit_msg>robot pose publisher dummy<commit_after>/* * Copyright (C) 2008, Morgan Quigley and Willow Garage, Inc. * * 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 names of Stanford University or Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "ros/ros.h" #include <transitbuddy_robot_publisher/robot_publisher_node.h> int main(int argc, char **argv) { ros::init ( argc, argv, "robot_publisher" ); ros::NodeHandle n; RobotPublisherNode bridge ( n ); ros::Rate rate ( bridge.frequency() ); while ( ros::ok() ) { bridge.publishRobotPose(); ros::spinOnce(); rate.sleep(); } return 0; } RobotPublisherNode::RobotPublisherNode(ros::NodeHandle & n) : n_ ( n ), n_param_ ( "~" ), frequency_ ( DEFAUTL_FRQ), publish_(true), frame_id_(DEFAULT_FRAME_ID) { n_param_.getParam ( "frequency", frequency_ ); ROS_INFO ( "frequency: %5.2f", frequency_ ); n_param_.getParam ( "publish", publish_ ); ROS_INFO ( "publish: %s", (publish_?"true":"false") ); n_param_.getParam ( "frame_id", frame_id_ ); ROS_INFO ( "frame_id: %s", frame_id_.c_str() ); sub_ = n_.subscribe( NAME_SUB, 1, &RobotPublisherNode::callbackHumanPose, this ); pub_ = n_param_.advertise<transitbuddy_msgs::PoseWithIDArray> ( NAME_PUB, 1 ); } RobotPublisherNode::~RobotPublisherNode(){ } void RobotPublisherNode::callbackHumanPose(const transitbuddy_msgs::PoseWithIDArray::ConstPtr& msg){ ROS_INFO ( "robotPoseCallback"); } void RobotPublisherNode::publishRobotPose(){ if(publish_ == false) return; ROS_INFO ( "publishHumanPose"); transitbuddy_msgs::PoseWithIDArray poses; poses.header.stamp = ros::Time::now(); poses.header.frame_id = frame_id_; poses.poses.resize(2); poses.poses[0].id = 10; poses.poses[0].valid = true; poses.poses[0].pose.position.x = -12.0; poses.poses[1].id = 12; poses.poses[1].valid = false; poses.poses[1].pose.position.x = 24.0; pub_.publish(poses); } <|endoftext|>
<commit_before>// // Name: app.cpp // Purpose: The application class for a wxWindows application. // // Copyright (c) 2001-2003 Virtual Terrain Project // Free for all uses, see license.txt for details. // #ifdef __GNUG__ #pragma implementation #pragma interface #endif // For compilers that support precompilation, includes "wx.h". #include "wx/wxprec.h" #ifndef WX_PRECOMP #include "wx/wx.h" #endif #include "vtlib/vtlib.h" #include "vtlib/core/NavEngines.h" #include "vtlib/core/vtSOG.h" #include "vtdata/vtLog.h" #include "app.h" #include "frame.h" static void Args(int argc, wxChar **argv) { return; } IMPLEMENT_APP(vtApp) // // Initialize the app object // bool vtApp::OnInit(void) { Args(argc, argv); g_Log._StartLog("debug.txt"); VTLOG("CManager\n"); // // Create the main frame window // VTLOG("Creating frame\n"); wxString title = _T("Content Manager"); vtFrame *frame = new vtFrame(NULL, title, wxPoint(50, 50), wxSize(800, 600)); VTLOG("Setup scene\n"); vtScene *pScene = vtGetScene(); pScene->Init(); pScene->SetBgColor(RGBf(0.5f, 0.5f, 0.5f)); VTLOG(" creating camera\n"); vtCamera *pCamera = pScene->GetCamera(); pCamera->SetName2("Default Camera"); m_pRoot = new vtGroup(); pScene->SetRoot(m_pRoot); #if VTLIB_SGL CreateTestSGLScene(); #endif // make a simple directional light VTLOG(" creating light\n"); vtLight *pLight = new vtLight(); pLight->SetName2("Light"); vtMovLight *pMovLight = new vtMovLight(pLight); pMovLight->SetName2("Movable Light"); pLight->SetAmbient2(RGBf(1, 1, 1)); pMovLight->SetTrans(FPoint3(0.0f, 0.0f, 5.0f)); m_pRoot->AddChild(pMovLight); #if 0 #if 0 // make a yellow sphere vtMaterialArray *pMats = new vtMaterialArray(); pMats->AddRGBMaterial(RGBf(1.0f, 1.0f, 0.0f), RGBf(0.0f, 0.0f, 1.0f)); vtGeom *pGeom = CreateSphereGeom(pMats, 0, VT_Normals, 0.5, 16); pGeom->SetName2("Yellow Sphere"); OutputSOG osog; FILE *fp = fopen("output.sog", "wb"); osog.WriteHeader(fp); osog.WriteSingleGeometry(fp, pGeom); fclose(fp); m_pRoot->AddChild(pGeom); #else InputSOG isog; FILE *fp = fopen("output.sog", "rb"); vtGroup *pGroup = new vtGroup; bool success = isog.ReadContents(fp, pGroup); fclose(fp); m_pRoot->AddChild(pGroup); #endif #endif // make a trackball controller for the camera VTLOG(" creating trackball\n"); m_pTrackball = new vtTrackball(3.0f); m_pTrackball->SetTarget(pScene->GetCamera()); m_pTrackball->SetName2("Trackball"); m_pTrackball->SetRotateButton(VT_LEFT, 0); m_pTrackball->SetZoomButton(VT_RIGHT, 0); m_pTrackball->SetZoomScale(3000.0f); pScene->AddEngine(m_pTrackball); VTLOG(" end of OnInit\n"); return TRUE; } int vtApp::OnExit(void) { m_pRoot->Release(); return 0; } <commit_msg>enabled translate button for trackball, fixed memleak with camera<commit_after>// // Name: app.cpp // Purpose: The application class the CManager application. // // Copyright (c) 2001-2003 Virtual Terrain Project // Free for all uses, see license.txt for details. // #ifdef __GNUG__ #pragma implementation #pragma interface #endif // For compilers that support precompilation, includes "wx.h". #include "wx/wxprec.h" #ifndef WX_PRECOMP #include "wx/wx.h" #endif #include "vtlib/vtlib.h" #include "vtlib/core/NavEngines.h" #include "vtlib/core/vtSOG.h" #include "vtdata/vtLog.h" #include "app.h" #include "frame.h" static void Args(int argc, wxChar **argv) { return; } IMPLEMENT_APP(vtApp) // // Initialize the app object // bool vtApp::OnInit(void) { Args(argc, argv); g_Log._StartLog("debug.txt"); VTLOG("CManager\n"); // // Create the main frame window // VTLOG("Creating frame\n"); wxString title = _T("Content Manager"); vtFrame *frame = new vtFrame(NULL, title, wxPoint(50, 50), wxSize(800, 600)); VTLOG("Setup scene\n"); vtScene *pScene = vtGetScene(); pScene->Init(); pScene->SetBgColor(RGBf(0.5f, 0.5f, 0.5f)); VTLOG(" creating camera\n"); vtCamera *pCamera = pScene->GetCamera(); pCamera->SetName2("Default Camera"); m_pRoot = new vtGroup(); pScene->SetRoot(m_pRoot); #if VTLIB_SGL CreateTestSGLScene(); #endif // make a simple directional light VTLOG(" creating light\n"); vtLight *pLight = new vtLight(); pLight->SetName2("Light"); vtMovLight *pMovLight = new vtMovLight(pLight); pMovLight->SetName2("Movable Light"); pLight->SetAmbient(RGBf(1, 1, 1)); pMovLight->SetTrans(FPoint3(0.0f, 0.0f, 5.0f)); m_pRoot->AddChild(pMovLight); // SOG testing, currently disabled #if 0 #if 0 // make a yellow sphere vtMaterialArray *pMats = new vtMaterialArray(); pMats->AddRGBMaterial(RGBf(1.0f, 1.0f, 0.0f), RGBf(0.0f, 0.0f, 1.0f)); vtGeom *pGeom = CreateSphereGeom(pMats, 0, VT_Normals, 0.5, 16); pGeom->SetName2("Yellow Sphere"); pMats->Release(); OutputSOG osog; FILE *fp = fopen("output.sog", "wb"); osog.WriteHeader(fp); osog.WriteSingleGeometry(fp, pGeom); fclose(fp); m_pRoot->AddChild(pGeom); #else InputSOG isog; FILE *fp = fopen("output.sog", "rb"); vtGroup *pGroup = new vtGroup; bool success = isog.ReadContents(fp, pGroup); fclose(fp); m_pRoot->AddChild(pGroup); #endif #endif // make a trackball controller for the camera VTLOG(" creating trackball\n"); m_pTrackball = new vtTrackball(3.0f); m_pTrackball->SetTarget(pScene->GetCamera()); m_pTrackball->SetName2("Trackball"); m_pTrackball->SetRotateButton(VT_LEFT, 0); m_pTrackball->SetZoomButton(VT_LEFT|VT_RIGHT, 0); m_pTrackball->SetZoomScale(3000.0f); m_pTrackball->SetTranslateButton(VT_RIGHT, 0); pScene->AddEngine(m_pTrackball); // Memleak Testing // GetMainFrame()->AddModelFromFile("E:/3D/IDA Free Models/schoolbus.flt"); // GetMainFrame()->AddNewItem(); VTLOG(" end of OnInit\n"); return TRUE; } int vtApp::OnExit(void) { vtCamera *pCamera = vtGetScene()->GetCamera(); pCamera->Release(); m_pRoot->Release(); return 0; } <|endoftext|>
<commit_before>// Copyright (c) 2014, Robert Escriva // 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 libtreadstone 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. // C #include <assert.h> #include <stdio.h> #include <stdlib.h> #include <string.h> // POSIX #include <errno.h> // e #include <e/guard.h> // Treadstone #include <treadstone.h> int main(int argc, const char* argv[]) { while (true) { char* line = NULL; size_t line_sz = 0; ssize_t amt = getline(&line, &line_sz, stdin); if (amt < 0) { if (feof(stdin) != 0) { break; } fprintf(stderr, "could not read from stdin: %s\n", strerror(ferror(stdin))); return EXIT_FAILURE; } if (!line) { continue; } e::guard line_guard = e::makeguard(free, line); (void) line_guard; if (amt < 1) { continue; } line[amt - 1] = '\0'; unsigned char* binary1 = NULL; size_t binary1_sz = 0; if (treadstone_json_to_binary(line, &binary1, &binary1_sz) < 0) { printf("failure on binary1 conversion\n"); continue; } assert(binary1); e::guard binary1_guard = e::makeguard(free, binary1); char* json1 = NULL; if (treadstone_binary_to_json(binary1, binary1_sz, &json1) < 0) { printf("failure on json1 conversion\n"); continue; } assert(json1); e::guard json1_guard = e::makeguard(free, json1); unsigned char* binary2 = NULL; size_t binary2_sz = 0; if (treadstone_json_to_binary(json1, &binary2, &binary2_sz) < 0) { printf("failure on binary2 conversion\n"); continue; } assert(binary2); e::guard binary2_guard = e::makeguard(free, binary2); char* json2 = NULL; if (treadstone_binary_to_json(binary2, binary2_sz, &json2) < 0) { printf("failure on json2 conversion\n"); continue; } assert(json2); e::guard json2_guard = e::makeguard(free, json2); unsigned char* binary3 = NULL; size_t binary3_sz = 0; if (treadstone_json_to_binary(json1, &binary3, &binary3_sz) < 0) { printf("failure on binary3 conversion\n"); continue; } assert(binary3); e::guard binary3_guard = e::makeguard(free, binary3); char* json3 = NULL; if (treadstone_binary_to_json(binary3, binary3_sz, &json3) < 0) { printf("failure on json3 conversion\n"); continue; } assert(json3); e::guard json3_guard = e::makeguard(free, json3); bool json_same = strcmp(json1, json2) == 0 && strcmp(json2, json3) == 0; bool binary_same = binary2_sz == binary3_sz && memcmp(binary2, binary3, binary2_sz) == 0; if (!json_same || !binary_same) { printf("json_same=%s binary_same=%s\n\t%s\n", (json_same ? "yes" : "no"), (binary_same ? "yes" : "no"), line); } } (void) argc; (void) argv; return EXIT_SUCCESS; } <commit_msg>Compile on freebsd<commit_after>// Copyright (c) 2014, Robert Escriva // 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 libtreadstone 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. #define _WITH_GETLINE // C #include <assert.h> #include <stdio.h> #include <stdlib.h> #include <string.h> // POSIX #include <errno.h> // e #include <e/guard.h> // Treadstone #include <treadstone.h> int main(int argc, const char* argv[]) { while (true) { char* line = NULL; size_t line_sz = 0; ssize_t amt = getline(&line, &line_sz, stdin); if (amt < 0) { if (feof(stdin) != 0) { break; } fprintf(stderr, "could not read from stdin: %s\n", strerror(ferror(stdin))); return EXIT_FAILURE; } if (!line) { continue; } e::guard line_guard = e::makeguard(free, line); (void) line_guard; if (amt < 1) { continue; } line[amt - 1] = '\0'; unsigned char* binary1 = NULL; size_t binary1_sz = 0; if (treadstone_json_to_binary(line, &binary1, &binary1_sz) < 0) { printf("failure on binary1 conversion\n"); continue; } assert(binary1); e::guard binary1_guard = e::makeguard(free, binary1); char* json1 = NULL; if (treadstone_binary_to_json(binary1, binary1_sz, &json1) < 0) { printf("failure on json1 conversion\n"); continue; } assert(json1); e::guard json1_guard = e::makeguard(free, json1); unsigned char* binary2 = NULL; size_t binary2_sz = 0; if (treadstone_json_to_binary(json1, &binary2, &binary2_sz) < 0) { printf("failure on binary2 conversion\n"); continue; } assert(binary2); e::guard binary2_guard = e::makeguard(free, binary2); char* json2 = NULL; if (treadstone_binary_to_json(binary2, binary2_sz, &json2) < 0) { printf("failure on json2 conversion\n"); continue; } assert(json2); e::guard json2_guard = e::makeguard(free, json2); unsigned char* binary3 = NULL; size_t binary3_sz = 0; if (treadstone_json_to_binary(json1, &binary3, &binary3_sz) < 0) { printf("failure on binary3 conversion\n"); continue; } assert(binary3); e::guard binary3_guard = e::makeguard(free, binary3); char* json3 = NULL; if (treadstone_binary_to_json(binary3, binary3_sz, &json3) < 0) { printf("failure on json3 conversion\n"); continue; } assert(json3); e::guard json3_guard = e::makeguard(free, json3); bool json_same = strcmp(json1, json2) == 0 && strcmp(json2, json3) == 0; bool binary_same = binary2_sz == binary3_sz && memcmp(binary2, binary3, binary2_sz) == 0; if (!json_same || !binary_same) { printf("json_same=%s binary_same=%s\n\t%s\n", (json_same ? "yes" : "no"), (binary_same ? "yes" : "no"), line); } } (void) argc; (void) argv; return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Module: $RCSfile$ Language: C++ Date: $Date$ Version: $Revision$ 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 <mitkImage.h> #include <mitkDataTree.h> #include <mitkRenderWindow.h> #include <mitkImageMapper2D.h> #include <mitkLevelWindow.h> #include <mitkLevelWindowProperty.h> #include <mitkNativeRenderWindowInteractor.h> #include "itkTextOutput.h" #include <fstream> int mitkDataTreeTest(int argc, char* argv[]) { itk::OutputWindow::SetInstance( itk::TextOutput::New().GetPointer() ); //Create Image out of nowhere mitk::Image::Pointer image; mitk::PixelType pt(typeid(int)); unsigned int dim[]={100,100,20}; std::cout << "Creating image: "; image=mitk::Image::New(); image->DebugOn(); image->Initialize(mitk::PixelType(typeid(int)), 3, dim); int *p = (int*)image->GetData(); int size = dim[0]*dim[1]*dim[2]; int i; for(i=0; i<size; ++i, ++p) *p=i; std::cout<<"[PASSED]"<<std::endl; { std::cout << "Creating node: "; mitk::DataTreeNode::Pointer node = mitk::DataTreeNode::New(); node->SetData(image); std::cout<<"[PASSED]"<<std::endl; } std::cout << "Creating node: "; mitk::DataTreeNode::Pointer node = mitk::DataTreeNode::New(); node->SetData(image); std::cout<<"[PASSED]"<<std::endl; std::cout << "Creating tree: "; mitk::DataTree::Pointer tree; tree=mitk::DataTree::New(); //@FIXME: da DataTreeIteratorClone keinen Smartpointer auf DataTree hlt, wird tree sonst gelscht. std::cout<<"[PASSED]"<<std::endl; std::cout << "Creating iterator on tree: "; mitk::DataTreePreOrderIterator it(tree); std::cout<<"[PASSED]"<<std::endl; std::cout << "Adding node via iterator: "; it.Add(node); std::cout<<"[PASSED]"<<std::endl; std::cout << "Adding level-window property: "; mitk::LevelWindowProperty::Pointer levWinProp = new mitk::LevelWindowProperty(); mitk::LevelWindow levelwindow; levelwindow.SetAuto( image ); levWinProp->SetLevelWindow( levelwindow ); node->GetPropertyList()->SetProperty( "levelwindow", levWinProp ); std::cout<<"[PASSED]"<<std::endl; std::cout<<"[TEST DONE]"<<std::endl; return EXIT_SUCCESS; } <commit_msg>ENH: enable data tree test and test to remove node<commit_after>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Module: $RCSfile$ Language: C++ Date: $Date$ Version: $Revision$ 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 <mitkImage.h> #include <mitkDataTree.h> #include <mitkRenderWindow.h> #include <mitkImageMapper2D.h> #include <mitkLevelWindow.h> #include <mitkLevelWindowProperty.h> #include <mitkNativeRenderWindowInteractor.h> #include "itkTextOutput.h" #include <fstream> int mitkDataTreeTest(int argc, char* argv[]) { itk::OutputWindow::SetInstance( itk::TextOutput::New().GetPointer() ); //Create Image out of nowhere mitk::Image::Pointer image; mitk::PixelType pt(typeid(int)); unsigned int dim[]={100,100,20}; std::cout << "Creating image: "; image=mitk::Image::New(); image->DebugOn(); image->Initialize(mitk::PixelType(typeid(int)), 3, dim); int *p = (int*)image->GetData(); int size = dim[0]*dim[1]*dim[2]; int i; for(i=0; i<size; ++i, ++p) *p=i; std::cout<<"[PASSED]"<<std::endl; { std::cout << "Creating node: "; mitk::DataTreeNode::Pointer node = mitk::DataTreeNode::New(); node->SetData(image); std::cout<<"[PASSED]"<<std::endl; } std::cout << "Creating node: "; mitk::DataTreeNode::Pointer node = mitk::DataTreeNode::New(); node->SetData(image); std::cout<<"[PASSED]"<<std::endl; std::cout << "Creating tree: "; mitk::DataTree::Pointer tree; tree=mitk::DataTree::New(); //@FIXME: da DataTreeIteratorClone keinen Smartpointer auf DataTree hlt, wird tree sonst gelscht. std::cout<<"[PASSED]"<<std::endl; std::cout << "Creating iterator on tree: "; mitk::DataTreePreOrderIterator it(tree); std::cout<<"[PASSED]"<<std::endl; std::cout << "Adding node via iterator: "; it.Add(node); std::cout<<"[PASSED]"<<std::endl; std::cout << "Adding level-window property: "; mitk::LevelWindowProperty::Pointer levWinProp = new mitk::LevelWindowProperty(); mitk::LevelWindow levelwindow; levelwindow.SetAuto( image ); levWinProp->SetLevelWindow( levelwindow ); node->GetPropertyList()->SetProperty( "levelwindow", levWinProp ); std::cout<<"[PASSED]"<<std::endl; std::cout << "Remove node after incrementing iterator: "; it++; if (it.Remove()) std::cout<<"[PASSED]"<<std::endl; else std::cout<<"[FAILED]"<<std::endl; std::cout<<"[TEST DONE]"<<std::endl; return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/// @file /// @author uentity /// @date 22.11.2017 /// @brief BS tree-related functions impl /// @copyright /// 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 https://mozilla.org/MPL/2.0/ #include <bs/tree/tree.h> #include "tree_impl.h" #include <set> #include <boost/uuid/uuid_io.hpp> #include <boost/algorithm/string.hpp> NAMESPACE_BEGIN(blue_sky) NAMESPACE_BEGIN(tree) using Key = node::Key; template<Key K> using Key_type = typename node::Key_type<K>; /*----------------------------------------------------------------------------- * impl details *-----------------------------------------------------------------------------*/ // hidden namespace { template<class Callback> void walk_impl( const std::vector<sp_link>& nodes, const Callback& step_f, const bool topdown, const bool follow_symlinks, std::set<Key_type<Key::ID>> active_symlinks = {} ) { sp_node cur_node; std::vector<sp_link> next_nodes; std::vector<sp_link> next_leafs; // for each node for(const auto& N : nodes) { if(!N) continue; // remember symlink const auto is_symlink = N->type_id() == "sym_link"; if(is_symlink) { if(follow_symlinks && active_symlinks.find(N->id()) == active_symlinks.end()) active_symlinks.insert(N->id()); else continue; } // obtain node from link honoring LazyLoad flag cur_node = ( !(N->flags() & link::LazyLoad) || N->req_status(link::Req::DataNode) == link::ReqStatus::OK ) ? N->data_node() : nullptr; next_nodes.clear(); next_leafs.clear(); if(cur_node) { // for each link in node for(const auto& l : *cur_node) { // collect nodes if(l->data_node()) { next_nodes.push_back(l); } else next_leafs.push_back(l); } } // if `topdown` == true, process this node BEFORE leafs processing if(topdown) step_f(N, next_nodes, next_leafs); // process list of next nodes if(!next_nodes.empty()) walk_impl(next_nodes, step_f, topdown, follow_symlinks, active_symlinks); // if walking from most deep subdir, process current node after all subtree if(!topdown) step_f(N, next_nodes, next_leafs); // forget symlink if(is_symlink) active_symlinks.erase(N->id()); } } inline std::string link2path_unit(const sp_clink& l, Key path_unit) { switch(path_unit) { default: case Key::ID : return boost::uuids::to_string(l->id()); case Key::OID : return l->oid(); case Key::Name : return l->name(); case Key::Type : return l->type_id(); } } } // hidden ns // public NAMESPACE_BEGIN(detail) sp_link walk_down_tree(const std::string& cur_lid, const sp_node& level, node::Key path_unit) { if(cur_lid != "..") { const auto next = level->find(cur_lid, path_unit); if(next != level->end()) { return *next; } } return nullptr; } NAMESPACE_END(detail) /*----------------------------------------------------------------------------- * public API *-----------------------------------------------------------------------------*/ std::string abspath(sp_clink l, Key path_unit) { std::deque<std::string> res; while(l) { res.push_front(link2path_unit(l, path_unit)); if(const auto parent = l->owner()) { l = parent->handle(); } else return boost::join(res, "/"); } // leadind slash is appended only if we have 'real' root node without self link return std::string("/") + boost::join(res, "/"); // another possible implementation without multiple returns // just leave it here -) //sp_node parent; //do { // if(l) // res.push_front(human_readable ? l->name() : boost::uuids::to_string(l->id())); // else { // // for root node // res.emplace_front(""); // break; // } // if((parent = l->owner())) { // l = parent->handle(); // } //} while(parent); //return boost::join(res, "/"); } std::string convert_path( std::string src_path, const sp_clink& start, Key src_path_unit, Key dst_path_unit ) { std::string res_path; // convert from ID-based path to human-readable const auto converter = [&res_path, src_path_unit, dst_path_unit](std::string part, const sp_node& level) { sp_link res; if(part != "..") { const auto next = level->find(part, src_path_unit); if(next != level->end()) { res = *next; part = link2path_unit(res, dst_path_unit); } } // append link ID to link's path if(res_path.size()) res_path += '/'; res_path += std::move(part); return res; }; // do conversion boost::trim(src_path); detail::deref_path(src_path, *start, converter); // if abs path given, return abs path if(src_path[0] == '/') res_path.insert(res_path.begin(), '/'); return res_path; } sp_link deref_path(const std::string& path, const sp_link& start, node::Key path_unit) { if(!start) return nullptr; return detail::deref_path(path, *start, detail::gen_walk_down_tree(path_unit)); } void walk(const sp_link& root, step_process_fp step_f, bool topdown, bool follow_symlinks) { walk_impl({root}, step_f, topdown, follow_symlinks); } void walk(const sp_link& root, const step_process_f& step_f,bool topdown, bool follow_symlinks) { walk_impl({root}, step_f, topdown, follow_symlinks); } auto make_root_link( const std::string& link_type, std::string name, sp_node root_node ) -> sp_link { if(!root_node) root_node = std::make_shared<node>(); // create link depending on type if(link_type == "fusion_link") return link::make_root<fusion_link>(std::move(name), std::move(root_node)); else return link::make_root<hard_link>(std::move(name), std::move(root_node)); } NAMESPACE_END(tree) NAMESPACE_END(blue_sky) <commit_msg>tree: fix `tree::walk()` honor `LazyLoad` flag<commit_after>/// @file /// @author uentity /// @date 22.11.2017 /// @brief BS tree-related functions impl /// @copyright /// 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 https://mozilla.org/MPL/2.0/ #include <bs/tree/tree.h> #include "tree_impl.h" #include <set> #include <boost/uuid/uuid_io.hpp> #include <boost/algorithm/string.hpp> #define CAN_CALL_DNODE(L) \ ( !(L->flags() & link::LazyLoad) || L->req_status(link::Req::DataNode) == link::ReqStatus::OK ) NAMESPACE_BEGIN(blue_sky) NAMESPACE_BEGIN(tree) using Key = node::Key; template<Key K> using Key_type = typename node::Key_type<K>; /*----------------------------------------------------------------------------- * impl details *-----------------------------------------------------------------------------*/ // hidden namespace { template<class Callback> void walk_impl( const std::vector<sp_link>& nodes, const Callback& step_f, const bool topdown, const bool follow_symlinks, std::set<Key_type<Key::ID>> active_symlinks = {} ) { sp_node cur_node; std::vector<sp_link> next_nodes; std::vector<sp_link> next_leafs; // for each node for(const auto& N : nodes) { if(!N) continue; // remember symlink const auto is_symlink = N->type_id() == "sym_link"; if(is_symlink) { if(follow_symlinks && active_symlinks.find(N->id()) == active_symlinks.end()) active_symlinks.insert(N->id()); else continue; } // obtain node from link honoring LazyLoad flag cur_node = CAN_CALL_DNODE(N) ? N->data_node() : nullptr; next_nodes.clear(); next_leafs.clear(); if(cur_node) { // for each link in node for(const auto& l : *cur_node) { // collect nodes if(CAN_CALL_DNODE(l) && l->data_node()) { next_nodes.push_back(l); } else next_leafs.push_back(l); } } // if `topdown` == true, process this node BEFORE leafs processing if(topdown) step_f(N, next_nodes, next_leafs); // process list of next nodes if(!next_nodes.empty()) walk_impl(next_nodes, step_f, topdown, follow_symlinks, active_symlinks); // if walking from most deep subdir, process current node after all subtree if(!topdown) step_f(N, next_nodes, next_leafs); // forget symlink if(is_symlink) active_symlinks.erase(N->id()); } } inline std::string link2path_unit(const sp_clink& l, Key path_unit) { switch(path_unit) { default: case Key::ID : return boost::uuids::to_string(l->id()); case Key::OID : return l->oid(); case Key::Name : return l->name(); case Key::Type : return l->type_id(); } } } // hidden ns // public NAMESPACE_BEGIN(detail) sp_link walk_down_tree(const std::string& cur_lid, const sp_node& level, node::Key path_unit) { if(cur_lid != "..") { const auto next = level->find(cur_lid, path_unit); if(next != level->end()) { return *next; } } return nullptr; } NAMESPACE_END(detail) /*----------------------------------------------------------------------------- * public API *-----------------------------------------------------------------------------*/ std::string abspath(sp_clink l, Key path_unit) { std::deque<std::string> res; while(l) { res.push_front(link2path_unit(l, path_unit)); if(const auto parent = l->owner()) { l = parent->handle(); } else return boost::join(res, "/"); } // leadind slash is appended only if we have 'real' root node without self link return std::string("/") + boost::join(res, "/"); // another possible implementation without multiple returns // just leave it here -) //sp_node parent; //do { // if(l) // res.push_front(human_readable ? l->name() : boost::uuids::to_string(l->id())); // else { // // for root node // res.emplace_front(""); // break; // } // if((parent = l->owner())) { // l = parent->handle(); // } //} while(parent); //return boost::join(res, "/"); } std::string convert_path( std::string src_path, const sp_clink& start, Key src_path_unit, Key dst_path_unit ) { std::string res_path; // convert from ID-based path to human-readable const auto converter = [&res_path, src_path_unit, dst_path_unit](std::string part, const sp_node& level) { sp_link res; if(part != "..") { const auto next = level->find(part, src_path_unit); if(next != level->end()) { res = *next; part = link2path_unit(res, dst_path_unit); } } // append link ID to link's path if(res_path.size()) res_path += '/'; res_path += std::move(part); return res; }; // do conversion boost::trim(src_path); detail::deref_path(src_path, *start, converter); // if abs path given, return abs path if(src_path[0] == '/') res_path.insert(res_path.begin(), '/'); return res_path; } sp_link deref_path(const std::string& path, const sp_link& start, node::Key path_unit) { if(!start) return nullptr; return detail::deref_path(path, *start, detail::gen_walk_down_tree(path_unit)); } void walk(const sp_link& root, step_process_fp step_f, bool topdown, bool follow_symlinks) { walk_impl({root}, step_f, topdown, follow_symlinks); } void walk(const sp_link& root, const step_process_f& step_f,bool topdown, bool follow_symlinks) { walk_impl({root}, step_f, topdown, follow_symlinks); } auto make_root_link( const std::string& link_type, std::string name, sp_node root_node ) -> sp_link { if(!root_node) root_node = std::make_shared<node>(); // create link depending on type if(link_type == "fusion_link") return link::make_root<fusion_link>(std::move(name), std::move(root_node)); else return link::make_root<hard_link>(std::move(name), std::move(root_node)); } NAMESPACE_END(tree) NAMESPACE_END(blue_sky) <|endoftext|>
<commit_before>#include <sstream> #include <cstdint> #include "xUnit++/xUnit++.h" SUITE("ToString") { DATA_THEORY("ToString should not move parameters", (const std::string &s), []() -> std::vector<std::tuple<std::string>> { std::vector<std::tuple<std::string>> data; data.emplace_back("ABCD"); return data; }) { Assert.Equal("ABCD", s); } FACT("ToString will print pointer addresses") { int x; int y; auto result = Assert.Throws<xUnitpp::xUnitAssert>([&]() { Assert.Equal(&x, &y); }); std::stringstream str; str << "int *: " << std::showbase << std::hex << reinterpret_cast<intptr_t>(&x); Assert.Equal(str.str(), result.Expected()); } } <commit_msg>fixes #23: tostring unittest failing<commit_after>#include <sstream> #include <cstdint> #include <typeinfo> #include "xUnit++/xUnit++.h" SUITE("ToString") { DATA_THEORY("ToString should not move parameters", (const std::string &s), []() -> std::vector<std::tuple<std::string>> { std::vector<std::tuple<std::string>> data; data.emplace_back("ABCD"); return data; }) { Assert.Equal("ABCD", s); } FACT("ToString will print pointer addresses") { int x; int y; auto result = Assert.Throws<xUnitpp::xUnitAssert>([&]() { Assert.Equal(&x, &y); }); std::stringstream str; str << typeid(int).name() << " *: " << std::showbase << std::hex << reinterpret_cast<intptr_t>(&x); Assert.Equal(str.str(), result.Expected()); } } <|endoftext|>
<commit_before>// Probabilistic Question-Answering system // @2017 Sarge Rogatch // This software is distributed under GNU AGPLv3 license. See file LICENSE in repository root for details. #include "stdafx.h" #include "../PqaCore/PermanentIdManager.h" using namespace SRPlat; namespace ProbQA { TPqaId PermanentIdManager::PermFromComp(const TPqaId compId) { if (compId >= TPqaId(_comp2perm.size())) { return cInvalidPqaId; } return _comp2perm[compId]; } TPqaId PermanentIdManager::CompFromPerm(const TPqaId permId) { auto it = _perm2comp.find(permId); if (it == _perm2comp.end()) { return cInvalidPqaId; } return it->second; } bool PermanentIdManager::Save(FILE *fpout, const bool empty) { const TPqaId nComp = (empty ? 0 : _comp2perm.size()); if (fwrite(&_nextPermId, sizeof(_nextPermId), 1, fpout) != 1) { return false; } if (fwrite(&nComp, sizeof(nComp), 1, fpout) != 1) { return false; } if (TPqaId(fwrite(_comp2perm.data(), sizeof(_comp2perm[0]), nComp, fpout)) != nComp) { return false; } return true; } bool PermanentIdManager::Load(FILE *fpin) { TPqaId nComp; if (fread(&_nextPermId, sizeof(_nextPermId), 1, fpin) != 1) { return false; } if (fread(&nComp, sizeof(nComp), 1, fpin) != 1) { return false; } _comp2perm.resize(nComp); _perm2comp.clear(); if (TPqaId(fread(_comp2perm.data(), sizeof(_comp2perm[0]), nComp, fpin)) != nComp) { return false; } for (TPqaId i = 0; i < nComp; i++) { if (_comp2perm[i] == cInvalidPqaId) { continue; } _perm2comp.emplace(_comp2perm[i], i); } return true; } bool PermanentIdManager::EnsurePermIdGreater(const TPqaId bound) { if (_nextPermId <= bound) { _nextPermId = bound + 1; return true; } return false; } bool PermanentIdManager::RemoveComp(const TPqaId compId) { if (compId >= TPqaId(_comp2perm.size())) { SRUtils::RequestDebug(); return false; } const TPqaId iPerm = _comp2perm[compId]; if (iPerm == cInvalidPqaId) { SRUtils::RequestDebug(); return false; } auto it = _perm2comp.find(iPerm); if (it == _perm2comp.end()) { //TODO: actually, this is inconsistency in the manager itself - consider throwing an exception SRUtils::RequestDebug(); return false; } _perm2comp.erase(it); _comp2perm[compId] = cInvalidPqaId; return true; } bool PermanentIdManager::RenewComp(const TPqaId compId) { if (compId >= TPqaId(_comp2perm.size())) { SRUtils::RequestDebug(); return false; // out of range for compact IDs on record } if (_comp2perm[compId] != cInvalidPqaId) { // Compact ID is already mapped to a permanent ID. Use RemoveComp() first. SRUtils::RequestDebug(); return false; } _comp2perm[compId] = _nextPermId; _perm2comp.emplace(_nextPermId, compId); _nextPermId++; return true; } bool PermanentIdManager::GrowTo(const TPqaId nComp) { if (nComp < TPqaId(_comp2perm.size())) { SRUtils::RequestDebug(); return false; } for (TPqaId i = _comp2perm.size(); i < nComp; i++) { _comp2perm.push_back(_nextPermId); _perm2comp.emplace(_nextPermId, i); _nextPermId++; } return true; } bool PermanentIdManager::OnCompact(const TPqaId nNew, const TPqaId *pOldIds) { if (nNew > TPqaId(_comp2perm.size())) { SRUtils::RequestDebug(); return false; } if (nNew != TPqaId(_perm2comp.size())) { SRUtils::RequestDebug(); return false; } for (TPqaId i = 0; i < nNew; i++) { const TPqaId oldComp = pOldIds[i]; if (oldComp < 0 || oldComp >= TPqaId(_comp2perm.size())) { SRUtils::RequestDebug(); return false; } const TPqaId oldPerm = _comp2perm[oldComp]; if (oldPerm == cInvalidPqaId) { //TODO: actually, this is inconsistency in the manager itself - consider throwing an exception SRUtils::RequestDebug(); return false; } auto it = _perm2comp.find(oldPerm); if (it == _perm2comp.end()) { //TODO: actually, this is inconsistency in the manager itself - consider throwing an exception SRUtils::RequestDebug(); return false; } it->second = i; } _comp2perm.clear(); _comp2perm.resize(nNew, cInvalidPqaId); for (std::pair<TPqaId, TPqaId> m : _perm2comp) { if (m.second < 0 || m.second >= nNew) { //TODO: actually, this is inconsistency in the manager itself - consider throwing an exception SRUtils::RequestDebug(); return false; } _comp2perm[m.second] = m.first; } return true; } bool PermanentIdManager::RemapPermId(const TPqaId srcPermId, const TPqaId destPermId) { if (destPermId >= _nextPermId) { return false; // can't remap to future permId's } auto jt = _perm2comp.find(destPermId); if (jt != _perm2comp.end()) { return false; // there's already such permId on record } auto it = _perm2comp.find(srcPermId); if (it == _perm2comp.end()) { return false; // no such permId on record } const TPqaId compId = it->second; _perm2comp.erase(it); _perm2comp.emplace(destPermId, compId); _comp2perm[compId] = destPermId; return true; } } // namespace ProbQA <commit_msg>Fixed a bug where compact ID was not checked if it's below 0<commit_after>// Probabilistic Question-Answering system // @2017 Sarge Rogatch // This software is distributed under GNU AGPLv3 license. See file LICENSE in repository root for details. #include "stdafx.h" #include "../PqaCore/PermanentIdManager.h" using namespace SRPlat; namespace ProbQA { TPqaId PermanentIdManager::PermFromComp(const TPqaId compId) { if (compId < 0 || compId >= TPqaId(_comp2perm.size())) { return cInvalidPqaId; } return _comp2perm[compId]; } TPqaId PermanentIdManager::CompFromPerm(const TPqaId permId) { auto it = _perm2comp.find(permId); if (it == _perm2comp.end()) { return cInvalidPqaId; } return it->second; } bool PermanentIdManager::Save(FILE *fpout, const bool empty) { const TPqaId nComp = (empty ? 0 : _comp2perm.size()); if (fwrite(&_nextPermId, sizeof(_nextPermId), 1, fpout) != 1) { return false; } if (fwrite(&nComp, sizeof(nComp), 1, fpout) != 1) { return false; } if (TPqaId(fwrite(_comp2perm.data(), sizeof(_comp2perm[0]), nComp, fpout)) != nComp) { return false; } return true; } bool PermanentIdManager::Load(FILE *fpin) { TPqaId nComp; if (fread(&_nextPermId, sizeof(_nextPermId), 1, fpin) != 1) { return false; } if (fread(&nComp, sizeof(nComp), 1, fpin) != 1) { return false; } _comp2perm.resize(nComp); _perm2comp.clear(); if (TPqaId(fread(_comp2perm.data(), sizeof(_comp2perm[0]), nComp, fpin)) != nComp) { return false; } for (TPqaId i = 0; i < nComp; i++) { if (_comp2perm[i] == cInvalidPqaId) { continue; } _perm2comp.emplace(_comp2perm[i], i); } return true; } bool PermanentIdManager::EnsurePermIdGreater(const TPqaId bound) { if (_nextPermId <= bound) { _nextPermId = bound + 1; return true; } return false; } bool PermanentIdManager::RemoveComp(const TPqaId compId) { if (compId >= TPqaId(_comp2perm.size())) { SRUtils::RequestDebug(); return false; } const TPqaId iPerm = _comp2perm[compId]; if (iPerm == cInvalidPqaId) { SRUtils::RequestDebug(); return false; } auto it = _perm2comp.find(iPerm); if (it == _perm2comp.end()) { //TODO: actually, this is inconsistency in the manager itself - consider throwing an exception SRUtils::RequestDebug(); return false; } _perm2comp.erase(it); _comp2perm[compId] = cInvalidPqaId; return true; } bool PermanentIdManager::RenewComp(const TPqaId compId) { if (compId >= TPqaId(_comp2perm.size())) { SRUtils::RequestDebug(); return false; // out of range for compact IDs on record } if (_comp2perm[compId] != cInvalidPqaId) { // Compact ID is already mapped to a permanent ID. Use RemoveComp() first. SRUtils::RequestDebug(); return false; } _comp2perm[compId] = _nextPermId; _perm2comp.emplace(_nextPermId, compId); _nextPermId++; return true; } bool PermanentIdManager::GrowTo(const TPqaId nComp) { if (nComp < TPqaId(_comp2perm.size())) { SRUtils::RequestDebug(); return false; } for (TPqaId i = _comp2perm.size(); i < nComp; i++) { _comp2perm.push_back(_nextPermId); _perm2comp.emplace(_nextPermId, i); _nextPermId++; } return true; } bool PermanentIdManager::OnCompact(const TPqaId nNew, const TPqaId *pOldIds) { if (nNew > TPqaId(_comp2perm.size())) { SRUtils::RequestDebug(); return false; } if (nNew != TPqaId(_perm2comp.size())) { SRUtils::RequestDebug(); return false; } for (TPqaId i = 0; i < nNew; i++) { const TPqaId oldComp = pOldIds[i]; if (oldComp < 0 || oldComp >= TPqaId(_comp2perm.size())) { SRUtils::RequestDebug(); return false; } const TPqaId oldPerm = _comp2perm[oldComp]; if (oldPerm == cInvalidPqaId) { //TODO: actually, this is inconsistency in the manager itself - consider throwing an exception SRUtils::RequestDebug(); return false; } auto it = _perm2comp.find(oldPerm); if (it == _perm2comp.end()) { //TODO: actually, this is inconsistency in the manager itself - consider throwing an exception SRUtils::RequestDebug(); return false; } it->second = i; } _comp2perm.clear(); _comp2perm.resize(nNew, cInvalidPqaId); for (std::pair<TPqaId, TPqaId> m : _perm2comp) { if (m.second < 0 || m.second >= nNew) { //TODO: actually, this is inconsistency in the manager itself - consider throwing an exception SRUtils::RequestDebug(); return false; } _comp2perm[m.second] = m.first; } return true; } bool PermanentIdManager::RemapPermId(const TPqaId srcPermId, const TPqaId destPermId) { if (destPermId >= _nextPermId) { return false; // can't remap to future permId's } auto jt = _perm2comp.find(destPermId); if (jt != _perm2comp.end()) { return false; // there's already such permId on record } auto it = _perm2comp.find(srcPermId); if (it == _perm2comp.end()) { return false; // no such permId on record } const TPqaId compId = it->second; _perm2comp.erase(it); _perm2comp.emplace(destPermId, compId); _comp2perm[compId] = destPermId; return true; } } // namespace ProbQA <|endoftext|>
<commit_before>// ROS #include <ros/ros.h> // for debugging #include <iostream> // predicator stuff #include "predicator.h" #include "planning_tool.h" int main(int argc, char **argv) { ros::init(argc, argv, "predicator_planning_node"); predicator_planning::PredicateContext pc(true); int max_iter = 5000u; double step = 0.10; double chance = 0.30; double skip_distance = 0.75; ros::NodeHandle nh("~"); nh.param("max_iter", max_iter, int(5000)); nh.param("step", step, double(0.10)); nh.param("chance", chance, double(0.30)); nh.param("skip_distance", skip_distance, double(0.75)); predicator_planning::Planner planner(&pc, (unsigned int)max_iter, step, chance, skip_distance); // define spin rate ros::Rate rate(30); // start main loop while(ros::ok()) { ros::spinOnce(); pc.tick(); rate.sleep(); } pc.cleanup(); } <commit_msg>volume size parameter in main file; accessed as ros parameter<commit_after>// ROS #include <ros/ros.h> // for debugging #include <iostream> // predicator stuff #include "predicator.h" #include "planning_tool.h" int main(int argc, char **argv) { ros::init(argc, argv, "predicator_planning_node"); predicator_planning::PredicateContext pc(true); int max_iter = 5000u; double step = 0.10; double chance = 0.30; double skip_distance = 0.75; double search_volume = 0.50; ros::NodeHandle nh("~"); nh.param("max_iter", max_iter, int(5000)); nh.param("step", step, double(0.10)); nh.param("chance", chance, double(0.30)); nh.param("skip_distance", skip_distance, double(0.75)); nh.param("search_volume", search_volume, double(0.50)); predicator_planning::Planner planner(&pc, (unsigned int)max_iter, step, chance, skip_distance, search_volume); // define spin rate ros::Rate rate(30); // start main loop while(ros::ok()) { ros::spinOnce(); pc.tick(); rate.sleep(); } pc.cleanup(); } <|endoftext|>
<commit_before>//Author: Anders Strand Vestbo //Author: Uli Frankenfeld //Last Modified: 06.03.2001 //____________________________________ // AliL3Track // // Base track class for L3 //Changes: //14.03.01: Moved fHitNumbers from protected to private.-ASV // Set memory to zero in ctor. // Moved fNHits 2 private. Protected data members not a good idea after all. //19.03.01: Made the method void Set(AliL3Track) virtual. #include "AliL3RootTypes.h" #include "AliL3Logging.h" #include "AliL3Track.h" #include <math.h> ClassImp(AliL3Track) Float_t AliL3Track::BFACT = 0.0029980; Float_t AliL3Track::bField = 0.2; Double_t AliL3Track::pi=3.14159265358979323846; AliL3Track::AliL3Track() { //Constructor fNHits = 0; fMCid = -1; fKappa=0; fRadius=0; fCenterX=0; fCenterY=0; ComesFromMainVertex(false); fQ = 0; fPhi0=0; fPsi=0; fR0=0; fTanl=0; fZ0=0; fPt=0; fLength=0; fIsLocal=true; fRowRange[0]=0; fRowRange[1]=0; memset(fHitNumbers,0,174*sizeof(UInt_t)); } void AliL3Track::Set(AliL3Track *tpt){ SetRowRange(tpt->GetFirstRow(),tpt->GetLastRow()); SetPhi0(tpt->GetPhi0()); SetKappa(tpt->GetKappa()); SetNHits(tpt->GetNHits()); SetFirstPoint(tpt->GetFirstPointX(),tpt->GetFirstPointY(),tpt->GetFirstPointZ()); SetLastPoint(tpt->GetLastPointX(),tpt->GetLastPointY(),tpt->GetLastPointZ()); SetPt(tpt->GetPt()); SetPsi(tpt->GetPsi()); SetTgl(tpt->GetTgl()); SetCharge(tpt->GetCharge()); SetHits(tpt->GetNHits(),(UInt_t *)tpt->GetHitNumbers()); /* fPhi0 = track->GetPhi0(); fKappa = track->GetKappa(); fRowRange[0] = track->GetFirstRow(); fRowRange[1] = track->GetLastRow(); fQ = track->GetCharge(); fFirstPoint[0] = track->GetFirstPointX(); fFirstPoint[1] = track->GetFirstPointY(); fFirstPoint[2] = track->GetFirstPointZ(); fLastPoint[0] = track->GetLastPointX(); fLastPoint[1] = track->GetLastPointY(); fLastPoint[2] = track->GetLastPointZ(); fPt = track->GetPt(); fTanl = track->GetTgl(); fPsi = track->GetPsi(); fQ = track->GetCharge(); fNHits = track->GetNHits(); memcpy(fHitNumbers,track->GetHitNumbers(),fNHits*sizeof(UInt_t)); */ } AliL3Track::~AliL3Track() { } Double_t AliL3Track::GetP() const { // Returns total momentum. return fabs(GetPt())*sqrt(1. + GetTgl()*GetTgl()); } Double_t AliL3Track::GetPseudoRapidity() const { return 0.5 * log((GetP() + GetPz()) / (GetP() - GetPz())); } Double_t AliL3Track::GetEta() const { return GetPseudoRapidity(); } Double_t AliL3Track::GetRapidity() const { Double_t m_pi = 0.13957; return 0.5 * log((m_pi + GetPz()) / (m_pi - GetPz())); } void AliL3Track::CalculateHelix(){ //Calculate Radius, CenterX and Centery from Psi, X0, Y0 // fRadius = fPt / (BFACT*bField); if(fRadius) fKappa = 1./fRadius; else fRadius = 999999; //just zero Double_t trackPhi0 = fPsi + fQ *0.5 * pi; fCenterX = fFirstPoint[0] - fRadius * cos(trackPhi0); fCenterY = fFirstPoint[1] - fRadius * sin(trackPhi0); } Bool_t AliL3Track::CalculateReferencePoint(Double_t angle){ // Global coordinate: crossing point with y = ax+ b; a=tan(angle-Pi/2); // const Double_t rr=132; //position of referece plane const Double_t xr = cos(angle) *rr; const Double_t yr = sin(angle) *rr; Double_t a = tan(angle-pi/2); Double_t b = yr - a * xr; Double_t pp=(fCenterX+a*fCenterY-a*b)/(1+pow(a,2)); Double_t qq=(pow(fCenterX,2)+pow(fCenterY,2)-2*fCenterY*b+pow(b,2)-pow(fRadius,2))/(1+pow(a,2)); Double_t racine = pp*pp-qq; if(racine<0) return IsPoint(kFALSE); //no Point Double_t rootRacine = sqrt(racine); Double_t x0 = pp+rootRacine; Double_t x1 = pp-rootRacine; Double_t y0 = a*x0 + b; Double_t y1 = a*x1 + b; Double_t diff0 = sqrt(pow(x0-xr,2)+pow(y0-yr,2)); Double_t diff1 = sqrt(pow(x1-xr,2)+pow(y1-yr,2)); if(diff0<diff1){ fPoint[0]=x0; fPoint[1]=y0; } else{ fPoint[0]=x1; fPoint[1]=y1; } Double_t pointPhi0 = atan2(fPoint[1]-fCenterY,fPoint[0]-fCenterX); Double_t trackPhi0 = atan2(fFirstPoint[1]-fCenterY,fFirstPoint[0]-fCenterX); if(fabs(trackPhi0-pointPhi0)>pi){ if(trackPhi0<pointPhi0) trackPhi0 += 2*pi; else pointPhi0 += 2*pi; } Double_t stot = -fQ * (pointPhi0-trackPhi0) * fRadius ; fPoint[2] = fFirstPoint[2] + stot * fTanl; fPointPsi = pointPhi0 - fQ * 0.5 * pi; if(fPointPsi<0.) fPointPsi+= 2*pi; fPointPsi = fmod(fPointPsi, 2*pi); return IsPoint(kTRUE); } Bool_t AliL3Track::CalculateEdgePoint(Double_t angle){ // Global coordinate: crossing point with y = ax; a=tan(angle); // Double_t rmin=80; //min Radius of TPC Double_t rmax=260; //max Radius of TPC Double_t a = tan(angle); Double_t pp=(fCenterX+a*fCenterY)/(1+pow(a,2)); Double_t qq=(pow(fCenterX,2)+pow(fCenterY,2)-pow(fRadius,2))/(1+pow(a,2)); Double_t racine = pp*pp-qq; if(racine<0) return IsPoint(kFALSE); //no Point Double_t rootRacine = sqrt(racine); Double_t x0 = pp+rootRacine; Double_t x1 = pp-rootRacine; Double_t y0 = a*x0; Double_t y1 = a*x1; Double_t r0 = sqrt(pow(x0,2)+pow(y0,2)); Double_t r1 = sqrt(pow(x1,2)+pow(y1,2)); //find the right crossing point: //inside the TPC modules Bool_t ok0 = kFALSE; Bool_t ok1 = kFALSE; if(r0>rmin&&r0<rmax){ Double_t da=atan2(y0,x0); if(da<0) da+=pi; if(fabs(da-angle)<0.5) ok0 = kTRUE; } if(r1>rmin&&r1<rmax){ Double_t da=atan2(y1,y1); if(da<0) da+=pi; if(fabs(da-angle)<0.5) ok1 = kTRUE; } if(!(ok0||ok1)) return IsPoint(kFALSE); //no Point if(ok0&&ok1){ Double_t diff0 = sqrt(pow(fFirstPoint[0]-x0,2)+pow(fFirstPoint[1]-y0,2)); Double_t diff1 = sqrt(pow(fFirstPoint[0]-x1,2)+pow(fFirstPoint[1]-y1,2)); if(diff0<diff1) ok1 = kFALSE; //use ok0 else ok0 = kFALSE; //use ok1 } if(ok0){fPoint[0]=x0; fPoint[1]=y0;} else {fPoint[0]=x1; fPoint[1]=y1;} Double_t pointPhi0 = atan2(fPoint[1]-fCenterY,fPoint[0]-fCenterX); Double_t trackPhi0 = atan2(fFirstPoint[1]-fCenterY,fFirstPoint[0]-fCenterX); if(fabs(trackPhi0-pointPhi0)>pi){ if(trackPhi0<pointPhi0) trackPhi0 += 2*pi; else pointPhi0 += 2*pi; } Double_t stot = -fQ * (pointPhi0-trackPhi0) * fRadius ; fPoint[2] = fFirstPoint[2] + stot * fTanl; fPointPsi = pointPhi0 - fQ * 0.5 * pi; if(fPointPsi<0.) fPointPsi+= 2*pi; fPointPsi = fmod(fPointPsi, 2*pi); return IsPoint(kTRUE); } Bool_t AliL3Track::CalculatePoint(Double_t xplane){ // Local coordinate: crossing point with x plane // Double_t racine = pow(fRadius,2)-pow(xplane-fCenterX,2); if(racine<0) return IsPoint(kFALSE); Double_t rootRacine = sqrt(racine); Double_t y0 = fCenterY + rootRacine; Double_t y1 = fCenterY - rootRacine; //Double_t diff0 = sqrt(pow(fFirstPoint[0]-xplane)+pow(fFirstPoint[1]-y0)); //Double_t diff1 = sqrt(pow(fFirstPoint[0]-xplane)+pow(fFirstPoint[1]-y1)); Double_t diff0 = fabs(y0-fFirstPoint[1]); Double_t diff1 = fabs(y1-fFirstPoint[1]); fPoint[0]=xplane; if(diff0<diff1) fPoint[1]=y0; else fPoint[1]=y1; Double_t pointPhi0 = atan2(fPoint[1]-fCenterY,fPoint[0]-fCenterX); Double_t trackPhi0 = atan2(fFirstPoint[1]-fCenterY,fFirstPoint[0]-fCenterX); if(fabs(trackPhi0-pointPhi0)>pi){ if(trackPhi0<pointPhi0) trackPhi0 += 2*pi; else pointPhi0 += 2*pi; } Double_t stot = -fQ * (pointPhi0-trackPhi0) * fRadius ; fPoint[2] = fFirstPoint[2] + stot * fTanl; fPointPsi = pointPhi0 - fQ * 0.5 * pi; if(fPointPsi<0.) fPointPsi+= 2*pi; fPointPsi = fmod(fPointPsi, 2*pi); return IsPoint(kTRUE); } <commit_msg>Removed junk<commit_after>//Author: Anders Strand Vestbo //Author: Uli Frankenfeld //Last Modified: 06.03.2001 //____________________________________ // AliL3Track // // Base track class for L3 //Changes: //14.03.01: Moved fHitNumbers from protected to private.-ASV // Set memory to zero in ctor. // Moved fNHits 2 private. Protected data members not a good idea after all. //19.03.01: Made the method void Set(AliL3Track) virtual. #include "AliL3RootTypes.h" #include "AliL3Logging.h" #include "AliL3Track.h" #include <math.h> ClassImp(AliL3Track) Float_t AliL3Track::BFACT = 0.0029980; Float_t AliL3Track::bField = 0.2; Double_t AliL3Track::pi=3.14159265358979323846; AliL3Track::AliL3Track() { //Constructor fNHits = 0; fMCid = -1; fKappa=0; fRadius=0; fCenterX=0; fCenterY=0; ComesFromMainVertex(false); fQ = 0; fPhi0=0; fPsi=0; fR0=0; fTanl=0; fZ0=0; fPt=0; fLength=0; fIsLocal=true; fRowRange[0]=0; fRowRange[1]=0; memset(fHitNumbers,0,174*sizeof(UInt_t)); } void AliL3Track::Set(AliL3Track *tpt){ SetRowRange(tpt->GetFirstRow(),tpt->GetLastRow()); SetPhi0(tpt->GetPhi0()); SetKappa(tpt->GetKappa()); SetNHits(tpt->GetNHits()); SetFirstPoint(tpt->GetFirstPointX(),tpt->GetFirstPointY(),tpt->GetFirstPointZ()); SetLastPoint(tpt->GetLastPointX(),tpt->GetLastPointY(),tpt->GetLastPointZ()); SetPt(tpt->GetPt()); SetPsi(tpt->GetPsi()); SetTgl(tpt->GetTgl()); SetCharge(tpt->GetCharge()); SetHits(tpt->GetNHits(),(UInt_t *)tpt->GetHitNumbers()); } AliL3Track::~AliL3Track() { } Double_t AliL3Track::GetP() const { // Returns total momentum. return fabs(GetPt())*sqrt(1. + GetTgl()*GetTgl()); } Double_t AliL3Track::GetPseudoRapidity() const { return 0.5 * log((GetP() + GetPz()) / (GetP() - GetPz())); } Double_t AliL3Track::GetEta() const { return GetPseudoRapidity(); } Double_t AliL3Track::GetRapidity() const { Double_t m_pi = 0.13957; return 0.5 * log((m_pi + GetPz()) / (m_pi - GetPz())); } void AliL3Track::CalculateHelix(){ //Calculate Radius, CenterX and Centery from Psi, X0, Y0 // fRadius = fPt / (BFACT*bField); if(fRadius) fKappa = 1./fRadius; else fRadius = 999999; //just zero Double_t trackPhi0 = fPsi + fQ *0.5 * pi; fCenterX = fFirstPoint[0] - fRadius * cos(trackPhi0); fCenterY = fFirstPoint[1] - fRadius * sin(trackPhi0); } Bool_t AliL3Track::CalculateReferencePoint(Double_t angle){ // Global coordinate: crossing point with y = ax+ b; a=tan(angle-Pi/2); // const Double_t rr=132; //position of referece plane const Double_t xr = cos(angle) *rr; const Double_t yr = sin(angle) *rr; Double_t a = tan(angle-pi/2); Double_t b = yr - a * xr; Double_t pp=(fCenterX+a*fCenterY-a*b)/(1+pow(a,2)); Double_t qq=(pow(fCenterX,2)+pow(fCenterY,2)-2*fCenterY*b+pow(b,2)-pow(fRadius,2))/(1+pow(a,2)); Double_t racine = pp*pp-qq; if(racine<0) return IsPoint(kFALSE); //no Point Double_t rootRacine = sqrt(racine); Double_t x0 = pp+rootRacine; Double_t x1 = pp-rootRacine; Double_t y0 = a*x0 + b; Double_t y1 = a*x1 + b; Double_t diff0 = sqrt(pow(x0-xr,2)+pow(y0-yr,2)); Double_t diff1 = sqrt(pow(x1-xr,2)+pow(y1-yr,2)); if(diff0<diff1){ fPoint[0]=x0; fPoint[1]=y0; } else{ fPoint[0]=x1; fPoint[1]=y1; } Double_t pointPhi0 = atan2(fPoint[1]-fCenterY,fPoint[0]-fCenterX); Double_t trackPhi0 = atan2(fFirstPoint[1]-fCenterY,fFirstPoint[0]-fCenterX); if(fabs(trackPhi0-pointPhi0)>pi){ if(trackPhi0<pointPhi0) trackPhi0 += 2*pi; else pointPhi0 += 2*pi; } Double_t stot = -fQ * (pointPhi0-trackPhi0) * fRadius ; fPoint[2] = fFirstPoint[2] + stot * fTanl; fPointPsi = pointPhi0 - fQ * 0.5 * pi; if(fPointPsi<0.) fPointPsi+= 2*pi; fPointPsi = fmod(fPointPsi, 2*pi); return IsPoint(kTRUE); } Bool_t AliL3Track::CalculateEdgePoint(Double_t angle){ // Global coordinate: crossing point with y = ax; a=tan(angle); // Double_t rmin=80; //min Radius of TPC Double_t rmax=260; //max Radius of TPC Double_t a = tan(angle); Double_t pp=(fCenterX+a*fCenterY)/(1+pow(a,2)); Double_t qq=(pow(fCenterX,2)+pow(fCenterY,2)-pow(fRadius,2))/(1+pow(a,2)); Double_t racine = pp*pp-qq; if(racine<0) return IsPoint(kFALSE); //no Point Double_t rootRacine = sqrt(racine); Double_t x0 = pp+rootRacine; Double_t x1 = pp-rootRacine; Double_t y0 = a*x0; Double_t y1 = a*x1; Double_t r0 = sqrt(pow(x0,2)+pow(y0,2)); Double_t r1 = sqrt(pow(x1,2)+pow(y1,2)); //find the right crossing point: //inside the TPC modules Bool_t ok0 = kFALSE; Bool_t ok1 = kFALSE; if(r0>rmin&&r0<rmax){ Double_t da=atan2(y0,x0); if(da<0) da+=pi; if(fabs(da-angle)<0.5) ok0 = kTRUE; } if(r1>rmin&&r1<rmax){ Double_t da=atan2(y1,y1); if(da<0) da+=pi; if(fabs(da-angle)<0.5) ok1 = kTRUE; } if(!(ok0||ok1)) return IsPoint(kFALSE); //no Point if(ok0&&ok1){ Double_t diff0 = sqrt(pow(fFirstPoint[0]-x0,2)+pow(fFirstPoint[1]-y0,2)); Double_t diff1 = sqrt(pow(fFirstPoint[0]-x1,2)+pow(fFirstPoint[1]-y1,2)); if(diff0<diff1) ok1 = kFALSE; //use ok0 else ok0 = kFALSE; //use ok1 } if(ok0){fPoint[0]=x0; fPoint[1]=y0;} else {fPoint[0]=x1; fPoint[1]=y1;} Double_t pointPhi0 = atan2(fPoint[1]-fCenterY,fPoint[0]-fCenterX); Double_t trackPhi0 = atan2(fFirstPoint[1]-fCenterY,fFirstPoint[0]-fCenterX); if(fabs(trackPhi0-pointPhi0)>pi){ if(trackPhi0<pointPhi0) trackPhi0 += 2*pi; else pointPhi0 += 2*pi; } Double_t stot = -fQ * (pointPhi0-trackPhi0) * fRadius ; fPoint[2] = fFirstPoint[2] + stot * fTanl; fPointPsi = pointPhi0 - fQ * 0.5 * pi; if(fPointPsi<0.) fPointPsi+= 2*pi; fPointPsi = fmod(fPointPsi, 2*pi); return IsPoint(kTRUE); } Bool_t AliL3Track::CalculatePoint(Double_t xplane){ // Local coordinate: crossing point with x plane // Double_t racine = pow(fRadius,2)-pow(xplane-fCenterX,2); if(racine<0) return IsPoint(kFALSE); Double_t rootRacine = sqrt(racine); Double_t y0 = fCenterY + rootRacine; Double_t y1 = fCenterY - rootRacine; //Double_t diff0 = sqrt(pow(fFirstPoint[0]-xplane)+pow(fFirstPoint[1]-y0)); //Double_t diff1 = sqrt(pow(fFirstPoint[0]-xplane)+pow(fFirstPoint[1]-y1)); Double_t diff0 = fabs(y0-fFirstPoint[1]); Double_t diff1 = fabs(y1-fFirstPoint[1]); fPoint[0]=xplane; if(diff0<diff1) fPoint[1]=y0; else fPoint[1]=y1; Double_t pointPhi0 = atan2(fPoint[1]-fCenterY,fPoint[0]-fCenterX); Double_t trackPhi0 = atan2(fFirstPoint[1]-fCenterY,fFirstPoint[0]-fCenterX); if(fabs(trackPhi0-pointPhi0)>pi){ if(trackPhi0<pointPhi0) trackPhi0 += 2*pi; else pointPhi0 += 2*pi; } Double_t stot = -fQ * (pointPhi0-trackPhi0) * fRadius ; fPoint[2] = fFirstPoint[2] + stot * fTanl; fPointPsi = pointPhi0 - fQ * 0.5 * pi; if(fPointPsi<0.) fPointPsi+= 2*pi; fPointPsi = fmod(fPointPsi, 2*pi); return IsPoint(kTRUE); } <|endoftext|>
<commit_before>/******************************************************************************\ * File: svn.cpp * Purpose: Implementation of wxExSVN class * Author: Anton van Wezenbeek * RCS-ID: $Id$ * * Copyright (c) 1998-2009 Anton van Wezenbeek * All rights are reserved. Reproduction in whole or part is prohibited * without the written consent of the copyright owner. \******************************************************************************/ #include <wx/config.h> #include <wx/extension/svn.h> #include <wx/extension/configdlg.h> #include <wx/extension/defs.h> #include <wx/extension/log.h> #include <wx/extension/stc.h> #include <wx/extension/util.h> wxExSVN* wxExSVN::m_Self = NULL; #if wxUSE_GUI wxExSTCEntryDialog* wxExSVN::m_STCEntryDialog = NULL; #endif wxString wxExSVN::m_UsageKey; wxExSVN::wxExSVN() : m_Type(SVN_NONE) , m_FullPath(wxEmptyString) { Initialize(); } wxExSVN::wxExSVN(int command_id, const wxString& fullpath) : m_Type(GetType(command_id)) , m_FullPath(fullpath) { Initialize(); } wxExSVN::wxExSVN(wxExSVNType type, const wxString& fullpath) : m_Type(type) , m_FullPath(fullpath) { Initialize(); } #if wxUSE_GUI int wxExSVN::ConfigDialog( wxWindow* parent, const wxString& title) const { std::vector<wxExConfigItem> v; v.push_back(wxExConfigItem()); // a spacer v.push_back(wxExConfigItem(m_UsageKey, CONFIG_CHECKBOX)); v.push_back(wxExConfigItem(_("Comparator"), CONFIG_FILEPICKERCTRL)); return wxExConfigDialog(parent, v, title).ShowModal(); } #endif bool wxExSVN::DirExists(const wxFileName& filename) const { wxFileName path(filename); path.AppendDir(".svn"); return path.DirExists(); } wxStandardID wxExSVN::Execute() { wxASSERT(m_Type != SVN_NONE); const wxString cwd = wxGetCwd(); wxString file; if (m_FullPath.empty()) { if (!wxSetWorkingDirectory(wxExConfigFirstOf(_("Base folder")))) { m_Output = _("Cannot set working directory"); m_ReturnCode = wxID_ABORT; return m_ReturnCode; } if (m_Type == SVN_ADD) { file = wxExConfigFirstOf(_("Path")); } } else { file = " \"" + m_FullPath + "\""; } wxString comment; if (m_Type == SVN_COMMIT) { comment = " -m \"" + wxExConfigFirstOf(_("Revision comment")) + "\""; } wxString flags; wxString subcommand; if (UseSubcommand()) { subcommand = wxConfigBase::Get()->Read(_("Subcommand")); if (!subcommand.empty()) { subcommand = " " + subcommand; } } if (UseFlags()) { flags = wxConfigBase::Get()->Read(_("Flags")); if (!flags.empty()) { flags = " " + flags; } } m_CommandWithFlags = m_Command + flags; const wxString commandline = "svn " + m_Command + subcommand + flags + comment + file; wxArrayString output; wxArrayString errors; m_Output.clear(); if (wxExecute( commandline, output, errors) == -1) { if (m_Output.empty()) { m_Output = "Could not execute: " + commandline; } m_ReturnCode = wxID_ABORT; return m_ReturnCode; } wxExLog::Get()->Log(commandline); if (m_FullPath.empty()) { wxSetWorkingDirectory(cwd); } // First output the errors. for (size_t i = 0; i < errors.GetCount(); i++) { m_Output += errors[i] + "\n"; } // Then the normal output, will be empty if there are errors. for (size_t j = 0; j < output.GetCount(); j++) { m_Output += output[j] + "\n"; } m_ReturnCode = wxID_OK; return m_ReturnCode; } #if wxUSE_GUI wxStandardID wxExSVN::Execute(wxWindow* parent) { wxASSERT(parent != NULL); // Key SVN is already used, so use other name. const wxString svn_flags_name = wxString::Format("svnflags/name%d", m_Type); std::vector<wxExConfigItem> v; if (m_Type == SVN_COMMIT) { v.push_back(wxExConfigItem( _("Revision comment"), CONFIG_COMBOBOX, wxEmptyString, true)); // required } if (m_FullPath.empty() && m_Type != SVN_HELP) { v.push_back(wxExConfigItem( _("Base folder"), CONFIG_COMBOBOXDIR, wxEmptyString, true)); // required if (m_Type == SVN_ADD) { v.push_back(wxExConfigItem( _("Path"), CONFIG_COMBOBOX, wxEmptyString, true)); // required } } if (UseFlags()) { wxConfigBase::Get()->Write( _("Flags"), wxConfigBase::Get()->Read(svn_flags_name)); v.push_back(wxExConfigItem(_("Flags"))); } if (UseSubcommand()) { v.push_back(wxExConfigItem(_("Subcommand"))); } m_ReturnCode = (wxStandardID)wxExConfigDialog(parent, v, m_Caption).ShowModal(); if (m_ReturnCode == wxID_CANCEL) { return m_ReturnCode; } if (UseFlags()) { wxConfigBase::Get()->Write(svn_flags_name, wxConfigBase::Get()->Read(svn_flags_name)); } return Execute(); } #endif #if wxUSE_GUI wxStandardID wxExSVN::ExecuteAndShowOutput(wxWindow* parent) { // We must have a parent. wxASSERT(parent != NULL); // If an error occurred, already shown by wxExecute itself. if (Execute(parent) == wxID_OK) { ShowOutput(parent); } return m_ReturnCode; } #endif wxExSVN* wxExSVN::Get(bool createOnDemand) { if (m_Self == NULL && createOnDemand) { m_Self = new wxExSVN; if (!wxConfigBase::Get()->Exists(m_UsageKey)) { if (!wxConfigBase::Get()->Write(m_UsageKey, true)) { wxFAIL; } } } return m_Self; } wxExSVNType wxExSVN::GetType(int command_id) const { switch (command_id) { case ID_EDIT_SVN_ADD: return SVN_ADD; break; case ID_EDIT_SVN_BLAME: return SVN_BLAME; break; case ID_EDIT_SVN_CAT: return SVN_CAT; break; case ID_EDIT_SVN_COMMIT: return SVN_COMMIT; break; case ID_EDIT_SVN_DIFF: return SVN_DIFF; break; case ID_EDIT_SVN_HELP: return SVN_HELP; break; case ID_EDIT_SVN_INFO: return SVN_INFO; break; case ID_EDIT_SVN_LOG: return SVN_LOG; break; case ID_EDIT_SVN_PROPLIST: return SVN_PROPLIST; break; case ID_EDIT_SVN_PROPSET: return SVN_PROPSET; break; case ID_EDIT_SVN_REVERT: return SVN_REVERT; break; case ID_EDIT_SVN_STAT: return SVN_STAT; break; case ID_EDIT_SVN_UPDATE: return SVN_UPDATE; break; default: wxFAIL; return SVN_NONE; break; } } void wxExSVN::Initialize() { switch (m_Type) { case SVN_NONE: m_Caption = ""; break; case SVN_ADD: m_Caption = "SVN Add"; break; case SVN_BLAME: m_Caption = "SVN Blame"; break; case SVN_CAT: m_Caption = "SVN Cat"; break; case SVN_COMMIT: m_Caption = "SVN Commit"; break; case SVN_DIFF: m_Caption = "SVN Diff"; break; case SVN_HELP: m_Caption = "SVN Help"; break; case SVN_INFO: m_Caption = "SVN Info"; break; case SVN_LOG: m_Caption = "SVN Log"; break; case SVN_LS: m_Caption = "SVN Ls"; break; case SVN_PROPLIST: m_Caption = "SVN Proplist"; break; case SVN_PROPSET: m_Caption = "SVN Propset"; break; case SVN_REVERT: m_Caption = "SVN Revert"; break; case SVN_STAT: m_Caption = "SVN Stat"; break; case SVN_UPDATE: m_Caption = "SVN Update"; break; default: wxFAIL; break; } m_Command = m_Caption.AfterFirst(' ').Lower(); // Currently no flags, as no command was executed. m_CommandWithFlags = m_Command; m_Output.clear(); m_ReturnCode = wxID_NONE; m_UsageKey = _("Use SVN"); } wxExSVN* wxExSVN::Set(wxExSVN* svn) { wxExSVN* old = m_Self; m_Self = svn; return old; } #if wxUSE_GUI void wxExSVN::ShowOutput(wxWindow* parent) const { switch (m_ReturnCode) { case wxID_CANCEL: break; case wxID_ABORT: wxMessageBox(m_Output); break; case wxID_OK: { wxString caption = m_Caption; if (m_Type != SVN_HELP) { caption += " " + (!m_FullPath.empty() ? wxFileName(m_FullPath).GetFullName(): wxExConfigFirstOf(_("Base folder"))); } // Create a dialog for contents. if (m_STCEntryDialog == NULL) { m_STCEntryDialog = new wxExSTCEntryDialog( parent, caption, m_Output, wxEmptyString, wxOK, wxID_ANY, wxDefaultPosition, wxSize(575, 250)); } else { m_STCEntryDialog->SetText(m_Output); m_STCEntryDialog->SetTitle(caption); // Reset a previous lexer. if (!m_STCEntryDialog->GetLexer().empty()) { m_STCEntryDialog->SetLexer(wxEmptyString); } } // Add a lexer if we specified a path, asked for cat or blame // and there is a lexer. if ( !m_FullPath.empty() && (m_Type == SVN_CAT || m_Type == SVN_BLAME)) { const wxExFileName fn(m_FullPath); if (!fn.GetLexer().GetScintillaLexer().empty()) { m_STCEntryDialog->SetLexer(fn.GetLexer().GetScintillaLexer()); } } m_STCEntryDialog->Show(); } break; default: wxFAIL; break; } } #endif bool wxExSVN::Use() const { return wxConfigBase::Get()->ReadBool(m_UsageKey, true); } bool wxExSVN::UseFlags() const { return m_Type != SVN_UPDATE && m_Type != SVN_HELP; } bool wxExSVN::UseSubcommand() const { return m_Type == SVN_HELP; } <commit_msg>fixed error with flags<commit_after>/******************************************************************************\ * File: svn.cpp * Purpose: Implementation of wxExSVN class * Author: Anton van Wezenbeek * RCS-ID: $Id$ * * Copyright (c) 1998-2009 Anton van Wezenbeek * All rights are reserved. Reproduction in whole or part is prohibited * without the written consent of the copyright owner. \******************************************************************************/ #include <wx/config.h> #include <wx/extension/svn.h> #include <wx/extension/configdlg.h> #include <wx/extension/defs.h> #include <wx/extension/log.h> #include <wx/extension/stc.h> #include <wx/extension/util.h> wxExSVN* wxExSVN::m_Self = NULL; #if wxUSE_GUI wxExSTCEntryDialog* wxExSVN::m_STCEntryDialog = NULL; #endif wxString wxExSVN::m_UsageKey; wxExSVN::wxExSVN() : m_Type(SVN_NONE) , m_FullPath(wxEmptyString) { Initialize(); } wxExSVN::wxExSVN(int command_id, const wxString& fullpath) : m_Type(GetType(command_id)) , m_FullPath(fullpath) { Initialize(); } wxExSVN::wxExSVN(wxExSVNType type, const wxString& fullpath) : m_Type(type) , m_FullPath(fullpath) { Initialize(); } #if wxUSE_GUI int wxExSVN::ConfigDialog( wxWindow* parent, const wxString& title) const { std::vector<wxExConfigItem> v; v.push_back(wxExConfigItem()); // a spacer v.push_back(wxExConfigItem(m_UsageKey, CONFIG_CHECKBOX)); v.push_back(wxExConfigItem(_("Comparator"), CONFIG_FILEPICKERCTRL)); return wxExConfigDialog(parent, v, title).ShowModal(); } #endif bool wxExSVN::DirExists(const wxFileName& filename) const { wxFileName path(filename); path.AppendDir(".svn"); return path.DirExists(); } wxStandardID wxExSVN::Execute() { wxASSERT(m_Type != SVN_NONE); const wxString cwd = wxGetCwd(); wxString file; if (m_FullPath.empty()) { if (!wxSetWorkingDirectory(wxExConfigFirstOf(_("Base folder")))) { m_Output = _("Cannot set working directory"); m_ReturnCode = wxID_ABORT; return m_ReturnCode; } if (m_Type == SVN_ADD) { file = wxExConfigFirstOf(_("Path")); } } else { file = " \"" + m_FullPath + "\""; } wxString comment; if (m_Type == SVN_COMMIT) { comment = " -m \"" + wxExConfigFirstOf(_("Revision comment")) + "\""; } wxString flags; wxString subcommand; if (UseSubcommand()) { subcommand = wxConfigBase::Get()->Read(_("Subcommand")); if (!subcommand.empty()) { subcommand = " " + subcommand; } } if (UseFlags()) { flags = wxConfigBase::Get()->Read(_("Flags")); if (!flags.empty()) { flags = " " + flags; } } m_CommandWithFlags = m_Command + flags; const wxString commandline = "svn " + m_Command + subcommand + flags + comment + file; wxArrayString output; wxArrayString errors; m_Output.clear(); if (wxExecute( commandline, output, errors) == -1) { if (m_Output.empty()) { m_Output = "Could not execute: " + commandline; } m_ReturnCode = wxID_ABORT; return m_ReturnCode; } wxExLog::Get()->Log(commandline); if (m_FullPath.empty()) { wxSetWorkingDirectory(cwd); } // First output the errors. for (size_t i = 0; i < errors.GetCount(); i++) { m_Output += errors[i] + "\n"; } // Then the normal output, will be empty if there are errors. for (size_t j = 0; j < output.GetCount(); j++) { m_Output += output[j] + "\n"; } m_ReturnCode = wxID_OK; return m_ReturnCode; } #if wxUSE_GUI wxStandardID wxExSVN::Execute(wxWindow* parent) { wxASSERT(parent != NULL); // Key SVN is already used, so use other name. const wxString svn_flags_name = wxString::Format("svnflags/name%d", m_Type); std::vector<wxExConfigItem> v; if (m_Type == SVN_COMMIT) { v.push_back(wxExConfigItem( _("Revision comment"), CONFIG_COMBOBOX, wxEmptyString, true)); // required } if (m_FullPath.empty() && m_Type != SVN_HELP) { v.push_back(wxExConfigItem( _("Base folder"), CONFIG_COMBOBOXDIR, wxEmptyString, true)); // required if (m_Type == SVN_ADD) { v.push_back(wxExConfigItem( _("Path"), CONFIG_COMBOBOX, wxEmptyString, true)); // required } } if (UseFlags()) { wxConfigBase::Get()->Write( _("Flags"), wxConfigBase::Get()->Read(svn_flags_name)); v.push_back(wxExConfigItem(_("Flags"))); } if (UseSubcommand()) { v.push_back(wxExConfigItem(_("Subcommand"))); } m_ReturnCode = (wxStandardID)wxExConfigDialog(parent, v, m_Caption).ShowModal(); if (m_ReturnCode == wxID_CANCEL) { return m_ReturnCode; } if (UseFlags()) { wxConfigBase::Get()->Write(svn_flags_name, wxConfigBase::Get()->Read(_("Flags"))); } return Execute(); } #endif #if wxUSE_GUI wxStandardID wxExSVN::ExecuteAndShowOutput(wxWindow* parent) { // We must have a parent. wxASSERT(parent != NULL); // If an error occurred, already shown by wxExecute itself. if (Execute(parent) == wxID_OK) { ShowOutput(parent); } return m_ReturnCode; } #endif wxExSVN* wxExSVN::Get(bool createOnDemand) { if (m_Self == NULL && createOnDemand) { m_Self = new wxExSVN; if (!wxConfigBase::Get()->Exists(m_UsageKey)) { if (!wxConfigBase::Get()->Write(m_UsageKey, true)) { wxFAIL; } } } return m_Self; } wxExSVNType wxExSVN::GetType(int command_id) const { switch (command_id) { case ID_EDIT_SVN_ADD: return SVN_ADD; break; case ID_EDIT_SVN_BLAME: return SVN_BLAME; break; case ID_EDIT_SVN_CAT: return SVN_CAT; break; case ID_EDIT_SVN_COMMIT: return SVN_COMMIT; break; case ID_EDIT_SVN_DIFF: return SVN_DIFF; break; case ID_EDIT_SVN_HELP: return SVN_HELP; break; case ID_EDIT_SVN_INFO: return SVN_INFO; break; case ID_EDIT_SVN_LOG: return SVN_LOG; break; case ID_EDIT_SVN_PROPLIST: return SVN_PROPLIST; break; case ID_EDIT_SVN_PROPSET: return SVN_PROPSET; break; case ID_EDIT_SVN_REVERT: return SVN_REVERT; break; case ID_EDIT_SVN_STAT: return SVN_STAT; break; case ID_EDIT_SVN_UPDATE: return SVN_UPDATE; break; default: wxFAIL; return SVN_NONE; break; } } void wxExSVN::Initialize() { switch (m_Type) { case SVN_NONE: m_Caption = ""; break; case SVN_ADD: m_Caption = "SVN Add"; break; case SVN_BLAME: m_Caption = "SVN Blame"; break; case SVN_CAT: m_Caption = "SVN Cat"; break; case SVN_COMMIT: m_Caption = "SVN Commit"; break; case SVN_DIFF: m_Caption = "SVN Diff"; break; case SVN_HELP: m_Caption = "SVN Help"; break; case SVN_INFO: m_Caption = "SVN Info"; break; case SVN_LOG: m_Caption = "SVN Log"; break; case SVN_LS: m_Caption = "SVN Ls"; break; case SVN_PROPLIST: m_Caption = "SVN Proplist"; break; case SVN_PROPSET: m_Caption = "SVN Propset"; break; case SVN_REVERT: m_Caption = "SVN Revert"; break; case SVN_STAT: m_Caption = "SVN Stat"; break; case SVN_UPDATE: m_Caption = "SVN Update"; break; default: wxFAIL; break; } m_Command = m_Caption.AfterFirst(' ').Lower(); // Currently no flags, as no command was executed. m_CommandWithFlags = m_Command; m_Output.clear(); m_ReturnCode = wxID_NONE; m_UsageKey = _("Use SVN"); } wxExSVN* wxExSVN::Set(wxExSVN* svn) { wxExSVN* old = m_Self; m_Self = svn; return old; } #if wxUSE_GUI void wxExSVN::ShowOutput(wxWindow* parent) const { switch (m_ReturnCode) { case wxID_CANCEL: break; case wxID_ABORT: wxMessageBox(m_Output); break; case wxID_OK: { wxString caption = m_Caption; if (m_Type != SVN_HELP) { caption += " " + (!m_FullPath.empty() ? wxFileName(m_FullPath).GetFullName(): wxExConfigFirstOf(_("Base folder"))); } // Create a dialog for contents. if (m_STCEntryDialog == NULL) { m_STCEntryDialog = new wxExSTCEntryDialog( parent, caption, m_Output, wxEmptyString, wxOK, wxID_ANY, wxDefaultPosition, wxSize(575, 250)); } else { m_STCEntryDialog->SetText(m_Output); m_STCEntryDialog->SetTitle(caption); // Reset a previous lexer. if (!m_STCEntryDialog->GetLexer().empty()) { m_STCEntryDialog->SetLexer(wxEmptyString); } } // Add a lexer if we specified a path, asked for cat or blame // and there is a lexer. if ( !m_FullPath.empty() && (m_Type == SVN_CAT || m_Type == SVN_BLAME)) { const wxExFileName fn(m_FullPath); if (!fn.GetLexer().GetScintillaLexer().empty()) { m_STCEntryDialog->SetLexer(fn.GetLexer().GetScintillaLexer()); } } m_STCEntryDialog->Show(); } break; default: wxFAIL; break; } } #endif bool wxExSVN::Use() const { return wxConfigBase::Get()->ReadBool(m_UsageKey, true); } bool wxExSVN::UseFlags() const { return m_Type != SVN_UPDATE && m_Type != SVN_HELP; } bool wxExSVN::UseSubcommand() const { return m_Type == SVN_HELP; } <|endoftext|>
<commit_before>//**************************************************************************** // Copyright © 2017 Jan Erik Breimo. All rights reserved. // Created by Jan Erik Breimo on 18.03.2017. // // This file is distributed under the BSD License. // License text is included with the source distribution. //**************************************************************************** #include "../Yson/JsonWriter.hpp" #include <limits> #include <sstream> #include "../Externals/Ytest/Ytest.hpp" namespace { using namespace Yson; void test_Basics() { std::ostringstream stream; JsonWriter writer(stream); writer.key("Key"); Y_EQUAL(writer.key(), "Key"); writer.beginArray().value(12345678) .endArray(); Y_EQUAL(stream.str(), "[12345678]"); } void test_EscapedString() { std::stringstream ss; JsonWriter(ss) .value("\"foo\nbar\t\\x89baz\""); std::string expected = "\"\\\"foo\\nbar\\t\\\\x89baz\\\"\""; Y_EQUAL(ss.str(), expected); } void test_ManualFormatting() { std::stringstream ss; JsonWriter(ss) .beginArray(JsonParameters(JsonFormatting::FLAT)) .writeNewline() .indent() .writeIndentation() .rawText("// A 4x4 sudoku") .writeNewline() .writeIndentation() .value(1).value(2).writeComma().writeSeparator(2) .value(3).value(4).writeComma().writeNewline() .writeIndentation() .value(3).value(4).writeComma().writeSeparator(2) .value(1).value(2).writeComma().writeNewline() .writeNewline() .writeIndentation() .value(2).value(1).writeComma().writeSeparator(2) .value(4).value(3).writeComma().writeNewline() .writeIndentation() .value(4).value(3).writeComma().writeSeparator(2) .value(2).value(1).writeNewline() .outdent() .endArray(); std::string expected = "[\n" " // A 4x4 sudoku\n" " 1, 2, 3, 4,\n" " 3, 4, 1, 2,\n" "\n" " 2, 1, 4, 3,\n" " 4, 3, 2, 1\n" "]"; Y_EQUAL(ss.str(), expected); } void test_MultiValueLines() { std::stringstream ss; JsonWriter(ss) .beginArray(JsonParameters(4)) .writeNewline().writeIndentation() .rawText("// A 4x4 sudoku").writeNewline() .value(1).value(2).writeComma().writeSeparator(2) .value(3).value(4) .value(3).value(4).writeComma().writeSeparator(2) .value(1).value(2) .writeComma().writeNewline().writeNewline() .value(2).value(1).writeComma().writeSeparator(2) .value(4).value(3) .value(4).value(3).writeComma().writeSeparator(2) .value(2).value(1) .endArray(); std::string expected = "[\n" " // A 4x4 sudoku\n" " 1, 2, 3, 4,\n" " 3, 4, 1, 2,\n" "\n" " 2, 1, 4, 3,\n" " 4, 3, 2, 1\n" "]"; Y_EQUAL(ss.str(), expected); } void test_SimpleObject() { std::stringstream ss; JsonWriter(ss, JsonFormatting::FORMAT) .beginObject() .key("name") .beginObject() .endObject() .endObject(); std::string expected = "{\n" " \"name\": {}\n" "}"; Y_EQUAL(ss.str(), expected); } template <typename T> void doTestInteger(T value, const std::string& expected) { std::stringstream ss; JsonWriter writer(ss); writer.value(value); Y_EQUAL(ss.str(), expected); } void test_Integers() { doTestInteger(32, "32"); doTestInteger(char(20), "20"); } void test_FloatingPointValues() { std::stringstream ss; JsonWriter writer(ss); Y_THROWS(writer.value(std::numeric_limits<double>::infinity()), std::logic_error); writer.setNonFiniteFloatsAsStringsEnabled(true); writer.value(std::numeric_limits<double>::infinity()); Y_EQUAL(ss.str(), "\"infinity\""); } void test_UnquotedValueNames() { std::stringstream ss; JsonWriter writer(ss); writer.setUnquotedValueNamesEnabled(true); writer.beginObject() .key("Key1").value(0) .key("$Key2_").value(1) .key("_Key$3").value(2) .key("4Key4").value(3) .key("Key 5").value(4) .endObject(); Y_EQUAL(ss.str(), "{Key1:0,$Key2_:1,_Key$3:2,\"4Key4\":3,\"Key 5\":4}"); } void test_FormatAndFlat() { std::stringstream ss; JsonWriter writer(ss, JsonFormatting::FORMAT); writer.beginObject(); writer.key("1").value(2); writer.key("array").beginArray(JsonParameters(JsonFormatting::FLAT)).value(1).value(2).endArray(); writer.endObject(); Y_EQUAL(ss.str(), "{\n" " \"1\": 2,\n" " \"array\": [1, 2]\n" "}"); } Y_TEST(test_Basics, test_EscapedString, test_ManualFormatting, test_MultiValueLines, test_SimpleObject, test_Integers, test_FloatingPointValues, test_UnquotedValueNames, test_FormatAndFlat); } <commit_msg>Added test for null, bool etc.<commit_after>//**************************************************************************** // Copyright © 2017 Jan Erik Breimo. All rights reserved. // Created by Jan Erik Breimo on 18.03.2017. // // This file is distributed under the BSD License. // License text is included with the source distribution. //**************************************************************************** #include "../Yson/JsonWriter.hpp" #include <limits> #include <sstream> #include "../Externals/Ytest/Ytest.hpp" namespace { using namespace Yson; void test_Basics() { std::ostringstream stream; JsonWriter writer(stream); writer.key("Key"); Y_EQUAL(writer.key(), "Key"); writer.beginArray().value(12345678) .endArray(); Y_EQUAL(stream.str(), "[12345678]"); } void test_EscapedString() { std::stringstream ss; JsonWriter(ss) .value("\"foo\nbar\t\\x89baz\""); std::string expected = "\"\\\"foo\\nbar\\t\\\\x89baz\\\"\""; Y_EQUAL(ss.str(), expected); } void test_ManualFormatting() { std::stringstream ss; JsonWriter(ss) .beginArray(JsonParameters(JsonFormatting::FLAT)) .writeNewline() .indent() .writeIndentation() .rawText("// A 4x4 sudoku") .writeNewline() .writeIndentation() .value(1).value(2).writeComma().writeSeparator(2) .value(3).value(4).writeComma().writeNewline() .writeIndentation() .value(3).value(4).writeComma().writeSeparator(2) .value(1).value(2).writeComma().writeNewline() .writeNewline() .writeIndentation() .value(2).value(1).writeComma().writeSeparator(2) .value(4).value(3).writeComma().writeNewline() .writeIndentation() .value(4).value(3).writeComma().writeSeparator(2) .value(2).value(1).writeNewline() .outdent() .endArray(); std::string expected = "[\n" " // A 4x4 sudoku\n" " 1, 2, 3, 4,\n" " 3, 4, 1, 2,\n" "\n" " 2, 1, 4, 3,\n" " 4, 3, 2, 1\n" "]"; Y_EQUAL(ss.str(), expected); } void test_SemiManualFormatting() { std::stringstream ss; JsonWriter(ss) .beginArray(JsonParameters(4)) .writeNewline().writeIndentation() .rawText("// A 4x4 sudoku").writeNewline() .value(1).value(2).writeComma().writeSeparator(2) .value(3).value(4) .value(3).value(4).writeComma().writeSeparator(2) .value(1).value(2) .writeComma().writeNewline().writeNewline() .value(2).value(1).writeComma().writeSeparator(2) .value(4).value(3) .value(4).value(3).writeComma().writeSeparator(2) .value(2).value(1) .endArray(); std::string expected = "[\n" " // A 4x4 sudoku\n" " 1, 2, 3, 4,\n" " 3, 4, 1, 2,\n" "\n" " 2, 1, 4, 3,\n" " 4, 3, 2, 1\n" "]"; Y_EQUAL(ss.str(), expected); } void test_SimpleObject() { std::stringstream ss; JsonWriter(ss, JsonFormatting::FORMAT) .beginObject() .key("name") .beginObject() .endObject() .endObject(); std::string expected = "{\n" " \"name\": {}\n" "}"; Y_EQUAL(ss.str(), expected); } template <typename T> void doTestInteger(T value, const std::string& expected) { std::stringstream ss; JsonWriter writer(ss); writer.value(value); Y_EQUAL(ss.str(), expected); } void test_Integers() { doTestInteger(32, "32"); doTestInteger(char(20), "20"); } void test_FloatingPointValues() { std::stringstream ss; JsonWriter writer(ss); Y_THROWS(writer.value(std::numeric_limits<double>::infinity()), std::logic_error); writer.setNonFiniteFloatsAsStringsEnabled(true); writer.value(std::numeric_limits<double>::infinity()); Y_EQUAL(ss.str(), "\"infinity\""); } void test_UnquotedValueNames() { std::stringstream ss; JsonWriter writer(ss); writer.setUnquotedValueNamesEnabled(true); writer.beginObject() .key("Key1").value(0) .key("$Key2_").value(1) .key("_Key$3").value(2) .key("4Key4").value(3) .key("Key 5").value(4) .endObject(); Y_EQUAL(ss.str(), "{Key1:0,$Key2_:1,_Key$3:2,\"4Key4\":3,\"Key 5\":4}"); } void test_FormatAndFlat() { std::stringstream ss; JsonWriter writer(ss, JsonFormatting::FORMAT); writer.beginObject(); writer.key("1").value(2); writer.key("array").beginArray(JsonParameters(JsonFormatting::FLAT)).value(1).value(2).endArray(); writer.endObject(); Y_EQUAL(ss.str(), "{\n" " \"1\": 2,\n" " \"array\": [1, 2]\n" "}"); } void test_SpecialValues() { std::stringstream ss; JsonWriter writer(ss); writer.beginArray(); writer.boolean(true).boolean(false).null(); writer.endArray(); Y_EQUAL(ss.str(), "[true,false,null]"); } Y_TEST(test_Basics, test_EscapedString, test_ManualFormatting, test_SemiManualFormatting, test_SimpleObject, test_Integers, test_FloatingPointValues, test_UnquotedValueNames, test_FormatAndFlat, test_SpecialValues); } <|endoftext|>
<commit_before>/// \file /// \ingroup tutorial_tree /// Illustrates how to retrieve TTree variables in arrays. /// /// This example: /// - creates a simple TTree, /// - generates TTree variables thanks to the `Draw` method with `goff` option, /// - retrieves some of them in arrays thanks to `GetVal`, /// - generates and draw graphs with these arrays. /// /// The option `goff` in `TTree::Draw` behaves like any other drawing option except /// that, at the end, no graphics is produced ( `goff`= graphics off). This allows /// to generate as many TTree variables as needed. All the graphics options /// (except `para` and `candle`) are limited to four variables only. And `para` /// and `candle` need at least two variables. /// /// \macro_image /// \macro_output /// \macro_code /// /// \author Olivier Couet void treegetval() { // create a simple TTree with 5 branches Int_t run, evt; Float_t x,y,z; TTree *T = new TTree("T","test friend trees"); T->Branch("Run",&run,"Run/I"); T->Branch("Event",&evt,"Event/I"); T->Branch("x",&x,"x/F"); T->Branch("y",&y,"y/F"); T->Branch("z",&z,"z/F"); TRandom r; for (Int_t i=0;i<10000;i++) { if (i < 5000) run = 1; else run = 2; evt = i; x = r.Gaus(10,1); y = r.Gaus(20,2); z = r.Landau(2,1); T->Fill(); } // Draw with option goff and generate seven variables Int_t n = T->Draw("x:y:z:Run:Event:sin(x):cos(x)","Run==1","goff"); printf("The arrays' dimension is %d\n",n); // Retrieve variables 5 et 6 Double_t *vxs = T->GetVal(5); Double_t *vxc = T->GetVal(6); // Draw with option goff and generate only one variable T->Draw("x","Run==1","goff"); // Retrieve variable 0 Double_t *vx = T->GetVal(0); // Create and draw graphs TGraph *gs = new TGraph(n,vx,vxs); TGraph *gc = new TGraph(n,vx,vxc); gs->Draw("ap"); gc->Draw("p"); } <commit_msg>complete doc<commit_after>/// \file /// \ingroup tutorial_tree /// Illustrates how to retrieve TTree variables in arrays. /// /// This example: /// - creates a simple TTree, /// - generates TTree variables thanks to the `Draw` method with `goff` option, /// - retrieves some of them in arrays thanks to `GetVal`, /// - generates and draw graphs with these arrays. /// /// The option `goff` in `TTree::Draw` behaves like any other drawing option except /// that, at the end, no graphics is produced ( `goff`= graphics off). This allows /// to generate as many TTree variables as needed. All the graphics options /// (except `para` and `candle`) are limited to four variables only. And `para` /// and `candle` need at least two variables. /// /// Note that by default TTree::Draw creates the arrays obtained /// with GetVal with a length corresponding to the parameter `fEstimate`. /// By default fEstimate=1000000 and can be modified /// via TTree::SetEstimate. To keep in memory all the results use: /// ~~~ {.cpp} /// tree->SetEstimate(-1); /// ~~~ /// SetEstimate should be called if the expected number of selected rows /// is greater than 1000000. /// /// \macro_image /// \macro_output /// \macro_code /// /// \author Olivier Couet void treegetval() { // create a simple TTree with 5 branches Int_t run, evt; Float_t x,y,z; TTree *T = new TTree("T","test friend trees"); T->Branch("Run",&run,"Run/I"); T->Branch("Event",&evt,"Event/I"); T->Branch("x",&x,"x/F"); T->Branch("y",&y,"y/F"); T->Branch("z",&z,"z/F"); TRandom r; for (Int_t i=0;i<10000;i++) { if (i < 5000) run = 1; else run = 2; evt = i; x = r.Gaus(10,1); y = r.Gaus(20,2); z = r.Landau(2,1); T->Fill(); } // Draw with option goff and generate seven variables Int_t n = T->Draw("x:y:z:Run:Event:sin(x):cos(x)","Run==1","goff"); printf("The arrays' dimension is %d\n",n); // Retrieve variables 5 et 6 Double_t *vxs = T->GetVal(5); Double_t *vxc = T->GetVal(6); // Draw with option goff and generate only one variable T->Draw("x","Run==1","goff"); // Retrieve variable 0 Double_t *vx = T->GetVal(0); // Create and draw graphs TGraph *gs = new TGraph(n,vx,vxs); TGraph *gc = new TGraph(n,vx,vxc); gs->Draw("ap"); gc->Draw("p"); } <|endoftext|>
<commit_before>#include "project.h" /** * @brief Project::Project * @param id * @param name */ Project::Project(FileHandler* file_handler, ID id, std::string name){ this->file_handler = file_handler; this->name = name; this->save_name = name; this->id = id; this->dir = -1; this->dir_videos = -1; this->dir_bookmarks = -1; this->v_id = 0; this->videos.clear(); this->changes_made = true; } /** * @brief Project::Project */ Project::Project(FileHandler* file_handler){ this->file_handler = file_handler; this->name = ""; this->save_name = ""; this->id = -1; this->id = 0; this->dir = -1; this->dir_bookmarks = -1; this->dir_videos = -1; this->videos.clear(); } /** * @brief Project::~Project * Clears contents of video map */ Project::~Project(){ for (auto vid_it = this->videos.begin(); vid_it != this->videos.end(); ++vid_it) { delete vid_it->second; } for (auto rep_it = this->reports.begin(); rep_it != this->reports.end(); ++rep_it) { delete *rep_it; } } /** * @brief Project::remove_video * @param id * Remove video from videos and delete its contents. */ void Project::remove_video_project(ID id){ VideoProject* temp = this->videos.at(id); delete temp; videos.erase(id); this->changes_made = true; } /** * @brief Project::add_video * @return Video ID to be used for identifying the video. */ ID Project::add_video(Video* vid){ vid->id = this->v_id; this->videos.insert(std::make_pair(this->v_id, new VideoProject(vid))); this->changes_made = true; return this->v_id++; } /** * @brief Project::add_report * @param file_path */ void Project::add_report(std::string file_path){ this->reports.push_back(new Report(file_path)); this->saved = false; } /** * @brief Project::add_report * @param report * Required for load, object locally allocated */ void Project::add_report(Report* report){ this->reports.push_back(report); } /** * @brief Project::add_video * @return Video ID to be used for identifying the video. */ ID Project::add_video_project(VideoProject* vid_proj){ vid_proj->get_video()->id = this->v_id; this->videos.insert(std::make_pair(this->v_id, vid_proj)); this->changes_made = true; return this->v_id++; } /** * @brief Project::delete_artifacts * Delete all projects files. */ void Project::delete_artifacts(){ // Delete files in all videoprojects for(auto it = videos.begin(); it != videos.end(); it++){ VideoProject* vp = it->second; vp->delete_artifacts(); } // Delete all reports. for(auto it = reports.begin(); it != reports.end(); it++){ Report* temp = *it; QFile file (QString::fromStdString(temp->get_file_path())); file.remove(); } } /** * @brief Project::read * @param json * Read project parameters from json object. */ void Project::read(const QJsonObject& json){ this->name = json["name"].toString().toStdString(); this->dir = file_handler->create_directory(json["root_dir"].toString()); this->dir_bookmarks = file_handler->create_directory(json["bookmark_dir"].toString()); this->dir_videos = file_handler->create_directory(json["video_dir"].toString()); this->save_name = this->name; // Read videos from json QJsonArray json_vid_projs = json["videos"].toArray(); for (int i = 0; i < json_vid_projs.size(); ++i) { QJsonObject json_vid_proj = json_vid_projs[i].toObject(); VideoProject* v = new VideoProject(); v->read(json_vid_proj); this->add_video_project(v); } // Read reports from json QJsonArray json_reports = json["reports"].toArray(); for (int i = 0; i < json_reports.size(); ++i) { QJsonObject json_report = json_reports[i].toObject(); Report* report = new Report(); report->read(json_report); this->add_report(report); } } /** * @brief Project::write * @param json * Write project parameters to json object. */ void Project::write(QJsonObject& json){ json["name"] = QString::fromStdString(this->name); json["root_dir"] = file_handler->get_dir(this->dir).absolutePath(); json["bookmark_dir"] = file_handler->get_dir(this->dir_bookmarks).absolutePath(); json["video_dir"] = file_handler->get_dir(this->dir_videos).absolutePath(); QJsonArray json_proj; // Write Videos to json for(auto it = this->videos.begin(); it != this->videos.end(); it++){ QJsonObject json_vid_proj; VideoProject* v = it->second; v->write(json_vid_proj); json_proj.append(json_vid_proj); } json["videos"] = json_proj; // Write reports to json QJsonArray json_reports; for(auto it = this->reports.begin(); it != this->reports.end(); it++){ QJsonObject json_report; Report* report = *it; report->write(json_report); json_reports.append(json_report); } json["reports"] = json_reports; } /** * @brief Project::add_bookmark * @param v_id the id of the video * @param bookmark * Add new bookmark to Videoproj corresponding to id. */ ID Project::add_bookmark(ID v_id, Bookmark *bookmark){ VideoProject* v = this->videos.at(v_id); this->changes_made = true; return v->add_bookmark(bookmark); } /** * @brief Project::is_saved * @return true if saved */ bool Project::is_saved(){ return !this->changes_made; } /** * @brief Project::save_project * @return sets saved =true */ void Project::save_project(){ this->changes_made = false; } /** * @brief Project::get_videos * @return videos& */ std::map<ID, VideoProject* > &Project::get_videos(){ return this->videos; } <commit_msg>Fixed old variable name. (#149)<commit_after>#include "project.h" /** * @brief Project::Project * @param id * @param name */ Project::Project(FileHandler* file_handler, ID id, std::string name){ this->file_handler = file_handler; this->name = name; this->save_name = name; this->id = id; this->dir = -1; this->dir_videos = -1; this->dir_bookmarks = -1; this->v_id = 0; this->videos.clear(); this->changes_made = true; } /** * @brief Project::Project */ Project::Project(FileHandler* file_handler){ this->file_handler = file_handler; this->name = ""; this->save_name = ""; this->id = -1; this->id = 0; this->dir = -1; this->dir_bookmarks = -1; this->dir_videos = -1; this->videos.clear(); } /** * @brief Project::~Project * Clears contents of video map */ Project::~Project(){ for (auto vid_it = this->videos.begin(); vid_it != this->videos.end(); ++vid_it) { delete vid_it->second; } for (auto rep_it = this->reports.begin(); rep_it != this->reports.end(); ++rep_it) { delete *rep_it; } } /** * @brief Project::remove_video * @param id * Remove video from videos and delete its contents. */ void Project::remove_video_project(ID id){ VideoProject* temp = this->videos.at(id); delete temp; videos.erase(id); this->changes_made = true; } /** * @brief Project::add_video * @return Video ID to be used for identifying the video. */ ID Project::add_video(Video* vid){ vid->id = this->v_id; this->videos.insert(std::make_pair(this->v_id, new VideoProject(vid))); this->changes_made = true; return this->v_id++; } /** * @brief Project::add_report * @param file_path */ void Project::add_report(std::string file_path){ this->reports.push_back(new Report(file_path)); this->changes_made = true; } /** * @brief Project::add_report * @param report * Required for load, object locally allocated */ void Project::add_report(Report* report){ this->reports.push_back(report); } /** * @brief Project::add_video * @return Video ID to be used for identifying the video. */ ID Project::add_video_project(VideoProject* vid_proj){ vid_proj->get_video()->id = this->v_id; this->videos.insert(std::make_pair(this->v_id, vid_proj)); this->changes_made = true; return this->v_id++; } /** * @brief Project::delete_artifacts * Delete all projects files. */ void Project::delete_artifacts(){ // Delete files in all videoprojects for(auto it = videos.begin(); it != videos.end(); it++){ VideoProject* vp = it->second; vp->delete_artifacts(); } // Delete all reports. for(auto it = reports.begin(); it != reports.end(); it++){ Report* temp = *it; QFile file (QString::fromStdString(temp->get_file_path())); file.remove(); } } /** * @brief Project::read * @param json * Read project parameters from json object. */ void Project::read(const QJsonObject& json){ this->name = json["name"].toString().toStdString(); this->dir = file_handler->create_directory(json["root_dir"].toString()); this->dir_bookmarks = file_handler->create_directory(json["bookmark_dir"].toString()); this->dir_videos = file_handler->create_directory(json["video_dir"].toString()); this->save_name = this->name; // Read videos from json QJsonArray json_vid_projs = json["videos"].toArray(); for (int i = 0; i < json_vid_projs.size(); ++i) { QJsonObject json_vid_proj = json_vid_projs[i].toObject(); VideoProject* v = new VideoProject(); v->read(json_vid_proj); this->add_video_project(v); } // Read reports from json QJsonArray json_reports = json["reports"].toArray(); for (int i = 0; i < json_reports.size(); ++i) { QJsonObject json_report = json_reports[i].toObject(); Report* report = new Report(); report->read(json_report); this->add_report(report); } } /** * @brief Project::write * @param json * Write project parameters to json object. */ void Project::write(QJsonObject& json){ json["name"] = QString::fromStdString(this->name); json["root_dir"] = file_handler->get_dir(this->dir).absolutePath(); json["bookmark_dir"] = file_handler->get_dir(this->dir_bookmarks).absolutePath(); json["video_dir"] = file_handler->get_dir(this->dir_videos).absolutePath(); QJsonArray json_proj; // Write Videos to json for(auto it = this->videos.begin(); it != this->videos.end(); it++){ QJsonObject json_vid_proj; VideoProject* v = it->second; v->write(json_vid_proj); json_proj.append(json_vid_proj); } json["videos"] = json_proj; // Write reports to json QJsonArray json_reports; for(auto it = this->reports.begin(); it != this->reports.end(); it++){ QJsonObject json_report; Report* report = *it; report->write(json_report); json_reports.append(json_report); } json["reports"] = json_reports; } /** * @brief Project::add_bookmark * @param v_id the id of the video * @param bookmark * Add new bookmark to Videoproj corresponding to id. */ ID Project::add_bookmark(ID v_id, Bookmark *bookmark){ VideoProject* v = this->videos.at(v_id); this->changes_made = true; return v->add_bookmark(bookmark); } /** * @brief Project::is_saved * @return true if saved */ bool Project::is_saved(){ return !this->changes_made; } /** * @brief Project::save_project * @return sets saved =true */ void Project::save_project(){ this->changes_made = false; } /** * @brief Project::get_videos * @return videos& */ std::map<ID, VideoProject* > &Project::get_videos(){ return this->videos; } <|endoftext|>
<commit_before>/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2022 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 <inviwo/volume/algorithm/volumemap.h> #include <algorithm> #include <unordered_map> #include <inviwo/core/util/exception.h> namespace inviwo { void remap(std::shared_ptr<Volume>& volume, std::vector<int> src, std::vector<int> dst, int missingValue, bool useMissingValue) { if (src.size() == 0 || src.size() != dst.size()) { throw Exception(IVW_CONTEXT_CUSTOM("Remap"), "Invalid dataframe size (src = {}, dst = {})", src.size(), dst.size()); } // Create sorted copy of src and check if it contains duplicates std::vector<int> sorted = src; std::sort(sorted.begin(), sorted.end()); auto uniqueIterator = std::unique(sorted.begin(), sorted.end()); if (uniqueIterator != sorted.end()) { throw Exception(IVW_CONTEXT_CUSTOM("Remap"), "Duplicate elements in source row (numberOfDuplicates = {})", sorted.size() - std::distance(sorted.begin(), uniqueIterator)); } auto volRep = volume->getEditableRepresentation<VolumeRAM>(); volRep->dispatch<void, dispatching::filter::Scalars>([&](auto volram) { using ValueType = util::PrecisionValueType<decltype(volram)>; ValueType* dataPtr = volram->getDataTyped(); const auto& dim = volram->getDimensions(); // Check state of dataframe bool sorted = std::is_sorted(src.begin(), src.end()); if (sorted && (src.back() - src.front()) == static_cast<int>(src.size()) - 1) { // Sorted + continuous std::transform(dataPtr, dataPtr + glm::compMul(dim), dataPtr, [&](const ValueType& v) { // Voxel value is inside src range if (static_cast<int>(v) >= src.front() && static_cast<int>(v) <= src.back()) { int index = static_cast<int>(v) - src.front(); return static_cast<ValueType>(dst[index]); } else if (useMissingValue) { return static_cast<ValueType>(missingValue); } else { return v; } }); } else if (sorted) { // Sorted + non continuous std::transform(dataPtr, dataPtr + glm::compMul(dim), dataPtr, [&](const ValueType& v) { auto index = std::distance( src.begin(), std::lower_bound(src.begin(), src.end(), static_cast<int>(v))); if (index < static_cast<int>(src.size())) { return static_cast<ValueType>(dst[index]); } else if (useMissingValue) { return static_cast<ValueType>(missingValue); } else { return v; } }); } else { std::unordered_map<int, int> unorderedIndexMap; for (size_t i = 0; i < src.size(); ++i) { unorderedIndexMap[src[i]] = dst[i]; } std::transform(dataPtr, dataPtr + glm::compMul(dim), dataPtr, [&](const ValueType& v) { if (unorderedIndexMap.count(static_cast<int>(v)) == 1) { return static_cast<ValueType>(unorderedIndexMap[static_cast<int>(v)]); } else if (useMissingValue) { return static_cast<ValueType>(missingValue); } else { return v; } }); } }); } } // namespace inviwo <commit_msg>Volume: duplicate fix<commit_after>/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2022 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 <inviwo/volume/algorithm/volumemap.h> #include <algorithm> #include <unordered_map> #include <unordered_set> #include <inviwo/core/util/exception.h> namespace inviwo { void remap(std::shared_ptr<Volume>& volume, std::vector<int> src, std::vector<int> dst, int missingValue, bool useMissingValue) { if (src.size() == 0 || src.size() != dst.size()) { throw Exception(IVW_CONTEXT_CUSTOM("Remap"), "Invalid dataframe size (src = {}, dst = {})", src.size(), dst.size()); } // Create sorted copy of src and check if it contains duplicates std::unordered_set<int> set(src.begin(), src.end()); if (src.size() != set.size()) { throw Exception(IVW_CONTEXT_CUSTOM("Remap"), "Duplicate elements in source row (numberOfDuplicates = {})", src.size() - set.size()); } auto volRep = volume->getEditableRepresentation<VolumeRAM>(); volRep->dispatch<void, dispatching::filter::Scalars>([&](auto volram) { using ValueType = util::PrecisionValueType<decltype(volram)>; ValueType* dataPtr = volram->getDataTyped(); const auto& dim = volram->getDimensions(); // Check state of dataframe bool sorted = std::is_sorted(src.begin(), src.end()); if (sorted && (src.back() - src.front()) == static_cast<int>(src.size()) - 1) { // Sorted + continuous std::transform(dataPtr, dataPtr + glm::compMul(dim), dataPtr, [&](const ValueType& v) { // Voxel value is inside src range if (static_cast<int>(v) >= src.front() && static_cast<int>(v) <= src.back()) { int index = static_cast<int>(v) - src.front(); return static_cast<ValueType>(dst[index]); } else if (useMissingValue) { return static_cast<ValueType>(missingValue); } else { return v; } }); } else if (sorted) { // Sorted + non continuous std::transform(dataPtr, dataPtr + glm::compMul(dim), dataPtr, [&](const ValueType& v) { auto index = std::distance( src.begin(), std::lower_bound(src.begin(), src.end(), static_cast<int>(v))); if (index < static_cast<int>(src.size())) { return static_cast<ValueType>(dst[index]); } else if (useMissingValue) { return static_cast<ValueType>(missingValue); } else { return v; } }); } else { std::unordered_map<int, int> unorderedIndexMap; for (size_t i = 0; i < src.size(); ++i) { unorderedIndexMap[src[i]] = dst[i]; } std::transform(dataPtr, dataPtr + glm::compMul(dim), dataPtr, [&](const ValueType& v) { if (unorderedIndexMap.count(static_cast<int>(v)) == 1) { return static_cast<ValueType>(unorderedIndexMap[static_cast<int>(v)]); } else if (useMissingValue) { return static_cast<ValueType>(missingValue); } else { return v; } }); } }); } } // namespace inviwo <|endoftext|>
<commit_before>/*=================================================================== 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 <mitkToFDistanceImageToSurfaceFilter.h> #include <mitkInstantiateAccessFunctions.h> #include <mitkSurface.h> #include <itkImage.h> #include <vtkCellArray.h> #include <vtkPoints.h> #include <vtkPolyData.h> #include <vtkPointData.h> #include <vtkFloatArray.h> #include <vtkPolyDataNormals.h> #include <vtkCleanPolyData.h> #include <vtkSmartPointer.h> #include <math.h> mitk::ToFDistanceImageToSurfaceFilter::ToFDistanceImageToSurfaceFilter() : m_IplScalarImage(NULL), m_CameraIntrinsics(), m_TextureImageWidth(0), m_TextureImageHeight(0), m_InterPixelDistance(), m_TextureIndex(0) { m_InterPixelDistance.Fill(0.045); m_CameraIntrinsics = mitk::CameraIntrinsics::New(); m_CameraIntrinsics->SetFocalLength(295.78960196187319,296.1255427948447); m_CameraIntrinsics->SetFocalLength(5.9421434211923247e+02,5.9104053696870778e+02); m_CameraIntrinsics->SetPrincipalPoint(3.3930780975300314e+02,2.4273913761751615e+02); m_CameraIntrinsics->SetDistorsionCoeffs(-0.36874385358645773f,-0.14339503290129013,0.0033210108720361795,-0.004277703352074105); m_ReconstructionMode = WithInterPixelDistance; } mitk::ToFDistanceImageToSurfaceFilter::~ToFDistanceImageToSurfaceFilter() { } void mitk::ToFDistanceImageToSurfaceFilter::SetInput( Image* distanceImage, mitk::CameraIntrinsics::Pointer cameraIntrinsics ) { this->SetCameraIntrinsics(cameraIntrinsics); this->SetInput(0,distanceImage); } void mitk::ToFDistanceImageToSurfaceFilter::SetInput( unsigned int idx, Image* distanceImage, mitk::CameraIntrinsics::Pointer cameraIntrinsics ) { this->SetCameraIntrinsics(cameraIntrinsics); this->SetInput(idx,distanceImage); } void mitk::ToFDistanceImageToSurfaceFilter::SetInput( mitk::Image* distanceImage ) { this->SetInput(0,distanceImage); } //TODO: braucht man diese Methode? void mitk::ToFDistanceImageToSurfaceFilter::SetInput( unsigned int idx, mitk::Image* distanceImage ) { if ((distanceImage == NULL) && (idx == this->GetNumberOfInputs() - 1)) // if the last input is set to NULL, reduce the number of inputs by one this->SetNumberOfInputs(this->GetNumberOfInputs() - 1); else this->ProcessObject::SetNthInput(idx, distanceImage); // Process object is not const-correct so the const_cast is required here this->CreateOutputsForAllInputs(); } mitk::Image* mitk::ToFDistanceImageToSurfaceFilter::GetInput() { return this->GetInput(0); } mitk::Image* mitk::ToFDistanceImageToSurfaceFilter::GetInput( unsigned int idx ) { if (this->GetNumberOfInputs() < 1) return NULL; //TODO: geeignete exception werfen return static_cast< mitk::Image*>(this->ProcessObject::GetInput(idx)); } void mitk::ToFDistanceImageToSurfaceFilter::GenerateData() { mitk::Surface::Pointer output = this->GetOutput(); assert(output); mitk::Image::Pointer input = this->GetInput(); assert(input); // mesh points int xDimension = input->GetDimension(0); int yDimension = input->GetDimension(1); unsigned int size = xDimension*yDimension; //size of the image-array std::vector<bool> isPointValid; isPointValid.resize(size); int pointCount = 0; vtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New(); points->SetDataTypeToDouble(); vtkSmartPointer<vtkCellArray> polys = vtkSmartPointer<vtkCellArray>::New(); vtkSmartPointer<vtkFloatArray> scalarArray = vtkSmartPointer<vtkFloatArray>::New(); vtkSmartPointer<vtkFloatArray> textureCoords = vtkSmartPointer<vtkFloatArray>::New(); textureCoords->SetNumberOfComponents(2); // float textureScaleCorrection1 = 0.0; // float textureScaleCorrection2 = 0.0; // if (this->m_TextureImageHeight > 0.0 && this->m_TextureImageWidth > 0.0) // { // textureScaleCorrection1 = float(this->m_TextureImageHeight) / float(this->m_TextureImageWidth); // textureScaleCorrection2 = ((float(this->m_TextureImageWidth) - float(this->m_TextureImageHeight))/2) / float(this->m_TextureImageWidth); // } float* scalarFloatData = NULL; if (this->m_IplScalarImage) // if scalar image is defined use it for texturing { scalarFloatData = (float*)this->m_IplScalarImage->imageData; } else if (this->GetInput(m_TextureIndex)) // otherwise use intensity image (input(2)) { scalarFloatData = (float*)this->GetInput(m_TextureIndex)->GetData(); } float* inputFloatData = (float*)(input->GetSliceData(0, 0, 0)->GetData()); //calculate world coordinates mitk::ToFProcessingCommon::ToFPoint2D focalLengthInPixelUnits; mitk::ToFProcessingCommon::ToFScalarType focalLengthInMm; if((m_ReconstructionMode == WithOutInterPixelDistance) || (m_ReconstructionMode == Kinect)) { focalLengthInPixelUnits[0] = m_CameraIntrinsics->GetFocalLengthX(); focalLengthInPixelUnits[1] = m_CameraIntrinsics->GetFocalLengthY(); } else if( m_ReconstructionMode == WithInterPixelDistance) { //convert focallength from pixel to mm focalLengthInMm = (m_CameraIntrinsics->GetFocalLengthX()*m_InterPixelDistance[0]+m_CameraIntrinsics->GetFocalLengthY()*m_InterPixelDistance[1])/2.0; } mitk::ToFProcessingCommon::ToFPoint2D principalPoint; principalPoint[0] = m_CameraIntrinsics->GetPrincipalPointX(); principalPoint[1] = m_CameraIntrinsics->GetPrincipalPointY(); mitk::Point3D origin = input->GetGeometry()->GetOrigin(); for (int j=0; j<yDimension; j++) { for (int i=0; i<xDimension; i++) { // distance value mitk::Index3D pixel; pixel[0] = i; pixel[1] = j; pixel[2] = 0; unsigned int pixelID = pixel[0]+pixel[1]*xDimension; mitk::ToFProcessingCommon::ToFScalarType distance = (double)inputFloatData[pixelID]; mitk::ToFProcessingCommon::ToFPoint3D cartesianCoordinates; switch (m_ReconstructionMode) { case WithOutInterPixelDistance: { cartesianCoordinates = mitk::ToFProcessingCommon::IndexToCartesianCoordinates(i+origin[0],j+origin[1],distance,focalLengthInPixelUnits,principalPoint); break; } case WithInterPixelDistance: { cartesianCoordinates = mitk::ToFProcessingCommon::IndexToCartesianCoordinatesWithInterpixdist(i+origin[0],j+origin[1],distance,focalLengthInMm,m_InterPixelDistance,principalPoint); break; } case Kinect: { cartesianCoordinates = mitk::ToFProcessingCommon::KinectIndexToCartesianCoordinates(i+origin[0],j+origin[1],distance,focalLengthInPixelUnits,principalPoint); break; } default: { MITK_ERROR << "Incorrect reconstruction mode!"; } } //Epsilon here, because we may have small float values like 0.00000001 which in fact represents 0. if (distance<=mitk::eps) { isPointValid[pointCount] = false; } else { isPointValid[pointCount] = true; points->InsertPoint(pixelID, cartesianCoordinates.GetDataPointer()); if((i >= 1) && (j >= 1)) { vtkIdType xy = i+j*xDimension; vtkIdType x_1y = i-1+j*xDimension; vtkIdType xy_1 = i+(j-1)*xDimension; vtkIdType x_1y_1 = (i-1)+(j-1)*xDimension; if (isPointValid[xy]&&isPointValid[x_1y]&&isPointValid[x_1y_1]&&isPointValid[xy_1]) // check if points of cell are valid { polys->InsertNextCell(3); polys->InsertCellPoint(x_1y); polys->InsertCellPoint(xy); polys->InsertCellPoint(x_1y_1); polys->InsertNextCell(3); polys->InsertCellPoint(x_1y_1); polys->InsertCellPoint(xy); polys->InsertCellPoint(xy_1); } } if (scalarFloatData) { scalarArray->InsertTuple1(pixelID, scalarFloatData[pixel[0]+pixel[1]*xDimension]); //scalarArray->InsertTuple1(pixelID, scalarFloatData[pixelID]); } if (this->m_TextureImageHeight > 0.0 && this->m_TextureImageWidth > 0.0) { float xNorm = (((float)pixel[0])/xDimension)/**textureScaleCorrection1 + textureScaleCorrection2 */; // correct video texture scale 640 * 480!! float yNorm = ((float)pixel[1])/yDimension; //don't flip. we don't need to flip. textureCoords->InsertTuple2(pixelID, xNorm, yNorm); } } pointCount++; } } vtkSmartPointer<vtkPolyData> mesh = vtkSmartPointer<vtkPolyData>::New(); mesh->SetPoints(points); mesh->SetPolys(polys); if (scalarArray->GetNumberOfTuples()>0) { mesh->GetPointData()->SetScalars(scalarArray); if (this->m_TextureImageHeight > 0.0 && this->m_TextureImageWidth > 0.0) { mesh->GetPointData()->SetTCoords(textureCoords); } } output->SetVtkPolyData(mesh); } void mitk::ToFDistanceImageToSurfaceFilter::CreateOutputsForAllInputs() { this->SetNumberOfOutputs(this->GetNumberOfInputs()); // create outputs for all inputs for (unsigned int idx = 0; idx < this->GetNumberOfOutputs(); ++idx) if (this->GetOutput(idx) == NULL) { DataObjectPointer newOutput = this->MakeOutput(idx); this->SetNthOutput(idx, newOutput); } this->Modified(); } void mitk::ToFDistanceImageToSurfaceFilter::GenerateOutputInformation() { this->GetOutput(); itkDebugMacro(<<"GenerateOutputInformation()"); } void mitk::ToFDistanceImageToSurfaceFilter::SetScalarImage(IplImage* iplScalarImage) { this->m_IplScalarImage = iplScalarImage; this->Modified(); } IplImage* mitk::ToFDistanceImageToSurfaceFilter::GetScalarImage() { return this->m_IplScalarImage; } void mitk::ToFDistanceImageToSurfaceFilter::SetTextureImageWidth(int width) { this->m_TextureImageWidth = width; } void mitk::ToFDistanceImageToSurfaceFilter::SetTextureImageHeight(int height) { this->m_TextureImageHeight = height; } <commit_msg>COMP: Format commit.<commit_after>/*=================================================================== 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 <mitkToFDistanceImageToSurfaceFilter.h> #include <mitkInstantiateAccessFunctions.h> #include <mitkSurface.h> #include <itkImage.h> #include <vtkCellArray.h> #include <vtkPoints.h> #include <vtkPolyData.h> #include <vtkPointData.h> #include <vtkFloatArray.h> #include <vtkPolyDataNormals.h> #include <vtkCleanPolyData.h> #include <vtkSmartPointer.h> #include <math.h> mitk::ToFDistanceImageToSurfaceFilter::ToFDistanceImageToSurfaceFilter() : m_IplScalarImage(NULL), m_CameraIntrinsics(), m_TextureImageWidth(0), m_TextureImageHeight(0), m_InterPixelDistance(), m_TextureIndex(0) { m_InterPixelDistance.Fill(0.045); m_CameraIntrinsics = mitk::CameraIntrinsics::New(); m_CameraIntrinsics->SetFocalLength(295.78960196187319,296.1255427948447); m_CameraIntrinsics->SetFocalLength(5.9421434211923247e+02,5.9104053696870778e+02); m_CameraIntrinsics->SetPrincipalPoint(3.3930780975300314e+02,2.4273913761751615e+02); m_CameraIntrinsics->SetDistorsionCoeffs(-0.36874385358645773f,-0.14339503290129013,0.0033210108720361795,-0.004277703352074105); m_ReconstructionMode = WithInterPixelDistance; } mitk::ToFDistanceImageToSurfaceFilter::~ToFDistanceImageToSurfaceFilter() { } void mitk::ToFDistanceImageToSurfaceFilter::SetInput( Image* distanceImage, mitk::CameraIntrinsics::Pointer cameraIntrinsics ) { this->SetCameraIntrinsics(cameraIntrinsics); this->SetInput(0,distanceImage); } void mitk::ToFDistanceImageToSurfaceFilter::SetInput( unsigned int idx, Image* distanceImage, mitk::CameraIntrinsics::Pointer cameraIntrinsics ) { this->SetCameraIntrinsics(cameraIntrinsics); this->SetInput(idx,distanceImage); } void mitk::ToFDistanceImageToSurfaceFilter::SetInput( mitk::Image* distanceImage ) { this->SetInput(0,distanceImage); } //TODO: braucht man diese Methode? void mitk::ToFDistanceImageToSurfaceFilter::SetInput( unsigned int idx, mitk::Image* distanceImage ) { if ((distanceImage == NULL) && (idx == this->GetNumberOfInputs() - 1)) // if the last input is set to NULL, reduce the number of inputs by one this->SetNumberOfInputs(this->GetNumberOfInputs() - 1); else this->ProcessObject::SetNthInput(idx, distanceImage); // Process object is not const-correct so the const_cast is required here this->CreateOutputsForAllInputs(); } mitk::Image* mitk::ToFDistanceImageToSurfaceFilter::GetInput() { return this->GetInput(0); } mitk::Image* mitk::ToFDistanceImageToSurfaceFilter::GetInput( unsigned int idx ) { if (this->GetNumberOfInputs() < 1) return NULL; //TODO: geeignete exception werfen return static_cast< mitk::Image*>(this->ProcessObject::GetInput(idx)); } void mitk::ToFDistanceImageToSurfaceFilter::GenerateData() { mitk::Surface::Pointer output = this->GetOutput(); assert(output); mitk::Image::Pointer input = this->GetInput(); assert(input); // mesh points int xDimension = input->GetDimension(0); int yDimension = input->GetDimension(1); unsigned int size = xDimension*yDimension; //size of the image-array std::vector<bool> isPointValid; isPointValid.resize(size); int pointCount = 0; vtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New(); points->SetDataTypeToDouble(); vtkSmartPointer<vtkCellArray> polys = vtkSmartPointer<vtkCellArray>::New(); vtkSmartPointer<vtkFloatArray> scalarArray = vtkSmartPointer<vtkFloatArray>::New(); vtkSmartPointer<vtkFloatArray> textureCoords = vtkSmartPointer<vtkFloatArray>::New(); textureCoords->SetNumberOfComponents(2); // float textureScaleCorrection1 = 0.0; // float textureScaleCorrection2 = 0.0; // if (this->m_TextureImageHeight > 0.0 && this->m_TextureImageWidth > 0.0) // { // textureScaleCorrection1 = float(this->m_TextureImageHeight) / float(this->m_TextureImageWidth); // textureScaleCorrection2 = ((float(this->m_TextureImageWidth) - float(this->m_TextureImageHeight))/2) / float(this->m_TextureImageWidth); // } float* scalarFloatData = NULL; if (this->m_IplScalarImage) // if scalar image is defined use it for texturing { scalarFloatData = (float*)this->m_IplScalarImage->imageData; } else if (this->GetInput(m_TextureIndex)) // otherwise use intensity image (input(2)) { scalarFloatData = (float*)this->GetInput(m_TextureIndex)->GetData(); } float* inputFloatData = (float*)(input->GetSliceData(0, 0, 0)->GetData()); //calculate world coordinates mitk::ToFProcessingCommon::ToFPoint2D focalLengthInPixelUnits; mitk::ToFProcessingCommon::ToFScalarType focalLengthInMm; if((m_ReconstructionMode == WithOutInterPixelDistance) || (m_ReconstructionMode == Kinect)) { focalLengthInPixelUnits[0] = m_CameraIntrinsics->GetFocalLengthX(); focalLengthInPixelUnits[1] = m_CameraIntrinsics->GetFocalLengthY(); } else if( m_ReconstructionMode == WithInterPixelDistance) { //convert focallength from pixel to mm focalLengthInMm = (m_CameraIntrinsics->GetFocalLengthX()*m_InterPixelDistance[0]+m_CameraIntrinsics->GetFocalLengthY()*m_InterPixelDistance[1])/2.0; } mitk::ToFProcessingCommon::ToFPoint2D principalPoint; principalPoint[0] = m_CameraIntrinsics->GetPrincipalPointX(); principalPoint[1] = m_CameraIntrinsics->GetPrincipalPointY(); mitk::Point3D origin = input->GetGeometry()->GetOrigin(); for (int j=0; j<yDimension; j++) { for (int i=0; i<xDimension; i++) { // distance value mitk::Index3D pixel; pixel[0] = i; pixel[1] = j; pixel[2] = 0; unsigned int pixelID = pixel[0]+pixel[1]*xDimension; mitk::ToFProcessingCommon::ToFScalarType distance = (double)inputFloatData[pixelID]; mitk::ToFProcessingCommon::ToFPoint3D cartesianCoordinates; switch (m_ReconstructionMode) { case WithOutInterPixelDistance: { cartesianCoordinates = mitk::ToFProcessingCommon::IndexToCartesianCoordinates(i+origin[0],j+origin[1],distance,focalLengthInPixelUnits,principalPoint); break; } case WithInterPixelDistance: { cartesianCoordinates = mitk::ToFProcessingCommon::IndexToCartesianCoordinatesWithInterpixdist(i+origin[0],j+origin[1],distance,focalLengthInMm,m_InterPixelDistance,principalPoint); break; } case Kinect: { cartesianCoordinates = mitk::ToFProcessingCommon::KinectIndexToCartesianCoordinates(i+origin[0],j+origin[1],distance,focalLengthInPixelUnits,principalPoint); break; } default: { MITK_ERROR << "Incorrect reconstruction mode!"; } } //Epsilon here, because we may have small float values like 0.00000001 which in fact represents 0. if (distance<=mitk::eps) { isPointValid[pointCount] = false; } else { isPointValid[pointCount] = true; points->InsertPoint(pixelID, cartesianCoordinates.GetDataPointer()); if((i >= 1) && (j >= 1)) { vtkIdType xy = i+j*xDimension; vtkIdType x_1y = i-1+j*xDimension; vtkIdType xy_1 = i+(j-1)*xDimension; vtkIdType x_1y_1 = (i-1)+(j-1)*xDimension; if (isPointValid[xy]&&isPointValid[x_1y]&&isPointValid[x_1y_1]&&isPointValid[xy_1]) // check if points of cell are valid { polys->InsertNextCell(3); polys->InsertCellPoint(x_1y); polys->InsertCellPoint(xy); polys->InsertCellPoint(x_1y_1); polys->InsertNextCell(3); polys->InsertCellPoint(x_1y_1); polys->InsertCellPoint(xy); polys->InsertCellPoint(xy_1); } } if (scalarFloatData) { scalarArray->InsertTuple1(pixelID, scalarFloatData[pixel[0]+pixel[1]*xDimension]); //scalarArray->InsertTuple1(pixelID, scalarFloatData[pixelID]); } if (this->m_TextureImageHeight > 0.0 && this->m_TextureImageWidth > 0.0) { float xNorm = (((float)pixel[0])/xDimension)/**textureScaleCorrection1 + textureScaleCorrection2 */; // correct video texture scale 640 * 480!! float yNorm = ((float)pixel[1])/yDimension; //don't flip. we don't need to flip. textureCoords->InsertTuple2(pixelID, xNorm, yNorm); } } pointCount++; } } vtkSmartPointer<vtkPolyData> mesh = vtkSmartPointer<vtkPolyData>::New(); mesh->SetPoints(points); mesh->SetPolys(polys); if (scalarArray->GetNumberOfTuples()>0) { mesh->GetPointData()->SetScalars(scalarArray); if (this->m_TextureImageHeight > 0.0 && this->m_TextureImageWidth > 0.0) { mesh->GetPointData()->SetTCoords(textureCoords); } } output->SetVtkPolyData(mesh); } void mitk::ToFDistanceImageToSurfaceFilter::CreateOutputsForAllInputs() { this->SetNumberOfOutputs(this->GetNumberOfInputs()); // create outputs for all inputs for (unsigned int idx = 0; idx < this->GetNumberOfOutputs(); ++idx) if (this->GetOutput(idx) == NULL) { DataObjectPointer newOutput = this->MakeOutput(idx); this->SetNthOutput(idx, newOutput); } this->Modified(); } void mitk::ToFDistanceImageToSurfaceFilter::GenerateOutputInformation() { this->GetOutput(); itkDebugMacro(<<"GenerateOutputInformation()"); } void mitk::ToFDistanceImageToSurfaceFilter::SetScalarImage(IplImage* iplScalarImage) { this->m_IplScalarImage = iplScalarImage; this->Modified(); } IplImage* mitk::ToFDistanceImageToSurfaceFilter::GetScalarImage() { return this->m_IplScalarImage; } void mitk::ToFDistanceImageToSurfaceFilter::SetTextureImageWidth(int width) { this->m_TextureImageWidth = width; } void mitk::ToFDistanceImageToSurfaceFilter::SetTextureImageHeight(int height) { this->m_TextureImageHeight = height; } <|endoftext|>
<commit_before>/* -*- c++ -*- filehtmlwriter.cpp This file is part of KMail, the KDE mail client. Copyright (c) 2003 Marc Mutz <[email protected]> KMail is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2, as published by the Free Software Foundation. KMail is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #include "filehtmlwriter.h" #include <kdebug.h> #include <qstring.h> namespace KMail { FileHtmlWriter::FileHtmlWriter( const QString & filename ) : HtmlWriter(), mFile( filename.isEmpty() ? QString( "filehtmlwriter.out" ) : filename ) { mStream.setEncoding( QTextStream::UnicodeUTF8 ); } FileHtmlWriter::~FileHtmlWriter() { if ( mFile.isOpen() ) { kdWarning( 5006 ) << "FileHtmlWriter: file still open!" << endl; mStream.unsetDevice(); mFile.close(); } } void FileHtmlWriter::begin() { openOrWarn(); } void FileHtmlWriter::end() { flush(); mStream.unsetDevice(); mFile.close(); } void FileHtmlWriter::reset() { if ( mFile.isOpen() ) { mStream.unsetDevice(); mFile.close(); } } void FileHtmlWriter::write( const QString & str ) { mStream << str; } void FileHtmlWriter::queue( const QString & str ) { write( str ); } void FileHtmlWriter::flush() { mFile.flush(); } void FileHtmlWriter::openOrWarn() { if ( mFile.isOpen() ) { kdWarning( 5006 ) << "FileHtmlWriter: file still open!" << endl; mStream.unsetDevice(); mFile.close(); } if ( !mFile.open( IO_WriteOnly ) ) kdWarning( 5006 ) << "FileHtmlWriter: Cannot open file " << mFile.name() << endl; else mStream.setDevice( &mFile ); } }; // namespace KMail <commit_msg>flush on write (helps with debugging)<commit_after>/* -*- c++ -*- filehtmlwriter.cpp This file is part of KMail, the KDE mail client. Copyright (c) 2003 Marc Mutz <[email protected]> KMail is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2, as published by the Free Software Foundation. KMail is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #include "filehtmlwriter.h" #include <kdebug.h> #include <qstring.h> namespace KMail { FileHtmlWriter::FileHtmlWriter( const QString & filename ) : HtmlWriter(), mFile( filename.isEmpty() ? QString( "filehtmlwriter.out" ) : filename ) { mStream.setEncoding( QTextStream::UnicodeUTF8 ); } FileHtmlWriter::~FileHtmlWriter() { if ( mFile.isOpen() ) { kdWarning( 5006 ) << "FileHtmlWriter: file still open!" << endl; mStream.unsetDevice(); mFile.close(); } } void FileHtmlWriter::begin() { openOrWarn(); } void FileHtmlWriter::end() { flush(); mStream.unsetDevice(); mFile.close(); } void FileHtmlWriter::reset() { if ( mFile.isOpen() ) { mStream.unsetDevice(); mFile.close(); } } void FileHtmlWriter::write( const QString & str ) { mStream << str; flush(); } void FileHtmlWriter::queue( const QString & str ) { write( str ); } void FileHtmlWriter::flush() { mFile.flush(); } void FileHtmlWriter::openOrWarn() { if ( mFile.isOpen() ) { kdWarning( 5006 ) << "FileHtmlWriter: file still open!" << endl; mStream.unsetDevice(); mFile.close(); } if ( !mFile.open( IO_WriteOnly ) ) kdWarning( 5006 ) << "FileHtmlWriter: Cannot open file " << mFile.name() << endl; else mStream.setDevice( &mFile ); } }; // namespace KMail <|endoftext|>
<commit_before>12e24d5a-2e4e-11e5-9284-b827eb9e62be<commit_msg>12e77a8c-2e4e-11e5-9284-b827eb9e62be<commit_after>12e77a8c-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>/* -*- c++ -*- kmmimeparttree.h A MIME part tree viwer. This file is part of KMail, the KDE mail client. Copyright (c) 2002-2004 Klarälvdalens Datakonsult AB KMail is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2, as published by the Free Software Foundation. KMail is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #include "kmmimeparttree.h" #include "kmreaderwin.h" #include "partNode.h" #include "kmmsgpart.h" #include "kmkernel.h" #include "kmcommands.h" #include <kdebug.h> #include <klocale.h> #include <kfiledialog.h> #include <kmessagebox.h> #include <kiconloader.h> #include <QClipboard> #include <QStyle> //Added by qt3to4: #include <q3header.h> #include <kurl.h> KMMimePartTree::KMMimePartTree( KMReaderWin* readerWin, QWidget* parent ) : K3ListView( parent ), mReaderWin( readerWin ), mSizeColumn(0) { setStyleDependantFrameWidth(); addColumn( i18n("Description") ); addColumn( i18n("Type") ); addColumn( i18n("Encoding") ); mSizeColumn = addColumn( i18n("Size") ); setColumnAlignment( 3, Qt::AlignRight ); restoreLayoutIfPresent(); connect( this, SIGNAL( clicked( Q3ListViewItem* ) ), this, SLOT( itemClicked( Q3ListViewItem* ) ) ); connect( this, SIGNAL( contextMenuRequested( Q3ListViewItem*, const QPoint&, int ) ), this, SLOT( itemRightClicked( Q3ListViewItem*, const QPoint& ) ) ); setSelectionMode( Q3ListView::Extended ); setRootIsDecorated( false ); setAllColumnsShowFocus( true ); setShowToolTips( true ); setSorting(-1); setDragEnabled( true ); } static const char configGroup[] = "MimePartTree"; KMMimePartTree::~KMMimePartTree() { saveLayout( KMKernel::config(), configGroup ); } void KMMimePartTree::restoreLayoutIfPresent() { // first column: soaks up the rest of the space: setColumnWidthMode( 0, Manual ); header()->setStretchEnabled( true, 0 ); // rest of the columns: if ( KMKernel::config()->hasGroup( configGroup ) ) { // there is a saved layout. use it... restoreLayout( KMKernel::config(), configGroup ); // and disable Maximum mode: for ( int i = 1 ; i < 4 ; ++i ) setColumnWidthMode( i, Manual ); } else { // columns grow with their contents: for ( int i = 1 ; i < 4 ; ++i ) setColumnWidthMode( i, Maximum ); } } void KMMimePartTree::itemClicked( Q3ListViewItem* item ) { if ( const KMMimePartTreeItem * i = dynamic_cast<KMMimePartTreeItem*>( item ) ) { if( mReaderWin->mRootNode == i->node() ) mReaderWin->update( true ); // Force update else mReaderWin->setMsgPart( i->node() ); } else kWarning(5006) <<"Item was not a KMMimePartTreeItem!"; } void KMMimePartTree::itemRightClicked( Q3ListViewItem *item, const QPoint &point ) { // TODO: remove this member var? mCurrentContextMenuItem = dynamic_cast<KMMimePartTreeItem *>( item ); if ( 0 == mCurrentContextMenuItem ) { kDebug(5006) <<"Item was not a KMMimePartTreeItem!"; return; } kDebug(5006) <<"\n**\n** KMMimePartTree::itemRightClicked() **\n**"; QMenu popup; popup.addAction( SmallIcon( "document-save-as" ),i18n( "Save &As..." ), this, SLOT( slotSaveAs() ) ); if ( mCurrentContextMenuItem->node()->nodeId() > 2 && mCurrentContextMenuItem->node()->typeString() != "Multipart" ) { popup.addAction( SmallIcon( "file-open" ), i18nc( "to open", "Open" ), this, SLOT( slotOpen() ) ); popup.addAction( i18n( "Open With..." ), this, SLOT( slotOpenWith() ) ); popup.addAction( i18nc( "to view something", "View" ), this, SLOT( slotView() ) ); } /* * FIXME make optional? popup.addAction( i18n( "Save as &Encoded..." ), this, SLOT( slotSaveAsEncoded() ) ); */ popup.addAction( i18n( "Save All Attachments..." ), this, SLOT( slotSaveAll() ) ); // edit + delete only for attachments if ( mCurrentContextMenuItem->node()->nodeId() > 2 && mCurrentContextMenuItem->node()->typeString() != "Multipart" ) { popup.addAction( SmallIcon( "edit-copy" ), i18n( "Copy" ), this, SLOT( slotCopy() ) ); if ( GlobalSettings::self()->allowAttachmentDeletion() ) popup.addAction( SmallIcon( "edit-delete" ), i18n( "Delete Attachment" ), this, SLOT( slotDelete() ) ); if ( GlobalSettings::self()->allowAttachmentEditing() ) popup.addAction( SmallIcon( "document-properties" ), i18n( "Edit Attachment" ), this, SLOT( slotEdit() ) ); } if ( mCurrentContextMenuItem->node()->nodeId() > 0 ) popup.addAction( i18n( "Properties" ), this, SLOT( slotProperties() ) ); popup.exec( point ); mCurrentContextMenuItem = 0; } //----------------------------------------------------------------------------- void KMMimePartTree::slotSaveAs() { saveSelectedBodyParts( false ); } //----------------------------------------------------------------------------- void KMMimePartTree::slotSaveAsEncoded() { saveSelectedBodyParts( true ); } //----------------------------------------------------------------------------- void KMMimePartTree::saveSelectedBodyParts( bool encoded ) { QList<Q3ListViewItem*> selected = selectedItems(); Q_ASSERT( !selected.isEmpty() ); if ( selected.isEmpty() ) return; QList<partNode*> parts; for ( QList<Q3ListViewItem*>::Iterator it = selected.begin(); it != selected.end(); ++it ) { parts.append( static_cast<KMMimePartTreeItem *>( *it )->node() ); } mReaderWin->setUpdateAttachment(); KMSaveAttachmentsCommand *command = new KMSaveAttachmentsCommand( this, parts, mReaderWin->message(), encoded ); command->start(); } //----------------------------------------------------------------------------- void KMMimePartTree::slotSaveAll() { if( childCount() == 0) return; mReaderWin->setUpdateAttachment(); KMCommand *command = new KMSaveAttachmentsCommand( this, mReaderWin->message() ); command->start(); } //----------------------------------------------------------------------------- void KMMimePartTree::setStyleDependantFrameWidth() { // set the width of the frame to a reasonable value for the current GUI style int frameWidth; #if 0 // is this hack still needed with kde4? if( !qstrcmp( style()->metaObject()->className(), "KeramikStyle" ) ) frameWidth = style()->pixelMetric( QStyle::PM_DefaultFrameWidth ) - 1; else #endif frameWidth = style()->pixelMetric( QStyle::PM_DefaultFrameWidth ); if ( frameWidth < 0 ) frameWidth = 0; if ( frameWidth != lineWidth() ) setLineWidth( frameWidth ); } //----------------------------------------------------------------------------- void KMMimePartTree::styleChange( QStyle& oldStyle ) { setStyleDependantFrameWidth(); K3ListView::styleChange( oldStyle ); } //----------------------------------------------------------------------------- void KMMimePartTree::correctSize( Q3ListViewItem * item ) { if (!item) return; KIO::filesize_t totalSize = 0; Q3ListViewItem * myChild = item->firstChild(); while ( myChild ) { totalSize += static_cast<KMMimePartTreeItem*>(myChild)->origSize(); myChild = myChild->nextSibling(); } if ( totalSize > static_cast<KMMimePartTreeItem*>(item)->origSize() ) item->setText( mSizeColumn, KIO::convertSize(totalSize) ); if ( item->parent() ) correctSize( item->parent() ); } void KMMimePartTree::slotDelete() { QList<Q3ListViewItem*> selected = selectedItems(); if ( selected.count() != 1 ) return; mReaderWin->slotDeleteAttachment( static_cast<KMMimePartTreeItem*>( selected.first() )->node() ); } void KMMimePartTree::slotEdit() { QList<Q3ListViewItem*> selected = selectedItems(); if ( selected.count() != 1 ) return; mReaderWin->slotEditAttachment( static_cast<KMMimePartTreeItem*>( selected.first() )->node() ); } void KMMimePartTree::slotOpen() { startHandleAttachmentCommand( KMHandleAttachmentCommand::Open ); } void KMMimePartTree::slotOpenWith() { startHandleAttachmentCommand( KMHandleAttachmentCommand::OpenWith ); } void KMMimePartTree::slotView() { startHandleAttachmentCommand( KMHandleAttachmentCommand::View ); } void KMMimePartTree::slotProperties() { startHandleAttachmentCommand( KMHandleAttachmentCommand::Properties ); } void KMMimePartTree::startHandleAttachmentCommand( int action ) { QList<Q3ListViewItem *> selected = selectedItems(); if ( selected.count() != 1 ) return; partNode *node = static_cast<KMMimePartTreeItem *>( selected.first() )->node(); QString name = mReaderWin->tempFileUrlFromPartNode( node ).path(); KMHandleAttachmentCommand *command = new KMHandleAttachmentCommand( node, mReaderWin->message(), node->nodeId(), name, KMHandleAttachmentCommand::AttachmentAction( action ), KService::Ptr(), this ); connect( command, SIGNAL( showAttachment( int, const QString& ) ), mReaderWin, SLOT( slotAtmView( int, const QString& ) ) ); command->start(); } void KMMimePartTree::slotCopy() { QList<Q3ListViewItem *> selected = selectedItems(); if ( selected.count() != 1 ) return; partNode *node = static_cast<KMMimePartTreeItem *>( selected.first() )->node(); QList<QUrl> urls; KUrl kUrl = mReaderWin->tempFileUrlFromPartNode( node ); QUrl url = QUrl::fromPercentEncoding( kUrl.toEncoded() ); if ( !url.isValid() ) return; urls.append( url ); QMimeData *mimeData = new QMimeData; mimeData->setUrls( urls ); QApplication::clipboard()->setMimeData( mimeData, QClipboard::Clipboard ); } //============================================================================= KMMimePartTreeItem::KMMimePartTreeItem( KMMimePartTree * parent, partNode* node, const QString & description, const QString & mimetype, const QString & encoding, KIO::filesize_t size ) : Q3ListViewItem( parent, description, QString(), // set by setIconAndTextForType() encoding, KIO::convertSize( size ) ), mPartNode( node ), mOrigSize(size) { Q_ASSERT(parent); if( node ) node->setMimePartTreeItem( this ); setIconAndTextForType( mimetype ); parent->correctSize(this); } KMMimePartTreeItem::KMMimePartTreeItem( KMMimePartTreeItem * parent, partNode* node, const QString & description, const QString & mimetype, const QString & encoding, KIO::filesize_t size, bool revertOrder ) : Q3ListViewItem( parent, description, QString(), // set by setIconAndTextForType() encoding, KIO::convertSize( size ) ), mPartNode( node ), mOrigSize(size) { if( revertOrder && nextSibling() ){ Q3ListViewItem* sib = nextSibling(); while( sib->nextSibling() ) sib = sib->nextSibling(); moveItem( sib ); } if( node ) node->setMimePartTreeItem( this ); setIconAndTextForType( mimetype ); if ( listView() ) static_cast<KMMimePartTree*>(listView())->correctSize(this); } void KMMimePartTreeItem::setIconAndTextForType( const QString & mime ) { QString mimetype = mime.toLower(); if ( mimetype.startsWith( "multipart/" ) ) { setText( 1, mimetype ); setPixmap( 0, SmallIcon("folder") ); } else if ( mimetype == "application/octet-stream" ) { setText( 1, i18n("Unspecified Binary Data") ); // do not show "Unknown"... setPixmap( 0, SmallIcon("application-octet-stream") ); } else { KMimeType::Ptr mtp = KMimeType::mimeType( mimetype ); setText( 1, (mtp && !mtp->comment().isEmpty()) ? mtp->comment() : mimetype ); setPixmap( 0, mtp ? KIconLoader::global()->loadMimeTypeIcon(mtp->iconName(), KIconLoader::Small) : SmallIcon("unknown") ); } } void KMMimePartTree::startDrag() { KMMimePartTreeItem *item = static_cast<KMMimePartTreeItem*>( currentItem() ); if ( !item ) return; partNode *node = item->node(); if ( !node ) return; QList<QUrl> urls; KUrl kUrl = mReaderWin->tempFileUrlFromPartNode( node ); QUrl url = QUrl::fromPercentEncoding( kUrl.toEncoded() ); if ( !url.isValid() ) return; urls.append( url ); QDrag *drag = new QDrag( this ); QMimeData *mimeData = new QMimeData; mimeData->setUrls( urls ); drag->setMimeData( mimeData ); QApplication::clipboard()->setMimeData( mimeData, QClipboard::Clipboard ); drag->exec( Qt::CopyAction ); } #include "kmmimeparttree.moc" <commit_msg>Don't put the URLs of the mime part in the clipboard. The QDrag already has ownership, so the clipboard can't have ownership too.<commit_after>/* -*- c++ -*- kmmimeparttree.h A MIME part tree viwer. This file is part of KMail, the KDE mail client. Copyright (c) 2002-2004 Klarälvdalens Datakonsult AB KMail is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2, as published by the Free Software Foundation. KMail is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #include "kmmimeparttree.h" #include "kmreaderwin.h" #include "partNode.h" #include "kmmsgpart.h" #include "kmkernel.h" #include "kmcommands.h" #include <kdebug.h> #include <klocale.h> #include <kfiledialog.h> #include <kmessagebox.h> #include <kiconloader.h> #include <QClipboard> #include <QStyle> //Added by qt3to4: #include <q3header.h> #include <kurl.h> KMMimePartTree::KMMimePartTree( KMReaderWin* readerWin, QWidget* parent ) : K3ListView( parent ), mReaderWin( readerWin ), mSizeColumn(0) { setStyleDependantFrameWidth(); addColumn( i18n("Description") ); addColumn( i18n("Type") ); addColumn( i18n("Encoding") ); mSizeColumn = addColumn( i18n("Size") ); setColumnAlignment( 3, Qt::AlignRight ); restoreLayoutIfPresent(); connect( this, SIGNAL( clicked( Q3ListViewItem* ) ), this, SLOT( itemClicked( Q3ListViewItem* ) ) ); connect( this, SIGNAL( contextMenuRequested( Q3ListViewItem*, const QPoint&, int ) ), this, SLOT( itemRightClicked( Q3ListViewItem*, const QPoint& ) ) ); setSelectionMode( Q3ListView::Extended ); setRootIsDecorated( false ); setAllColumnsShowFocus( true ); setShowToolTips( true ); setSorting(-1); setDragEnabled( true ); } static const char configGroup[] = "MimePartTree"; KMMimePartTree::~KMMimePartTree() { saveLayout( KMKernel::config(), configGroup ); } void KMMimePartTree::restoreLayoutIfPresent() { // first column: soaks up the rest of the space: setColumnWidthMode( 0, Manual ); header()->setStretchEnabled( true, 0 ); // rest of the columns: if ( KMKernel::config()->hasGroup( configGroup ) ) { // there is a saved layout. use it... restoreLayout( KMKernel::config(), configGroup ); // and disable Maximum mode: for ( int i = 1 ; i < 4 ; ++i ) setColumnWidthMode( i, Manual ); } else { // columns grow with their contents: for ( int i = 1 ; i < 4 ; ++i ) setColumnWidthMode( i, Maximum ); } } void KMMimePartTree::itemClicked( Q3ListViewItem* item ) { if ( const KMMimePartTreeItem * i = dynamic_cast<KMMimePartTreeItem*>( item ) ) { if( mReaderWin->mRootNode == i->node() ) mReaderWin->update( true ); // Force update else mReaderWin->setMsgPart( i->node() ); } else kWarning(5006) <<"Item was not a KMMimePartTreeItem!"; } void KMMimePartTree::itemRightClicked( Q3ListViewItem *item, const QPoint &point ) { // TODO: remove this member var? mCurrentContextMenuItem = dynamic_cast<KMMimePartTreeItem *>( item ); if ( 0 == mCurrentContextMenuItem ) { kDebug(5006) <<"Item was not a KMMimePartTreeItem!"; return; } kDebug(5006) <<"\n**\n** KMMimePartTree::itemRightClicked() **\n**"; QMenu popup; popup.addAction( SmallIcon( "document-save-as" ),i18n( "Save &As..." ), this, SLOT( slotSaveAs() ) ); if ( mCurrentContextMenuItem->node()->nodeId() > 2 && mCurrentContextMenuItem->node()->typeString() != "Multipart" ) { popup.addAction( SmallIcon( "file-open" ), i18nc( "to open", "Open" ), this, SLOT( slotOpen() ) ); popup.addAction( i18n( "Open With..." ), this, SLOT( slotOpenWith() ) ); popup.addAction( i18nc( "to view something", "View" ), this, SLOT( slotView() ) ); } /* * FIXME make optional? popup.addAction( i18n( "Save as &Encoded..." ), this, SLOT( slotSaveAsEncoded() ) ); */ popup.addAction( i18n( "Save All Attachments..." ), this, SLOT( slotSaveAll() ) ); // edit + delete only for attachments if ( mCurrentContextMenuItem->node()->nodeId() > 2 && mCurrentContextMenuItem->node()->typeString() != "Multipart" ) { popup.addAction( SmallIcon( "edit-copy" ), i18n( "Copy" ), this, SLOT( slotCopy() ) ); if ( GlobalSettings::self()->allowAttachmentDeletion() ) popup.addAction( SmallIcon( "edit-delete" ), i18n( "Delete Attachment" ), this, SLOT( slotDelete() ) ); if ( GlobalSettings::self()->allowAttachmentEditing() ) popup.addAction( SmallIcon( "document-properties" ), i18n( "Edit Attachment" ), this, SLOT( slotEdit() ) ); } if ( mCurrentContextMenuItem->node()->nodeId() > 0 ) popup.addAction( i18n( "Properties" ), this, SLOT( slotProperties() ) ); popup.exec( point ); mCurrentContextMenuItem = 0; } //----------------------------------------------------------------------------- void KMMimePartTree::slotSaveAs() { saveSelectedBodyParts( false ); } //----------------------------------------------------------------------------- void KMMimePartTree::slotSaveAsEncoded() { saveSelectedBodyParts( true ); } //----------------------------------------------------------------------------- void KMMimePartTree::saveSelectedBodyParts( bool encoded ) { QList<Q3ListViewItem*> selected = selectedItems(); Q_ASSERT( !selected.isEmpty() ); if ( selected.isEmpty() ) return; QList<partNode*> parts; for ( QList<Q3ListViewItem*>::Iterator it = selected.begin(); it != selected.end(); ++it ) { parts.append( static_cast<KMMimePartTreeItem *>( *it )->node() ); } mReaderWin->setUpdateAttachment(); KMSaveAttachmentsCommand *command = new KMSaveAttachmentsCommand( this, parts, mReaderWin->message(), encoded ); command->start(); } //----------------------------------------------------------------------------- void KMMimePartTree::slotSaveAll() { if( childCount() == 0) return; mReaderWin->setUpdateAttachment(); KMCommand *command = new KMSaveAttachmentsCommand( this, mReaderWin->message() ); command->start(); } //----------------------------------------------------------------------------- void KMMimePartTree::setStyleDependantFrameWidth() { // set the width of the frame to a reasonable value for the current GUI style int frameWidth; #if 0 // is this hack still needed with kde4? if( !qstrcmp( style()->metaObject()->className(), "KeramikStyle" ) ) frameWidth = style()->pixelMetric( QStyle::PM_DefaultFrameWidth ) - 1; else #endif frameWidth = style()->pixelMetric( QStyle::PM_DefaultFrameWidth ); if ( frameWidth < 0 ) frameWidth = 0; if ( frameWidth != lineWidth() ) setLineWidth( frameWidth ); } //----------------------------------------------------------------------------- void KMMimePartTree::styleChange( QStyle& oldStyle ) { setStyleDependantFrameWidth(); K3ListView::styleChange( oldStyle ); } //----------------------------------------------------------------------------- void KMMimePartTree::correctSize( Q3ListViewItem * item ) { if (!item) return; KIO::filesize_t totalSize = 0; Q3ListViewItem * myChild = item->firstChild(); while ( myChild ) { totalSize += static_cast<KMMimePartTreeItem*>(myChild)->origSize(); myChild = myChild->nextSibling(); } if ( totalSize > static_cast<KMMimePartTreeItem*>(item)->origSize() ) item->setText( mSizeColumn, KIO::convertSize(totalSize) ); if ( item->parent() ) correctSize( item->parent() ); } void KMMimePartTree::slotDelete() { QList<Q3ListViewItem*> selected = selectedItems(); if ( selected.count() != 1 ) return; mReaderWin->slotDeleteAttachment( static_cast<KMMimePartTreeItem*>( selected.first() )->node() ); } void KMMimePartTree::slotEdit() { QList<Q3ListViewItem*> selected = selectedItems(); if ( selected.count() != 1 ) return; mReaderWin->slotEditAttachment( static_cast<KMMimePartTreeItem*>( selected.first() )->node() ); } void KMMimePartTree::slotOpen() { startHandleAttachmentCommand( KMHandleAttachmentCommand::Open ); } void KMMimePartTree::slotOpenWith() { startHandleAttachmentCommand( KMHandleAttachmentCommand::OpenWith ); } void KMMimePartTree::slotView() { startHandleAttachmentCommand( KMHandleAttachmentCommand::View ); } void KMMimePartTree::slotProperties() { startHandleAttachmentCommand( KMHandleAttachmentCommand::Properties ); } void KMMimePartTree::startHandleAttachmentCommand( int action ) { QList<Q3ListViewItem *> selected = selectedItems(); if ( selected.count() != 1 ) return; partNode *node = static_cast<KMMimePartTreeItem *>( selected.first() )->node(); QString name = mReaderWin->tempFileUrlFromPartNode( node ).path(); KMHandleAttachmentCommand *command = new KMHandleAttachmentCommand( node, mReaderWin->message(), node->nodeId(), name, KMHandleAttachmentCommand::AttachmentAction( action ), KService::Ptr(), this ); connect( command, SIGNAL( showAttachment( int, const QString& ) ), mReaderWin, SLOT( slotAtmView( int, const QString& ) ) ); command->start(); } void KMMimePartTree::slotCopy() { QList<Q3ListViewItem *> selected = selectedItems(); if ( selected.count() != 1 ) return; partNode *node = static_cast<KMMimePartTreeItem *>( selected.first() )->node(); QList<QUrl> urls; KUrl kUrl = mReaderWin->tempFileUrlFromPartNode( node ); QUrl url = QUrl::fromPercentEncoding( kUrl.toEncoded() ); if ( !url.isValid() ) return; urls.append( url ); QMimeData *mimeData = new QMimeData; mimeData->setUrls( urls ); QApplication::clipboard()->setMimeData( mimeData, QClipboard::Clipboard ); } //============================================================================= KMMimePartTreeItem::KMMimePartTreeItem( KMMimePartTree * parent, partNode* node, const QString & description, const QString & mimetype, const QString & encoding, KIO::filesize_t size ) : Q3ListViewItem( parent, description, QString(), // set by setIconAndTextForType() encoding, KIO::convertSize( size ) ), mPartNode( node ), mOrigSize(size) { Q_ASSERT(parent); if( node ) node->setMimePartTreeItem( this ); setIconAndTextForType( mimetype ); parent->correctSize(this); } KMMimePartTreeItem::KMMimePartTreeItem( KMMimePartTreeItem * parent, partNode* node, const QString & description, const QString & mimetype, const QString & encoding, KIO::filesize_t size, bool revertOrder ) : Q3ListViewItem( parent, description, QString(), // set by setIconAndTextForType() encoding, KIO::convertSize( size ) ), mPartNode( node ), mOrigSize(size) { if( revertOrder && nextSibling() ){ Q3ListViewItem* sib = nextSibling(); while( sib->nextSibling() ) sib = sib->nextSibling(); moveItem( sib ); } if( node ) node->setMimePartTreeItem( this ); setIconAndTextForType( mimetype ); if ( listView() ) static_cast<KMMimePartTree*>(listView())->correctSize(this); } void KMMimePartTreeItem::setIconAndTextForType( const QString & mime ) { QString mimetype = mime.toLower(); if ( mimetype.startsWith( "multipart/" ) ) { setText( 1, mimetype ); setPixmap( 0, SmallIcon("folder") ); } else if ( mimetype == "application/octet-stream" ) { setText( 1, i18n("Unspecified Binary Data") ); // do not show "Unknown"... setPixmap( 0, SmallIcon("application-octet-stream") ); } else { KMimeType::Ptr mtp = KMimeType::mimeType( mimetype ); setText( 1, (mtp && !mtp->comment().isEmpty()) ? mtp->comment() : mimetype ); setPixmap( 0, mtp ? KIconLoader::global()->loadMimeTypeIcon(mtp->iconName(), KIconLoader::Small) : SmallIcon("unknown") ); } } void KMMimePartTree::startDrag() { KMMimePartTreeItem *item = static_cast<KMMimePartTreeItem*>( currentItem() ); if ( !item ) return; partNode *node = item->node(); if ( !node ) return; QList<QUrl> urls; KUrl kUrl = mReaderWin->tempFileUrlFromPartNode( node ); QUrl url = QUrl::fromPercentEncoding( kUrl.toEncoded() ); if ( !url.isValid() ) return; urls.append( url ); QDrag *drag = new QDrag( this ); QMimeData *mimeData = new QMimeData; mimeData->setUrls( urls ); drag->setMimeData( mimeData ); drag->exec( Qt::CopyAction ); } #include "kmmimeparttree.moc" <|endoftext|>
<commit_before>209f2342-2e4d-11e5-9284-b827eb9e62be<commit_msg>20a4290a-2e4d-11e5-9284-b827eb9e62be<commit_after>20a4290a-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>dec7ee84-2e4e-11e5-9284-b827eb9e62be<commit_msg>decce81c-2e4e-11e5-9284-b827eb9e62be<commit_after>decce81c-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>762c50a0-2e4d-11e5-9284-b827eb9e62be<commit_msg>763149d4-2e4d-11e5-9284-b827eb9e62be<commit_after>763149d4-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>19940f0e-2e4d-11e5-9284-b827eb9e62be<commit_msg>199914fe-2e4d-11e5-9284-b827eb9e62be<commit_after>199914fe-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>baec95b0-2e4d-11e5-9284-b827eb9e62be<commit_msg>baf19556-2e4d-11e5-9284-b827eb9e62be<commit_after>baf19556-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>c6735bfe-2e4c-11e5-9284-b827eb9e62be<commit_msg>c678526c-2e4c-11e5-9284-b827eb9e62be<commit_after>c678526c-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>c50c68ea-2e4d-11e5-9284-b827eb9e62be<commit_msg>c51157ba-2e4d-11e5-9284-b827eb9e62be<commit_after>c51157ba-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>// Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced // at the Lawrence Livermore National Laboratory. All Rights reserved. See files // LICENSE and NOTICE for details. LLNL-CODE-806117. // // This file is part of the MFEM library. For more information and source code // availability visit https://mfem.org. // // MFEM is free software; you can redistribute it and/or modify it under the // terms of the BSD-3 license. We welcome feedback and contributions, see file // CONTRIBUTING.md for details. #ifndef MFEM_TEMPLATE_CONFIG #define MFEM_TEMPLATE_CONFIG // the main MFEM config header #include "config.hpp" // --- MFEM_STATIC_ASSERT #if (__cplusplus >= 201103L) #define MFEM_STATIC_ASSERT(cond, msg) static_assert((cond), msg) #else #define MFEM_STATIC_ASSERT(cond, msg) if (cond) { } #endif // --- MFEM_ALWAYS_INLINE #if !defined(MFEM_DEBUG) && (defined(__GNUC__) || defined(__clang__)) #define MFEM_ALWAYS_INLINE __attribute__((always_inline)) #else #define MFEM_ALWAYS_INLINE #endif // --- MFEM_VECTORIZE_LOOP (disabled) #if (__cplusplus >= 201103L) && !defined(MFEM_DEBUG) && defined(__GNUC__) //#define MFEM_VECTORIZE_LOOP _Pragma("GCC ivdep") #define MFEM_VECTORIZE_LOOP #else #define MFEM_VECTORIZE_LOOP #endif // --- MFEM_ALIGN_AS #if (__cplusplus >= 201103L) #define MFEM_ALIGN_AS(bytes) alignas(bytes) #elif !defined(MFEM_DEBUG) && (defined(__GNUC__) || defined(__clang__)) #define MFEM_ALIGN_AS(bytes) __attribute__ ((aligned (bytes))) #else #define MFEM_ALIGN_AS(bytes) #endif // --- POSIX MEMALIGN #ifdef _WIN32 #define MFEM_POSIX_MEMALIGN(p,a,s) (((*(p))=_aligned_malloc((s),(a))),*(p)?0:errno) #define MFEM_POSIX_MEMALIGN_FREE _aligned_free #else #define MFEM_POSIX_MEMALIGN posix_memalign #define MFEM_POSIX_MEMALIGN_FREE free #endif // --- AutoSIMD or intrinsics #ifndef MFEM_USE_SIMD #include "simd/auto.hpp" #else #if defined(__VSX__) #include "simd/vsx.hpp" #elif defined (__bgq__) #include "simd/qpx.hpp" #elif defined(__x86_64__) #include "simd/x86.hpp" #else #error Unknown SIMD architecture #endif #endif // --- SIMD and BLOCK sizes #if defined(_WIN32) #define MFEM_SIMD_SIZE 8 #define MFEM_TEMPLATE_BLOCK_SIZE 1 #elif defined(__VSX__) #define MFEM_SIMD_SIZE 16 #define MFEM_TEMPLATE_BLOCK_SIZE 2 #elif defined(__x86_64__) #define MFEM_SIMD_SIZE 32 #define MFEM_TEMPLATE_BLOCK_SIZE 4 #else #error Unknown SIMD architecture #endif template<typename complex_t, typename real_t, bool simd> struct AutoImplTraits { static const int block_size = MFEM_TEMPLATE_BLOCK_SIZE; static const int align_size = MFEM_SIMD_SIZE; // in bytes static const int batch_size = 1; static const int simd_size = simd?(MFEM_SIMD_SIZE/sizeof(complex_t)):1; static const int valign_size = simd?simd_size:1; typedef AutoSIMD<complex_t,simd_size,valign_size> vcomplex_t; typedef AutoSIMD< real_t,simd_size,valign_size> vreal_t; #ifndef MFEM_USE_SIMD typedef AutoSIMD< int,simd_size,valign_size> vint_t; #endif // MFEM_USE_SIMD }; #define MFEM_TEMPLATE_ENABLE_SERIALIZE // #define MFEM_TEMPLATE_ELTRANS_HAS_NODE_DOFS // #define MFEM_TEMPLATE_ELTRANS_RESULT_HAS_NODES // #define MFEM_TEMPLATE_FIELD_EVAL_DATA_HAS_DOFS #define MFEM_TEMPLATE_INTRULE_COEFF_PRECOMP // derived macros #define MFEM_ROUNDUP(val,base) ((((val)+(base)-1)/(base))*(base)) #define MFEM_ALIGN_SIZE(size,type) \ MFEM_ROUNDUP(size,(MFEM_SIMD_SIZE)/sizeof(type)) #ifdef MFEM_COUNT_FLOPS namespace mfem { namespace internal { extern long long flop_count; } } #define MFEM_FLOPS_RESET() (mfem::internal::flop_count = 0) #define MFEM_FLOPS_ADD(cnt) (mfem::internal::flop_count += (cnt)) #define MFEM_FLOPS_GET() (mfem::internal::flop_count) #else #define MFEM_FLOPS_RESET() #define MFEM_FLOPS_ADD(cnt) #define MFEM_FLOPS_GET() (0) #endif #endif // MFEM_TEMPLATE_CONFIG <commit_msg>Cleanup config/tconfig<commit_after>// Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced // at the Lawrence Livermore National Laboratory. All Rights reserved. See files // LICENSE and NOTICE for details. LLNL-CODE-806117. // // This file is part of the MFEM library. For more information and source code // availability visit https://mfem.org. // // MFEM is free software; you can redistribute it and/or modify it under the // terms of the BSD-3 license. We welcome feedback and contributions, see file // CONTRIBUTING.md for details. #ifndef MFEM_TEMPLATE_CONFIG #define MFEM_TEMPLATE_CONFIG // the main MFEM config header #include "config.hpp" // --- MFEM_STATIC_ASSERT #if (__cplusplus >= 201103L) #define MFEM_STATIC_ASSERT(cond, msg) static_assert((cond), msg) #else #define MFEM_STATIC_ASSERT(cond, msg) if (cond) { } #endif // --- MFEM_ALWAYS_INLINE #if !defined(MFEM_DEBUG) && (defined(__GNUC__) || defined(__clang__)) #define MFEM_ALWAYS_INLINE __attribute__((always_inline)) #else #define MFEM_ALWAYS_INLINE #endif // --- MFEM_VECTORIZE_LOOP (disabled) #if (__cplusplus >= 201103L) && !defined(MFEM_DEBUG) && defined(__GNUC__) //#define MFEM_VECTORIZE_LOOP _Pragma("GCC ivdep") #define MFEM_VECTORIZE_LOOP #else #define MFEM_VECTORIZE_LOOP #endif // --- MFEM_ALIGN_AS #if (__cplusplus >= 201103L) #define MFEM_ALIGN_AS(bytes) alignas(bytes) #elif !defined(MFEM_DEBUG) && (defined(__GNUC__) || defined(__clang__)) #define MFEM_ALIGN_AS(bytes) __attribute__ ((aligned (bytes))) #else #define MFEM_ALIGN_AS(bytes) #endif // --- POSIX MEMALIGN #ifdef _WIN32 #define MFEM_POSIX_MEMALIGN(p,a,s) (((*(p))=_aligned_malloc((s),(a))),*(p)?0:errno) #define MFEM_POSIX_MEMALIGN_FREE _aligned_free #else #define MFEM_POSIX_MEMALIGN posix_memalign #define MFEM_POSIX_MEMALIGN_FREE free #endif // --- AutoSIMD or intrinsics #ifndef MFEM_USE_SIMD #include "simd/auto.hpp" #else #if defined(__VSX__) #include "simd/vsx.hpp" #elif defined (__bgq__) #include "simd/qpx.hpp" #elif defined(__x86_64__) #include "simd/x86.hpp" #else #error Unknown SIMD architecture #endif #endif // --- SIMD and BLOCK sizes #if defined(_WIN32) #define MFEM_SIMD_SIZE 8 #define MFEM_TEMPLATE_BLOCK_SIZE 1 #elif defined(__VSX__) #define MFEM_SIMD_SIZE 16 #define MFEM_TEMPLATE_BLOCK_SIZE 2 #elif defined(__x86_64__) #define MFEM_SIMD_SIZE 32 #define MFEM_TEMPLATE_BLOCK_SIZE 4 #else #error Unknown SIMD architecture #endif template<typename complex_t, typename real_t, bool simd> struct AutoImplTraits { static const int block_size = MFEM_TEMPLATE_BLOCK_SIZE; static const int align_size = MFEM_SIMD_SIZE; // in bytes static const int batch_size = 1; static const int simd_size = simd ? (MFEM_SIMD_SIZE/sizeof(complex_t)) : 1; static const int valign_size = simd ? simd_size : 1; typedef AutoSIMD<complex_t, simd_size, valign_size> vcomplex_t; typedef AutoSIMD<real_t, simd_size, valign_size> vreal_t; #ifndef MFEM_USE_SIMD typedef AutoSIMD<int, simd_size, valign_size> vint_t; #endif // MFEM_USE_SIMD }; #define MFEM_TEMPLATE_ENABLE_SERIALIZE // #define MFEM_TEMPLATE_ELTRANS_HAS_NODE_DOFS // #define MFEM_TEMPLATE_ELTRANS_RESULT_HAS_NODES // #define MFEM_TEMPLATE_FIELD_EVAL_DATA_HAS_DOFS #define MFEM_TEMPLATE_INTRULE_COEFF_PRECOMP // derived macros #define MFEM_ROUNDUP(val,base) ((((val)+(base)-1)/(base))*(base)) #define MFEM_ALIGN_SIZE(size,type) \ MFEM_ROUNDUP(size,(MFEM_SIMD_SIZE)/sizeof(type)) #ifdef MFEM_COUNT_FLOPS namespace mfem { namespace internal { extern long long flop_count; } } #define MFEM_FLOPS_RESET() (mfem::internal::flop_count = 0) #define MFEM_FLOPS_ADD(cnt) (mfem::internal::flop_count += (cnt)) #define MFEM_FLOPS_GET() (mfem::internal::flop_count) #else #define MFEM_FLOPS_RESET() #define MFEM_FLOPS_ADD(cnt) #define MFEM_FLOPS_GET() (0) #endif #endif // MFEM_TEMPLATE_CONFIG <|endoftext|>
<commit_before>0004a576-2e4d-11e5-9284-b827eb9e62be<commit_msg>000e1cbe-2e4d-11e5-9284-b827eb9e62be<commit_after>000e1cbe-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>7951df42-2e4e-11e5-9284-b827eb9e62be<commit_msg>7956fcc0-2e4e-11e5-9284-b827eb9e62be<commit_after>7956fcc0-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>2b7ee80e-2e4f-11e5-9284-b827eb9e62be<commit_msg>2b83f646-2e4f-11e5-9284-b827eb9e62be<commit_after>2b83f646-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>2e78beec-2e4d-11e5-9284-b827eb9e62be<commit_msg>2e7db578-2e4d-11e5-9284-b827eb9e62be<commit_after>2e7db578-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>471253a4-2e4e-11e5-9284-b827eb9e62be<commit_msg>47176556-2e4e-11e5-9284-b827eb9e62be<commit_after>47176556-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>a7a668b8-2e4e-11e5-9284-b827eb9e62be<commit_msg>a7ab7bdc-2e4e-11e5-9284-b827eb9e62be<commit_after>a7ab7bdc-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>16f57684-2e4d-11e5-9284-b827eb9e62be<commit_msg>16fa94de-2e4d-11e5-9284-b827eb9e62be<commit_after>16fa94de-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>6c789708-2e4d-11e5-9284-b827eb9e62be<commit_msg>6c7d9866-2e4d-11e5-9284-b827eb9e62be<commit_after>6c7d9866-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>00fc6fd0-2e4e-11e5-9284-b827eb9e62be<commit_msg>01016652-2e4e-11e5-9284-b827eb9e62be<commit_after>01016652-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>161a6506-2e4f-11e5-9284-b827eb9e62be<commit_msg>161f5a34-2e4f-11e5-9284-b827eb9e62be<commit_after>161f5a34-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>/* kopeteballoon.cpp - Nice Balloon Copyright (c) 2002 by Duncan Mac-Vicar Prett <[email protected]> Kopete (c) 2002-2003 by the Kopete developers <[email protected]> Portions of this code based on Kim Applet code Copyright (c) 2000-2002 by Malte Starostik <[email protected]> ************************************************************************* * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ************************************************************************* */ #include <qpointarray.h> #include <qpushbutton.h> #include <qtooltip.h> #include <qlayout.h> #include <kdeversion.h> #if KDE_IS_VERSION( 3, 1, 90 ) #include <kglobalsettings.h> #endif #include <kapplication.h> #include <kdialog.h> #include <klocale.h> #include <kstandarddirs.h> #include <kactivelabel.h> #include "kopeteballoon.h" #include "systemtray.h" KopeteBalloon::KopeteBalloon(const QString &text, const QString &pix) : QWidget(0L, "KopeteBalloon", WStyle_StaysOnTop | WStyle_Customize | WStyle_NoBorder | WStyle_Tool | WX11BypassWM) { setCaption(""); QVBoxLayout *BalloonLayout = new QVBoxLayout(this, 22, KDialog::spacingHint(), "BalloonLayout"); // BEGIN Layout1 QHBoxLayout *Layout1 = new QHBoxLayout(BalloonLayout, KDialog::spacingHint(), "Layout1"); //QLabel *mCaption = new QLabel(text, this, "mCaption"); KActiveLabel *mCaption = new KActiveLabel(text, this, "mCaption"); mCaption->setPalette(QToolTip::palette()); mCaption->setSizePolicy( QSizePolicy::Minimum, QSizePolicy::Minimum ); if (!pix.isEmpty()) { QLabel *mImage = new QLabel(this, "mImage"); mImage->setScaledContents(FALSE); mImage->setPixmap(locate("data", pix)); Layout1->addWidget(mImage); } Layout1->addWidget(mCaption); // END Layout1 // BEGIN Layout2 QHBoxLayout *Layout2 = new QHBoxLayout(BalloonLayout, KDialog::spacingHint(), "Layout2"); QPushButton *mViewButton = new QPushButton(i18n("to view", "View"), this, "mViewButton"); QPushButton *mIgnoreButton = new QPushButton(i18n("Ignore"), this, "mIgnoreButton"); Layout2->addStretch(); Layout2->addWidget(mViewButton); Layout2->addWidget(mIgnoreButton); Layout2->addStretch(); // END Layout2 setPalette(QToolTip::palette()); setAutoMask(TRUE); connect(mViewButton, SIGNAL(clicked()), this, SIGNAL(signalButtonClicked())); connect(mViewButton, SIGNAL(clicked()), this, SLOT(deleteLater())); connect(mIgnoreButton, SIGNAL(clicked()), this, SIGNAL(signalIgnoreButtonClicked())); connect(mIgnoreButton, SIGNAL(clicked()), this, SLOT(deleteLater())); connect(mCaption, SIGNAL(linkClicked(const QString &)), this, SIGNAL(signalIgnoreButtonClicked())); connect(mCaption, SIGNAL(linkClicked(const QString &)), this, SLOT(deleteLater())); } void KopeteBalloon::setAnchor(const QPoint &anchor) { mAnchor = anchor; updateMask(); } void KopeteBalloon::updateMask() { QRegion mask(10, 10, width() - 20, height() - 20); QPoint corners[8] = { QPoint(width() - 50, 10), QPoint(10, 10), QPoint(10, height() - 50), QPoint(width() - 50, height() - 50), QPoint(width() - 10, 10), QPoint(10, 10), QPoint(10, height() - 10), QPoint(width() - 10, height() - 10) }; for (int i = 0; i < 4; ++i) { QPointArray corner; corner.makeArc(corners[i].x(), corners[i].y(), 40, 40, i * 16 * 90, 16 * 90); corner.resize(corner.size() + 1); corner.setPoint(corner.size() - 1, corners[i + 4]); mask -= corner; } // get screen-geometry for screen our anchor is on // (geometry can differ from screen to screen! #if KDE_IS_VERSION( 3, 1, 90 ) QRect deskRect = KGlobalSettings::desktopGeometry(mAnchor); #else QDesktopWidget* tmp = QApplication::desktop(); QRect deskRect = tmp->screenGeometry(tmp->screenNumber(mAnchor)); #endif bool bottom = (mAnchor.y() + height()) > (deskRect.height() - 48); bool right = (mAnchor.x() + width()) > (deskRect.width() - 48); QPointArray arrow(4); arrow.setPoint(0, QPoint(right ? width() : 0, bottom ? height() : 0)); arrow.setPoint(1, QPoint(right ? width() - 10 : 10, bottom ? height() - 30 : 30)); arrow.setPoint(2, QPoint(right ? width() - 30 : 30, bottom ? height() - 10 : 10)); arrow.setPoint(3, arrow[0]); mask += arrow; setMask(mask); move(right ? mAnchor.x() - width() : ( mAnchor.x() < 0 ? 0 : mAnchor.x() ), bottom ? mAnchor.y() - height() : ( mAnchor.y() < 0 ? 0 : mAnchor.y() ) ); } #include "kopeteballoon.moc" // vim: set noet ts=4 sts=4 sw=4: <commit_msg>damn you balloon, show on my second display as well ;)<commit_after>/* kopeteballoon.cpp - Nice Balloon Copyright (c) 2002 by Duncan Mac-Vicar Prett <[email protected]> Kopete (c) 2002-2003 by the Kopete developers <[email protected]> Portions of this code based on Kim Applet code Copyright (c) 2000-2002 by Malte Starostik <[email protected]> ************************************************************************* * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ************************************************************************* */ #include <qpointarray.h> #include <qpushbutton.h> #include <qtooltip.h> #include <qlayout.h> #include <kdeversion.h> #if KDE_IS_VERSION( 3, 1, 90 ) #include <kglobalsettings.h> #endif #include <kapplication.h> #include <kdialog.h> #include <klocale.h> #include <kstandarddirs.h> #include <kactivelabel.h> #include "kopeteballoon.h" #include "systemtray.h" KopeteBalloon::KopeteBalloon(const QString &text, const QString &pix) : QWidget(0L, "KopeteBalloon", WStyle_StaysOnTop | WStyle_Customize | WStyle_NoBorder | WStyle_Tool | WX11BypassWM) { setCaption(""); QVBoxLayout *BalloonLayout = new QVBoxLayout(this, 22, KDialog::spacingHint(), "BalloonLayout"); // BEGIN Layout1 QHBoxLayout *Layout1 = new QHBoxLayout(BalloonLayout, KDialog::spacingHint(), "Layout1"); //QLabel *mCaption = new QLabel(text, this, "mCaption"); KActiveLabel *mCaption = new KActiveLabel(text, this, "mCaption"); mCaption->setPalette(QToolTip::palette()); mCaption->setSizePolicy( QSizePolicy::Minimum, QSizePolicy::Minimum ); if (!pix.isEmpty()) { QLabel *mImage = new QLabel(this, "mImage"); mImage->setScaledContents(FALSE); mImage->setPixmap(locate("data", pix)); Layout1->addWidget(mImage); } Layout1->addWidget(mCaption); // END Layout1 // BEGIN Layout2 QHBoxLayout *Layout2 = new QHBoxLayout(BalloonLayout, KDialog::spacingHint(), "Layout2"); QPushButton *mViewButton = new QPushButton(i18n("to view", "View"), this, "mViewButton"); QPushButton *mIgnoreButton = new QPushButton(i18n("Ignore"), this, "mIgnoreButton"); Layout2->addStretch(); Layout2->addWidget(mViewButton); Layout2->addWidget(mIgnoreButton); Layout2->addStretch(); // END Layout2 setPalette(QToolTip::palette()); setAutoMask(TRUE); connect(mViewButton, SIGNAL(clicked()), this, SIGNAL(signalButtonClicked())); connect(mViewButton, SIGNAL(clicked()), this, SLOT(deleteLater())); connect(mIgnoreButton, SIGNAL(clicked()), this, SIGNAL(signalIgnoreButtonClicked())); connect(mIgnoreButton, SIGNAL(clicked()), this, SLOT(deleteLater())); connect(mCaption, SIGNAL(linkClicked(const QString &)), this, SIGNAL(signalIgnoreButtonClicked())); connect(mCaption, SIGNAL(linkClicked(const QString &)), this, SLOT(deleteLater())); } void KopeteBalloon::setAnchor(const QPoint &anchor) { mAnchor = anchor; updateMask(); } void KopeteBalloon::updateMask() { QRegion mask(10, 10, width() - 20, height() - 20); QPoint corners[8] = { QPoint(width() - 50, 10), QPoint(10, 10), QPoint(10, height() - 50), QPoint(width() - 50, height() - 50), QPoint(width() - 10, 10), QPoint(10, 10), QPoint(10, height() - 10), QPoint(width() - 10, height() - 10) }; for (int i = 0; i < 4; ++i) { QPointArray corner; corner.makeArc(corners[i].x(), corners[i].y(), 40, 40, i * 16 * 90, 16 * 90); corner.resize(corner.size() + 1); corner.setPoint(corner.size() - 1, corners[i + 4]); mask -= corner; } // get screen-geometry for screen our anchor is on // (geometry can differ from screen to screen! #if KDE_IS_VERSION( 3, 1, 90 ) QRect deskRect = KGlobalSettings::desktopGeometry(mAnchor); #else QDesktopWidget* tmp = QApplication::desktop(); QRect deskRect = tmp->screenGeometry(tmp->screenNumber(mAnchor)); #endif bool bottom = (mAnchor.y() + height()) > ((deskRect.y() + deskRect.height()) - 48); bool right = (mAnchor.x() + width()) > ((deskRect.x() + deskRect.width()) - 48); QPointArray arrow(4); arrow.setPoint(0, QPoint(right ? width() : 0, bottom ? height() : 0)); arrow.setPoint(1, QPoint(right ? width() - 10 : 10, bottom ? height() - 30 : 30)); arrow.setPoint(2, QPoint(right ? width() - 30 : 30, bottom ? height() - 10 : 10)); arrow.setPoint(3, arrow[0]); mask += arrow; setMask(mask); move(right ? mAnchor.x() - width() : ( mAnchor.x() < 0 ? 0 : mAnchor.x() ), bottom ? mAnchor.y() - height() : ( mAnchor.y() < 0 ? 0 : mAnchor.y() ) ); } #include "kopeteballoon.moc" // vim: set noet ts=4 sts=4 sw=4: <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: animationtransitionfilternode.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: obo $ $Date: 2006-09-17 08:35:10 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_slideshow.hxx" // must be first #include "canvas/debug.hxx" #include "canvas/verbosetrace.hxx" #include "animationtransitionfilternode.hxx" #include "transitionfactory.hxx" namespace presentation { namespace internal { void AnimationTransitionFilterNode::dispose() { mxTransitionFilterNode.clear(); AnimationBaseNode::dispose(); } AnimationActivitySharedPtr AnimationTransitionFilterNode::createActivity() const { return TransitionFactory::createShapeTransition( fillCommonParameters(), getShape(), getContext().mpLayerManager, mxTransitionFilterNode ); } } // namespace internal } // namespace presentation <commit_msg>INTEGRATION: CWS presfixes09 (1.3.18); FILE MERGED 2006/10/18 19:55:09 thb 1.3.18.3: RESYNC: (1.4-1.5); FILE MERGED 2006/09/15 22:15:14 thb 1.3.18.2: RESYNC: (1.3-1.4); FILE MERGED 2006/03/24 18:23:17 thb 1.3.18.1: #i37778# Moved whole slideshow engine from namespace presentation (which conflicts with one of the UNO subnamespaces) to slideshow<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: animationtransitionfilternode.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: kz $ $Date: 2006-12-13 15:31:49 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_slideshow.hxx" // must be first #include "canvas/debug.hxx" #include "canvas/verbosetrace.hxx" #include "animationtransitionfilternode.hxx" #include "transitionfactory.hxx" namespace slideshow { namespace internal { void AnimationTransitionFilterNode::dispose() { mxTransitionFilterNode.clear(); AnimationBaseNode::dispose(); } AnimationActivitySharedPtr AnimationTransitionFilterNode::createActivity() const { return TransitionFactory::createShapeTransition( fillCommonParameters(), getShape(), getContext().mpLayerManager, mxTransitionFilterNode ); } } // namespace internal } // namespace slideshow <|endoftext|>
<commit_before>c7b578ce-2e4e-11e5-9284-b827eb9e62be<commit_msg>c7ba7018-2e4e-11e5-9284-b827eb9e62be<commit_after>c7ba7018-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>/* This file is part of KOrganizer. Copyright (c) 2003 Cornelius Schumacher <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ #include "aboutdata.h" #include "version.h" using namespace KOrg; AboutData *AboutData::mSelf = 0; AboutData::AboutData() : KAboutData( "korganizer", I18N_NOOP("KOrganizer"), korgVersion, I18N_NOOP("A Personal Organizer for KDE"), KAboutData::License_GPL, "(c) 1997-1999 Preston Brown\n" "(c) 2000-2004 Cornelius Schumacher\n" "(c) 2004-2005 Reinhold Kainhofer", 0, "http://korganizer.kde.org" ) { addAuthor("Reinhold Kainhofer",I18N_NOOP("Current Maintainer"), "[email protected]"); addAuthor("Cornelius Schumacher",I18N_NOOP("Co-Maintainer"), "[email protected]"); addAuthor("Preston Brown",I18N_NOOP("Original Author"), "[email protected]"); addCredit("Richard Apodaca"); addCredit("Jan-Pascal van Best"); addCredit("Laszlo Boloni"); addCredit("Barry Benowitz"); addCredit("Christopher Beard"); addCredit("Ian Dawes"); addCredit("Thomas Eitzenberger"); addCredit("Neil Hart"); addCredit("Declan Houlihan"); addCredit("Hans-Jürgen Husel"); addCredit("Tim Jansen"); addCredit("Christian Kirsch"); addCredit("Tobias König"); addCredit("Martin Koller"); addCredit("Uwe Koloska"); addCredit("Glen Parker"); addCredit("Dan Pilone"); addCredit("Roman Rohr"); addCredit("Don Sanders"); addCredit("Bram Schoenmakers"); addCredit("Günter Schwann"); addCredit("Herwin Jan Steehouwer"); addCredit("Mario Teijeiro"); addCredit("Nick Thompson"); addCredit("Bo Thorsen"); addCredit("Larry Wright"); addCredit("Thomas Zander"); addCredit("Fester Zigterman"); } AboutData *AboutData::self() { if ( !mSelf ) mSelf = new AboutData; return mSelf; } <commit_msg>give myself a little credit...<commit_after>/* This file is part of KOrganizer. Copyright (c) 2003 Cornelius Schumacher <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ #include "aboutdata.h" #include "version.h" using namespace KOrg; AboutData *AboutData::mSelf = 0; AboutData::AboutData() : KAboutData( "korganizer", I18N_NOOP("KOrganizer"), korgVersion, I18N_NOOP("A Personal Organizer for KDE"), KAboutData::License_GPL, "(c) 1997-1999 Preston Brown\n" "(c) 2000-2004 Cornelius Schumacher\n" "(c) 2004-2005 Reinhold Kainhofer", 0, "http://korganizer.kde.org" ) { addAuthor("Reinhold Kainhofer",I18N_NOOP("Current Maintainer"), "[email protected]"); addAuthor("Cornelius Schumacher",I18N_NOOP("Co-Maintainer"), "[email protected]"); addAuthor("Preston Brown",I18N_NOOP("Original Author"), "[email protected]"); addCredit("Richard Apodaca"); addCredit("Jan-Pascal van Best"); addCredit("Laszlo Boloni"); addCredit("Barry Benowitz"); addCredit("Christopher Beard"); addCredit("Ian Dawes"); addCredit("Thomas Eitzenberger"); addCredit("Neil Hart"); addCredit("Declan Houlihan"); addCredit("Hans-Jürgen Husel"); addCredit("Tim Jansen"); addCredit("Christian Kirsch"); addCredit("Tobias König"); addCredit("Martin Koller"); addCredit("Uwe Koloska"); addCredit("Glen Parker"); addCredit("Dan Pilone"); addCredit("Roman Rohr"); addCredit("Don Sanders"); addCredit("Bram Schoenmakers"); addCredit("Günter Schwann"); addCredit("Herwin Jan Steehouwer"); addCredit("Mario Teijeiro"); addCredit("Nick Thompson"); addCredit("Bo Thorsen"); addCredit("Allen Winter"); addCredit("Larry Wright"); addCredit("Thomas Zander"); addCredit("Fester Zigterman"); } AboutData *AboutData::self() { if ( !mSelf ) mSelf = new AboutData; return mSelf; } <|endoftext|>
<commit_before>69bb8998-2e4e-11e5-9284-b827eb9e62be<commit_msg>69c0d3a8-2e4e-11e5-9284-b827eb9e62be<commit_after>69c0d3a8-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>3a16cd42-2e4e-11e5-9284-b827eb9e62be<commit_msg>3a1bf790-2e4e-11e5-9284-b827eb9e62be<commit_after>3a1bf790-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>6463f1b6-2e4d-11e5-9284-b827eb9e62be<commit_msg>6468f5bc-2e4d-11e5-9284-b827eb9e62be<commit_after>6468f5bc-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>13965912-2e4e-11e5-9284-b827eb9e62be<commit_msg>139b4b02-2e4e-11e5-9284-b827eb9e62be<commit_after>139b4b02-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>55c790a4-2e4d-11e5-9284-b827eb9e62be<commit_msg>55cc9928-2e4d-11e5-9284-b827eb9e62be<commit_after>55cc9928-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>4409aaa0-2e4d-11e5-9284-b827eb9e62be<commit_msg>440eae06-2e4d-11e5-9284-b827eb9e62be<commit_after>440eae06-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>d478ce3c-2e4c-11e5-9284-b827eb9e62be<commit_msg>d47df506-2e4c-11e5-9284-b827eb9e62be<commit_after>d47df506-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>92858f0e-2e4e-11e5-9284-b827eb9e62be<commit_msg>928a98b4-2e4e-11e5-9284-b827eb9e62be<commit_after>928a98b4-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>907c5472-2e4e-11e5-9284-b827eb9e62be<commit_msg>90814ed2-2e4e-11e5-9284-b827eb9e62be<commit_after>90814ed2-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>c182df8c-2e4e-11e5-9284-b827eb9e62be<commit_msg>c187d780-2e4e-11e5-9284-b827eb9e62be<commit_after>c187d780-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>878e2d9a-2e4e-11e5-9284-b827eb9e62be<commit_msg>87933a1a-2e4e-11e5-9284-b827eb9e62be<commit_after>87933a1a-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>cc3f4700-2e4c-11e5-9284-b827eb9e62be<commit_msg>cc443ae4-2e4c-11e5-9284-b827eb9e62be<commit_after>cc443ae4-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>d71f4106-2e4d-11e5-9284-b827eb9e62be<commit_msg>d72436a2-2e4d-11e5-9284-b827eb9e62be<commit_after>d72436a2-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>6fbb45be-2e4d-11e5-9284-b827eb9e62be<commit_msg>6fc06652-2e4d-11e5-9284-b827eb9e62be<commit_after>6fc06652-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>e5986ce0-2e4c-11e5-9284-b827eb9e62be<commit_msg>e5b5b098-2e4c-11e5-9284-b827eb9e62be<commit_after>e5b5b098-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>3d015258-2e4d-11e5-9284-b827eb9e62be<commit_msg>3d065488-2e4d-11e5-9284-b827eb9e62be<commit_after>3d065488-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>e340a926-2e4c-11e5-9284-b827eb9e62be<commit_msg>e345b6c8-2e4c-11e5-9284-b827eb9e62be<commit_after>e345b6c8-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>6f1c9cba-2e4e-11e5-9284-b827eb9e62be<commit_msg>6f2194ae-2e4e-11e5-9284-b827eb9e62be<commit_after>6f2194ae-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>d31a391c-2e4d-11e5-9284-b827eb9e62be<commit_msg>d31f3912-2e4d-11e5-9284-b827eb9e62be<commit_after>d31f3912-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>a705df3e-2e4d-11e5-9284-b827eb9e62be<commit_msg>a70ae3da-2e4d-11e5-9284-b827eb9e62be<commit_after>a70ae3da-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>644aae4a-2e4d-11e5-9284-b827eb9e62be<commit_msg>644fcbf0-2e4d-11e5-9284-b827eb9e62be<commit_after>644fcbf0-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>35429908-2e4f-11e5-9284-b827eb9e62be<commit_msg>35478cd8-2e4f-11e5-9284-b827eb9e62be<commit_after>35478cd8-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>ce1cf6a2-2e4d-11e5-9284-b827eb9e62be<commit_msg>ce21f166-2e4d-11e5-9284-b827eb9e62be<commit_after>ce21f166-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>6e8cf160-2e4d-11e5-9284-b827eb9e62be<commit_msg>6e92016e-2e4d-11e5-9284-b827eb9e62be<commit_after>6e92016e-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>fb9133cc-2e4e-11e5-9284-b827eb9e62be<commit_msg>fb9645e2-2e4e-11e5-9284-b827eb9e62be<commit_after>fb9645e2-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>d774a6a6-2e4c-11e5-9284-b827eb9e62be<commit_msg>d77b06fe-2e4c-11e5-9284-b827eb9e62be<commit_after>d77b06fe-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>d79bbbdc-2e4d-11e5-9284-b827eb9e62be<commit_msg>d7a0c10e-2e4d-11e5-9284-b827eb9e62be<commit_after>d7a0c10e-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>b32375b0-2e4d-11e5-9284-b827eb9e62be<commit_msg>b3286f02-2e4d-11e5-9284-b827eb9e62be<commit_after>b3286f02-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>2432d6d2-2e4f-11e5-9284-b827eb9e62be<commit_msg>2437da74-2e4f-11e5-9284-b827eb9e62be<commit_after>2437da74-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>5dfbb106-2e4d-11e5-9284-b827eb9e62be<commit_msg>5e00b782-2e4d-11e5-9284-b827eb9e62be<commit_after>5e00b782-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>4d9d7b8c-2e4d-11e5-9284-b827eb9e62be<commit_msg>4da2952c-2e4d-11e5-9284-b827eb9e62be<commit_after>4da2952c-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>ae85b35a-2e4e-11e5-9284-b827eb9e62be<commit_msg>ae8ab8f0-2e4e-11e5-9284-b827eb9e62be<commit_after>ae8ab8f0-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>40c9476a-2e4d-11e5-9284-b827eb9e62be<commit_msg>40ce5598-2e4d-11e5-9284-b827eb9e62be<commit_after>40ce5598-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>ee7a72fe-2e4c-11e5-9284-b827eb9e62be<commit_msg>ee7f5ad0-2e4c-11e5-9284-b827eb9e62be<commit_after>ee7f5ad0-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>27322538-2e4d-11e5-9284-b827eb9e62be<commit_msg>2737216e-2e4d-11e5-9284-b827eb9e62be<commit_after>2737216e-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>bda603c6-2e4e-11e5-9284-b827eb9e62be<commit_msg>bdab202c-2e4e-11e5-9284-b827eb9e62be<commit_after>bdab202c-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>c3621522-2e4c-11e5-9284-b827eb9e62be<commit_msg>c3670528-2e4c-11e5-9284-b827eb9e62be<commit_after>c3670528-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>032d6204-2e4f-11e5-9284-b827eb9e62be<commit_msg>03325886-2e4f-11e5-9284-b827eb9e62be<commit_after>03325886-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>ecf8bfd4-2e4d-11e5-9284-b827eb9e62be<commit_msg>ecfdb6ec-2e4d-11e5-9284-b827eb9e62be<commit_after>ecfdb6ec-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>aa34b76c-2e4c-11e5-9284-b827eb9e62be<commit_msg>aa3aa3d4-2e4c-11e5-9284-b827eb9e62be<commit_after>aa3aa3d4-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>b99903e8-2e4c-11e5-9284-b827eb9e62be<commit_msg>b99e35de-2e4c-11e5-9284-b827eb9e62be<commit_after>b99e35de-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>d9746a0e-2e4c-11e5-9284-b827eb9e62be<commit_msg>d9797cd8-2e4c-11e5-9284-b827eb9e62be<commit_after>d9797cd8-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>90ae23a8-2e4e-11e5-9284-b827eb9e62be<commit_msg>90b31d68-2e4e-11e5-9284-b827eb9e62be<commit_after>90b31d68-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>05cc681c-2e4e-11e5-9284-b827eb9e62be<commit_msg>05d1d28e-2e4e-11e5-9284-b827eb9e62be<commit_after>05d1d28e-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>1d2c692c-2e4d-11e5-9284-b827eb9e62be<commit_msg>1d316206-2e4d-11e5-9284-b827eb9e62be<commit_after>1d316206-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>b7bd2cbe-2e4e-11e5-9284-b827eb9e62be<commit_msg>b7c23984-2e4e-11e5-9284-b827eb9e62be<commit_after>b7c23984-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>04e08b46-2e4d-11e5-9284-b827eb9e62be<commit_msg>04e585f6-2e4d-11e5-9284-b827eb9e62be<commit_after>04e585f6-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>2ad529d8-2e4d-11e5-9284-b827eb9e62be<commit_msg>2adaa4da-2e4d-11e5-9284-b827eb9e62be<commit_after>2adaa4da-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>3b831c1c-2e4e-11e5-9284-b827eb9e62be<commit_msg>3b881ece-2e4e-11e5-9284-b827eb9e62be<commit_after>3b881ece-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>c3520032-2e4d-11e5-9284-b827eb9e62be<commit_msg>c357092e-2e4d-11e5-9284-b827eb9e62be<commit_after>c357092e-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>0c19bd5e-2e4f-11e5-9284-b827eb9e62be<commit_msg>0c1ebd04-2e4f-11e5-9284-b827eb9e62be<commit_after>0c1ebd04-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>30ae79c0-2e4f-11e5-9284-b827eb9e62be<commit_msg>30b36fc0-2e4f-11e5-9284-b827eb9e62be<commit_after>30b36fc0-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>d79af2b4-2e4e-11e5-9284-b827eb9e62be<commit_msg>d79fed8c-2e4e-11e5-9284-b827eb9e62be<commit_after>d79fed8c-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: XMLCalculationSettingsContext.cxx,v $ * * $Revision: 1.14 $ * * last change: $Author: kz $ $Date: 2006-07-21 12:38:39 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sc.hxx" // INCLUDE --------------------------------------------------------------- #ifndef _SC_XMLCALCULATIONSETTINGSCONTEXT_HXX #include "XMLCalculationSettingsContext.hxx" #endif #ifndef SC_XMLIMPRT_HXX #include "xmlimprt.hxx" #endif #ifndef SC_UNONAMES_HXX #include "unonames.hxx" #endif #ifndef SC_DOCOPTIO_HXX #include "docoptio.hxx" #endif #ifndef SC_DOCUMENT_HXX #include "document.hxx" #endif #ifndef _XMLOFF_XMLTOKEN_HXX #include <xmloff/xmltoken.hxx> #endif #ifndef _XMLOFF_XMLNMSPE_HXX #include <xmloff/xmlnmspe.hxx> #endif #ifndef _XMLOFF_XMLUCONV_HXX #include <xmloff/xmluconv.hxx> #endif #ifndef _XMLOFF_NMSPMAP_HXX #include <xmloff/nmspmap.hxx> #endif #ifndef _COM_SUN_STAR_SHEET_XSPREADSHEETDOCUMENT_HPP_ #include <com/sun/star/sheet/XSpreadsheetDocument.hpp> #endif #ifndef _COMPHELPER_EXTRACT_HXX_ #include <comphelper/extract.hxx> #endif using namespace com::sun::star; using namespace xmloff::token; //------------------------------------------------------------------ ScXMLCalculationSettingsContext::ScXMLCalculationSettingsContext( ScXMLImport& rImport, USHORT nPrfx, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList) : SvXMLImportContext( rImport, nPrfx, rLName ), fIterationEpsilon(0.001), nIterationCount(100), nYear2000(1930), bIsIterationEnabled(sal_False), bCalcAsShown(sal_False), bIgnoreCase(sal_False), bLookUpLabels(sal_True), bMatchWholeCell(sal_True), bUseRegularExpressions(sal_True) { aNullDate.Day = 30; aNullDate.Month = 12; aNullDate.Year = 1899; sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0; for( sal_Int16 i=0; i < nAttrCount; ++i ) { const rtl::OUString& sAttrName(xAttrList->getNameByIndex( i )); rtl::OUString aLocalName; sal_uInt16 nPrefix = GetScImport().GetNamespaceMap().GetKeyByAttrName( sAttrName, &aLocalName ); const rtl::OUString& sValue(xAttrList->getValueByIndex( i )); if (nPrefix == XML_NAMESPACE_TABLE) { if (IsXMLToken(aLocalName, XML_CASE_SENSITIVE)) { if (IsXMLToken(sValue, XML_FALSE)) bIgnoreCase = sal_True; } else if (IsXMLToken(aLocalName, XML_PRECISION_AS_SHOWN)) { if (IsXMLToken(sValue, XML_TRUE)) bCalcAsShown = sal_True; } else if (IsXMLToken(aLocalName, XML_SEARCH_CRITERIA_MUST_APPLY_TO_WHOLE_CELL)) { if (IsXMLToken(sValue, XML_FALSE)) bMatchWholeCell = sal_False; } else if (IsXMLToken(aLocalName, XML_AUTOMATIC_FIND_LABELS)) { if (IsXMLToken(sValue, XML_FALSE)) bLookUpLabels = sal_False; } else if (IsXMLToken(aLocalName, XML_NULL_YEAR)) { sal_Int32 nTemp; GetScImport().GetMM100UnitConverter().convertNumber(nTemp, sValue); nYear2000 = static_cast<sal_uInt16>(nTemp); } else if (IsXMLToken(aLocalName, XML_USE_REGULAR_EXPRESSIONS)) { if (IsXMLToken(sValue, XML_FALSE)) bUseRegularExpressions = sal_False; } } } } ScXMLCalculationSettingsContext::~ScXMLCalculationSettingsContext() { } SvXMLImportContext *ScXMLCalculationSettingsContext::CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList ) { SvXMLImportContext *pContext = 0; if (nPrefix == XML_NAMESPACE_TABLE) { if (IsXMLToken(rLName, XML_NULL_DATE)) pContext = new ScXMLNullDateContext(GetScImport(), nPrefix, rLName, xAttrList, this); else if (IsXMLToken(rLName, XML_ITERATION)) pContext = new ScXMLIterationContext(GetScImport(), nPrefix, rLName, xAttrList, this); } if( !pContext ) pContext = new SvXMLImportContext( GetImport(), nPrefix, rLName ); return pContext; } void ScXMLCalculationSettingsContext::EndElement() { if (GetScImport().GetModel().is()) { uno::Reference <beans::XPropertySet> xPropertySet (GetScImport().GetModel(), uno::UNO_QUERY); if (xPropertySet.is()) { xPropertySet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNO_CALCASSHOWN)), uno::makeAny(bCalcAsShown) ); xPropertySet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNO_IGNORECASE)), uno::makeAny(bIgnoreCase) ); xPropertySet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNO_LOOKUPLABELS)), uno::makeAny(bLookUpLabels) ); xPropertySet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNO_MATCHWHOLE)), uno::makeAny(bMatchWholeCell) ); xPropertySet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNO_REGEXENABLED)), uno::makeAny(bUseRegularExpressions) ); xPropertySet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNO_ITERENABLED)), uno::makeAny(bIsIterationEnabled) ); xPropertySet->setPropertyValue( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNO_ITERCOUNT)), uno::makeAny(nIterationCount) ); xPropertySet->setPropertyValue( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNO_ITEREPSILON)), uno::makeAny(fIterationEpsilon) ); xPropertySet->setPropertyValue( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNO_NULLDATE)), uno::makeAny(aNullDate) ); if (GetScImport().GetDocument()) { GetScImport().LockSolarMutex(); ScDocOptions aDocOptions (GetScImport().GetDocument()->GetDocOptions()); aDocOptions.SetYear2000(nYear2000); GetScImport().GetDocument()->SetDocOptions(aDocOptions); GetScImport().UnlockSolarMutex(); } } } } ScXMLNullDateContext::ScXMLNullDateContext( ScXMLImport& rImport, USHORT nPrfx, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList, ScXMLCalculationSettingsContext* pCalcSet) : SvXMLImportContext( rImport, nPrfx, rLName ) { sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0; for( sal_Int16 i=0; i < nAttrCount; ++i ) { const rtl::OUString& sAttrName(xAttrList->getNameByIndex( i )); rtl::OUString aLocalName; sal_uInt16 nPrefix = GetScImport().GetNamespaceMap().GetKeyByAttrName( sAttrName, &aLocalName ); const rtl::OUString& sValue(xAttrList->getValueByIndex( i )); if (nPrefix == XML_NAMESPACE_TABLE && IsXMLToken(aLocalName, XML_DATE_VALUE)) { util::DateTime aDateTime; GetScImport().GetMM100UnitConverter().convertDateTime(aDateTime, sValue); util::Date aDate; aDate.Day = aDateTime.Day; aDate.Month = aDateTime.Month; aDate.Year = aDateTime.Year; pCalcSet->SetNullDate(aDate); } } } ScXMLNullDateContext::~ScXMLNullDateContext() { } SvXMLImportContext *ScXMLNullDateContext::CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList ) { SvXMLImportContext *pContext = new SvXMLImportContext( GetImport(), nPrefix, rLName ); return pContext; } void ScXMLNullDateContext::EndElement() { } ScXMLIterationContext::ScXMLIterationContext( ScXMLImport& rImport, USHORT nPrfx, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList, ScXMLCalculationSettingsContext* pCalcSet) : SvXMLImportContext( rImport, nPrfx, rLName ) { sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0; for( sal_Int16 i=0; i < nAttrCount; ++i ) { const rtl::OUString& sAttrName(xAttrList->getNameByIndex( i )); rtl::OUString aLocalName; sal_uInt16 nPrefix = GetScImport().GetNamespaceMap().GetKeyByAttrName( sAttrName, &aLocalName ); const rtl::OUString& sValue(xAttrList->getValueByIndex( i )); if (nPrefix == XML_NAMESPACE_TABLE) { if (IsXMLToken(aLocalName, XML_STATUS)) { if (IsXMLToken(sValue, XML_ENABLE)) pCalcSet->SetIterationStatus(sal_True); } else if (IsXMLToken(aLocalName, XML_STEPS)) { sal_Int32 nSteps; GetScImport().GetMM100UnitConverter().convertNumber(nSteps, sValue); pCalcSet->SetIterationCount(nSteps); } else if (IsXMLToken(aLocalName, XML_MAXIMUM_DIFFERENCE)) { double fDif; GetScImport().GetMM100UnitConverter().convertDouble(fDif, sValue); pCalcSet->SetIterationEpsilon(fDif); } } } } ScXMLIterationContext::~ScXMLIterationContext() { } SvXMLImportContext *ScXMLIterationContext::CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList ) { SvXMLImportContext *pContext = new SvXMLImportContext( GetImport(), nPrefix, rLName ); return pContext; } void ScXMLIterationContext::EndElement() { } <commit_msg>INTEGRATION: CWS calcwarnings (1.14.110); FILE MERGED 2006/12/01 13:29:14 nn 1.14.110.1: #i69284# warning-free: filter/xml, wntmsci10<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: XMLCalculationSettingsContext.cxx,v $ * * $Revision: 1.15 $ * * last change: $Author: vg $ $Date: 2007-02-27 12:43:29 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sc.hxx" // INCLUDE --------------------------------------------------------------- #ifndef _SC_XMLCALCULATIONSETTINGSCONTEXT_HXX #include "XMLCalculationSettingsContext.hxx" #endif #ifndef SC_XMLIMPRT_HXX #include "xmlimprt.hxx" #endif #ifndef SC_UNONAMES_HXX #include "unonames.hxx" #endif #ifndef SC_DOCOPTIO_HXX #include "docoptio.hxx" #endif #ifndef SC_DOCUMENT_HXX #include "document.hxx" #endif #ifndef _XMLOFF_XMLTOKEN_HXX #include <xmloff/xmltoken.hxx> #endif #ifndef _XMLOFF_XMLNMSPE_HXX #include <xmloff/xmlnmspe.hxx> #endif #ifndef _XMLOFF_XMLUCONV_HXX #include <xmloff/xmluconv.hxx> #endif #ifndef _XMLOFF_NMSPMAP_HXX #include <xmloff/nmspmap.hxx> #endif #ifndef _COM_SUN_STAR_SHEET_XSPREADSHEETDOCUMENT_HPP_ #include <com/sun/star/sheet/XSpreadsheetDocument.hpp> #endif #ifndef _COMPHELPER_EXTRACT_HXX_ #include <comphelper/extract.hxx> #endif using namespace com::sun::star; using namespace xmloff::token; //------------------------------------------------------------------ ScXMLCalculationSettingsContext::ScXMLCalculationSettingsContext( ScXMLImport& rImport, USHORT nPrfx, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList) : SvXMLImportContext( rImport, nPrfx, rLName ), fIterationEpsilon(0.001), nIterationCount(100), nYear2000(1930), bIsIterationEnabled(sal_False), bCalcAsShown(sal_False), bIgnoreCase(sal_False), bLookUpLabels(sal_True), bMatchWholeCell(sal_True), bUseRegularExpressions(sal_True) { aNullDate.Day = 30; aNullDate.Month = 12; aNullDate.Year = 1899; sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0; for( sal_Int16 i=0; i < nAttrCount; ++i ) { const rtl::OUString& sAttrName(xAttrList->getNameByIndex( i )); rtl::OUString aLocalName; sal_uInt16 nPrefix = GetScImport().GetNamespaceMap().GetKeyByAttrName( sAttrName, &aLocalName ); const rtl::OUString& sValue(xAttrList->getValueByIndex( i )); if (nPrefix == XML_NAMESPACE_TABLE) { if (IsXMLToken(aLocalName, XML_CASE_SENSITIVE)) { if (IsXMLToken(sValue, XML_FALSE)) bIgnoreCase = sal_True; } else if (IsXMLToken(aLocalName, XML_PRECISION_AS_SHOWN)) { if (IsXMLToken(sValue, XML_TRUE)) bCalcAsShown = sal_True; } else if (IsXMLToken(aLocalName, XML_SEARCH_CRITERIA_MUST_APPLY_TO_WHOLE_CELL)) { if (IsXMLToken(sValue, XML_FALSE)) bMatchWholeCell = sal_False; } else if (IsXMLToken(aLocalName, XML_AUTOMATIC_FIND_LABELS)) { if (IsXMLToken(sValue, XML_FALSE)) bLookUpLabels = sal_False; } else if (IsXMLToken(aLocalName, XML_NULL_YEAR)) { sal_Int32 nTemp; GetScImport().GetMM100UnitConverter().convertNumber(nTemp, sValue); nYear2000 = static_cast<sal_uInt16>(nTemp); } else if (IsXMLToken(aLocalName, XML_USE_REGULAR_EXPRESSIONS)) { if (IsXMLToken(sValue, XML_FALSE)) bUseRegularExpressions = sal_False; } } } } ScXMLCalculationSettingsContext::~ScXMLCalculationSettingsContext() { } SvXMLImportContext *ScXMLCalculationSettingsContext::CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList ) { SvXMLImportContext *pContext = 0; if (nPrefix == XML_NAMESPACE_TABLE) { if (IsXMLToken(rLName, XML_NULL_DATE)) pContext = new ScXMLNullDateContext(GetScImport(), nPrefix, rLName, xAttrList, this); else if (IsXMLToken(rLName, XML_ITERATION)) pContext = new ScXMLIterationContext(GetScImport(), nPrefix, rLName, xAttrList, this); } if( !pContext ) pContext = new SvXMLImportContext( GetImport(), nPrefix, rLName ); return pContext; } void ScXMLCalculationSettingsContext::EndElement() { if (GetScImport().GetModel().is()) { uno::Reference <beans::XPropertySet> xPropertySet (GetScImport().GetModel(), uno::UNO_QUERY); if (xPropertySet.is()) { xPropertySet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNO_CALCASSHOWN)), uno::makeAny(bCalcAsShown) ); xPropertySet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNO_IGNORECASE)), uno::makeAny(bIgnoreCase) ); xPropertySet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNO_LOOKUPLABELS)), uno::makeAny(bLookUpLabels) ); xPropertySet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNO_MATCHWHOLE)), uno::makeAny(bMatchWholeCell) ); xPropertySet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNO_REGEXENABLED)), uno::makeAny(bUseRegularExpressions) ); xPropertySet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNO_ITERENABLED)), uno::makeAny(bIsIterationEnabled) ); xPropertySet->setPropertyValue( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNO_ITERCOUNT)), uno::makeAny(nIterationCount) ); xPropertySet->setPropertyValue( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNO_ITEREPSILON)), uno::makeAny(fIterationEpsilon) ); xPropertySet->setPropertyValue( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNO_NULLDATE)), uno::makeAny(aNullDate) ); if (GetScImport().GetDocument()) { GetScImport().LockSolarMutex(); ScDocOptions aDocOptions (GetScImport().GetDocument()->GetDocOptions()); aDocOptions.SetYear2000(nYear2000); GetScImport().GetDocument()->SetDocOptions(aDocOptions); GetScImport().UnlockSolarMutex(); } } } } ScXMLNullDateContext::ScXMLNullDateContext( ScXMLImport& rImport, USHORT nPrfx, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList, ScXMLCalculationSettingsContext* pCalcSet) : SvXMLImportContext( rImport, nPrfx, rLName ) { sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0; for( sal_Int16 i=0; i < nAttrCount; ++i ) { const rtl::OUString& sAttrName(xAttrList->getNameByIndex( i )); rtl::OUString aLocalName; sal_uInt16 nPrefix = GetScImport().GetNamespaceMap().GetKeyByAttrName( sAttrName, &aLocalName ); const rtl::OUString& sValue(xAttrList->getValueByIndex( i )); if (nPrefix == XML_NAMESPACE_TABLE && IsXMLToken(aLocalName, XML_DATE_VALUE)) { util::DateTime aDateTime; GetScImport().GetMM100UnitConverter().convertDateTime(aDateTime, sValue); util::Date aDate; aDate.Day = aDateTime.Day; aDate.Month = aDateTime.Month; aDate.Year = aDateTime.Year; pCalcSet->SetNullDate(aDate); } } } ScXMLNullDateContext::~ScXMLNullDateContext() { } SvXMLImportContext *ScXMLNullDateContext::CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& /* xAttrList */ ) { SvXMLImportContext *pContext = new SvXMLImportContext( GetImport(), nPrefix, rLName ); return pContext; } void ScXMLNullDateContext::EndElement() { } ScXMLIterationContext::ScXMLIterationContext( ScXMLImport& rImport, USHORT nPrfx, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList, ScXMLCalculationSettingsContext* pCalcSet) : SvXMLImportContext( rImport, nPrfx, rLName ) { sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0; for( sal_Int16 i=0; i < nAttrCount; ++i ) { const rtl::OUString& sAttrName(xAttrList->getNameByIndex( i )); rtl::OUString aLocalName; sal_uInt16 nPrefix = GetScImport().GetNamespaceMap().GetKeyByAttrName( sAttrName, &aLocalName ); const rtl::OUString& sValue(xAttrList->getValueByIndex( i )); if (nPrefix == XML_NAMESPACE_TABLE) { if (IsXMLToken(aLocalName, XML_STATUS)) { if (IsXMLToken(sValue, XML_ENABLE)) pCalcSet->SetIterationStatus(sal_True); } else if (IsXMLToken(aLocalName, XML_STEPS)) { sal_Int32 nSteps; GetScImport().GetMM100UnitConverter().convertNumber(nSteps, sValue); pCalcSet->SetIterationCount(nSteps); } else if (IsXMLToken(aLocalName, XML_MAXIMUM_DIFFERENCE)) { double fDif; GetScImport().GetMM100UnitConverter().convertDouble(fDif, sValue); pCalcSet->SetIterationEpsilon(fDif); } } } } ScXMLIterationContext::~ScXMLIterationContext() { } SvXMLImportContext *ScXMLIterationContext::CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& /* xAttrList */ ) { SvXMLImportContext *pContext = new SvXMLImportContext( GetImport(), nPrefix, rLName ); return pContext; } void ScXMLIterationContext::EndElement() { } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: ctrltool.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: obo $ $Date: 2005-04-13 10:04:30 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _CTRLTOOL_HXX #define _CTRLTOOL_HXX #ifndef INCLUDED_SVTDLLAPI_H #include "svtools/svtdllapi.h" #endif #ifndef _SAL_TYPES_H #include <sal/types.h> #endif #ifndef _LIST_HXX #include <tools/list.hxx> #endif #ifndef _METRIC_HXX #include <vcl/metric.hxx> #endif class ImplFontListNameInfo; /************************************************************************* Beschreibung ============ class FontList Diese Klasse verwaltet alle Fonts, die auf einem oder zwei Ausgabegeraeten dargestellt werden koennen. Zusaetzlich bietet die Klasse Methoden an, um aus Fett und Kursiv den StyleName zu generieren oder aus einem Stylename die fehlenden Attribute. Zusaetzlich kann diese Klasse syntetisch nachgebildete Fonts verarbeiten. Diese Klasse kann mit verschiedenen Standard-Controls und Standard-Menus zusammenarbeiten. Querverweise class FontNameBox, class FontStyleBox, class FontSizeBox, class FontNameMenu, class FontStyleMenu, class FontSizeMenu -------------------------------------------------------------------------- FontList::FontList( OutputDevice* pDevice, OutputDevice* pDevice2 = NULL, BOOL bAll = TRUE ); Konstruktor der Klasse FontList. Vom uebergebenen OutputDevice werden die entsprechenden Fonts abgefragt. Das OutputDevice muss solange existieren, wie auch die Klasse FontList existiert. Optional kann noch ein 2tes Ausgabedevice uebergeben werden, damit man zum Beispiel die Fonts von einem Drucker und dem Bildschirm zusammen in einer FontListe verwalten kann und somit auch den FontListen und FontMenus die Fonts von beiden OutputDevices zu uebergeben. Auch das pDevice2 muss solange existieren, wie die Klasse FontList existiert. Das OutputDevice, welches als erstes uebergeben wird, sollte das bevorzugte sein. Dies sollte im normalfall der Drucker sein. Denn wenn 2 verschiede Device-Schriften (eine fuer Drucker und eine fuer den Bildschirm) vorhanden sind, wird die vom uebergebenen Device "pDevice" bevorzugt. Mit dem dritten Parameter kann man angeben, ob nur skalierbare Schriften abgefragt werden sollen oder alle. Wenn TRUE uebergeben wird, werden auch Bitmap-Schriften mit abgefragt. Bei FALSE werden Vector-Schriften und scalierbare Schriften abgefragt. -------------------------------------------------------------------------- String FontList::GetStyleName( const FontInfo& rInfo ) const; Diese Methode gibt den StyleName von einer FontInfo zurueck. Falls kein StyleName gesetzt ist, wird aus den gesetzten Attributen ein entsprechender Name generiert, der dem Anwender praesentiert werden kann. -------------------------------------------------------------------------- XubString FontList::GetFontMapText( const FontInfo& rInfo ) const; Diese Methode gibt einen Matchstring zurueck, der dem Anwender anzeigen soll, welche Probleme es mit diesem Font geben kann. -------------------------------------------------------------------------- FontInfo FontList::Get( const String& rName, const String& rStyleName ) const; Diese Methode sucht aus dem uebergebenen Namen und dem uebergebenen StyleName die entsprechende FontInfo-Struktur raus. Der Stylename kann in dieser Methode auch ein syntetischer sein. In diesem Fall werden die entsprechenden Werte in der FontInfo-Struktur entsprechend gesetzt. Wenn ein StyleName uebergeben wird, kann jedoch eine FontInfo-Struktur ohne Stylename zurueckgegeben werden. Um den StyleName dem Anwender zu repraesentieren, muss GetStyleName() mit dieser FontInfo-Struktur aufgerufen werden. Querverweise FontList::GetStyleName() -------------------------------------------------------------------------- FontInfo FontList::Get( const String& rName, FontWeight eWeight, FontItalic eItalic ) const; Diese Methode sucht aus dem uebergebenen Namen und den uebergebenen Styles die entsprechende FontInfo-Struktur raus. Diese Methode kann auch eine FontInfo-Struktur ohne Stylename zurueckgegeben. Um den StyleName dem Anwender zu repraesentieren, muss GetStyleName() mit dieser FontInfo-Struktur aufgerufen werden. Querverweise FontList::GetStyleName() -------------------------------------------------------------------------- const long* FontList::GetSizeAry( const FontInfo& rInfo ) const; Diese Methode liefert zum uebergebenen Font die vorhandenen Groessen. Falls es sich dabei um einen skalierbaren Font handelt, werden Standard- Groessen zurueckgegeben. Das Array enthaelt die Hoehen des Fonts in 10tel Point. Der letzte Wert des Array ist 0. Das Array, was zurueckgegeben wird, wird von der FontList wieder zerstoert. Nach dem Aufruf der naechsten Methode von der FontList, sollte deshalb das Array nicht mehr referenziert werden. *************************************************************************/ // ------------ // - FontList - // ------------ #define FONTLIST_FONTINFO_NOTFOUND ((USHORT)0xFFFF) #define FONTLIST_FONTNAMETYPE_PRINTER ((USHORT)0x0001) #define FONTLIST_FONTNAMETYPE_SCREEN ((USHORT)0x0002) #define FONTLIST_FONTNAMETYPE_SCALABLE ((USHORT)0x0004) class SVT_DLLPUBLIC FontList : private List { private: XubString maMapBoth; XubString maMapPrinterOnly; XubString maMapScreenOnly; XubString maMapSizeNotAvailable; XubString maMapStyleNotAvailable; XubString maMapNotAvailable; XubString maLight; XubString maLightItalic; XubString maNormal; XubString maNormalItalic; XubString maBold; XubString maBoldItalic; XubString maBlack; XubString maBlackItalic; long* mpSizeAry; OutputDevice* mpDev; OutputDevice* mpDev2; #ifdef CTRLTOOL_CXX SVT_DLLPRIVATE ImplFontListNameInfo* ImplFind( const XubString& rSearchName, ULONG* pIndex ) const; SVT_DLLPRIVATE ImplFontListNameInfo* ImplFindByName( const XubString& rStr ) const; SVT_DLLPRIVATE void ImplInsertFonts( OutputDevice* pDev, BOOL bAll, BOOL bInsertData ); #endif public: FontList( OutputDevice* pDevice, OutputDevice* pDevice2 = NULL, BOOL bAll = TRUE ); ~FontList(); FontList* Clone() const; OutputDevice* GetDevice() const { return mpDev; } OutputDevice* GetDevice2() const { return mpDev2; } XubString GetFontMapText( const FontInfo& rInfo ) const; USHORT GetFontNameType( const XubString& rFontName ) const; const XubString& GetNormalStr() const { return maNormal; } const XubString& GetItalicStr() const { return maNormalItalic; } const XubString& GetBoldStr() const { return maBold; } const XubString& GetBoldItalicStr() const { return maBoldItalic; } const XubString& GetStyleName( FontWeight eWeight, FontItalic eItalic ) const; XubString GetStyleName( const FontInfo& rInfo ) const; FontInfo Get( const XubString& rName, const XubString& rStyleName ) const; FontInfo Get( const XubString& rName, FontWeight eWeight, FontItalic eItalic ) const; BOOL IsAvailable( const XubString& rName ) const; USHORT GetFontNameCount() const { return (USHORT)List::Count(); } const FontInfo& GetFontName( USHORT nFont ) const; USHORT GetFontNameType( USHORT nFont ) const; sal_Handle GetFirstFontInfo( const XubString& rName ) const; sal_Handle GetNextFontInfo( sal_Handle hFontInfo ) const; const FontInfo& GetFontInfo( sal_Handle hFontInfo ) const; const long* GetSizeAry( const FontInfo& rInfo ) const; static const long* GetStdSizeAry(); private: FontList( const FontList& ); FontList& operator =( const FontList& ); }; // ----------------- // - FontSizeNames - // ----------------- class SVT_DLLPUBLIC FontSizeNames { private: struct ImplFSNameItem* mpArray; ULONG mnElem; public: FontSizeNames( LanguageType eLanguage /* = LANGUAGE_DONTKNOW */ ); ULONG Count() const { return mnElem; } BOOL IsEmpty() const { return !mnElem; } long Name2Size( const String& ) const; String Size2Name( long ) const; String GetIndexName( ULONG nIndex ) const; long GetIndexSize( ULONG nIndex ) const; }; #endif // _CTRLTOOL_HXX <commit_msg>INTEGRATION: CWS gcc4fwdecl (1.5.58); FILE MERGED 2005/06/01 17:46:34 pmladek 1.5.58.1: #i50074# Fixed forward declarations for gcc4 in svtools<commit_after>/************************************************************************* * * $RCSfile: ctrltool.hxx,v $ * * $Revision: 1.6 $ * * last change: $Author: obo $ $Date: 2005-06-14 16:39:16 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _CTRLTOOL_HXX #define _CTRLTOOL_HXX #ifndef INCLUDED_SVTDLLAPI_H #include "svtools/svtdllapi.h" #endif #ifndef _SAL_TYPES_H #include <sal/types.h> #endif #ifndef _LIST_HXX #include <tools/list.hxx> #endif #ifndef _METRIC_HXX #include <vcl/metric.hxx> #endif class ImplFontListNameInfo; class OutputDevice; /************************************************************************* Beschreibung ============ class FontList Diese Klasse verwaltet alle Fonts, die auf einem oder zwei Ausgabegeraeten dargestellt werden koennen. Zusaetzlich bietet die Klasse Methoden an, um aus Fett und Kursiv den StyleName zu generieren oder aus einem Stylename die fehlenden Attribute. Zusaetzlich kann diese Klasse syntetisch nachgebildete Fonts verarbeiten. Diese Klasse kann mit verschiedenen Standard-Controls und Standard-Menus zusammenarbeiten. Querverweise class FontNameBox, class FontStyleBox, class FontSizeBox, class FontNameMenu, class FontStyleMenu, class FontSizeMenu -------------------------------------------------------------------------- FontList::FontList( OutputDevice* pDevice, OutputDevice* pDevice2 = NULL, BOOL bAll = TRUE ); Konstruktor der Klasse FontList. Vom uebergebenen OutputDevice werden die entsprechenden Fonts abgefragt. Das OutputDevice muss solange existieren, wie auch die Klasse FontList existiert. Optional kann noch ein 2tes Ausgabedevice uebergeben werden, damit man zum Beispiel die Fonts von einem Drucker und dem Bildschirm zusammen in einer FontListe verwalten kann und somit auch den FontListen und FontMenus die Fonts von beiden OutputDevices zu uebergeben. Auch das pDevice2 muss solange existieren, wie die Klasse FontList existiert. Das OutputDevice, welches als erstes uebergeben wird, sollte das bevorzugte sein. Dies sollte im normalfall der Drucker sein. Denn wenn 2 verschiede Device-Schriften (eine fuer Drucker und eine fuer den Bildschirm) vorhanden sind, wird die vom uebergebenen Device "pDevice" bevorzugt. Mit dem dritten Parameter kann man angeben, ob nur skalierbare Schriften abgefragt werden sollen oder alle. Wenn TRUE uebergeben wird, werden auch Bitmap-Schriften mit abgefragt. Bei FALSE werden Vector-Schriften und scalierbare Schriften abgefragt. -------------------------------------------------------------------------- String FontList::GetStyleName( const FontInfo& rInfo ) const; Diese Methode gibt den StyleName von einer FontInfo zurueck. Falls kein StyleName gesetzt ist, wird aus den gesetzten Attributen ein entsprechender Name generiert, der dem Anwender praesentiert werden kann. -------------------------------------------------------------------------- XubString FontList::GetFontMapText( const FontInfo& rInfo ) const; Diese Methode gibt einen Matchstring zurueck, der dem Anwender anzeigen soll, welche Probleme es mit diesem Font geben kann. -------------------------------------------------------------------------- FontInfo FontList::Get( const String& rName, const String& rStyleName ) const; Diese Methode sucht aus dem uebergebenen Namen und dem uebergebenen StyleName die entsprechende FontInfo-Struktur raus. Der Stylename kann in dieser Methode auch ein syntetischer sein. In diesem Fall werden die entsprechenden Werte in der FontInfo-Struktur entsprechend gesetzt. Wenn ein StyleName uebergeben wird, kann jedoch eine FontInfo-Struktur ohne Stylename zurueckgegeben werden. Um den StyleName dem Anwender zu repraesentieren, muss GetStyleName() mit dieser FontInfo-Struktur aufgerufen werden. Querverweise FontList::GetStyleName() -------------------------------------------------------------------------- FontInfo FontList::Get( const String& rName, FontWeight eWeight, FontItalic eItalic ) const; Diese Methode sucht aus dem uebergebenen Namen und den uebergebenen Styles die entsprechende FontInfo-Struktur raus. Diese Methode kann auch eine FontInfo-Struktur ohne Stylename zurueckgegeben. Um den StyleName dem Anwender zu repraesentieren, muss GetStyleName() mit dieser FontInfo-Struktur aufgerufen werden. Querverweise FontList::GetStyleName() -------------------------------------------------------------------------- const long* FontList::GetSizeAry( const FontInfo& rInfo ) const; Diese Methode liefert zum uebergebenen Font die vorhandenen Groessen. Falls es sich dabei um einen skalierbaren Font handelt, werden Standard- Groessen zurueckgegeben. Das Array enthaelt die Hoehen des Fonts in 10tel Point. Der letzte Wert des Array ist 0. Das Array, was zurueckgegeben wird, wird von der FontList wieder zerstoert. Nach dem Aufruf der naechsten Methode von der FontList, sollte deshalb das Array nicht mehr referenziert werden. *************************************************************************/ // ------------ // - FontList - // ------------ #define FONTLIST_FONTINFO_NOTFOUND ((USHORT)0xFFFF) #define FONTLIST_FONTNAMETYPE_PRINTER ((USHORT)0x0001) #define FONTLIST_FONTNAMETYPE_SCREEN ((USHORT)0x0002) #define FONTLIST_FONTNAMETYPE_SCALABLE ((USHORT)0x0004) class SVT_DLLPUBLIC FontList : private List { private: XubString maMapBoth; XubString maMapPrinterOnly; XubString maMapScreenOnly; XubString maMapSizeNotAvailable; XubString maMapStyleNotAvailable; XubString maMapNotAvailable; XubString maLight; XubString maLightItalic; XubString maNormal; XubString maNormalItalic; XubString maBold; XubString maBoldItalic; XubString maBlack; XubString maBlackItalic; long* mpSizeAry; OutputDevice* mpDev; OutputDevice* mpDev2; #ifdef CTRLTOOL_CXX SVT_DLLPRIVATE ImplFontListNameInfo* ImplFind( const XubString& rSearchName, ULONG* pIndex ) const; SVT_DLLPRIVATE ImplFontListNameInfo* ImplFindByName( const XubString& rStr ) const; SVT_DLLPRIVATE void ImplInsertFonts( OutputDevice* pDev, BOOL bAll, BOOL bInsertData ); #endif public: FontList( OutputDevice* pDevice, OutputDevice* pDevice2 = NULL, BOOL bAll = TRUE ); ~FontList(); FontList* Clone() const; OutputDevice* GetDevice() const { return mpDev; } OutputDevice* GetDevice2() const { return mpDev2; } XubString GetFontMapText( const FontInfo& rInfo ) const; USHORT GetFontNameType( const XubString& rFontName ) const; const XubString& GetNormalStr() const { return maNormal; } const XubString& GetItalicStr() const { return maNormalItalic; } const XubString& GetBoldStr() const { return maBold; } const XubString& GetBoldItalicStr() const { return maBoldItalic; } const XubString& GetStyleName( FontWeight eWeight, FontItalic eItalic ) const; XubString GetStyleName( const FontInfo& rInfo ) const; FontInfo Get( const XubString& rName, const XubString& rStyleName ) const; FontInfo Get( const XubString& rName, FontWeight eWeight, FontItalic eItalic ) const; BOOL IsAvailable( const XubString& rName ) const; USHORT GetFontNameCount() const { return (USHORT)List::Count(); } const FontInfo& GetFontName( USHORT nFont ) const; USHORT GetFontNameType( USHORT nFont ) const; sal_Handle GetFirstFontInfo( const XubString& rName ) const; sal_Handle GetNextFontInfo( sal_Handle hFontInfo ) const; const FontInfo& GetFontInfo( sal_Handle hFontInfo ) const; const long* GetSizeAry( const FontInfo& rInfo ) const; static const long* GetStdSizeAry(); private: FontList( const FontList& ); FontList& operator =( const FontList& ); }; // ----------------- // - FontSizeNames - // ----------------- class SVT_DLLPUBLIC FontSizeNames { private: struct ImplFSNameItem* mpArray; ULONG mnElem; public: FontSizeNames( LanguageType eLanguage /* = LANGUAGE_DONTKNOW */ ); ULONG Count() const { return mnElem; } BOOL IsEmpty() const { return !mnElem; } long Name2Size( const String& ) const; String Size2Name( long ) const; String GetIndexName( ULONG nIndex ) const; long GetIndexSize( ULONG nIndex ) const; }; #endif // _CTRLTOOL_HXX <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: nfsymbol.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2005-09-08 10:00:25 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef INCLUDED_SVTOOLS_NFSYMBOL_HXX #define INCLUDED_SVTOOLS_NFSYMBOL_HXX /* ATTENTION! If new types arrive that had its content previously handled as * SYMBOLTYPE_STRING, they have to be added at several places in zforscan.cxx * and/or zformat.cxx, and in xmloff/source/style/xmlnumfe.cxx. Mostly these * are places where already NF_SYMBOLTYPE_STRING together with * NF_SYMBOLTYPE_CURRENCY or NF_SYMBOLTYPE_DATESEP are used in the same case of * a switch respectively an if-condition. */ namespace svt { /// Number formatter's symbol types of a token, if not key words, which are >0 enum NfSymbolType { NF_SYMBOLTYPE_STRING = -1, // literal string in output NF_SYMBOLTYPE_DEL = -2, // special character NF_SYMBOLTYPE_BLANK = -3, // blank for '_' NF_SYMBOLTYPE_STAR = -4, // *-character NF_SYMBOLTYPE_DIGIT = -5, // digit place holder NF_SYMBOLTYPE_DECSEP = -6, // decimal separator NF_SYMBOLTYPE_THSEP = -7, // group AKA thousand separator NF_SYMBOLTYPE_EXP = -8, // exponent E NF_SYMBOLTYPE_FRAC = -9, // fraction / NF_SYMBOLTYPE_EMPTY = -10, // deleted symbols NF_SYMBOLTYPE_FRACBLANK = -11, // delimiter between integer and fraction NF_SYMBOLTYPE_COMMENT = -12, // comment is following NF_SYMBOLTYPE_CURRENCY = -13, // currency symbol NF_SYMBOLTYPE_CURRDEL = -14, // currency symbol delimiter [$] NF_SYMBOLTYPE_CURREXT = -15, // currency symbol extension -xxx NF_SYMBOLTYPE_CALENDAR = -16, // calendar ID NF_SYMBOLTYPE_CALDEL = -17, // calendar delimiter [~] NF_SYMBOLTYPE_DATESEP = -18, // date separator NF_SYMBOLTYPE_TIMESEP = -19, // time separator NF_SYMBOLTYPE_TIME100SECSEP = -20, // time 100th seconds separator NF_SYMBOLTYPE_PERCENT = -21 // percent % }; } // namespace svt #endif // INCLUDED_SVTOOLS_NFSYMBOL_HXX <commit_msg>INTEGRATION: CWS changefileheader (1.3.774); FILE MERGED 2008/03/31 13:00:54 rt 1.3.774.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: nfsymbol.hxx,v $ * $Revision: 1.4 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef INCLUDED_SVTOOLS_NFSYMBOL_HXX #define INCLUDED_SVTOOLS_NFSYMBOL_HXX /* ATTENTION! If new types arrive that had its content previously handled as * SYMBOLTYPE_STRING, they have to be added at several places in zforscan.cxx * and/or zformat.cxx, and in xmloff/source/style/xmlnumfe.cxx. Mostly these * are places where already NF_SYMBOLTYPE_STRING together with * NF_SYMBOLTYPE_CURRENCY or NF_SYMBOLTYPE_DATESEP are used in the same case of * a switch respectively an if-condition. */ namespace svt { /// Number formatter's symbol types of a token, if not key words, which are >0 enum NfSymbolType { NF_SYMBOLTYPE_STRING = -1, // literal string in output NF_SYMBOLTYPE_DEL = -2, // special character NF_SYMBOLTYPE_BLANK = -3, // blank for '_' NF_SYMBOLTYPE_STAR = -4, // *-character NF_SYMBOLTYPE_DIGIT = -5, // digit place holder NF_SYMBOLTYPE_DECSEP = -6, // decimal separator NF_SYMBOLTYPE_THSEP = -7, // group AKA thousand separator NF_SYMBOLTYPE_EXP = -8, // exponent E NF_SYMBOLTYPE_FRAC = -9, // fraction / NF_SYMBOLTYPE_EMPTY = -10, // deleted symbols NF_SYMBOLTYPE_FRACBLANK = -11, // delimiter between integer and fraction NF_SYMBOLTYPE_COMMENT = -12, // comment is following NF_SYMBOLTYPE_CURRENCY = -13, // currency symbol NF_SYMBOLTYPE_CURRDEL = -14, // currency symbol delimiter [$] NF_SYMBOLTYPE_CURREXT = -15, // currency symbol extension -xxx NF_SYMBOLTYPE_CALENDAR = -16, // calendar ID NF_SYMBOLTYPE_CALDEL = -17, // calendar delimiter [~] NF_SYMBOLTYPE_DATESEP = -18, // date separator NF_SYMBOLTYPE_TIMESEP = -19, // time separator NF_SYMBOLTYPE_TIME100SECSEP = -20, // time 100th seconds separator NF_SYMBOLTYPE_PERCENT = -21 // percent % }; } // namespace svt #endif // INCLUDED_SVTOOLS_NFSYMBOL_HXX <|endoftext|>
<commit_before>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: fmurl.hxx,v $ * $Revision: 1.5 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef _SVX_FMURL_HXX #define _SVX_FMURL_HXX #include "fmstatic.hxx" namespace svxform { DECLARE_CONSTASCII_USTRING(FMURL_FORMSLOTS_PREFIX); DECLARE_CONSTASCII_USTRING(FMURL_FORM_POSITION); DECLARE_CONSTASCII_USTRING(FMURL_FORM_RECORDCOUNT); DECLARE_CONSTASCII_USTRING(FMURL_RECORD_MOVEFIRST); DECLARE_CONSTASCII_USTRING(FMURL_RECORD_MOVEPREV); DECLARE_CONSTASCII_USTRING(FMURL_RECORD_MOVENEXT); DECLARE_CONSTASCII_USTRING(FMURL_RECORD_MOVELAST); DECLARE_CONSTASCII_USTRING(FMURL_RECORD_MOVETONEW); DECLARE_CONSTASCII_USTRING(FMURL_RECORD_UNDO); DECLARE_CONSTASCII_USTRING(FMURL_RECORD_SAVE); DECLARE_CONSTASCII_USTRING(FMURL_RECORD_DELETE); DECLARE_CONSTASCII_USTRING(FMURL_FORM_REFRESH); DECLARE_CONSTASCII_USTRING(FMURL_FORM_SORT_UP); DECLARE_CONSTASCII_USTRING(FMURL_FORM_SORT_DOWN); DECLARE_CONSTASCII_USTRING(FMURL_FORM_SORT); DECLARE_CONSTASCII_USTRING(FMURL_FORM_AUTO_FILTER); DECLARE_CONSTASCII_USTRING(FMURL_FORM_FILTER); DECLARE_CONSTASCII_USTRING(FMURL_FORM_APPLY_FILTER); DECLARE_CONSTASCII_USTRING(FMURL_FORM_REMOVE_FILTER); DECLARE_CONSTASCII_USTRING(FMURL_CONFIRM_DELETION); DECLARE_CONSTASCII_USTRING(FMURL_COMPONENT_FORMGRIDVIEW); DECLARE_CONSTASCII_USTRING(FMURL_GRIDVIEW_CLEARVIEW); DECLARE_CONSTASCII_USTRING(FMURL_GRIDVIEW_ADDCOLUMN); DECLARE_CONSTASCII_USTRING(FMURL_GRIDVIEW_ATTACHTOFORM); DECLARE_CONSTASCII_USTRING(FMARG_ATTACHTO_MASTERFORM); DECLARE_CONSTASCII_USTRING(FMARG_ADDCOL_COLUMNTYPE); DECLARE_CONSTASCII_USTRING(FMARG_ADDCOL_COLUMNPOS); } // namespace svxform #endif // _SVX_FMURL_HXX <commit_msg>INTEGRATION: CWS dba31a (1.5.100); FILE MERGED 2008/07/03 08:46:59 fs 1.5.100.1: #i66628# FMURL_FORM_REFRESH_CURRENT_CONTROL<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: fmurl.hxx,v $ * $Revision: 1.6 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef _SVX_FMURL_HXX #define _SVX_FMURL_HXX #include "fmstatic.hxx" namespace svxform { DECLARE_CONSTASCII_USTRING(FMURL_FORMSLOTS_PREFIX); DECLARE_CONSTASCII_USTRING(FMURL_FORM_POSITION); DECLARE_CONSTASCII_USTRING(FMURL_FORM_RECORDCOUNT); DECLARE_CONSTASCII_USTRING(FMURL_RECORD_MOVEFIRST); DECLARE_CONSTASCII_USTRING(FMURL_RECORD_MOVEPREV); DECLARE_CONSTASCII_USTRING(FMURL_RECORD_MOVENEXT); DECLARE_CONSTASCII_USTRING(FMURL_RECORD_MOVELAST); DECLARE_CONSTASCII_USTRING(FMURL_RECORD_MOVETONEW); DECLARE_CONSTASCII_USTRING(FMURL_RECORD_UNDO); DECLARE_CONSTASCII_USTRING(FMURL_RECORD_SAVE); DECLARE_CONSTASCII_USTRING(FMURL_RECORD_DELETE); DECLARE_CONSTASCII_USTRING(FMURL_FORM_REFRESH); DECLARE_CONSTASCII_USTRING(FMURL_FORM_REFRESH_CURRENT_CONTROL); DECLARE_CONSTASCII_USTRING(FMURL_FORM_SORT_UP); DECLARE_CONSTASCII_USTRING(FMURL_FORM_SORT_DOWN); DECLARE_CONSTASCII_USTRING(FMURL_FORM_SORT); DECLARE_CONSTASCII_USTRING(FMURL_FORM_AUTO_FILTER); DECLARE_CONSTASCII_USTRING(FMURL_FORM_FILTER); DECLARE_CONSTASCII_USTRING(FMURL_FORM_APPLY_FILTER); DECLARE_CONSTASCII_USTRING(FMURL_FORM_REMOVE_FILTER); DECLARE_CONSTASCII_USTRING(FMURL_CONFIRM_DELETION); DECLARE_CONSTASCII_USTRING(FMURL_COMPONENT_FORMGRIDVIEW); DECLARE_CONSTASCII_USTRING(FMURL_GRIDVIEW_CLEARVIEW); DECLARE_CONSTASCII_USTRING(FMURL_GRIDVIEW_ADDCOLUMN); DECLARE_CONSTASCII_USTRING(FMURL_GRIDVIEW_ATTACHTOFORM); DECLARE_CONSTASCII_USTRING(FMARG_ATTACHTO_MASTERFORM); DECLARE_CONSTASCII_USTRING(FMARG_ADDCOL_COLUMNTYPE); DECLARE_CONSTASCII_USTRING(FMARG_ADDCOL_COLUMNPOS); } // namespace svxform #endif // _SVX_FMURL_HXX <|endoftext|>
<commit_before>// RUN: %clang_hwasan -fsanitize=cfi -fno-sanitize-trap=cfi -flto -fvisibility=hidden -fuse-ld=lld %s -o %t // RUN: not %run %t 2>&1 | FileCheck %s // REQUIRES: android // Smoke test for CFI + HWASAN. struct A { virtual void f(); }; void A::f() {} int main() { // CHECK: control flow integrity check for type {{.*}} failed during cast to unrelated type A *a = reinterpret_cast<A *>(reinterpret_cast<void *>(&main)); (void)a; } <commit_msg>hwasan: Use C++ driver for cfi.cc test.<commit_after>// RUN: %clangxx_hwasan -fsanitize=cfi -fno-sanitize-trap=cfi -flto -fvisibility=hidden -fuse-ld=lld %s -o %t // RUN: not %run %t 2>&1 | FileCheck %s // REQUIRES: android // Smoke test for CFI + HWASAN. struct A { virtual void f(); }; void A::f() {} int main() { // CHECK: control flow integrity check for type {{.*}} failed during cast to unrelated type A *a = reinterpret_cast<A *>(reinterpret_cast<void *>(&main)); (void)a; } <|endoftext|>
<commit_before>#include <vector> #include <list> #include <cmath> #include <boost/geometry/index/rtree.hpp> #include <boost/mpl/range_c.hpp> #include <boost/mpl/for_each.hpp> namespace bg = boost::geometry; namespace bmpl = boost::mpl; namespace bgi = bg::index; // Create a D dimensional point from an array of coordinates template <size_t D> struct point_setter { typedef bg::model::point<double, D, bg::cs::cartesian> point_t; point_t& point; double *loc; point_setter(point_t& point, double *loc) : point(point), loc(loc) {} template< typename U > void operator()(U i) { bg::set<i>(point, loc[i]); } }; // Calculate the square of the euclidian distance between two points template <size_t D> struct d2_calc { typedef bg::model::point<double, D, bg::cs::cartesian> point_t; const point_t &p1; const point_t &p2; double &d2; d2_calc(const point_t &p1, const point_t &p2, double &d2) : p1(p1), p2(p2), d2(d2) {} template< typename U > void operator()(U i) { d2 += pow( bg::get<i>(p1) - bg::get<i>(p2), 2); } }; // Add a scaler to all the coordinates of a point template <size_t D> struct add_scalar_to_point { typedef bg::model::point<double, D, bg::cs::cartesian> point_t; point_t &p; double c; add_scalar_to_point(point_t &p, double c) : p(p), c(c) {} template< typename U > void operator()(U i) { double new_coord = bg::get<i>(p) + c; bg::set<i>(p, new_coord); } }; template <size_t D> std::list< std::list<size_t> > friends_of_friends_rtree(double *data, size_t npts, double linking_length) { typedef bg::model::point<double, D, bg::cs::cartesian> point_t; typedef std::pair<point_t, size_t> value_t; typedef bgi::rtree< value_t, bgi::rstar<16> > tree_t; typedef bmpl::range_c<size_t, 0, D> dim_range; std::vector< std::pair<point_t, size_t> > points; points.reserve(npts); for(size_t i = 0 ; i<npts ; ++i) { point_t point; bmpl::for_each< dim_range >( point_setter<D>(point, data + i*D) ); points.push_back(std::make_pair(point, i)); } tree_t tree(points.begin(), points.end()); std::list< std::list< size_t > > groups; while( !tree.empty() ) { std::list< value_t > to_add; // Grab a point from the tree. to_add.push_back( *tree.qbegin( bgi::satisfies([](value_t const &){return true;})) ); tree.remove( to_add.begin(), to_add.end() ); for( auto it = to_add.begin() ; it != to_add.end() ; ++it ) { std::list< value_t > added; // Build box to query point_t lower = it->first; bmpl::for_each< dim_range >( add_scalar_to_point<D>(lower, -linking_length) ); point_t upper = it->first; bmpl::for_each< dim_range >( add_scalar_to_point<D>(upper, +linking_length)); bg::model::box< point_t > box( lower, upper ); auto within_ball = [&it, linking_length](value_t const &v) { double d2 = 0.; bmpl::for_each< dim_range >( d2_calc<D>(it->first, v.first, d2) ); return sqrt(d2) < linking_length; }; // Find all points within a linking length of the current point. tree.query( bgi::within(box) && bgi::satisfies(within_ball), std::back_inserter(added) ); // Remove any points we find from the tree as they have been assigned. tree.remove( added.begin(), added.end() ); // Add the found points to the list so we can find their "friends" as well to_add.splice(to_add.end(), added); } std::list< size_t > group; for( auto p : to_add ) { group.push_back(p.second); } groups.push_back(group); } return groups; } inline double dist(double *p1, double *p2, size_t ndim) { double d2 = 0.; for(size_t i = 0 ; i < ndim ; ++i) { d2 += pow(p1[i] - p2[i], 2); } return sqrt(d2); } // A brute force friends of friends finder without the Rtree accelerator. std::list< std::list<size_t> > friends_of_friends_brute(double *data, size_t npts, size_t ndim, double linking_length) { std::cerr << "Using non tree accelerated version" << std::endl; typedef std::pair<size_t, double*> Point; //Create list of unused points with indices std::list<Point> unused; std::list< std::list< size_t > > groups; for(size_t i=0 ; i<npts ; ++i) { unused.push_back(std::make_pair(i, data + i*ndim)); } //If there are unused points try to create a new group while( unused.size() > 0 ) { std::list<Point> toadd; toadd.push_back(unused.front()); unused.pop_front(); //Look through all points found in the group and attempt to for(auto toadd_it = toadd.begin() ; toadd_it != toadd.end() ; ++toadd_it) { auto unused_it = unused.begin(); while(unused_it != unused.end()) { if(dist(unused_it->second, toadd_it->second, ndim) < linking_length) { toadd.push_back(*unused_it); unused.erase(unused_it++); } else { ++unused_it; } } } std::list<size_t> group; for(const auto& p : toadd) { group.push_back(p.first); } groups.push_back(group); } return groups; } std::list< std::list<size_t> > friends_of_friends(double *data, size_t npts, size_t ndim, double linking_length) { switch(ndim) { case 1: return friends_of_friends_rtree<1>(data, npts, linking_length); break; case 2: return friends_of_friends_rtree<2>(data, npts, linking_length); break; case 3: return friends_of_friends_rtree<3>(data, npts, linking_length); break; case 4: return friends_of_friends_rtree<4>(data, npts, linking_length); break; default: return friends_of_friends_brute(data, npts, ndim, linking_length); break; } } <commit_msg>Add missing import to fix build with boost 1.6<commit_after>#include <iostream> #include <vector> #include <list> #include <cmath> #include <boost/geometry/index/rtree.hpp> #include <boost/mpl/range_c.hpp> #include <boost/mpl/for_each.hpp> namespace bg = boost::geometry; namespace bmpl = boost::mpl; namespace bgi = bg::index; // Create a D dimensional point from an array of coordinates template <size_t D> struct point_setter { typedef bg::model::point<double, D, bg::cs::cartesian> point_t; point_t& point; double *loc; point_setter(point_t& point, double *loc) : point(point), loc(loc) {} template< typename U > void operator()(U i) { bg::set<i>(point, loc[i]); } }; // Calculate the square of the euclidian distance between two points template <size_t D> struct d2_calc { typedef bg::model::point<double, D, bg::cs::cartesian> point_t; const point_t &p1; const point_t &p2; double &d2; d2_calc(const point_t &p1, const point_t &p2, double &d2) : p1(p1), p2(p2), d2(d2) {} template< typename U > void operator()(U i) { d2 += pow( bg::get<i>(p1) - bg::get<i>(p2), 2); } }; // Add a scaler to all the coordinates of a point template <size_t D> struct add_scalar_to_point { typedef bg::model::point<double, D, bg::cs::cartesian> point_t; point_t &p; double c; add_scalar_to_point(point_t &p, double c) : p(p), c(c) {} template< typename U > void operator()(U i) { double new_coord = bg::get<i>(p) + c; bg::set<i>(p, new_coord); } }; template <size_t D> std::list< std::list<size_t> > friends_of_friends_rtree(double *data, size_t npts, double linking_length) { typedef bg::model::point<double, D, bg::cs::cartesian> point_t; typedef std::pair<point_t, size_t> value_t; typedef bgi::rtree< value_t, bgi::rstar<16> > tree_t; typedef bmpl::range_c<size_t, 0, D> dim_range; std::vector< std::pair<point_t, size_t> > points; points.reserve(npts); for(size_t i = 0 ; i<npts ; ++i) { point_t point; bmpl::for_each< dim_range >( point_setter<D>(point, data + i*D) ); points.push_back(std::make_pair(point, i)); } tree_t tree(points.begin(), points.end()); std::list< std::list< size_t > > groups; while( !tree.empty() ) { std::list< value_t > to_add; // Grab a point from the tree. to_add.push_back( *tree.qbegin( bgi::satisfies([](value_t const &){return true;})) ); tree.remove( to_add.begin(), to_add.end() ); for( auto it = to_add.begin() ; it != to_add.end() ; ++it ) { std::list< value_t > added; // Build box to query point_t lower = it->first; bmpl::for_each< dim_range >( add_scalar_to_point<D>(lower, -linking_length) ); point_t upper = it->first; bmpl::for_each< dim_range >( add_scalar_to_point<D>(upper, +linking_length)); bg::model::box< point_t > box( lower, upper ); auto within_ball = [&it, linking_length](value_t const &v) { double d2 = 0.; bmpl::for_each< dim_range >( d2_calc<D>(it->first, v.first, d2) ); return sqrt(d2) < linking_length; }; // Find all points within a linking length of the current point. tree.query( bgi::within(box) && bgi::satisfies(within_ball), std::back_inserter(added) ); // Remove any points we find from the tree as they have been assigned. tree.remove( added.begin(), added.end() ); // Add the found points to the list so we can find their "friends" as well to_add.splice(to_add.end(), added); } std::list< size_t > group; for( auto p : to_add ) { group.push_back(p.second); } groups.push_back(group); } return groups; } inline double dist(double *p1, double *p2, size_t ndim) { double d2 = 0.; for(size_t i = 0 ; i < ndim ; ++i) { d2 += pow(p1[i] - p2[i], 2); } return sqrt(d2); } // A brute force friends of friends finder without the Rtree accelerator. std::list< std::list<size_t> > friends_of_friends_brute(double *data, size_t npts, size_t ndim, double linking_length) { std::cerr << "Using non tree accelerated version" << std::endl; typedef std::pair<size_t, double*> Point; //Create list of unused points with indices std::list<Point> unused; std::list< std::list< size_t > > groups; for(size_t i=0 ; i<npts ; ++i) { unused.push_back(std::make_pair(i, data + i*ndim)); } //If there are unused points try to create a new group while( unused.size() > 0 ) { std::list<Point> toadd; toadd.push_back(unused.front()); unused.pop_front(); //Look through all points found in the group and attempt to for(auto toadd_it = toadd.begin() ; toadd_it != toadd.end() ; ++toadd_it) { auto unused_it = unused.begin(); while(unused_it != unused.end()) { if(dist(unused_it->second, toadd_it->second, ndim) < linking_length) { toadd.push_back(*unused_it); unused.erase(unused_it++); } else { ++unused_it; } } } std::list<size_t> group; for(const auto& p : toadd) { group.push_back(p.first); } groups.push_back(group); } return groups; } std::list< std::list<size_t> > friends_of_friends(double *data, size_t npts, size_t ndim, double linking_length) { switch(ndim) { case 1: return friends_of_friends_rtree<1>(data, npts, linking_length); break; case 2: return friends_of_friends_rtree<2>(data, npts, linking_length); break; case 3: return friends_of_friends_rtree<3>(data, npts, linking_length); break; case 4: return friends_of_friends_rtree<4>(data, npts, linking_length); break; default: return friends_of_friends_brute(data, npts, ndim, linking_length); break; } } <|endoftext|>
<commit_before>/* This file is part of solidity. solidity 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. solidity 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 solidity. If not, see <http://www.gnu.org/licenses/>. */ /** * @author Christian <[email protected]> * @date 2015 * Tests for high level features like import. */ #include <string> #include <boost/test/unit_test.hpp> #include <libsolidity/interface/Exceptions.h> #include <libsolidity/interface/CompilerStack.h> using namespace std; namespace dev { namespace solidity { namespace test { BOOST_AUTO_TEST_SUITE(SolidityImports) BOOST_AUTO_TEST_CASE(smoke_test) { CompilerStack c; c.addSource("a", "contract C {} pragma solidity >=0.0;"); BOOST_CHECK(c.compile()); } BOOST_AUTO_TEST_CASE(regular_import) { CompilerStack c; c.addSource("a", "contract C {} pragma solidity >=0.0;"); c.addSource("b", "import \"a\"; contract D is C {} pragma solidity >=0.0;"); BOOST_CHECK(c.compile()); } BOOST_AUTO_TEST_CASE(import_does_not_clutter_importee) { CompilerStack c; c.addSource("a", "contract C { D d; } pragma solidity >=0.0;"); c.addSource("b", "import \"a\"; contract D is C {} pragma solidity >=0.0;"); BOOST_CHECK(!c.compile()); } BOOST_AUTO_TEST_CASE(import_is_transitive) { CompilerStack c; c.addSource("a", "contract C { } pragma solidity >=0.0;"); c.addSource("b", "import \"a\"; pragma solidity >=0.0;"); c.addSource("c", "import \"b\"; contract D is C {} pragma solidity >=0.0;"); BOOST_CHECK(c.compile()); } BOOST_AUTO_TEST_CASE(circular_import) { CompilerStack c; c.addSource("a", "import \"b\"; contract C { D d; } pragma solidity >=0.0;"); c.addSource("b", "import \"a\"; contract D { C c; } pragma solidity >=0.0;"); BOOST_CHECK(c.compile()); } BOOST_AUTO_TEST_CASE(relative_import) { CompilerStack c; c.addSource("a", "import \"./dir/b\"; contract A is B {} pragma solidity >=0.0;"); c.addSource("dir/b", "contract B {} pragma solidity >=0.0;"); c.addSource("dir/c", "import \"../a\"; contract C is A {} pragma solidity >=0.0;"); BOOST_CHECK(c.compile()); } BOOST_AUTO_TEST_CASE(relative_import_multiplex) { CompilerStack c; c.addSource("a", "contract A {} pragma solidity >=0.0;"); c.addSource("dir/a/b/c", "import \"../../.././a\"; contract B is A {} pragma solidity >=0.0;"); BOOST_CHECK(c.compile()); } BOOST_AUTO_TEST_CASE(simple_alias) { CompilerStack c; c.addSource("a", "contract A {} pragma solidity >=0.0;"); c.addSource("dir/a/b/c", "import \"../../.././a\" as x; contract B is x.A { function() { x.A r = x.A(20); } } pragma solidity >=0.0;"); BOOST_CHECK(c.compile()); } BOOST_AUTO_TEST_CASE(library_name_clash) { CompilerStack c; c.addSource("a", "library A {} pragma solidity >=0.0;"); c.addSource("b", "library A {} pragma solidity >=0.0;"); BOOST_CHECK(!c.compile()); } BOOST_AUTO_TEST_CASE(library_name_clash_with_contract) { CompilerStack c; c.addSource("a", "contract A {} pragma solidity >=0.0;"); c.addSource("b", "library A {} pragma solidity >=0.0;"); BOOST_CHECK(c.compile()); } BOOST_AUTO_TEST_CASE(complex_import) { CompilerStack c; c.addSource("a", "contract A {} contract B {} contract C { struct S { uint a; } } pragma solidity >=0.0;"); c.addSource("b", "import \"a\" as x; import {B as b, C as c, C} from \"a\"; " "contract D is b { function f(c.S var1, x.C.S var2, C.S var3) internal {} } pragma solidity >=0.0;"); BOOST_CHECK(c.compile()); } BOOST_AUTO_TEST_CASE(name_clash_in_import) { CompilerStack c; c.addSource("a", "contract A {} pragma solidity >=0.0;"); c.addSource("b", "import \"a\"; contract A {} pragma solidity >=0.0;"); BOOST_CHECK(!c.compile()); c.addSource("b", "import \"a\" as A; contract A {} pragma solidity >=0.0;"); BOOST_CHECK(!c.compile()); c.addSource("b", "import {A as b} from \"a\"; contract b {} pragma solidity >=0.0;"); BOOST_CHECK(!c.compile()); c.addSource("b", "import {A} from \"a\"; contract A {} pragma solidity >=0.0;"); BOOST_CHECK(!c.compile()); c.addSource("b", "import {A} from \"a\"; contract B {} pragma solidity >=0.0;"); BOOST_CHECK(c.compile()); } BOOST_AUTO_TEST_CASE(remappings) { CompilerStack c; c.setRemappings(vector<string>{"s=s_1.4.6", "t=Tee"}); c.addSource("a", "import \"s/s.sol\"; contract A is S {} pragma solidity >=0.0;"); c.addSource("b", "import \"t/tee.sol\"; contract A is Tee {} pragma solidity >=0.0;"); c.addSource("s_1.4.6/s.sol", "contract S {} pragma solidity >=0.0;"); c.addSource("Tee/tee.sol", "contract Tee {} pragma solidity >=0.0;"); BOOST_CHECK(c.compile()); } BOOST_AUTO_TEST_CASE(context_dependent_remappings) { CompilerStack c; c.setRemappings(vector<string>{"a:s=s_1.4.6", "b:s=s_1.4.7"}); c.addSource("a/a.sol", "import \"s/s.sol\"; contract A is SSix {} pragma solidity >=0.0;"); c.addSource("b/b.sol", "import \"s/s.sol\"; contract B is SSeven {} pragma solidity >=0.0;"); c.addSource("s_1.4.6/s.sol", "contract SSix {} pragma solidity >=0.0;"); c.addSource("s_1.4.7/s.sol", "contract SSeven {} pragma solidity >=0.0;"); BOOST_CHECK(c.compile()); } BOOST_AUTO_TEST_CASE(filename_with_period) { CompilerStack c; c.addSource("a/a.sol", "import \".b.sol\"; contract A is B {} pragma solidity >=0.0;"); c.addSource("a/.b.sol", "contract B {} pragma solidity >=0.0;"); BOOST_CHECK(!c.compile()); } BOOST_AUTO_TEST_CASE(context_dependent_remappings_ensure_default_and_module_preserved) { CompilerStack c; c.setRemappings(vector<string>{"foo=vendor/foo_2.0.0", "vendor/bar:foo=vendor/foo_1.0.0", "bar=vendor/bar"}); c.addSource("main.sol", "import \"foo/foo.sol\"; import {Bar} from \"bar/bar.sol\"; contract Main is Foo2, Bar {} pragma solidity >=0.0;"); c.addSource("vendor/bar/bar.sol", "import \"foo/foo.sol\"; contract Bar {Foo1 foo;} pragma solidity >=0.0;"); c.addSource("vendor/foo_1.0.0/foo.sol", "contract Foo1 {} pragma solidity >=0.0;"); c.addSource("vendor/foo_2.0.0/foo.sol", "contract Foo2 {} pragma solidity >=0.0;"); BOOST_CHECK(c.compile()); } BOOST_AUTO_TEST_CASE(context_dependent_remappings_order_independent) { CompilerStack c; c.setRemappings(vector<string>{"a:x/y/z=d", "a/b:x=e"}); c.addSource("a/main.sol", "import \"x/y/z/z.sol\"; contract Main is D {} pragma solidity >=0.0;"); c.addSource("a/b/main.sol", "import \"x/y/z/z.sol\"; contract Main is E {} pragma solidity >=0.0;"); c.addSource("d/z.sol", "contract D {} pragma solidity >=0.0;"); c.addSource("e/y/z/z.sol", "contract E {} pragma solidity >=0.0;"); BOOST_CHECK(c.compile()); CompilerStack d; d.setRemappings(vector<string>{"a/b:x=e", "a:x/y/z=d"}); d.addSource("a/main.sol", "import \"x/y/z/z.sol\"; contract Main is D {} pragma solidity >=0.0;"); d.addSource("a/b/main.sol", "import \"x/y/z/z.sol\"; contract Main is E {} pragma solidity >=0.0;"); d.addSource("d/z.sol", "contract D {} pragma solidity >=0.0;"); d.addSource("e/y/z/z.sol", "contract E {} pragma solidity >=0.0;"); BOOST_CHECK(d.compile()); } BOOST_AUTO_TEST_SUITE_END() } } } // end namespaces <commit_msg>Modify library collision test<commit_after>/* This file is part of solidity. solidity 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. solidity 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 solidity. If not, see <http://www.gnu.org/licenses/>. */ /** * @author Christian <[email protected]> * @date 2015 * Tests for high level features like import. */ #include <string> #include <boost/test/unit_test.hpp> #include <libsolidity/interface/Exceptions.h> #include <libsolidity/interface/CompilerStack.h> using namespace std; namespace dev { namespace solidity { namespace test { BOOST_AUTO_TEST_SUITE(SolidityImports) BOOST_AUTO_TEST_CASE(smoke_test) { CompilerStack c; c.addSource("a", "contract C {} pragma solidity >=0.0;"); BOOST_CHECK(c.compile()); } BOOST_AUTO_TEST_CASE(regular_import) { CompilerStack c; c.addSource("a", "contract C {} pragma solidity >=0.0;"); c.addSource("b", "import \"a\"; contract D is C {} pragma solidity >=0.0;"); BOOST_CHECK(c.compile()); } BOOST_AUTO_TEST_CASE(import_does_not_clutter_importee) { CompilerStack c; c.addSource("a", "contract C { D d; } pragma solidity >=0.0;"); c.addSource("b", "import \"a\"; contract D is C {} pragma solidity >=0.0;"); BOOST_CHECK(!c.compile()); } BOOST_AUTO_TEST_CASE(import_is_transitive) { CompilerStack c; c.addSource("a", "contract C { } pragma solidity >=0.0;"); c.addSource("b", "import \"a\"; pragma solidity >=0.0;"); c.addSource("c", "import \"b\"; contract D is C {} pragma solidity >=0.0;"); BOOST_CHECK(c.compile()); } BOOST_AUTO_TEST_CASE(circular_import) { CompilerStack c; c.addSource("a", "import \"b\"; contract C { D d; } pragma solidity >=0.0;"); c.addSource("b", "import \"a\"; contract D { C c; } pragma solidity >=0.0;"); BOOST_CHECK(c.compile()); } BOOST_AUTO_TEST_CASE(relative_import) { CompilerStack c; c.addSource("a", "import \"./dir/b\"; contract A is B {} pragma solidity >=0.0;"); c.addSource("dir/b", "contract B {} pragma solidity >=0.0;"); c.addSource("dir/c", "import \"../a\"; contract C is A {} pragma solidity >=0.0;"); BOOST_CHECK(c.compile()); } BOOST_AUTO_TEST_CASE(relative_import_multiplex) { CompilerStack c; c.addSource("a", "contract A {} pragma solidity >=0.0;"); c.addSource("dir/a/b/c", "import \"../../.././a\"; contract B is A {} pragma solidity >=0.0;"); BOOST_CHECK(c.compile()); } BOOST_AUTO_TEST_CASE(simple_alias) { CompilerStack c; c.addSource("a", "contract A {} pragma solidity >=0.0;"); c.addSource("dir/a/b/c", "import \"../../.././a\" as x; contract B is x.A { function() { x.A r = x.A(20); } } pragma solidity >=0.0;"); BOOST_CHECK(c.compile()); } BOOST_AUTO_TEST_CASE(library_name_clash) { CompilerStack c; c.addSource("a", "library A {} pragma solidity >=0.0;"); c.addSource("b", "library A {} pragma solidity >=0.0;"); c.addSource("c", "import {A} from \"./a\"; import {A} from \"./b\";"); BOOST_CHECK(!c.compile()); } BOOST_AUTO_TEST_CASE(library_name_clash_with_contract) { CompilerStack c; c.addSource("a", "contract A {} pragma solidity >=0.0;"); c.addSource("b", "library A {} pragma solidity >=0.0;"); BOOST_CHECK(c.compile()); } BOOST_AUTO_TEST_CASE(complex_import) { CompilerStack c; c.addSource("a", "contract A {} contract B {} contract C { struct S { uint a; } } pragma solidity >=0.0;"); c.addSource("b", "import \"a\" as x; import {B as b, C as c, C} from \"a\"; " "contract D is b { function f(c.S var1, x.C.S var2, C.S var3) internal {} } pragma solidity >=0.0;"); BOOST_CHECK(c.compile()); } BOOST_AUTO_TEST_CASE(name_clash_in_import) { CompilerStack c; c.addSource("a", "contract A {} pragma solidity >=0.0;"); c.addSource("b", "import \"a\"; contract A {} pragma solidity >=0.0;"); BOOST_CHECK(!c.compile()); c.addSource("b", "import \"a\" as A; contract A {} pragma solidity >=0.0;"); BOOST_CHECK(!c.compile()); c.addSource("b", "import {A as b} from \"a\"; contract b {} pragma solidity >=0.0;"); BOOST_CHECK(!c.compile()); c.addSource("b", "import {A} from \"a\"; contract A {} pragma solidity >=0.0;"); BOOST_CHECK(!c.compile()); c.addSource("b", "import {A} from \"a\"; contract B {} pragma solidity >=0.0;"); BOOST_CHECK(c.compile()); } BOOST_AUTO_TEST_CASE(remappings) { CompilerStack c; c.setRemappings(vector<string>{"s=s_1.4.6", "t=Tee"}); c.addSource("a", "import \"s/s.sol\"; contract A is S {} pragma solidity >=0.0;"); c.addSource("b", "import \"t/tee.sol\"; contract A is Tee {} pragma solidity >=0.0;"); c.addSource("s_1.4.6/s.sol", "contract S {} pragma solidity >=0.0;"); c.addSource("Tee/tee.sol", "contract Tee {} pragma solidity >=0.0;"); BOOST_CHECK(c.compile()); } BOOST_AUTO_TEST_CASE(context_dependent_remappings) { CompilerStack c; c.setRemappings(vector<string>{"a:s=s_1.4.6", "b:s=s_1.4.7"}); c.addSource("a/a.sol", "import \"s/s.sol\"; contract A is SSix {} pragma solidity >=0.0;"); c.addSource("b/b.sol", "import \"s/s.sol\"; contract B is SSeven {} pragma solidity >=0.0;"); c.addSource("s_1.4.6/s.sol", "contract SSix {} pragma solidity >=0.0;"); c.addSource("s_1.4.7/s.sol", "contract SSeven {} pragma solidity >=0.0;"); BOOST_CHECK(c.compile()); } BOOST_AUTO_TEST_CASE(filename_with_period) { CompilerStack c; c.addSource("a/a.sol", "import \".b.sol\"; contract A is B {} pragma solidity >=0.0;"); c.addSource("a/.b.sol", "contract B {} pragma solidity >=0.0;"); BOOST_CHECK(!c.compile()); } BOOST_AUTO_TEST_CASE(context_dependent_remappings_ensure_default_and_module_preserved) { CompilerStack c; c.setRemappings(vector<string>{"foo=vendor/foo_2.0.0", "vendor/bar:foo=vendor/foo_1.0.0", "bar=vendor/bar"}); c.addSource("main.sol", "import \"foo/foo.sol\"; import {Bar} from \"bar/bar.sol\"; contract Main is Foo2, Bar {} pragma solidity >=0.0;"); c.addSource("vendor/bar/bar.sol", "import \"foo/foo.sol\"; contract Bar {Foo1 foo;} pragma solidity >=0.0;"); c.addSource("vendor/foo_1.0.0/foo.sol", "contract Foo1 {} pragma solidity >=0.0;"); c.addSource("vendor/foo_2.0.0/foo.sol", "contract Foo2 {} pragma solidity >=0.0;"); BOOST_CHECK(c.compile()); } BOOST_AUTO_TEST_CASE(context_dependent_remappings_order_independent) { CompilerStack c; c.setRemappings(vector<string>{"a:x/y/z=d", "a/b:x=e"}); c.addSource("a/main.sol", "import \"x/y/z/z.sol\"; contract Main is D {} pragma solidity >=0.0;"); c.addSource("a/b/main.sol", "import \"x/y/z/z.sol\"; contract Main is E {} pragma solidity >=0.0;"); c.addSource("d/z.sol", "contract D {} pragma solidity >=0.0;"); c.addSource("e/y/z/z.sol", "contract E {} pragma solidity >=0.0;"); BOOST_CHECK(c.compile()); CompilerStack d; d.setRemappings(vector<string>{"a/b:x=e", "a:x/y/z=d"}); d.addSource("a/main.sol", "import \"x/y/z/z.sol\"; contract Main is D {} pragma solidity >=0.0;"); d.addSource("a/b/main.sol", "import \"x/y/z/z.sol\"; contract Main is E {} pragma solidity >=0.0;"); d.addSource("d/z.sol", "contract D {} pragma solidity >=0.0;"); d.addSource("e/y/z/z.sol", "contract E {} pragma solidity >=0.0;"); BOOST_CHECK(d.compile()); } BOOST_AUTO_TEST_SUITE_END() } } } // end namespaces <|endoftext|>