text
stringlengths
54
60.6k
<commit_before>/* * * Copyright 2016, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google 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 <grpc++/ext/health_check_service_server_builder_option.h> namespace grpc { HealthCheckServiceServerBuilderOption::HealthCheckServiceServerBuilderOption( std::unique_ptr<HealthCheckServiceInterface> hc) : hc_(std::move(hc)) {} HealthCheckServiceServerBuilderOption::UpdateArguments( ChannelArguments* args) override { args->SetPointer(DefaultHealthCheckServiceInterfaceArg(), hc_.release()); } void HealthCheckServiceServerBuilderOption::UpdatePlugins( std::vector<std::unique_ptr<ServerBuilderPlugin>>* plugins) override {} } // namespace grpc <commit_msg>remove file<commit_after><|endoftext|>
<commit_before>/* * A c++ version of (significant pieces of) the QPController.m mimoOutput method. * * Todo: * switch to spatial accelerations in motion constraints * use fixed-size matrices (or at least pre-allocated) * for instance: #define nq * set MaxRowsAtCompileTime (http://eigen.tuxfamily.org/dox/TutorialMatrixClass.html) * some matrices might be better off using RowMajor */ #include "QPCommon.h" #include <limits> #include <cmath> using namespace std; void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { if (nrhs<1) mexErrMsgTxt("usage: alpha=QPControllermex(ptr,t,x,qp_input,contact_sensor,use_fastqp)"); if (nlhs<1) mexErrMsgTxt("take at least one output... please."); double* pr; // first get the ptr back from matlab NewQPControllerData *pdata = (NewQPControllerData*) getDrakeMexPointer(prhs[0]); // now retrieve the runtime params from their matlab object int narg=1; // t double t = mxGetScalar(prhs[narg++]); // x int nq = pdata->r->num_positions; int nv = pdata->r->num_velocities; if (mxGetNumberOfElements(prhs[narg]) != (nq + nv)) mexErrMsgTxt("size of x should be nq + nv\n"); double *q_ptr = mxGetPrSafe(prhs[narg]); double *qd_ptr = &q_ptr[nq]; Map<VectorXd> q(q_ptr, nq); Map<VectorXd> qd(qd_ptr, nq); narg++; // qp_input shared_ptr<drake::lcmt_qp_controller_input> qp_input(new drake::lcmt_qp_controller_input()); qp_input->decode(mxGetData(prhs[narg]), 0, mxGetNumberOfElements(prhs[narg])); narg++; // contact_sensor const mxArray *pobj = prhs[narg]; Map<VectorXd> contact_force_detected(mxGetPrSafe(pobj), mxGetNumberOfElements(pobj), 1); Matrix<bool, Dynamic, 1> b_contact_force = Matrix<bool, Dynamic, 1>::Zero(contact_force_detected.size()); for (int i=0; i < b_contact_force.size(); i++) { b_contact_force(i) = (contact_force_detected(i) != 0); } narg++; QPControllerOutput qp_output; shared_ptr<QPControllerDebugData> debug; DrakeRobotState robot_state; robot_state.t = t; robot_state.q = q; robot_state.qd = qd; if (nlhs>3) { debug.reset(new QPControllerDebugData()); } int info = setupAndSolveQP(pdata, qp_input, robot_state, b_contact_force, &qp_output, debug); // return to matlab narg = 0; if (nlhs>narg) { plhs[narg] = eigenToMatlab(qp_output.u); } narg++; if (nlhs>narg) { plhs[narg] = eigenToMatlab(qp_output.qdd); } narg++; if (nlhs>narg) { plhs[narg] = eigenToMatlab(qp_output.qd_ref); } narg++; if (nlhs>narg) { plhs[narg] = mxCreateNumericMatrix(1,1,mxINT32_CLASS,mxREAL); memcpy(mxGetData(plhs[narg]),&(info),sizeof(int)); } narg++; if (nlhs>narg) { plhs[narg] = mxCreateDoubleMatrix(1,debug->active_supports.size(),mxREAL); pr = mxGetPrSafe(plhs[narg]); int i=0; for (vector<SupportStateElement,Eigen::aligned_allocator<SupportStateElement>>::iterator iter = debug->active_supports.begin(); iter!=debug->active_supports.end(); iter++) { pr[i++] = (double) (iter->body_idx + 1); } } narg++; if (nlhs>narg) { plhs[narg] = eigenToMatlab(debug->alpha); } narg++; if (nlhs>narg) { plhs[narg] = eigenToMatlab(pdata->Hqp); } narg++; if (nlhs>narg) { plhs[narg] = eigenToMatlab(debug->f); } narg++; if (nlhs>narg) { plhs[narg] = eigenToMatlab(debug->Aeq); } narg++; if (nlhs>narg) { plhs[narg] = eigenToMatlab(debug->beq); } narg++; if (nlhs>narg) { plhs[narg] = eigenToMatlab(debug->Ain_lb_ub); } narg++; if (nlhs>narg) { plhs[narg] = eigenToMatlab(debug->bin_lb_ub); } narg++; if (nlhs>narg) { plhs[narg] = eigenToMatlab(debug->Qnfdiag); } narg++; if (nlhs>narg) { plhs[narg] = eigenToMatlab(debug->Qneps); } narg++; if (nlhs>narg) { double Vdot; if (debug->nc>0) // note: Sdot is 0 for ZMP/double integrator dynamics, so we omit that term here Vdot = ((2*debug->x_bar.transpose()*debug->S + debug->s1.transpose())*(debug->A_ls*debug->x_bar + debug->B_ls*(debug->Jcomdotv + debug->Jcom*qp_output.qdd)) + debug->s1dot.transpose()*debug->x_bar)(0) + debug->s2dot; else Vdot = 0; plhs[narg] = mxCreateDoubleScalar(Vdot); } narg++; if (nlhs>narg) { RigidBodyManipulator* r = pdata->r; VectorXd individual_cops = individualSupportCOPs(r, debug->active_supports, debug->normals, debug->B, debug->beta); plhs[narg] = eigenToMatlab(individual_cops); } narg++; } <commit_msg>Type check in instantaneousQPControllermex.<commit_after>/* * A c++ version of (significant pieces of) the QPController.m mimoOutput method. * * Todo: * switch to spatial accelerations in motion constraints * use fixed-size matrices (or at least pre-allocated) * for instance: #define nq * set MaxRowsAtCompileTime (http://eigen.tuxfamily.org/dox/TutorialMatrixClass.html) * some matrices might be better off using RowMajor */ #include "QPCommon.h" #include <limits> #include <cmath> using namespace std; void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { if (nrhs<1) mexErrMsgTxt("usage: alpha=QPControllermex(ptr,t,x,qp_input,contact_sensor,use_fastqp)"); if (nlhs<1) mexErrMsgTxt("take at least one output... please."); double* pr; // first get the ptr back from matlab NewQPControllerData *pdata = (NewQPControllerData*) getDrakeMexPointer(prhs[0]); // now retrieve the runtime params from their matlab object int narg=1; // t double t = mxGetScalar(prhs[narg++]); // x int nq = pdata->r->num_positions; int nv = pdata->r->num_velocities; if (mxGetNumberOfElements(prhs[narg]) != (nq + nv)) mexErrMsgTxt("size of x should be nq + nv\n"); double *q_ptr = mxGetPrSafe(prhs[narg]); double *qd_ptr = &q_ptr[nq]; Map<VectorXd> q(q_ptr, nq); Map<VectorXd> qd(qd_ptr, nq); narg++; // qp_input shared_ptr<drake::lcmt_qp_controller_input> qp_input(new drake::lcmt_qp_controller_input()); const mxArray* lcm_message_mex = prhs[narg]; if (!mxIsInt8(lcm_message_mex)) mexErrMsgTxt("Expected an int8 array as the qp_input argument"); qp_input->decode(mxGetData(lcm_message_mex), 0, mxGetNumberOfElements(prhs[narg])); narg++; // contact_sensor const mxArray *pobj = prhs[narg]; Map<VectorXd> contact_force_detected(mxGetPrSafe(pobj), mxGetNumberOfElements(pobj), 1); Matrix<bool, Dynamic, 1> b_contact_force = Matrix<bool, Dynamic, 1>::Zero(contact_force_detected.size()); for (int i=0; i < b_contact_force.size(); i++) { b_contact_force(i) = (contact_force_detected(i) != 0); } narg++; QPControllerOutput qp_output; shared_ptr<QPControllerDebugData> debug; DrakeRobotState robot_state; robot_state.t = t; robot_state.q = q; robot_state.qd = qd; if (nlhs>3) { debug.reset(new QPControllerDebugData()); } int info = setupAndSolveQP(pdata, qp_input, robot_state, b_contact_force, &qp_output, debug); // return to matlab narg = 0; if (nlhs>narg) { plhs[narg] = eigenToMatlab(qp_output.u); } narg++; if (nlhs>narg) { plhs[narg] = eigenToMatlab(qp_output.qdd); } narg++; if (nlhs>narg) { plhs[narg] = eigenToMatlab(qp_output.qd_ref); } narg++; if (nlhs>narg) { plhs[narg] = mxCreateNumericMatrix(1,1,mxINT32_CLASS,mxREAL); memcpy(mxGetData(plhs[narg]),&(info),sizeof(int)); } narg++; if (nlhs>narg) { plhs[narg] = mxCreateDoubleMatrix(1,debug->active_supports.size(),mxREAL); pr = mxGetPrSafe(plhs[narg]); int i=0; for (vector<SupportStateElement,Eigen::aligned_allocator<SupportStateElement>>::iterator iter = debug->active_supports.begin(); iter!=debug->active_supports.end(); iter++) { pr[i++] = (double) (iter->body_idx + 1); } } narg++; if (nlhs>narg) { plhs[narg] = eigenToMatlab(debug->alpha); } narg++; if (nlhs>narg) { plhs[narg] = eigenToMatlab(pdata->Hqp); } narg++; if (nlhs>narg) { plhs[narg] = eigenToMatlab(debug->f); } narg++; if (nlhs>narg) { plhs[narg] = eigenToMatlab(debug->Aeq); } narg++; if (nlhs>narg) { plhs[narg] = eigenToMatlab(debug->beq); } narg++; if (nlhs>narg) { plhs[narg] = eigenToMatlab(debug->Ain_lb_ub); } narg++; if (nlhs>narg) { plhs[narg] = eigenToMatlab(debug->bin_lb_ub); } narg++; if (nlhs>narg) { plhs[narg] = eigenToMatlab(debug->Qnfdiag); } narg++; if (nlhs>narg) { plhs[narg] = eigenToMatlab(debug->Qneps); } narg++; if (nlhs>narg) { double Vdot; if (debug->nc>0) // note: Sdot is 0 for ZMP/double integrator dynamics, so we omit that term here Vdot = ((2*debug->x_bar.transpose()*debug->S + debug->s1.transpose())*(debug->A_ls*debug->x_bar + debug->B_ls*(debug->Jcomdotv + debug->Jcom*qp_output.qdd)) + debug->s1dot.transpose()*debug->x_bar)(0) + debug->s2dot; else Vdot = 0; plhs[narg] = mxCreateDoubleScalar(Vdot); } narg++; if (nlhs>narg) { RigidBodyManipulator* r = pdata->r; VectorXd individual_cops = individualSupportCOPs(r, debug->active_supports, debug->normals, debug->B, debug->beta); plhs[narg] = eigenToMatlab(individual_cops); } narg++; } <|endoftext|>
<commit_before> // // This source file is part of appleseed. // Visit http://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2010-2011 Francois Beaune // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // // Interface header. #include "cameracontroller.h" // appleseed.renderer headers. #include "renderer/api/camera.h" #include "renderer/api/scene.h" #include "renderer/api/utility.h" // appleseed.foundation headers. #include "foundation/math/transform.h" // Qt headers. #include <QEvent> #include <QMouseEvent> #include <QWidget> using namespace foundation; using namespace renderer; namespace appleseed { namespace studio { // // CameraController class implementation. // CameraController::CameraController( QWidget* render_widget, Scene* scene) : m_render_widget(render_widget) , m_camera(scene->get_camera()) { configure_controller(scene); m_render_widget->installEventFilter(this); } CameraController::~CameraController() { m_render_widget->removeEventFilter(this); m_camera->get_parameters().insert("controller_target", m_controller.get_target()); } void CameraController::update_camera_transform() { m_camera->set_transform(Transformd(m_controller.get_transform())); } bool CameraController::eventFilter(QObject* object, QEvent* event) { switch (event->type()) { case QEvent::MouseButtonPress: if (handle_mouse_button_press_event(static_cast<QMouseEvent*>(event))) return true; break; case QEvent::MouseButtonRelease: if (handle_mouse_button_release_event(static_cast<QMouseEvent*>(event))) return true; break; case QEvent::MouseMove: if (handle_mouse_move_event(static_cast<QMouseEvent*>(event))) return true; break; } return QObject::eventFilter(object, event); } void CameraController::configure_controller(const Scene* scene) { // Set the controller orientation and position based on the scene camera. m_controller.set_transform( m_camera->get_transform().get_local_to_parent()); if (m_camera->get_parameters().strings().exist("controller_target")) { // The camera already has a target position, use it. m_controller.set_target( m_camera->get_parameters().get_optional<Vector3d>( "controller_target", Vector3d(0.0))); } else { // Otherwise, if the scene is not empty, use its center as the target position. const GAABB3 scene_bbox = compute_parent_bbox<GAABB3>( scene->assembly_instances().begin(), scene->assembly_instances().end()); if (scene_bbox.is_valid()) m_controller.set_target(Vector3d(scene_bbox.center())); } } Vector2d CameraController::get_mouse_position(const QMouseEvent* event) const { const int width = m_render_widget->width(); const int height = m_render_widget->height(); const double x = static_cast<double>(event->x()) / width; const double y = -static_cast<double>(event->y()) / height; return Vector2d(x, y); } bool CameraController::handle_mouse_button_press_event(const QMouseEvent* event) { if (m_controller.is_dragging()) return false; if (!(event->modifiers() & Qt::ControlModifier)) return false; const Vector2d position = get_mouse_position(event); switch (event->button()) { case Qt::LeftButton: m_controller.begin_drag( (event->modifiers() & Qt::AltModifier) ? ControllerType::Track : ControllerType::Tumble, position); return true; case Qt::MidButton: m_controller.begin_drag(ControllerType::Track, position); return true; case Qt::RightButton: m_controller.begin_drag(ControllerType::Dolly, position); return true; } return false; } bool CameraController::handle_mouse_button_release_event(const QMouseEvent* event) { if (!m_controller.is_dragging()) return false; m_controller.end_drag(); return true; } bool CameraController::handle_mouse_move_event(const QMouseEvent* event) { if (!m_controller.is_dragging()) return false; const Vector2d position = get_mouse_position(event); m_controller.update_drag(position); emit signal_camera_changed(); return true; } } // namespace studio } // namespace appleseed <commit_msg>use new renderer::Scene::compute_bbox() method.<commit_after> // // This source file is part of appleseed. // Visit http://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2010-2011 Francois Beaune // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // // Interface header. #include "cameracontroller.h" // appleseed.renderer headers. #include "renderer/api/camera.h" #include "renderer/api/scene.h" // appleseed.foundation headers. #include "foundation/math/transform.h" // Qt headers. #include <QEvent> #include <QMouseEvent> #include <QWidget> using namespace foundation; using namespace renderer; namespace appleseed { namespace studio { // // CameraController class implementation. // CameraController::CameraController( QWidget* render_widget, Scene* scene) : m_render_widget(render_widget) , m_camera(scene->get_camera()) { configure_controller(scene); m_render_widget->installEventFilter(this); } CameraController::~CameraController() { m_render_widget->removeEventFilter(this); m_camera->get_parameters().insert("controller_target", m_controller.get_target()); } void CameraController::update_camera_transform() { m_camera->set_transform(Transformd(m_controller.get_transform())); } bool CameraController::eventFilter(QObject* object, QEvent* event) { switch (event->type()) { case QEvent::MouseButtonPress: if (handle_mouse_button_press_event(static_cast<QMouseEvent*>(event))) return true; break; case QEvent::MouseButtonRelease: if (handle_mouse_button_release_event(static_cast<QMouseEvent*>(event))) return true; break; case QEvent::MouseMove: if (handle_mouse_move_event(static_cast<QMouseEvent*>(event))) return true; break; } return QObject::eventFilter(object, event); } void CameraController::configure_controller(const Scene* scene) { // Set the controller orientation and position based on the scene camera. m_controller.set_transform( m_camera->get_transform().get_local_to_parent()); if (m_camera->get_parameters().strings().exist("controller_target")) { // The camera already has a target position, use it. m_controller.set_target( m_camera->get_parameters().get_optional<Vector3d>( "controller_target", Vector3d(0.0))); } else { // Otherwise, if the scene is not empty, use its center as the target position. const GAABB3 scene_bbox = scene->compute_bbox(); if (scene_bbox.is_valid()) m_controller.set_target(Vector3d(scene_bbox.center())); } } Vector2d CameraController::get_mouse_position(const QMouseEvent* event) const { const int width = m_render_widget->width(); const int height = m_render_widget->height(); const double x = static_cast<double>(event->x()) / width; const double y = -static_cast<double>(event->y()) / height; return Vector2d(x, y); } bool CameraController::handle_mouse_button_press_event(const QMouseEvent* event) { if (m_controller.is_dragging()) return false; if (!(event->modifiers() & Qt::ControlModifier)) return false; const Vector2d position = get_mouse_position(event); switch (event->button()) { case Qt::LeftButton: m_controller.begin_drag( (event->modifiers() & Qt::AltModifier) ? ControllerType::Track : ControllerType::Tumble, position); return true; case Qt::MidButton: m_controller.begin_drag(ControllerType::Track, position); return true; case Qt::RightButton: m_controller.begin_drag(ControllerType::Dolly, position); return true; } return false; } bool CameraController::handle_mouse_button_release_event(const QMouseEvent* event) { if (!m_controller.is_dragging()) return false; m_controller.end_drag(); return true; } bool CameraController::handle_mouse_move_event(const QMouseEvent* event) { if (!m_controller.is_dragging()) return false; const Vector2d position = get_mouse_position(event); m_controller.update_drag(position); emit signal_camera_changed(); return true; } } // namespace studio } // namespace appleseed <|endoftext|>
<commit_before> // // This source file is part of appleseed. // Visit http://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited // Copyright (c) 2014-2015 Francois Beaune, The appleseedhq Organization // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // // Interface header. #include "renderingmanager.h" // appleseed.studio headers. #include "mainwindow/rendering/cameracontroller.h" #include "mainwindow/rendering/rendertab.h" #include "mainwindow/rendering/renderwidget.h" #include "mainwindow/statusbar.h" // appleseed.shared headers. #include "application/application.h" // appleseed.renderer headers. #include "renderer/api/camera.h" #include "renderer/api/frame.h" #include "renderer/api/project.h" #include "renderer/api/scene.h" #include "renderer/api/utility.h" // appleseed.foundation headers. #include "foundation/image/analysis.h" #include "foundation/image/image.h" #include "foundation/platform/defaulttimers.h" #include "foundation/platform/types.h" #include "foundation/utility/job/iabortswitch.h" #include "foundation/utility/foreach.h" #include "foundation/utility/string.h" // Boost headers. #include "boost/filesystem/path.hpp" // Qt headers. #include <QApplication> // Standard headers. #include <cassert> using namespace appleseed::shared; using namespace boost; using namespace foundation; using namespace renderer; using namespace std; namespace appleseed { namespace studio { // // RenderingManager class implementation. // namespace { class MasterRendererThread : public QThread { public: // Constructor. explicit MasterRendererThread(MasterRenderer* master_renderer) : m_master_renderer(master_renderer) { } private: MasterRenderer* m_master_renderer; // The starting point for the thread. virtual void run() APPLESEED_OVERRIDE { set_current_thread_name("master_renderer"); m_master_renderer->render(); } }; } RenderingManager::RenderingManager(StatusBar& status_bar) : m_status_bar(status_bar) , m_project(0) , m_render_tab(0) { // // The connections below are using the Qt::BlockingQueuedConnection connection type. // // They are using a queued connection because the emitting thread is different from // the receiving thread (the emitting thread is the master renderer thread, and the // receiving thread is the UI thread of the main window (presumably). // // They are using a blocking queue connection because we need the receiving slot to // have returned in the receiving thread before the emitting thread can continue. // // See http://qt-project.org/doc/qt-4.8/qt.html#ConnectionType-enum for more details. // connect( &m_renderer_controller, SIGNAL(signal_frame_begin()), this, SLOT(slot_frame_begin()), Qt::BlockingQueuedConnection); connect( &m_renderer_controller, SIGNAL(signal_frame_end()), this, SLOT(slot_frame_end()), Qt::BlockingQueuedConnection); connect( &m_renderer_controller, SIGNAL(signal_rendering_begin()), this, SLOT(slot_rendering_begin()), Qt::BlockingQueuedConnection); connect( &m_renderer_controller, SIGNAL(signal_rendering_success()), this, SLOT(slot_rendering_end()), Qt::BlockingQueuedConnection); connect( &m_renderer_controller, SIGNAL(signal_rendering_abort()), this, SLOT(slot_rendering_end()), Qt::BlockingQueuedConnection); connect( &m_renderer_controller, SIGNAL(signal_rendering_success()), this, SIGNAL(signal_rendering_end())); connect( &m_renderer_controller, SIGNAL(signal_rendering_abort()), this, SIGNAL(signal_rendering_end())); } RenderingManager::~RenderingManager() { clear_scheduled_actions(); clear_sticky_actions(); } void RenderingManager::start_rendering( Project* project, const ParamArray& params, RenderTab* render_tab) { m_project = project; m_params = params; m_render_tab = render_tab; m_tile_callback_factory.reset( new QtTileCallbackFactory( m_render_tab->get_render_widget())); m_master_renderer.reset( new MasterRenderer( *m_project, m_params, &m_renderer_controller, m_tile_callback_factory.get())); m_master_renderer_thread.reset( new MasterRendererThread(m_master_renderer.get())); connect( m_master_renderer_thread.get(), SIGNAL(finished()), SLOT(slot_master_renderer_thread_finished())); m_master_renderer_thread->start(); } bool RenderingManager::is_rendering() const { return m_master_renderer_thread.get() && m_master_renderer_thread->isRunning(); } void RenderingManager::wait_until_rendering_end() { while (is_rendering()) QApplication::processEvents(); } void RenderingManager::abort_rendering() { RENDERER_LOG_INFO("aborting rendering..."); m_renderer_controller.set_status(IRendererController::AbortRendering); } void RenderingManager::restart_rendering() { m_renderer_controller.set_status(IRendererController::RestartRendering); } void RenderingManager::reinitialize_rendering() { m_renderer_controller.set_status(IRendererController::ReinitializeRendering); } void RenderingManager::pause_rendering() { m_renderer_controller.set_status(IRendererController::PauseRendering); } void RenderingManager::resume_rendering() { m_renderer_controller.set_status(IRendererController::ContinueRendering); } void RenderingManager::schedule(auto_ptr<IScheduledAction> action) { m_scheduled_actions.push_back(action.release()); } void RenderingManager::schedule_or_execute(auto_ptr<IScheduledAction> action) { if (is_rendering()) { m_scheduled_actions.push_back(action.release()); reinitialize_rendering(); } else { (*action)(*m_project); } } void RenderingManager::clear_scheduled_actions() { for (each<ScheduledActionCollection> i = m_scheduled_actions; i; ++i) delete *i; m_scheduled_actions.clear(); } void RenderingManager::set_sticky_action( const string& key, auto_ptr<IStickyAction> action) { m_sticky_actions[key] = action.release(); } void RenderingManager::clear_sticky_actions() { for (each<StickyActionCollection> i = m_sticky_actions; i; ++i) delete i->second; m_sticky_actions.clear(); } void RenderingManager::slot_abort_rendering() { abort_rendering(); } void RenderingManager::slot_restart_rendering() { restart_rendering(); } void RenderingManager::slot_reinitialize_rendering() { reinitialize_rendering(); } void RenderingManager::print_final_rendering_time() { const double rendering_time = m_rendering_timer.get_seconds(); const string rendering_time_string = pretty_time(rendering_time, 3); RENDERER_LOG_INFO("rendering finished in %s.", rendering_time_string.c_str()); m_status_bar.set_text("Rendering finished in " + rendering_time_string); } void RenderingManager::print_average_luminance() { Image final_image(m_project->get_frame()->image()); m_project->get_frame()->transform_to_output_color_space(final_image); const double average_luminance = compute_average_luminance(final_image); RENDERER_LOG_DEBUG( "final average luminance is %s.", pretty_scalar(average_luminance, 6).c_str()); } void RenderingManager::archive_frame_to_disk() { RENDERER_LOG_INFO("archiving frame to disk..."); const filesystem::path autosave_path = filesystem::path(Application::get_root_path()) / "images" / "autosave"; m_project->get_frame()->archive(autosave_path.string().c_str()); } void RenderingManager::run_scheduled_actions() { for (each<ScheduledActionCollection> i = m_scheduled_actions; i; ++i) { IScheduledAction* action = *i; (*action)(*m_project); delete action; } m_scheduled_actions.clear(); } void RenderingManager::run_sticky_actions() { assert(m_master_renderer.get()); for (each<StickyActionCollection> i = m_sticky_actions; i; ++i) { IStickyAction* action = i->second; (*action)(*m_master_renderer.get(), *m_project); } } void RenderingManager::slot_rendering_begin() { assert(m_master_renderer.get()); run_sticky_actions(); run_scheduled_actions(); m_rendering_timer.clear(); } void RenderingManager::slot_rendering_end() { // Save the controller target point into the camera when rendering ends. m_render_tab->get_camera_controller()->save_camera_target(); print_final_rendering_time(); if (m_params.get_optional<bool>("print_final_average_luminance", false)) print_average_luminance(); if (m_params.get_optional<bool>("autosave", true)) archive_frame_to_disk(); } void RenderingManager::slot_frame_begin() { // Update the scene's camera before rendering the frame. m_render_tab->get_camera_controller()->update_camera_transform(); // Start printing rendering time in the status bar. m_status_bar.start_rendering_time_display(&m_rendering_timer); m_rendering_timer.start(); } void RenderingManager::slot_frame_end() { // Stop printing rendering time in the status bar. m_rendering_timer.measure(); m_status_bar.stop_rendering_time_display(); // Ensure that the render widget is up-to-date. m_render_tab->get_render_widget()->update(); } void RenderingManager::slot_camera_change_begin() { if (m_params.get_optional<bool>("freeze_display_during_navigation", false)) { pause_rendering(); assert(m_frozen_display_func.get() == 0); assert(m_frozen_display_thread.get() == 0); m_frozen_display_abort_switch.clear(); m_frozen_display_func.reset( new FrozenDisplayFunc( get_sampling_context_mode(m_params), *m_project->get_scene()->get_camera(), *m_project->get_frame(), *m_tile_callback_factory.get(), m_frozen_display_abort_switch)); m_frozen_display_thread.reset( new boost::thread( ThreadFunctionWrapper<FrozenDisplayFunc>(m_frozen_display_func.get()))); } } void RenderingManager::slot_camera_changed() { if (m_frozen_display_func.get()) { m_frozen_display_func->set_camera_transform( m_render_tab->get_camera_controller()->get_transform()); } else { restart_rendering(); } } void RenderingManager::slot_camera_change_end() { if (m_frozen_display_func.get()) { m_frozen_display_abort_switch.abort(); m_frozen_display_thread->join(); m_frozen_display_thread.reset(); m_frozen_display_func.reset(); m_project->get_frame()->clear_main_image(); restart_rendering(); } } void RenderingManager::slot_master_renderer_thread_finished() { m_master_renderer.reset(); } // // RenderingManager::FrozenDisplayFunc class implementation. // RenderingManager::FrozenDisplayFunc::FrozenDisplayFunc( const SamplingContext::Mode sampling_mode, const Camera& camera, const Frame& frame, ITileCallbackFactory& tile_callback_factory, IAbortSwitch& abort_switch) : m_renderer(sampling_mode, camera, frame) , m_frame(frame) , m_tile_callback(tile_callback_factory.create()) , m_abort_switch(abort_switch) { // Start by capturing the current frame as a point cloud. m_renderer.capture(); } void RenderingManager::FrozenDisplayFunc::set_camera_transform(const Transformd& transform) { m_renderer.set_camera_transform(transform); } void RenderingManager::FrozenDisplayFunc::operator()() { const double TargetElapsed = 1.0 / 30.0; DefaultWallclockTimer timer; const double rcp_timer_freq = 1.0 / timer.frequency(); uint64 last_time = timer.read(); while (!m_abort_switch.is_aborted()) { // Render the point cloud to the frame. m_renderer.render(); // Display the frame. m_tile_callback->post_render(&m_frame); // Limit frame rate. const uint64 time = timer.read(); const double elapsed = (time - last_time) * rcp_timer_freq; if (elapsed < TargetElapsed) { const double ms = ceil(1000.0 * (TargetElapsed - elapsed)); sleep(truncate<uint32>(ms), m_abort_switch); } last_time = time; } } } // namespace studio } // namespace appleseed <commit_msg>set thread name in frozen display thread.<commit_after> // // This source file is part of appleseed. // Visit http://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited // Copyright (c) 2014-2015 Francois Beaune, The appleseedhq Organization // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // // Interface header. #include "renderingmanager.h" // appleseed.studio headers. #include "mainwindow/rendering/cameracontroller.h" #include "mainwindow/rendering/rendertab.h" #include "mainwindow/rendering/renderwidget.h" #include "mainwindow/statusbar.h" // appleseed.shared headers. #include "application/application.h" // appleseed.renderer headers. #include "renderer/api/camera.h" #include "renderer/api/frame.h" #include "renderer/api/project.h" #include "renderer/api/scene.h" #include "renderer/api/utility.h" // appleseed.foundation headers. #include "foundation/image/analysis.h" #include "foundation/image/image.h" #include "foundation/platform/defaulttimers.h" #include "foundation/platform/types.h" #include "foundation/utility/job/iabortswitch.h" #include "foundation/utility/foreach.h" #include "foundation/utility/string.h" // Boost headers. #include "boost/filesystem/path.hpp" // Qt headers. #include <QApplication> // Standard headers. #include <cassert> using namespace appleseed::shared; using namespace boost; using namespace foundation; using namespace renderer; using namespace std; namespace appleseed { namespace studio { // // RenderingManager class implementation. // namespace { class MasterRendererThread : public QThread { public: // Constructor. explicit MasterRendererThread(MasterRenderer* master_renderer) : m_master_renderer(master_renderer) { } private: MasterRenderer* m_master_renderer; // The starting point for the thread. virtual void run() APPLESEED_OVERRIDE { set_current_thread_name("master_renderer"); m_master_renderer->render(); } }; } RenderingManager::RenderingManager(StatusBar& status_bar) : m_status_bar(status_bar) , m_project(0) , m_render_tab(0) { // // The connections below are using the Qt::BlockingQueuedConnection connection type. // // They are using a queued connection because the emitting thread is different from // the receiving thread (the emitting thread is the master renderer thread, and the // receiving thread is the UI thread of the main window (presumably). // // They are using a blocking queue connection because we need the receiving slot to // have returned in the receiving thread before the emitting thread can continue. // // See http://qt-project.org/doc/qt-4.8/qt.html#ConnectionType-enum for more details. // connect( &m_renderer_controller, SIGNAL(signal_frame_begin()), this, SLOT(slot_frame_begin()), Qt::BlockingQueuedConnection); connect( &m_renderer_controller, SIGNAL(signal_frame_end()), this, SLOT(slot_frame_end()), Qt::BlockingQueuedConnection); connect( &m_renderer_controller, SIGNAL(signal_rendering_begin()), this, SLOT(slot_rendering_begin()), Qt::BlockingQueuedConnection); connect( &m_renderer_controller, SIGNAL(signal_rendering_success()), this, SLOT(slot_rendering_end()), Qt::BlockingQueuedConnection); connect( &m_renderer_controller, SIGNAL(signal_rendering_abort()), this, SLOT(slot_rendering_end()), Qt::BlockingQueuedConnection); connect( &m_renderer_controller, SIGNAL(signal_rendering_success()), this, SIGNAL(signal_rendering_end())); connect( &m_renderer_controller, SIGNAL(signal_rendering_abort()), this, SIGNAL(signal_rendering_end())); } RenderingManager::~RenderingManager() { clear_scheduled_actions(); clear_sticky_actions(); } void RenderingManager::start_rendering( Project* project, const ParamArray& params, RenderTab* render_tab) { m_project = project; m_params = params; m_render_tab = render_tab; m_tile_callback_factory.reset( new QtTileCallbackFactory( m_render_tab->get_render_widget())); m_master_renderer.reset( new MasterRenderer( *m_project, m_params, &m_renderer_controller, m_tile_callback_factory.get())); m_master_renderer_thread.reset( new MasterRendererThread(m_master_renderer.get())); connect( m_master_renderer_thread.get(), SIGNAL(finished()), SLOT(slot_master_renderer_thread_finished())); m_master_renderer_thread->start(); } bool RenderingManager::is_rendering() const { return m_master_renderer_thread.get() && m_master_renderer_thread->isRunning(); } void RenderingManager::wait_until_rendering_end() { while (is_rendering()) QApplication::processEvents(); } void RenderingManager::abort_rendering() { RENDERER_LOG_INFO("aborting rendering..."); m_renderer_controller.set_status(IRendererController::AbortRendering); } void RenderingManager::restart_rendering() { m_renderer_controller.set_status(IRendererController::RestartRendering); } void RenderingManager::reinitialize_rendering() { m_renderer_controller.set_status(IRendererController::ReinitializeRendering); } void RenderingManager::pause_rendering() { m_renderer_controller.set_status(IRendererController::PauseRendering); } void RenderingManager::resume_rendering() { m_renderer_controller.set_status(IRendererController::ContinueRendering); } void RenderingManager::schedule(auto_ptr<IScheduledAction> action) { m_scheduled_actions.push_back(action.release()); } void RenderingManager::schedule_or_execute(auto_ptr<IScheduledAction> action) { if (is_rendering()) { m_scheduled_actions.push_back(action.release()); reinitialize_rendering(); } else { (*action)(*m_project); } } void RenderingManager::clear_scheduled_actions() { for (each<ScheduledActionCollection> i = m_scheduled_actions; i; ++i) delete *i; m_scheduled_actions.clear(); } void RenderingManager::set_sticky_action( const string& key, auto_ptr<IStickyAction> action) { m_sticky_actions[key] = action.release(); } void RenderingManager::clear_sticky_actions() { for (each<StickyActionCollection> i = m_sticky_actions; i; ++i) delete i->second; m_sticky_actions.clear(); } void RenderingManager::slot_abort_rendering() { abort_rendering(); } void RenderingManager::slot_restart_rendering() { restart_rendering(); } void RenderingManager::slot_reinitialize_rendering() { reinitialize_rendering(); } void RenderingManager::print_final_rendering_time() { const double rendering_time = m_rendering_timer.get_seconds(); const string rendering_time_string = pretty_time(rendering_time, 3); RENDERER_LOG_INFO("rendering finished in %s.", rendering_time_string.c_str()); m_status_bar.set_text("Rendering finished in " + rendering_time_string); } void RenderingManager::print_average_luminance() { Image final_image(m_project->get_frame()->image()); m_project->get_frame()->transform_to_output_color_space(final_image); const double average_luminance = compute_average_luminance(final_image); RENDERER_LOG_DEBUG( "final average luminance is %s.", pretty_scalar(average_luminance, 6).c_str()); } void RenderingManager::archive_frame_to_disk() { RENDERER_LOG_INFO("archiving frame to disk..."); const filesystem::path autosave_path = filesystem::path(Application::get_root_path()) / "images" / "autosave"; m_project->get_frame()->archive(autosave_path.string().c_str()); } void RenderingManager::run_scheduled_actions() { for (each<ScheduledActionCollection> i = m_scheduled_actions; i; ++i) { IScheduledAction* action = *i; (*action)(*m_project); delete action; } m_scheduled_actions.clear(); } void RenderingManager::run_sticky_actions() { assert(m_master_renderer.get()); for (each<StickyActionCollection> i = m_sticky_actions; i; ++i) { IStickyAction* action = i->second; (*action)(*m_master_renderer.get(), *m_project); } } void RenderingManager::slot_rendering_begin() { assert(m_master_renderer.get()); run_sticky_actions(); run_scheduled_actions(); m_rendering_timer.clear(); } void RenderingManager::slot_rendering_end() { // Save the controller target point into the camera when rendering ends. m_render_tab->get_camera_controller()->save_camera_target(); print_final_rendering_time(); if (m_params.get_optional<bool>("print_final_average_luminance", false)) print_average_luminance(); if (m_params.get_optional<bool>("autosave", true)) archive_frame_to_disk(); } void RenderingManager::slot_frame_begin() { // Update the scene's camera before rendering the frame. m_render_tab->get_camera_controller()->update_camera_transform(); // Start printing rendering time in the status bar. m_status_bar.start_rendering_time_display(&m_rendering_timer); m_rendering_timer.start(); } void RenderingManager::slot_frame_end() { // Stop printing rendering time in the status bar. m_rendering_timer.measure(); m_status_bar.stop_rendering_time_display(); // Ensure that the render widget is up-to-date. m_render_tab->get_render_widget()->update(); } void RenderingManager::slot_camera_change_begin() { if (m_params.get_optional<bool>("freeze_display_during_navigation", false)) { pause_rendering(); assert(m_frozen_display_func.get() == 0); assert(m_frozen_display_thread.get() == 0); m_frozen_display_abort_switch.clear(); m_frozen_display_func.reset( new FrozenDisplayFunc( get_sampling_context_mode(m_params), *m_project->get_scene()->get_camera(), *m_project->get_frame(), *m_tile_callback_factory.get(), m_frozen_display_abort_switch)); m_frozen_display_thread.reset( new boost::thread( ThreadFunctionWrapper<FrozenDisplayFunc>(m_frozen_display_func.get()))); } } void RenderingManager::slot_camera_changed() { if (m_frozen_display_func.get()) { m_frozen_display_func->set_camera_transform( m_render_tab->get_camera_controller()->get_transform()); } else { restart_rendering(); } } void RenderingManager::slot_camera_change_end() { if (m_frozen_display_func.get()) { m_frozen_display_abort_switch.abort(); m_frozen_display_thread->join(); m_frozen_display_thread.reset(); m_frozen_display_func.reset(); m_project->get_frame()->clear_main_image(); restart_rendering(); } } void RenderingManager::slot_master_renderer_thread_finished() { m_master_renderer.reset(); } // // RenderingManager::FrozenDisplayFunc class implementation. // RenderingManager::FrozenDisplayFunc::FrozenDisplayFunc( const SamplingContext::Mode sampling_mode, const Camera& camera, const Frame& frame, ITileCallbackFactory& tile_callback_factory, IAbortSwitch& abort_switch) : m_renderer(sampling_mode, camera, frame) , m_frame(frame) , m_tile_callback(tile_callback_factory.create()) , m_abort_switch(abort_switch) { // Start by capturing the current frame as a point cloud. m_renderer.capture(); } void RenderingManager::FrozenDisplayFunc::set_camera_transform(const Transformd& transform) { m_renderer.set_camera_transform(transform); } void RenderingManager::FrozenDisplayFunc::operator()() { set_current_thread_name("frozen_display"); const double TargetElapsed = 1.0 / 30.0; DefaultWallclockTimer timer; const double rcp_timer_freq = 1.0 / timer.frequency(); uint64 last_time = timer.read(); while (!m_abort_switch.is_aborted()) { // Render the point cloud to the frame. m_renderer.render(); // Display the frame. m_tile_callback->post_render(&m_frame); // Limit frame rate. const uint64 time = timer.read(); const double elapsed = (time - last_time) * rcp_timer_freq; if (elapsed < TargetElapsed) { const double ms = ceil(1000.0 * (TargetElapsed - elapsed)); sleep(truncate<uint32>(ms), m_abort_switch); } last_time = time; } } } // namespace studio } // namespace appleseed <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "desktopprocesssignaloperation.h" #include "localprocesslist.h" #include <utils/winutils.h> #include <QCoreApplication> #include <QDir> #include <QProcess> #ifdef Q_OS_WIN #define _WIN32_WINNT 0x0502 #include <windows.h> #ifndef PROCESS_SUSPEND_RESUME #define PROCESS_SUSPEND_RESUME 0x0800 #endif // PROCESS_SUSPEND_RESUME #else // Q_OS_WIN #include <errno.h> #include <signal.h> #endif // else Q_OS_WIN namespace ProjectExplorer { void DesktopProcessSignalOperation::killProcess(int pid) { killProcessSilently(pid); emit finished(m_errorMessage); } void DesktopProcessSignalOperation::killProcess(const QString &filePath) { m_errorMessage.clear(); foreach (const DeviceProcessItem &process, Internal::LocalProcessList::getLocalProcesses()) { if (process.cmdLine == filePath) killProcessSilently(process.pid); } emit finished(m_errorMessage); } void DesktopProcessSignalOperation::interruptProcess(int pid) { m_errorMessage.clear(); interruptProcessSilently(pid); emit finished(m_errorMessage); } void DesktopProcessSignalOperation::interruptProcess(const QString &filePath) { m_errorMessage.clear(); foreach (const DeviceProcessItem &process, Internal::LocalProcessList::getLocalProcesses()) { if (process.cmdLine == filePath) interruptProcessSilently(process.pid); } emit finished(m_errorMessage); } void DesktopProcessSignalOperation::appendMsgCannotKill(int pid, const QString &why) { if (!m_errorMessage.isEmpty()) m_errorMessage += QChar::fromLatin1('\n'); m_errorMessage += tr("Cannot kill process with pid %1: %2").arg(pid).arg(why); m_errorMessage += QLatin1Char(' '); } void DesktopProcessSignalOperation::appendMsgCannotInterrupt(int pid, const QString &why) { if (!m_errorMessage.isEmpty()) m_errorMessage += QChar::fromLatin1('\n'); m_errorMessage += tr("Cannot interrupt process with pid %1: %2").arg(pid).arg(why); m_errorMessage += QLatin1Char(' '); } void DesktopProcessSignalOperation::killProcessSilently(int pid) { #ifdef Q_OS_WIN const DWORD rights = PROCESS_QUERY_INFORMATION|PROCESS_SET_INFORMATION |PROCESS_VM_OPERATION|PROCESS_VM_WRITE|PROCESS_VM_READ |PROCESS_DUP_HANDLE|PROCESS_TERMINATE|PROCESS_CREATE_THREAD|PROCESS_SUSPEND_RESUME; if (const HANDLE handle = OpenProcess(rights, FALSE, pid)) { if (!TerminateProcess(handle, UINT(-1))) appendMsgCannotKill(pid, Utils::winErrorMessage(GetLastError())); CloseHandle(handle); } else { appendMsgCannotKill(pid, tr("Cannot open process.")); } #else if (pid <= 0) appendMsgCannotKill(pid, tr("Invalid process id.")); else if (kill(pid, SIGKILL)) appendMsgCannotKill(pid, QString::fromLocal8Bit(strerror(errno))); #endif // Q_OS_WIN } void DesktopProcessSignalOperation::interruptProcessSilently(int pid) { #ifdef Q_OS_WIN enum SpecialInterrupt { NoSpecialInterrupt, Win32Interrupt, Win64Interrupt }; bool is64BitSystem = Utils::is64BitWindowsSystem(); SpecialInterrupt si = NoSpecialInterrupt; if (is64BitSystem) si = Utils::is64BitWindowsBinary(m_debuggerCommand) ? Win64Interrupt : Win32Interrupt; /* Windows 64 bit has a 32 bit subsystem (WOW64) which makes it possible to run a 32 bit application inside a 64 bit environment. When GDB is used DebugBreakProcess must be called from the same system (32/64 bit) running the inferior. If CDB is used we could in theory break wow64 processes, but the break is actually a wow64 breakpoint. CDB is configured to ignore these breakpoints, because they also appear on module loading. Therefore we need helper executables (win(32/64)interrupt.exe) on Windows 64 bit calling DebugBreakProcess from the correct system. DebugBreak matrix for windows Api = UseDebugBreakApi Win64 = UseWin64InterruptHelper Win32 = UseWin32InterruptHelper N/A = This configuration is not possible | Windows 32bit | Windows 64bit | QtCreator 32bit | QtCreator 32bit | QtCreator 64bit | Inferior 32bit | Inferior 32bit | Inferior 64bit | Inferior 32bit | Inferior 64bit ----------|-----------------|-----------------|-----------------|-----------------|---------------- CDB 32bit | Api | Api | N/A | Win32 | N/A 64bit | N/A | Win64 | Win64 | Api | Api ----------|-----------------|-----------------|-----------------|-----------------|---------------- GDB 32bit | Api | Api | N/A | Win32 | N/A 64bit | N/A | N/A | Win64 | N/A | Api ----------|-----------------|-----------------|-----------------|-----------------|---------------- */ HANDLE inferior = NULL; do { const DWORD rights = PROCESS_QUERY_INFORMATION|PROCESS_SET_INFORMATION |PROCESS_VM_OPERATION|PROCESS_VM_WRITE|PROCESS_VM_READ |PROCESS_DUP_HANDLE|PROCESS_TERMINATE|PROCESS_CREATE_THREAD|PROCESS_SUSPEND_RESUME; inferior = OpenProcess(rights, FALSE, pid); if (inferior == NULL) { appendMsgCannotInterrupt(pid, tr("Cannot open process: %1") + Utils::winErrorMessage(GetLastError())); break; } bool creatorIs64Bit = Utils::is64BitWindowsBinary(qApp->applicationFilePath()); if (!is64BitSystem || si == NoSpecialInterrupt || si == Win64Interrupt && creatorIs64Bit || si == Win32Interrupt && !creatorIs64Bit) { if (!DebugBreakProcess(inferior)) { appendMsgCannotInterrupt(pid, tr("DebugBreakProcess failed:") + QLatin1Char(' ') + Utils::winErrorMessage(GetLastError())); } } else if (si == Win32Interrupt || si == Win64Interrupt) { QString executable = QCoreApplication::applicationDirPath(); executable += si == Win32Interrupt ? QLatin1String("/win32interrupt.exe") : QLatin1String("/win64interrupt.exe"); if (!QFile::exists(executable)) { appendMsgCannotInterrupt(pid, tr( "%1 does not exist. If you built Qt Creator " "yourself, check out http://qt.gitorious.org/" "qt-creator/binary-artifacts."). arg(QDir::toNativeSeparators(executable))); } switch (QProcess::execute(executable, QStringList(QString::number(pid)))) { case -2: appendMsgCannotInterrupt(pid, tr( "Cannot start %1. Check src\\tools\\win64interrupt\\win64interrupt.c " "for more information.").arg(QDir::toNativeSeparators(executable))); break; case 0: break; default: appendMsgCannotInterrupt(pid, QDir::toNativeSeparators(executable) + QLatin1Char(' ') + tr("could not break the process.")); break; } } } while (false); if (inferior != NULL) CloseHandle(inferior); #else if (pid <= 0) appendMsgCannotInterrupt(pid, tr("Invalid process id.")); else if (kill(pid, SIGINT)) appendMsgCannotInterrupt(pid, QString::fromLocal8Bit(strerror(errno))); #endif // Q_OS_WIN } } // namespace ProjectExplorer <commit_msg>ProjectExplorer: Add parentheses to clarify precedence<commit_after>/**************************************************************************** ** ** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "desktopprocesssignaloperation.h" #include "localprocesslist.h" #include <utils/winutils.h> #include <QCoreApplication> #include <QDir> #include <QProcess> #ifdef Q_OS_WIN #define _WIN32_WINNT 0x0502 #include <windows.h> #ifndef PROCESS_SUSPEND_RESUME #define PROCESS_SUSPEND_RESUME 0x0800 #endif // PROCESS_SUSPEND_RESUME #else // Q_OS_WIN #include <errno.h> #include <signal.h> #endif // else Q_OS_WIN namespace ProjectExplorer { void DesktopProcessSignalOperation::killProcess(int pid) { killProcessSilently(pid); emit finished(m_errorMessage); } void DesktopProcessSignalOperation::killProcess(const QString &filePath) { m_errorMessage.clear(); foreach (const DeviceProcessItem &process, Internal::LocalProcessList::getLocalProcesses()) { if (process.cmdLine == filePath) killProcessSilently(process.pid); } emit finished(m_errorMessage); } void DesktopProcessSignalOperation::interruptProcess(int pid) { m_errorMessage.clear(); interruptProcessSilently(pid); emit finished(m_errorMessage); } void DesktopProcessSignalOperation::interruptProcess(const QString &filePath) { m_errorMessage.clear(); foreach (const DeviceProcessItem &process, Internal::LocalProcessList::getLocalProcesses()) { if (process.cmdLine == filePath) interruptProcessSilently(process.pid); } emit finished(m_errorMessage); } void DesktopProcessSignalOperation::appendMsgCannotKill(int pid, const QString &why) { if (!m_errorMessage.isEmpty()) m_errorMessage += QChar::fromLatin1('\n'); m_errorMessage += tr("Cannot kill process with pid %1: %2").arg(pid).arg(why); m_errorMessage += QLatin1Char(' '); } void DesktopProcessSignalOperation::appendMsgCannotInterrupt(int pid, const QString &why) { if (!m_errorMessage.isEmpty()) m_errorMessage += QChar::fromLatin1('\n'); m_errorMessage += tr("Cannot interrupt process with pid %1: %2").arg(pid).arg(why); m_errorMessage += QLatin1Char(' '); } void DesktopProcessSignalOperation::killProcessSilently(int pid) { #ifdef Q_OS_WIN const DWORD rights = PROCESS_QUERY_INFORMATION|PROCESS_SET_INFORMATION |PROCESS_VM_OPERATION|PROCESS_VM_WRITE|PROCESS_VM_READ |PROCESS_DUP_HANDLE|PROCESS_TERMINATE|PROCESS_CREATE_THREAD|PROCESS_SUSPEND_RESUME; if (const HANDLE handle = OpenProcess(rights, FALSE, pid)) { if (!TerminateProcess(handle, UINT(-1))) appendMsgCannotKill(pid, Utils::winErrorMessage(GetLastError())); CloseHandle(handle); } else { appendMsgCannotKill(pid, tr("Cannot open process.")); } #else if (pid <= 0) appendMsgCannotKill(pid, tr("Invalid process id.")); else if (kill(pid, SIGKILL)) appendMsgCannotKill(pid, QString::fromLocal8Bit(strerror(errno))); #endif // Q_OS_WIN } void DesktopProcessSignalOperation::interruptProcessSilently(int pid) { #ifdef Q_OS_WIN enum SpecialInterrupt { NoSpecialInterrupt, Win32Interrupt, Win64Interrupt }; bool is64BitSystem = Utils::is64BitWindowsSystem(); SpecialInterrupt si = NoSpecialInterrupt; if (is64BitSystem) si = Utils::is64BitWindowsBinary(m_debuggerCommand) ? Win64Interrupt : Win32Interrupt; /* Windows 64 bit has a 32 bit subsystem (WOW64) which makes it possible to run a 32 bit application inside a 64 bit environment. When GDB is used DebugBreakProcess must be called from the same system (32/64 bit) running the inferior. If CDB is used we could in theory break wow64 processes, but the break is actually a wow64 breakpoint. CDB is configured to ignore these breakpoints, because they also appear on module loading. Therefore we need helper executables (win(32/64)interrupt.exe) on Windows 64 bit calling DebugBreakProcess from the correct system. DebugBreak matrix for windows Api = UseDebugBreakApi Win64 = UseWin64InterruptHelper Win32 = UseWin32InterruptHelper N/A = This configuration is not possible | Windows 32bit | Windows 64bit | QtCreator 32bit | QtCreator 32bit | QtCreator 64bit | Inferior 32bit | Inferior 32bit | Inferior 64bit | Inferior 32bit | Inferior 64bit ----------|-----------------|-----------------|-----------------|-----------------|---------------- CDB 32bit | Api | Api | N/A | Win32 | N/A 64bit | N/A | Win64 | Win64 | Api | Api ----------|-----------------|-----------------|-----------------|-----------------|---------------- GDB 32bit | Api | Api | N/A | Win32 | N/A 64bit | N/A | N/A | Win64 | N/A | Api ----------|-----------------|-----------------|-----------------|-----------------|---------------- */ HANDLE inferior = NULL; do { const DWORD rights = PROCESS_QUERY_INFORMATION|PROCESS_SET_INFORMATION |PROCESS_VM_OPERATION|PROCESS_VM_WRITE|PROCESS_VM_READ |PROCESS_DUP_HANDLE|PROCESS_TERMINATE|PROCESS_CREATE_THREAD|PROCESS_SUSPEND_RESUME; inferior = OpenProcess(rights, FALSE, pid); if (inferior == NULL) { appendMsgCannotInterrupt(pid, tr("Cannot open process: %1") + Utils::winErrorMessage(GetLastError())); break; } bool creatorIs64Bit = Utils::is64BitWindowsBinary(qApp->applicationFilePath()); if (!is64BitSystem || si == NoSpecialInterrupt || (si == Win64Interrupt && creatorIs64Bit) || (si == Win32Interrupt && !creatorIs64Bit)) { if (!DebugBreakProcess(inferior)) { appendMsgCannotInterrupt(pid, tr("DebugBreakProcess failed:") + QLatin1Char(' ') + Utils::winErrorMessage(GetLastError())); } } else if (si == Win32Interrupt || si == Win64Interrupt) { QString executable = QCoreApplication::applicationDirPath(); executable += si == Win32Interrupt ? QLatin1String("/win32interrupt.exe") : QLatin1String("/win64interrupt.exe"); if (!QFile::exists(executable)) { appendMsgCannotInterrupt(pid, tr( "%1 does not exist. If you built Qt Creator " "yourself, check out http://qt.gitorious.org/" "qt-creator/binary-artifacts."). arg(QDir::toNativeSeparators(executable))); } switch (QProcess::execute(executable, QStringList(QString::number(pid)))) { case -2: appendMsgCannotInterrupt(pid, tr( "Cannot start %1. Check src\\tools\\win64interrupt\\win64interrupt.c " "for more information.").arg(QDir::toNativeSeparators(executable))); break; case 0: break; default: appendMsgCannotInterrupt(pid, QDir::toNativeSeparators(executable) + QLatin1Char(' ') + tr("could not break the process.")); break; } } } while (false); if (inferior != NULL) CloseHandle(inferior); #else if (pid <= 0) appendMsgCannotInterrupt(pid, tr("Invalid process id.")); else if (kill(pid, SIGINT)) appendMsgCannotInterrupt(pid, QString::fromLocal8Bit(strerror(errno))); #endif // Q_OS_WIN } } // namespace ProjectExplorer <|endoftext|>
<commit_before>#include "contextpanetextwidget.h" #include "contextpanewidget.h" #include "ui_contextpanetext.h" #include <qmljs/qmljspropertyreader.h> #include <QTimerEvent> namespace QmlDesigner { ContextPaneTextWidget::ContextPaneTextWidget(QWidget *parent) : QWidget(parent), ui(new Ui::ContextPaneTextWidget), m_fontSizeTimer(-1) { ui->setupUi(this); ui->boldButton->setIcon(QIcon(QLatin1String(":/qmldesigner/images/bold-h-icon.png"))); ui->italicButton->setIcon(QIcon(QLatin1String(":/qmldesigner/images/italic-h-icon.png"))); ui->underlineButton->setIcon(QIcon(QLatin1String(":/qmldesigner/images/underline-h-icon.png"))); ui->strikeoutButton->setIcon(QIcon(QLatin1String(":/qmldesigner/images/strikeout-h-icon.png"))); ui->leftAlignmentButton->setIcon(QIcon(QLatin1String(":/qmldesigner/images/alignmentleft-h-icon.png"))); ui->centerHAlignmentButton->setIcon(QIcon(QLatin1String(":/qmldesigner/images/alignmentcenterh-h-icon.png"))); ui->rightAlignmentButton->setIcon(QIcon(QLatin1String(":/qmldesigner/images/alignmentright-h-icon.png"))); ui->centerVAlignmentButton->setIcon(QIcon(QLatin1String(":/qmldesigner/images/alignmentmiddle-h-icon.png"))); ui->bottomAlignmentButton->setIcon(QIcon(QLatin1String(":/qmldesigner/images/alignmentbottom-h-icon.png"))); ui->topAlignmentButton->setIcon(QIcon(QLatin1String(":/qmldesigner/images/alignmenttop-h-icon.png"))); ui->colorButton->setShowArrow(false); ui->textColorButton->setShowArrow(false); connect(ui->colorButton, SIGNAL(toggled(bool)), this, SLOT(onColorButtonToggled(bool))); connect(ui->textColorButton, SIGNAL(toggled(bool)), this, SLOT(onTextColorButtonToggled(bool))); ContextPaneWidget *parentContextWidget = qobject_cast<ContextPaneWidget*>(parentWidget()); connect(parentContextWidget->colorDialog(), SIGNAL(accepted(QColor)), this, SLOT(onColorDialogApplied(QColor))); connect(parentContextWidget->colorDialog(), SIGNAL(rejected()), this, SLOT(onColorDialogCancled())); connect(ui->fontSizeSpinBox, SIGNAL(valueChanged(int)), this, SLOT(onFontSizeChanged(int))); connect(ui->fontSizeSpinBox, SIGNAL(formatChanged()), this, SLOT(onFontFormatChanged())); connect(ui->boldButton, SIGNAL(toggled(bool)), this, SLOT(onBoldCheckedChanged(bool))); connect(ui->italicButton, SIGNAL(toggled(bool)), this, SLOT(onItalicCheckedChanged(bool))); connect(ui->underlineButton, SIGNAL(toggled(bool)), this, SLOT(onUnderlineCheckedChanged(bool))); connect(ui->strikeoutButton, SIGNAL(toggled(bool)), this, SLOT(onStrikeoutCheckedChanged(bool))); connect(ui->fontComboBox, SIGNAL(currentFontChanged(QFont)), this, SLOT(onCurrentFontChanged(QFont))); connect(ui->centerHAlignmentButton, SIGNAL(toggled(bool)), this, SLOT(onHorizontalAlignmentChanged())); connect(ui->leftAlignmentButton, SIGNAL(toggled(bool)), this, SLOT(onHorizontalAlignmentChanged())); connect(ui->rightAlignmentButton, SIGNAL(toggled(bool)), this, SLOT(onHorizontalAlignmentChanged())); connect(ui->centerVAlignmentButton, SIGNAL(toggled(bool)), this, SLOT(onVerticalAlignmentChanged())); connect(ui->topAlignmentButton, SIGNAL(toggled(bool)), this, SLOT(onVerticalAlignmentChanged())); connect(ui->bottomAlignmentButton, SIGNAL(toggled(bool)), this, SLOT(onVerticalAlignmentChanged())); connect(ui->styleComboBox, SIGNAL(currentIndexChanged(QString)), this, SLOT(onStyleComboBoxChanged(QString))); } void ContextPaneTextWidget::setProperties(QmlJS::PropertyReader *propertyReader) { if (propertyReader->hasProperty(QLatin1String("font.pointSize"))) { QVariant variant = propertyReader->readProperty(QLatin1String("font.pointSize")); bool b; ui->fontSizeSpinBox->setValue(variant.toInt(&b)); ui->fontSizeSpinBox->setEnabled(b); ui->fontSizeSpinBox->setIsPointSize(true); } else if (!propertyReader->hasProperty(QLatin1String("font.pixelSize"))) { ui->fontSizeSpinBox->setValue(8); ui->fontSizeSpinBox->setIsPointSize(true); } if (m_fontSizeTimer > 0) { killTimer(m_fontSizeTimer); m_fontSizeTimer = -1; } if (propertyReader->hasProperty(QLatin1String("font.pixelSize"))) { QVariant variant = propertyReader->readProperty(QLatin1String("font.pixelSize")); bool b; ui->fontSizeSpinBox->setValue(variant.toInt(&b)); ui->fontSizeSpinBox->setEnabled(b); ui->fontSizeSpinBox->setIsPixelSize(true); } if (propertyReader->hasProperty(QLatin1String("font.bold"))) { ui->boldButton->setChecked(propertyReader->readProperty(QLatin1String("font.bold")).toBool()); } else { ui->boldButton->setChecked(false); } if (propertyReader->hasProperty(QLatin1String("font.italic"))) { ui->italicButton->setChecked(propertyReader->readProperty(QLatin1String("font.italic")).toBool()); } else { ui->italicButton->setChecked(false); } if (propertyReader->hasProperty(QLatin1String("font.underline"))) { ui->underlineButton->setChecked(propertyReader->readProperty(QLatin1String("font.underline")).toBool()); } else { ui->underlineButton->setChecked(false); } if (propertyReader->hasProperty(QLatin1String("font.strikeout"))) { ui->strikeoutButton->setChecked(propertyReader->readProperty(QLatin1String("font.strikeout")).toBool()); } else { ui->strikeoutButton->setChecked(false); } if (propertyReader->hasProperty(QLatin1String("color"))) { ui->colorButton->setColor(propertyReader->readProperty("color").toString()); } else { ui->colorButton->setColor(QLatin1String("black")); } if (propertyReader->hasProperty(QLatin1String("styleColor"))) { ui->textColorButton->setColor(propertyReader->readProperty("styleColor").toString()); } else { ui->textColorButton->setColor(QLatin1String("black")); } if (propertyReader->hasProperty(QLatin1String("font.family"))) { QString familyName = propertyReader->readProperty(QLatin1String("font.family")).toString(); QFont font; font.setFamily(familyName); ui->fontComboBox->setCurrentFont(font); if (propertyReader->isBindingOrEnum(QLatin1String("font.family"))) ui->fontComboBox->setEnabled(false); else ui->fontComboBox->setEnabled(true); } if (propertyReader->hasProperty(QLatin1String("horizontalAlignment"))) { QString alignment = propertyReader->readProperty(QLatin1String("horizontalAlignment")).toString(); ui->leftAlignmentButton->setChecked(true); ui->leftAlignmentButton->setEnabled(true); if (alignment == QLatin1String("Text.AlignHCenter") || alignment == "AlignHCenter") ui->centerHAlignmentButton->setChecked(true); else if (alignment == QLatin1String("Text.AlignRight") || alignment == QLatin1String("AlignRight")) ui->rightAlignmentButton->setChecked(true); else if (alignment == QLatin1String("Text.AlignLeft") || alignment == QLatin1String("AlignLeft")) ui->leftAlignmentButton->setChecked(true); else ui->leftAlignmentButton->setEnabled(false); } else { ui->leftAlignmentButton->setChecked(true); } if (propertyReader->hasProperty(QLatin1String("verticalAlignment"))) { QString alignment = propertyReader->readProperty(QLatin1String("verticalAlignment")).toString(); ui->topAlignmentButton->setChecked(true); ui->bottomAlignmentButton->setEnabled(true); if (alignment == QLatin1String("Text.AlignVCenter") || alignment == QLatin1String("AlignVCenter")) ui->centerVAlignmentButton->setChecked(true); else if (alignment == QLatin1String("Text.AlignBottom") || alignment == QLatin1String("AlignBottom")) ui->bottomAlignmentButton->setChecked(true); else if (alignment == QLatin1String("Text.Top") || alignment == QLatin1String("AlignTop")) ui->topAlignmentButton->setChecked(true); else ui->bottomAlignmentButton->setEnabled(false); } else { ui->topAlignmentButton->setChecked(true); } if (propertyReader->hasProperty(QLatin1String("style"))) { QString style = propertyReader->readProperty(QLatin1String("style")).toString(); ui->styleComboBox->setCurrentIndex(0); ui->styleComboBox->setEnabled(true); if (style == QLatin1String("Text.Outline") || style == QLatin1String("Outline")) ui->styleComboBox->setCurrentIndex(1); if (style == QLatin1String("Text.Raised") || style == QLatin1String("Raised")) ui->styleComboBox->setCurrentIndex(2); else if (style == QLatin1String("Text.Sunken") || style == QLatin1String("Sunken")) ui->styleComboBox->setCurrentIndex(3); else if (style == QLatin1String("Text.Normal") || style == QLatin1String("Normal")) ui->styleComboBox->setCurrentIndex(0); else ui->styleComboBox->setEnabled(false); } else { ui->styleComboBox->setCurrentIndex(0); } } void ContextPaneTextWidget::setVerticalAlignmentVisible(bool b) { ui->centerVAlignmentButton->setEnabled(b); ui->topAlignmentButton->setEnabled(b); ui->bottomAlignmentButton->setEnabled(b); } void ContextPaneTextWidget::setStyleVisible(bool b) { ui->styleComboBox->setEnabled(b); ui->styleLabel->setEnabled(b); ui->textColorButton->setEnabled(b); } void ContextPaneTextWidget::onTextColorButtonToggled(bool flag) { ContextPaneWidget *parentContextWidget = qobject_cast<ContextPaneWidget*>(parentWidget()); if (flag) ui->colorButton->setChecked(false); QPoint p = mapToGlobal(ui->textColorButton->pos()); parentContextWidget->colorDialog()->setupColor(ui->textColorButton->color()); p = parentContextWidget->colorDialog()->parentWidget()->mapFromGlobal(p); parentContextWidget->onShowColorDialog(flag, p); } void ContextPaneTextWidget::onColorButtonToggled(bool flag) { if (flag) ui->textColorButton->setChecked(false); ContextPaneWidget *parentContextWidget = qobject_cast<ContextPaneWidget*>(parentWidget()); QPoint p = mapToGlobal(ui->colorButton->pos()); parentContextWidget->colorDialog()->setupColor(ui->colorButton->color()); p = parentContextWidget->colorDialog()->parentWidget()->mapFromGlobal(p); parentContextWidget->onShowColorDialog(flag, p); } void ContextPaneTextWidget::onColorDialogApplied(const QColor &) { ContextPaneWidget *parentContextWidget = qobject_cast<ContextPaneWidget*>(parentWidget()); parentContextWidget->onShowColorDialog(false, QPoint()); if (ui->textColorButton->isChecked()) emit propertyChanged(QLatin1String("styleColor"),parentContextWidget->colorDialog()->color());; //write back color if (ui->colorButton->isChecked()) emit propertyChanged(QLatin1String("color"),parentContextWidget->colorDialog()->color());; //write back color ui->textColorButton->setChecked(false); ui->colorButton->setChecked(false); } void ContextPaneTextWidget::onColorDialogCancled() { ContextPaneWidget *parentContextWidget = qobject_cast<ContextPaneWidget*>(parentWidget()); parentContextWidget->onShowColorDialog(false, QPoint()); ui->colorButton->setChecked(false); ui->colorButton->setChecked(false); } void ContextPaneTextWidget::onFontSizeChanged(int) { if (m_fontSizeTimer > 0) killTimer(m_fontSizeTimer); m_fontSizeTimer = startTimer(200); } void ContextPaneTextWidget::onFontFormatChanged() { int size = ui->fontSizeSpinBox->value(); if (ui->fontSizeSpinBox->isPointSize()) { emit removeAndChangeProperty(QLatin1String("font.pixelSize"), QLatin1String("font.pointSize"), size, true); } else { emit removeAndChangeProperty(QLatin1String("font.pointSize"), QLatin1String("font.pixelSize"), size, true); } } void ContextPaneTextWidget::onBoldCheckedChanged(bool value) { if (value) emit propertyChanged(QLatin1String("font.bold"), value); else emit removeProperty(QLatin1String("font.bold")); } void ContextPaneTextWidget::onItalicCheckedChanged(bool value) { if (value) emit propertyChanged(QLatin1String("font.italic"), value); else emit removeProperty(QLatin1String("font.italic")); } void ContextPaneTextWidget::onUnderlineCheckedChanged(bool value) { if (value) emit propertyChanged(QLatin1String("font.underline"), value); else emit removeProperty(QLatin1String("font.underline")); } void ContextPaneTextWidget::onStrikeoutCheckedChanged(bool value) { if (value) emit propertyChanged(QLatin1String("font.strikeout"), value); else emit removeProperty(QLatin1String("font.strikeout")); } void ContextPaneTextWidget::onCurrentFontChanged(const QFont &font) { font.family(); emit propertyChanged(QLatin1String("font.family"), QVariant(QString('\"') + font.family() + QString('\"'))); } void ContextPaneTextWidget::onHorizontalAlignmentChanged() { QString alignment; if (ui->centerHAlignmentButton->isChecked()) alignment = QLatin1String("AlignHCenter"); else if (ui->leftAlignmentButton->isChecked()) alignment = QLatin1String("AlignLeft"); else if (ui->rightAlignmentButton->isChecked()) alignment = QLatin1String("AlignRight"); if (m_horizontalAlignment != alignment) { m_horizontalAlignment = alignment; if (alignment == QLatin1String("AlignLeft")) emit removeProperty(QLatin1String("horizontalAlignment")); else emit propertyChanged(QLatin1String("horizontalAlignment"), alignment); } } void ContextPaneTextWidget::onStyleComboBoxChanged(const QString &style) { if (style == QLatin1String("Normal")) emit removeProperty(QLatin1String("style")); else emit propertyChanged(QLatin1String("style"), QVariant(QLatin1String("Text.") + style)); } void ContextPaneTextWidget::onVerticalAlignmentChanged() { QString alignment; if (ui->centerVAlignmentButton->isChecked()) alignment = QLatin1String("AlignVCenter"); else if (ui->topAlignmentButton->isChecked()) alignment = QLatin1String("AlignTop"); else if (ui->bottomAlignmentButton->isChecked()) alignment = QLatin1String("AlignBottom"); if (m_verticalAlignment != alignment) { m_verticalAlignment = alignment; if (alignment == QLatin1String("AlignTop")) emit removeProperty(QLatin1String("verticalAlignment")); else emit propertyChanged(QLatin1String("verticalAlignment"), alignment); } } ContextPaneTextWidget::~ContextPaneTextWidget() { delete ui; } void ContextPaneTextWidget::changeEvent(QEvent *e) { QWidget::changeEvent(e); switch (e->type()) { case QEvent::LanguageChange: ui->retranslateUi(this); break; default: break; } } void ContextPaneTextWidget::timerEvent(QTimerEvent *event) { if (event->timerId() == m_fontSizeTimer) { killTimer(m_fontSizeTimer); m_fontSizeTimer = -1; int value = ui->fontSizeSpinBox->value(); if (ui->fontSizeSpinBox->isPointSize()) emit propertyChanged(QLatin1String("font.pointSize"), value); else emit propertyChanged(QLatin1String("font.pixelSize"), value); } } } //QmlDesigner <commit_msg>QmlDesigner.propertyPane: bugfix<commit_after>#include "contextpanetextwidget.h" #include "contextpanewidget.h" #include "ui_contextpanetext.h" #include <qmljs/qmljspropertyreader.h> #include <QTimerEvent> namespace QmlDesigner { ContextPaneTextWidget::ContextPaneTextWidget(QWidget *parent) : QWidget(parent), ui(new Ui::ContextPaneTextWidget), m_fontSizeTimer(-1) { ui->setupUi(this); ui->boldButton->setIcon(QIcon(QLatin1String(":/qmldesigner/images/bold-h-icon.png"))); ui->italicButton->setIcon(QIcon(QLatin1String(":/qmldesigner/images/italic-h-icon.png"))); ui->underlineButton->setIcon(QIcon(QLatin1String(":/qmldesigner/images/underline-h-icon.png"))); ui->strikeoutButton->setIcon(QIcon(QLatin1String(":/qmldesigner/images/strikeout-h-icon.png"))); ui->leftAlignmentButton->setIcon(QIcon(QLatin1String(":/qmldesigner/images/alignmentleft-h-icon.png"))); ui->centerHAlignmentButton->setIcon(QIcon(QLatin1String(":/qmldesigner/images/alignmentcenterh-h-icon.png"))); ui->rightAlignmentButton->setIcon(QIcon(QLatin1String(":/qmldesigner/images/alignmentright-h-icon.png"))); ui->centerVAlignmentButton->setIcon(QIcon(QLatin1String(":/qmldesigner/images/alignmentmiddle-h-icon.png"))); ui->bottomAlignmentButton->setIcon(QIcon(QLatin1String(":/qmldesigner/images/alignmentbottom-h-icon.png"))); ui->topAlignmentButton->setIcon(QIcon(QLatin1String(":/qmldesigner/images/alignmenttop-h-icon.png"))); ui->colorButton->setShowArrow(false); ui->textColorButton->setShowArrow(false); connect(ui->colorButton, SIGNAL(toggled(bool)), this, SLOT(onColorButtonToggled(bool))); connect(ui->textColorButton, SIGNAL(toggled(bool)), this, SLOT(onTextColorButtonToggled(bool))); ContextPaneWidget *parentContextWidget = qobject_cast<ContextPaneWidget*>(parentWidget()); connect(parentContextWidget->colorDialog(), SIGNAL(accepted(QColor)), this, SLOT(onColorDialogApplied(QColor))); connect(parentContextWidget->colorDialog(), SIGNAL(rejected()), this, SLOT(onColorDialogCancled())); connect(ui->fontSizeSpinBox, SIGNAL(valueChanged(int)), this, SLOT(onFontSizeChanged(int))); connect(ui->fontSizeSpinBox, SIGNAL(formatChanged()), this, SLOT(onFontFormatChanged())); connect(ui->boldButton, SIGNAL(toggled(bool)), this, SLOT(onBoldCheckedChanged(bool))); connect(ui->italicButton, SIGNAL(toggled(bool)), this, SLOT(onItalicCheckedChanged(bool))); connect(ui->underlineButton, SIGNAL(toggled(bool)), this, SLOT(onUnderlineCheckedChanged(bool))); connect(ui->strikeoutButton, SIGNAL(toggled(bool)), this, SLOT(onStrikeoutCheckedChanged(bool))); connect(ui->fontComboBox, SIGNAL(currentFontChanged(QFont)), this, SLOT(onCurrentFontChanged(QFont))); connect(ui->centerHAlignmentButton, SIGNAL(toggled(bool)), this, SLOT(onHorizontalAlignmentChanged())); connect(ui->leftAlignmentButton, SIGNAL(toggled(bool)), this, SLOT(onHorizontalAlignmentChanged())); connect(ui->rightAlignmentButton, SIGNAL(toggled(bool)), this, SLOT(onHorizontalAlignmentChanged())); connect(ui->centerVAlignmentButton, SIGNAL(toggled(bool)), this, SLOT(onVerticalAlignmentChanged())); connect(ui->topAlignmentButton, SIGNAL(toggled(bool)), this, SLOT(onVerticalAlignmentChanged())); connect(ui->bottomAlignmentButton, SIGNAL(toggled(bool)), this, SLOT(onVerticalAlignmentChanged())); connect(ui->styleComboBox, SIGNAL(currentIndexChanged(QString)), this, SLOT(onStyleComboBoxChanged(QString))); } void ContextPaneTextWidget::setProperties(QmlJS::PropertyReader *propertyReader) { if (propertyReader->hasProperty(QLatin1String("font.pointSize"))) { QVariant variant = propertyReader->readProperty(QLatin1String("font.pointSize")); bool b; ui->fontSizeSpinBox->setValue(variant.toInt(&b)); ui->fontSizeSpinBox->setEnabled(b); ui->fontSizeSpinBox->setIsPointSize(true); } else if (!propertyReader->hasProperty(QLatin1String("font.pixelSize"))) { ui->fontSizeSpinBox->setValue(8); ui->fontSizeSpinBox->setIsPointSize(true); } if (m_fontSizeTimer > 0) { killTimer(m_fontSizeTimer); m_fontSizeTimer = -1; } if (propertyReader->hasProperty(QLatin1String("font.pixelSize"))) { QVariant variant = propertyReader->readProperty(QLatin1String("font.pixelSize")); bool b; ui->fontSizeSpinBox->setValue(variant.toInt(&b)); ui->fontSizeSpinBox->setEnabled(b); ui->fontSizeSpinBox->setIsPixelSize(true); } if (propertyReader->hasProperty(QLatin1String("font.bold"))) { ui->boldButton->setChecked(propertyReader->readProperty(QLatin1String("font.bold")).toBool()); } else { ui->boldButton->setChecked(false); } if (propertyReader->hasProperty(QLatin1String("font.italic"))) { ui->italicButton->setChecked(propertyReader->readProperty(QLatin1String("font.italic")).toBool()); } else { ui->italicButton->setChecked(false); } if (propertyReader->hasProperty(QLatin1String("font.underline"))) { ui->underlineButton->setChecked(propertyReader->readProperty(QLatin1String("font.underline")).toBool()); } else { ui->underlineButton->setChecked(false); } if (propertyReader->hasProperty(QLatin1String("font.strikeout"))) { ui->strikeoutButton->setChecked(propertyReader->readProperty(QLatin1String("font.strikeout")).toBool()); } else { ui->strikeoutButton->setChecked(false); } if (propertyReader->hasProperty(QLatin1String("color"))) { ui->colorButton->setColor(propertyReader->readProperty("color").toString()); } else { ui->colorButton->setColor(QLatin1String("black")); } if (propertyReader->hasProperty(QLatin1String("styleColor"))) { ui->textColorButton->setColor(propertyReader->readProperty("styleColor").toString()); } else { ui->textColorButton->setColor(QLatin1String("black")); } if (propertyReader->hasProperty(QLatin1String("font.family"))) { QString familyName = propertyReader->readProperty(QLatin1String("font.family")).toString(); QFont font; font.setFamily(familyName); ui->fontComboBox->setCurrentFont(font); if (propertyReader->isBindingOrEnum(QLatin1String("font.family"))) ui->fontComboBox->setEnabled(false); else ui->fontComboBox->setEnabled(true); } if (propertyReader->hasProperty(QLatin1String("horizontalAlignment"))) { QString alignment = propertyReader->readProperty(QLatin1String("horizontalAlignment")).toString(); ui->leftAlignmentButton->setChecked(true); ui->leftAlignmentButton->setEnabled(true); if (alignment == QLatin1String("Text.AlignHCenter") || alignment == "AlignHCenter") ui->centerHAlignmentButton->setChecked(true); else if (alignment == QLatin1String("Text.AlignRight") || alignment == QLatin1String("AlignRight")) ui->rightAlignmentButton->setChecked(true); else if (alignment == QLatin1String("Text.AlignLeft") || alignment == QLatin1String("AlignLeft")) ui->leftAlignmentButton->setChecked(true); else ui->leftAlignmentButton->setEnabled(false); } else { ui->leftAlignmentButton->setChecked(true); } if (propertyReader->hasProperty(QLatin1String("verticalAlignment"))) { QString alignment = propertyReader->readProperty(QLatin1String("verticalAlignment")).toString(); ui->topAlignmentButton->setChecked(true); ui->bottomAlignmentButton->setEnabled(true); if (alignment == QLatin1String("Text.AlignVCenter") || alignment == QLatin1String("AlignVCenter")) ui->centerVAlignmentButton->setChecked(true); else if (alignment == QLatin1String("Text.AlignBottom") || alignment == QLatin1String("AlignBottom")) ui->bottomAlignmentButton->setChecked(true); else if (alignment == QLatin1String("Text.Top") || alignment == QLatin1String("AlignTop")) ui->topAlignmentButton->setChecked(true); else ui->bottomAlignmentButton->setEnabled(false); } else { ui->topAlignmentButton->setChecked(true); } if (propertyReader->hasProperty(QLatin1String("style"))) { QString style = propertyReader->readProperty(QLatin1String("style")).toString(); ui->styleComboBox->setCurrentIndex(0); ui->styleComboBox->setEnabled(true); if (style == QLatin1String("Text.Outline") || style == QLatin1String("Outline")) ui->styleComboBox->setCurrentIndex(1); if (style == QLatin1String("Text.Raised") || style == QLatin1String("Raised")) ui->styleComboBox->setCurrentIndex(2); else if (style == QLatin1String("Text.Sunken") || style == QLatin1String("Sunken")) ui->styleComboBox->setCurrentIndex(3); else if (style == QLatin1String("Text.Normal") || style == QLatin1String("Normal")) ui->styleComboBox->setCurrentIndex(0); else ui->styleComboBox->setEnabled(false); } else { ui->styleComboBox->setCurrentIndex(0); } } void ContextPaneTextWidget::setVerticalAlignmentVisible(bool b) { ui->centerVAlignmentButton->setEnabled(b); ui->topAlignmentButton->setEnabled(b); ui->bottomAlignmentButton->setEnabled(b); } void ContextPaneTextWidget::setStyleVisible(bool b) { ui->styleComboBox->setEnabled(b); ui->styleLabel->setEnabled(b); ui->textColorButton->setEnabled(b); } void ContextPaneTextWidget::onTextColorButtonToggled(bool flag) { ContextPaneWidget *parentContextWidget = qobject_cast<ContextPaneWidget*>(parentWidget()); if (flag) ui->colorButton->setChecked(false); QPoint p = mapToGlobal(ui->textColorButton->pos()); parentContextWidget->colorDialog()->setupColor(ui->textColorButton->color()); p = parentContextWidget->colorDialog()->parentWidget()->mapFromGlobal(p); parentContextWidget->onShowColorDialog(flag, p); } void ContextPaneTextWidget::onColorButtonToggled(bool flag) { if (flag) ui->textColorButton->setChecked(false); ContextPaneWidget *parentContextWidget = qobject_cast<ContextPaneWidget*>(parentWidget()); QPoint p = mapToGlobal(ui->colorButton->pos()); parentContextWidget->colorDialog()->setupColor(ui->colorButton->color()); p = parentContextWidget->colorDialog()->parentWidget()->mapFromGlobal(p); parentContextWidget->onShowColorDialog(flag, p); } void ContextPaneTextWidget::onColorDialogApplied(const QColor &) { ContextPaneWidget *parentContextWidget = qobject_cast<ContextPaneWidget*>(parentWidget()); parentContextWidget->onShowColorDialog(false, QPoint()); if (ui->textColorButton->isChecked()) emit propertyChanged(QLatin1String("styleColor"),parentContextWidget->colorDialog()->color());; //write back color if (ui->colorButton->isChecked()) emit propertyChanged(QLatin1String("color"),parentContextWidget->colorDialog()->color());; //write back color ui->textColorButton->setChecked(false); ui->colorButton->setChecked(false); } void ContextPaneTextWidget::onColorDialogCancled() { ContextPaneWidget *parentContextWidget = qobject_cast<ContextPaneWidget*>(parentWidget()); parentContextWidget->onShowColorDialog(false, QPoint()); ui->colorButton->setChecked(false); ui->colorButton->setChecked(false); } void ContextPaneTextWidget::onFontSizeChanged(int) { if (m_fontSizeTimer > 0) killTimer(m_fontSizeTimer); m_fontSizeTimer = startTimer(200); } void ContextPaneTextWidget::onFontFormatChanged() { int size = ui->fontSizeSpinBox->value(); if (ui->fontSizeSpinBox->isPointSize()) { emit removeAndChangeProperty(QLatin1String("font.pixelSize"), QLatin1String("font.pointSize"), size, true); } else { emit removeAndChangeProperty(QLatin1String("font.pointSize"), QLatin1String("font.pixelSize"), size, true); } } void ContextPaneTextWidget::onBoldCheckedChanged(bool value) { if (value) emit propertyChanged(QLatin1String("font.bold"), value); else emit removeProperty(QLatin1String("font.bold")); } void ContextPaneTextWidget::onItalicCheckedChanged(bool value) { if (value) emit propertyChanged(QLatin1String("font.italic"), value); else emit removeProperty(QLatin1String("font.italic")); } void ContextPaneTextWidget::onUnderlineCheckedChanged(bool value) { if (value) emit propertyChanged(QLatin1String("font.underline"), value); else emit removeProperty(QLatin1String("font.underline")); } void ContextPaneTextWidget::onStrikeoutCheckedChanged(bool value) { if (value) emit propertyChanged(QLatin1String("font.strikeout"), value); else emit removeProperty(QLatin1String("font.strikeout")); } void ContextPaneTextWidget::onCurrentFontChanged(const QFont &font) { font.family(); emit propertyChanged(QLatin1String("font.family"), QVariant(QString('\"') + font.family() + QString('\"'))); } void ContextPaneTextWidget::onHorizontalAlignmentChanged() { QString alignment; if (ui->centerHAlignmentButton->isChecked()) alignment = QLatin1String("Text.AlignHCenter"); else if (ui->leftAlignmentButton->isChecked()) alignment = QLatin1String("Text.AlignLeft"); else if (ui->rightAlignmentButton->isChecked()) alignment = QLatin1String("Text.AlignRight"); if (m_horizontalAlignment != alignment) { m_horizontalAlignment = alignment; if (alignment == QLatin1String("Text.AlignLeft")) emit removeProperty(QLatin1String("horizontalAlignment")); else emit propertyChanged(QLatin1String("horizontalAlignment"), alignment); } } void ContextPaneTextWidget::onStyleComboBoxChanged(const QString &style) { if (style == QLatin1String("Normal")) emit removeProperty(QLatin1String("style")); else emit propertyChanged(QLatin1String("style"), QVariant(QLatin1String("Text.") + style)); } void ContextPaneTextWidget::onVerticalAlignmentChanged() { QString alignment; if (ui->centerVAlignmentButton->isChecked()) alignment = QLatin1String("Text.AlignVCenter"); else if (ui->topAlignmentButton->isChecked()) alignment = QLatin1String("Text.AlignTop"); else if (ui->bottomAlignmentButton->isChecked()) alignment = QLatin1String("Text.AlignBottom"); if (m_verticalAlignment != alignment) { m_verticalAlignment = alignment; if (alignment == QLatin1String("Text.AlignTop")) emit removeProperty(QLatin1String("verticalAlignment")); else emit propertyChanged(QLatin1String("verticalAlignment"), alignment); } } ContextPaneTextWidget::~ContextPaneTextWidget() { delete ui; } void ContextPaneTextWidget::changeEvent(QEvent *e) { QWidget::changeEvent(e); switch (e->type()) { case QEvent::LanguageChange: ui->retranslateUi(this); break; default: break; } } void ContextPaneTextWidget::timerEvent(QTimerEvent *event) { if (event->timerId() == m_fontSizeTimer) { killTimer(m_fontSizeTimer); m_fontSizeTimer = -1; int value = ui->fontSizeSpinBox->value(); if (ui->fontSizeSpinBox->isPointSize()) emit propertyChanged(QLatin1String("font.pointSize"), value); else emit propertyChanged(QLatin1String("font.pixelSize"), value); } } } //QmlDesigner <|endoftext|>
<commit_before>#include "contextpanetextwidget.h" #include "contextpanewidget.h" #include "ui_contextpanetext.h" #include <qmljs/qmljspropertyreader.h> #include <QTimerEvent> namespace QmlDesigner { ContextPaneTextWidget::ContextPaneTextWidget(QWidget *parent) : QWidget(parent), ui(new Ui::ContextPaneTextWidget), m_fontSizeTimer(-1) { ui->setupUi(this); ui->boldButton->setIcon(QIcon(QLatin1String(":/qmldesigner/images/bold-h-icon.png"))); ui->italicButton->setIcon(QIcon(QLatin1String(":/qmldesigner/images/italic-h-icon.png"))); ui->underlineButton->setIcon(QIcon(QLatin1String(":/qmldesigner/images/underline-h-icon.png"))); ui->strikeoutButton->setIcon(QIcon(QLatin1String(":/qmldesigner/images/strikeout-h-icon.png"))); ui->leftAlignmentButton->setIcon(QIcon(QLatin1String(":/qmldesigner/images/alignmentleft-h-icon.png"))); ui->centerHAlignmentButton->setIcon(QIcon(QLatin1String(":/qmldesigner/images/alignmentcenterh-h-icon.png"))); ui->rightAlignmentButton->setIcon(QIcon(QLatin1String(":/qmldesigner/images/alignmentright-h-icon.png"))); ui->centerVAlignmentButton->setIcon(QIcon(QLatin1String(":/qmldesigner/images/alignmentmiddle-h-icon.png"))); ui->bottomAlignmentButton->setIcon(QIcon(QLatin1String(":/qmldesigner/images/alignmentbottom-h-icon.png"))); ui->topAlignmentButton->setIcon(QIcon(QLatin1String(":/qmldesigner/images/alignmenttop-h-icon.png"))); ui->colorButton->setShowArrow(false); ui->textColorButton->setShowArrow(false); connect(ui->colorButton, SIGNAL(toggled(bool)), this, SLOT(onColorButtonToggled(bool))); connect(ui->textColorButton, SIGNAL(toggled(bool)), this, SLOT(onTextColorButtonToggled(bool))); ContextPaneWidget *parentContextWidget = qobject_cast<ContextPaneWidget*>(parentWidget()); connect(parentContextWidget->colorDialog(), SIGNAL(accepted(QColor)), this, SLOT(onColorDialogApplied(QColor))); connect(parentContextWidget->colorDialog(), SIGNAL(rejected()), this, SLOT(onColorDialogCancled())); connect(ui->fontSizeSpinBox, SIGNAL(valueChanged(int)), this, SLOT(onFontSizeChanged(int))); connect(ui->fontSizeSpinBox, SIGNAL(formatChanged()), this, SLOT(onFontFormatChanged())); connect(ui->boldButton, SIGNAL(toggled(bool)), this, SLOT(onBoldCheckedChanged(bool))); connect(ui->italicButton, SIGNAL(toggled(bool)), this, SLOT(onItalicCheckedChanged(bool))); connect(ui->underlineButton, SIGNAL(toggled(bool)), this, SLOT(onUnderlineCheckedChanged(bool))); connect(ui->strikeoutButton, SIGNAL(toggled(bool)), this, SLOT(onStrikeoutCheckedChanged(bool))); connect(ui->fontComboBox, SIGNAL(currentFontChanged(QFont)), this, SLOT(onCurrentFontChanged(QFont))); connect(ui->centerHAlignmentButton, SIGNAL(toggled(bool)), this, SLOT(onHorizontalAlignmentChanged())); connect(ui->leftAlignmentButton, SIGNAL(toggled(bool)), this, SLOT(onHorizontalAlignmentChanged())); connect(ui->rightAlignmentButton, SIGNAL(toggled(bool)), this, SLOT(onHorizontalAlignmentChanged())); connect(ui->centerVAlignmentButton, SIGNAL(toggled(bool)), this, SLOT(onVerticalAlignmentChanged())); connect(ui->topAlignmentButton, SIGNAL(toggled(bool)), this, SLOT(onVerticalAlignmentChanged())); connect(ui->bottomAlignmentButton, SIGNAL(toggled(bool)), this, SLOT(onVerticalAlignmentChanged())); connect(ui->styleComboBox, SIGNAL(currentIndexChanged(QString)), this, SLOT(onStyleComboBoxChanged(QString))); } void ContextPaneTextWidget::setProperties(QmlJS::PropertyReader *propertyReader) { if (propertyReader->hasProperty(QLatin1String("font.pointSize"))) { ui->fontSizeSpinBox->setValue(propertyReader->readProperty(QLatin1String("font.pointSize")).toInt()); ui->fontSizeSpinBox->setIsPointSize(true); } else if (!propertyReader->hasProperty(QLatin1String("font.pixelSize"))) { ui->fontSizeSpinBox->setValue(8); ui->fontSizeSpinBox->setIsPointSize(true); if (m_fontSizeTimer > 0) { killTimer(m_fontSizeTimer); m_fontSizeTimer = -1; } } if (propertyReader->hasProperty(QLatin1String("font.pixelSize"))) { ui->fontSizeSpinBox->setValue(propertyReader->readProperty(QLatin1String("font.pixelSize")).toInt()); ui->fontSizeSpinBox->setIsPixelSize(true); } if (propertyReader->hasProperty(QLatin1String("font.bold"))) { ui->boldButton->setChecked(propertyReader->readProperty(QLatin1String("font.bold")).toBool()); } else { ui->boldButton->setChecked(false); } if (propertyReader->hasProperty(QLatin1String("font.italic"))) { ui->italicButton->setChecked(propertyReader->readProperty(QLatin1String("font.italic")).toBool()); } else { ui->italicButton->setChecked(false); } if (propertyReader->hasProperty(QLatin1String("font.underline"))) { ui->underlineButton->setChecked(propertyReader->readProperty(QLatin1String("font.underline")).toBool()); } else { ui->underlineButton->setChecked(false); } if (propertyReader->hasProperty(QLatin1String("font.strikeout"))) { ui->strikeoutButton->setChecked(propertyReader->readProperty(QLatin1String("font.strikeout")).toBool()); } else { ui->strikeoutButton->setChecked(false); } if (propertyReader->hasProperty(QLatin1String("color"))) { ui->colorButton->setColor(propertyReader->readProperty("color").toString()); } else { ui->colorButton->setColor(QLatin1String("black")); } if (propertyReader->hasProperty(QLatin1String("styleColor"))) { ui->textColorButton->setColor(propertyReader->readProperty("styleColor").toString()); } else { ui->textColorButton->setColor(QLatin1String("black")); } if (propertyReader->hasProperty(QLatin1String("font.family"))) { QString familyName = propertyReader->readProperty(QLatin1String("font.family")).toString(); QFont font; font.setFamily(familyName); ui->fontComboBox->setCurrentFont(font); } if (propertyReader->hasProperty(QLatin1String("horizontalAlignment"))) { QString alignment = propertyReader->readProperty(QLatin1String("horizontalAlignment")).toString(); ui->leftAlignmentButton->setChecked(true); if (alignment == QLatin1String("Text.AlignHCenter") || alignment == "AlignHCenter") ui->centerHAlignmentButton->setChecked(true); else if (alignment == QLatin1String("Text.AlignRight") || alignment == QLatin1String("AlignRight")) ui->rightAlignmentButton->setChecked(true); } else { ui->leftAlignmentButton->setChecked(true); } if (propertyReader->hasProperty(QLatin1String("verticalAlignment"))) { QString alignment = propertyReader->readProperty(QLatin1String("verticalAlignment")).toString(); ui->bottomAlignmentButton->setChecked(true); if (alignment == QLatin1String("Text.AlignVCenter") || alignment == QLatin1String("AlignVCenter")) ui->centerVAlignmentButton->setChecked(true); else if (alignment == QLatin1String("Text.AlignTop") || alignment == QLatin1String("AlignTop")) ui->topAlignmentButton->setChecked(true); } else { ui->topAlignmentButton->setChecked(true); } if (propertyReader->hasProperty(QLatin1String("style"))) { QString style = propertyReader->readProperty(QLatin1String("style")).toString(); ui->styleComboBox->setCurrentIndex(0); if (style == QLatin1String("Text.Outline") || style == QLatin1String("Outline")) ui->styleComboBox->setCurrentIndex(1); if (style == QLatin1String("Text.Raised") || style == QLatin1String("Raised")) ui->styleComboBox->setCurrentIndex(2); else if (style == QLatin1String("Text.Sunken") || style == QLatin1String("Sunken")) ui->styleComboBox->setCurrentIndex(3); } else { ui->styleComboBox->setCurrentIndex(0); } } void ContextPaneTextWidget::setVerticalAlignmentVisible(bool b) { ui->centerVAlignmentButton->setEnabled(b); ui->topAlignmentButton->setEnabled(b); ui->bottomAlignmentButton->setEnabled(b); } void ContextPaneTextWidget::setStyleVisible(bool b) { ui->styleComboBox->setEnabled(b); ui->styleLabel->setEnabled(b); ui->textColorButton->setEnabled(b); } void ContextPaneTextWidget::onTextColorButtonToggled(bool flag) { ContextPaneWidget *parentContextWidget = qobject_cast<ContextPaneWidget*>(parentWidget()); if (flag) ui->colorButton->setChecked(false); QPoint p = mapToGlobal(ui->textColorButton->pos()); parentContextWidget->colorDialog()->setupColor(ui->textColorButton->color()); p = parentContextWidget->colorDialog()->parentWidget()->mapFromGlobal(p); parentContextWidget->onShowColorDialog(flag, p); } void ContextPaneTextWidget::onColorButtonToggled(bool flag) { if (flag) ui->textColorButton->setChecked(false); ContextPaneWidget *parentContextWidget = qobject_cast<ContextPaneWidget*>(parentWidget()); QPoint p = mapToGlobal(ui->colorButton->pos()); parentContextWidget->colorDialog()->setupColor(ui->colorButton->color()); p = parentContextWidget->colorDialog()->parentWidget()->mapFromGlobal(p); parentContextWidget->onShowColorDialog(flag, p); } void ContextPaneTextWidget::onColorDialogApplied(const QColor &) { ContextPaneWidget *parentContextWidget = qobject_cast<ContextPaneWidget*>(parentWidget()); parentContextWidget->onShowColorDialog(false, QPoint()); if (ui->textColorButton->isChecked()) emit propertyChanged(QLatin1String("styleColor"),parentContextWidget->colorDialog()->color());; //write back color if (ui->colorButton->isChecked()) emit propertyChanged(QLatin1String("color"),parentContextWidget->colorDialog()->color());; //write back color ui->textColorButton->setChecked(false); ui->colorButton->setChecked(false); } void ContextPaneTextWidget::onColorDialogCancled() { ContextPaneWidget *parentContextWidget = qobject_cast<ContextPaneWidget*>(parentWidget()); parentContextWidget->onShowColorDialog(false, QPoint()); ui->colorButton->setChecked(false); ui->colorButton->setChecked(false); } void ContextPaneTextWidget::onFontSizeChanged(int) { if (m_fontSizeTimer) killTimer(m_fontSizeTimer); m_fontSizeTimer = startTimer(200); } void ContextPaneTextWidget::onFontFormatChanged() { int size = ui->fontSizeSpinBox->value(); if (ui->fontSizeSpinBox->isPointSize()) { emit removeAndChangeProperty(QLatin1String("font.pixelSize"), QLatin1String("font.pointSize"), size); } else { emit removeAndChangeProperty(QLatin1String("font.pointSize"), QLatin1String("font.pixelSize"), size); } } void ContextPaneTextWidget::onBoldCheckedChanged(bool value) { if (value) emit propertyChanged(QLatin1String("font.bold"), value); else emit removeProperty(QLatin1String("font.bold")); } void ContextPaneTextWidget::onItalicCheckedChanged(bool value) { if (value) emit propertyChanged(QLatin1String("font.italic"), value); else emit removeProperty(QLatin1String("font.italic")); } void ContextPaneTextWidget::onUnderlineCheckedChanged(bool value) { if (value) emit propertyChanged(QLatin1String("font.underline"), value); else emit removeProperty(QLatin1String("font.underline")); } void ContextPaneTextWidget::onStrikeoutCheckedChanged(bool value) { if (value) emit propertyChanged(QLatin1String("font.strikeout"), value); else emit removeProperty(QLatin1String("font.strikeout")); } void ContextPaneTextWidget::onCurrentFontChanged(const QFont &font) { font.family(); emit propertyChanged(QLatin1String("font.family"), QVariant(QString('\"') + font.family() + QString('\"'))); } void ContextPaneTextWidget::onHorizontalAlignmentChanged() { QString alignment; if (ui->centerHAlignmentButton->isChecked()) alignment = QLatin1String("Text.AlignHCenter"); else if (ui->leftAlignmentButton->isChecked()) alignment = QLatin1String("Text.AlignLeft"); else if (ui->rightAlignmentButton->isChecked()) alignment = QLatin1String("Text.AlignRight"); if (m_horizontalAlignment != alignment) { m_horizontalAlignment = alignment; if (alignment == QLatin1String("Text.AlignLeft")) emit removeProperty(QLatin1String("horizontalAlignment")); else emit propertyChanged(QLatin1String("horizontalAlignment"), alignment); } } void ContextPaneTextWidget::onStyleComboBoxChanged(const QString &style) { if (style == QLatin1String("Normal")) emit removeProperty(QLatin1String("style")); else emit propertyChanged(QLatin1String("style"), QVariant(QLatin1String("Text.") + style)); } void ContextPaneTextWidget::onVerticalAlignmentChanged() { QString alignment; if (ui->centerVAlignmentButton->isChecked()) alignment = QLatin1String("Text.AlignVCenter"); else if (ui->topAlignmentButton->isChecked()) alignment = QLatin1String("Text.AlignTop"); else if (ui->bottomAlignmentButton->isChecked()) alignment = QLatin1String("Text.AlignBottom"); if (m_verticalAlignment != alignment) { m_verticalAlignment = alignment; if (alignment == QLatin1String("Text.AlignBottom")) emit removeProperty(QLatin1String("verticalAlignment")); else emit propertyChanged(QLatin1String("verticalAlignment"), alignment); } } ContextPaneTextWidget::~ContextPaneTextWidget() { delete ui; } void ContextPaneTextWidget::changeEvent(QEvent *e) { QWidget::changeEvent(e); switch (e->type()) { case QEvent::LanguageChange: ui->retranslateUi(this); break; default: break; } } void ContextPaneTextWidget::timerEvent(QTimerEvent *event) { if (event->timerId() == m_fontSizeTimer) { killTimer(m_fontSizeTimer); m_fontSizeTimer = -1; int value = ui->fontSizeSpinBox->value(); if (ui->fontSizeSpinBox->isPointSize()) emit propertyChanged(QLatin1String("font.pointSize"), value); else emit propertyChanged(QLatin1String("font.pixelSize"), value); } } } //QmlDesigner <commit_msg>QmlDesigner: fix text context pane<commit_after>#include "contextpanetextwidget.h" #include "contextpanewidget.h" #include "ui_contextpanetext.h" #include <qmljs/qmljspropertyreader.h> #include <QTimerEvent> namespace QmlDesigner { ContextPaneTextWidget::ContextPaneTextWidget(QWidget *parent) : QWidget(parent), ui(new Ui::ContextPaneTextWidget), m_fontSizeTimer(-1) { ui->setupUi(this); ui->boldButton->setIcon(QIcon(QLatin1String(":/qmldesigner/images/bold-h-icon.png"))); ui->italicButton->setIcon(QIcon(QLatin1String(":/qmldesigner/images/italic-h-icon.png"))); ui->underlineButton->setIcon(QIcon(QLatin1String(":/qmldesigner/images/underline-h-icon.png"))); ui->strikeoutButton->setIcon(QIcon(QLatin1String(":/qmldesigner/images/strikeout-h-icon.png"))); ui->leftAlignmentButton->setIcon(QIcon(QLatin1String(":/qmldesigner/images/alignmentleft-h-icon.png"))); ui->centerHAlignmentButton->setIcon(QIcon(QLatin1String(":/qmldesigner/images/alignmentcenterh-h-icon.png"))); ui->rightAlignmentButton->setIcon(QIcon(QLatin1String(":/qmldesigner/images/alignmentright-h-icon.png"))); ui->centerVAlignmentButton->setIcon(QIcon(QLatin1String(":/qmldesigner/images/alignmentmiddle-h-icon.png"))); ui->bottomAlignmentButton->setIcon(QIcon(QLatin1String(":/qmldesigner/images/alignmentbottom-h-icon.png"))); ui->topAlignmentButton->setIcon(QIcon(QLatin1String(":/qmldesigner/images/alignmenttop-h-icon.png"))); ui->colorButton->setShowArrow(false); ui->textColorButton->setShowArrow(false); connect(ui->colorButton, SIGNAL(toggled(bool)), this, SLOT(onColorButtonToggled(bool))); connect(ui->textColorButton, SIGNAL(toggled(bool)), this, SLOT(onTextColorButtonToggled(bool))); ContextPaneWidget *parentContextWidget = qobject_cast<ContextPaneWidget*>(parentWidget()); connect(parentContextWidget->colorDialog(), SIGNAL(accepted(QColor)), this, SLOT(onColorDialogApplied(QColor))); connect(parentContextWidget->colorDialog(), SIGNAL(rejected()), this, SLOT(onColorDialogCancled())); connect(ui->fontSizeSpinBox, SIGNAL(valueChanged(int)), this, SLOT(onFontSizeChanged(int))); connect(ui->fontSizeSpinBox, SIGNAL(formatChanged()), this, SLOT(onFontFormatChanged())); connect(ui->boldButton, SIGNAL(toggled(bool)), this, SLOT(onBoldCheckedChanged(bool))); connect(ui->italicButton, SIGNAL(toggled(bool)), this, SLOT(onItalicCheckedChanged(bool))); connect(ui->underlineButton, SIGNAL(toggled(bool)), this, SLOT(onUnderlineCheckedChanged(bool))); connect(ui->strikeoutButton, SIGNAL(toggled(bool)), this, SLOT(onStrikeoutCheckedChanged(bool))); connect(ui->fontComboBox, SIGNAL(currentFontChanged(QFont)), this, SLOT(onCurrentFontChanged(QFont))); connect(ui->centerHAlignmentButton, SIGNAL(toggled(bool)), this, SLOT(onHorizontalAlignmentChanged())); connect(ui->leftAlignmentButton, SIGNAL(toggled(bool)), this, SLOT(onHorizontalAlignmentChanged())); connect(ui->rightAlignmentButton, SIGNAL(toggled(bool)), this, SLOT(onHorizontalAlignmentChanged())); connect(ui->centerVAlignmentButton, SIGNAL(toggled(bool)), this, SLOT(onVerticalAlignmentChanged())); connect(ui->topAlignmentButton, SIGNAL(toggled(bool)), this, SLOT(onVerticalAlignmentChanged())); connect(ui->bottomAlignmentButton, SIGNAL(toggled(bool)), this, SLOT(onVerticalAlignmentChanged())); connect(ui->styleComboBox, SIGNAL(currentIndexChanged(QString)), this, SLOT(onStyleComboBoxChanged(QString))); } void ContextPaneTextWidget::setProperties(QmlJS::PropertyReader *propertyReader) { if (propertyReader->hasProperty(QLatin1String("font.pointSize"))) { ui->fontSizeSpinBox->setValue(propertyReader->readProperty(QLatin1String("font.pointSize")).toInt()); ui->fontSizeSpinBox->setIsPointSize(true); } else if (!propertyReader->hasProperty(QLatin1String("font.pixelSize"))) { ui->fontSizeSpinBox->setValue(8); ui->fontSizeSpinBox->setIsPointSize(true); } if (m_fontSizeTimer > 0) { killTimer(m_fontSizeTimer); m_fontSizeTimer = -1; } if (propertyReader->hasProperty(QLatin1String("font.pixelSize"))) { ui->fontSizeSpinBox->setValue(propertyReader->readProperty(QLatin1String("font.pixelSize")).toInt()); ui->fontSizeSpinBox->setIsPixelSize(true); } if (propertyReader->hasProperty(QLatin1String("font.bold"))) { ui->boldButton->setChecked(propertyReader->readProperty(QLatin1String("font.bold")).toBool()); } else { ui->boldButton->setChecked(false); } if (propertyReader->hasProperty(QLatin1String("font.italic"))) { ui->italicButton->setChecked(propertyReader->readProperty(QLatin1String("font.italic")).toBool()); } else { ui->italicButton->setChecked(false); } if (propertyReader->hasProperty(QLatin1String("font.underline"))) { ui->underlineButton->setChecked(propertyReader->readProperty(QLatin1String("font.underline")).toBool()); } else { ui->underlineButton->setChecked(false); } if (propertyReader->hasProperty(QLatin1String("font.strikeout"))) { ui->strikeoutButton->setChecked(propertyReader->readProperty(QLatin1String("font.strikeout")).toBool()); } else { ui->strikeoutButton->setChecked(false); } if (propertyReader->hasProperty(QLatin1String("color"))) { ui->colorButton->setColor(propertyReader->readProperty("color").toString()); } else { ui->colorButton->setColor(QLatin1String("black")); } if (propertyReader->hasProperty(QLatin1String("styleColor"))) { ui->textColorButton->setColor(propertyReader->readProperty("styleColor").toString()); } else { ui->textColorButton->setColor(QLatin1String("black")); } if (propertyReader->hasProperty(QLatin1String("font.family"))) { QString familyName = propertyReader->readProperty(QLatin1String("font.family")).toString(); QFont font; font.setFamily(familyName); ui->fontComboBox->setCurrentFont(font); } if (propertyReader->hasProperty(QLatin1String("horizontalAlignment"))) { QString alignment = propertyReader->readProperty(QLatin1String("horizontalAlignment")).toString(); ui->leftAlignmentButton->setChecked(true); if (alignment == QLatin1String("Text.AlignHCenter") || alignment == "AlignHCenter") ui->centerHAlignmentButton->setChecked(true); else if (alignment == QLatin1String("Text.AlignRight") || alignment == QLatin1String("AlignRight")) ui->rightAlignmentButton->setChecked(true); } else { ui->leftAlignmentButton->setChecked(true); } if (propertyReader->hasProperty(QLatin1String("verticalAlignment"))) { QString alignment = propertyReader->readProperty(QLatin1String("verticalAlignment")).toString(); ui->topAlignmentButton->setChecked(true); if (alignment == QLatin1String("Text.AlignVCenter") || alignment == QLatin1String("AlignVCenter")) ui->centerVAlignmentButton->setChecked(true); else if (alignment == QLatin1String("Text.AlignBottom") || alignment == QLatin1String("AlignBottom")) ui->bottomAlignmentButton->setChecked(true); } else { ui->topAlignmentButton->setChecked(true); } if (propertyReader->hasProperty(QLatin1String("style"))) { QString style = propertyReader->readProperty(QLatin1String("style")).toString(); ui->styleComboBox->setCurrentIndex(0); if (style == QLatin1String("Text.Outline") || style == QLatin1String("Outline")) ui->styleComboBox->setCurrentIndex(1); if (style == QLatin1String("Text.Raised") || style == QLatin1String("Raised")) ui->styleComboBox->setCurrentIndex(2); else if (style == QLatin1String("Text.Sunken") || style == QLatin1String("Sunken")) ui->styleComboBox->setCurrentIndex(3); } else { ui->styleComboBox->setCurrentIndex(0); } } void ContextPaneTextWidget::setVerticalAlignmentVisible(bool b) { ui->centerVAlignmentButton->setEnabled(b); ui->topAlignmentButton->setEnabled(b); ui->bottomAlignmentButton->setEnabled(b); } void ContextPaneTextWidget::setStyleVisible(bool b) { ui->styleComboBox->setEnabled(b); ui->styleLabel->setEnabled(b); ui->textColorButton->setEnabled(b); } void ContextPaneTextWidget::onTextColorButtonToggled(bool flag) { ContextPaneWidget *parentContextWidget = qobject_cast<ContextPaneWidget*>(parentWidget()); if (flag) ui->colorButton->setChecked(false); QPoint p = mapToGlobal(ui->textColorButton->pos()); parentContextWidget->colorDialog()->setupColor(ui->textColorButton->color()); p = parentContextWidget->colorDialog()->parentWidget()->mapFromGlobal(p); parentContextWidget->onShowColorDialog(flag, p); } void ContextPaneTextWidget::onColorButtonToggled(bool flag) { if (flag) ui->textColorButton->setChecked(false); ContextPaneWidget *parentContextWidget = qobject_cast<ContextPaneWidget*>(parentWidget()); QPoint p = mapToGlobal(ui->colorButton->pos()); parentContextWidget->colorDialog()->setupColor(ui->colorButton->color()); p = parentContextWidget->colorDialog()->parentWidget()->mapFromGlobal(p); parentContextWidget->onShowColorDialog(flag, p); } void ContextPaneTextWidget::onColorDialogApplied(const QColor &) { ContextPaneWidget *parentContextWidget = qobject_cast<ContextPaneWidget*>(parentWidget()); parentContextWidget->onShowColorDialog(false, QPoint()); if (ui->textColorButton->isChecked()) emit propertyChanged(QLatin1String("styleColor"),parentContextWidget->colorDialog()->color());; //write back color if (ui->colorButton->isChecked()) emit propertyChanged(QLatin1String("color"),parentContextWidget->colorDialog()->color());; //write back color ui->textColorButton->setChecked(false); ui->colorButton->setChecked(false); } void ContextPaneTextWidget::onColorDialogCancled() { ContextPaneWidget *parentContextWidget = qobject_cast<ContextPaneWidget*>(parentWidget()); parentContextWidget->onShowColorDialog(false, QPoint()); ui->colorButton->setChecked(false); ui->colorButton->setChecked(false); } void ContextPaneTextWidget::onFontSizeChanged(int) { if (m_fontSizeTimer > 0) killTimer(m_fontSizeTimer); m_fontSizeTimer = startTimer(200); } void ContextPaneTextWidget::onFontFormatChanged() { int size = ui->fontSizeSpinBox->value(); if (ui->fontSizeSpinBox->isPointSize()) { emit removeAndChangeProperty(QLatin1String("font.pixelSize"), QLatin1String("font.pointSize"), size); } else { emit removeAndChangeProperty(QLatin1String("font.pointSize"), QLatin1String("font.pixelSize"), size); } } void ContextPaneTextWidget::onBoldCheckedChanged(bool value) { if (value) emit propertyChanged(QLatin1String("font.bold"), value); else emit removeProperty(QLatin1String("font.bold")); } void ContextPaneTextWidget::onItalicCheckedChanged(bool value) { if (value) emit propertyChanged(QLatin1String("font.italic"), value); else emit removeProperty(QLatin1String("font.italic")); } void ContextPaneTextWidget::onUnderlineCheckedChanged(bool value) { if (value) emit propertyChanged(QLatin1String("font.underline"), value); else emit removeProperty(QLatin1String("font.underline")); } void ContextPaneTextWidget::onStrikeoutCheckedChanged(bool value) { if (value) emit propertyChanged(QLatin1String("font.strikeout"), value); else emit removeProperty(QLatin1String("font.strikeout")); } void ContextPaneTextWidget::onCurrentFontChanged(const QFont &font) { font.family(); emit propertyChanged(QLatin1String("font.family"), QVariant(QString('\"') + font.family() + QString('\"'))); } void ContextPaneTextWidget::onHorizontalAlignmentChanged() { QString alignment; if (ui->centerHAlignmentButton->isChecked()) alignment = QLatin1String("Text.AlignHCenter"); else if (ui->leftAlignmentButton->isChecked()) alignment = QLatin1String("Text.AlignLeft"); else if (ui->rightAlignmentButton->isChecked()) alignment = QLatin1String("Text.AlignRight"); if (m_horizontalAlignment != alignment) { m_horizontalAlignment = alignment; if (alignment == QLatin1String("Text.AlignLeft")) emit removeProperty(QLatin1String("horizontalAlignment")); else emit propertyChanged(QLatin1String("horizontalAlignment"), alignment); } } void ContextPaneTextWidget::onStyleComboBoxChanged(const QString &style) { if (style == QLatin1String("Normal")) emit removeProperty(QLatin1String("style")); else emit propertyChanged(QLatin1String("style"), QVariant(QLatin1String("Text.") + style)); } void ContextPaneTextWidget::onVerticalAlignmentChanged() { QString alignment; if (ui->centerVAlignmentButton->isChecked()) alignment = QLatin1String("Text.AlignVCenter"); else if (ui->topAlignmentButton->isChecked()) alignment = QLatin1String("Text.AlignTop"); else if (ui->bottomAlignmentButton->isChecked()) alignment = QLatin1String("Text.AlignBottom"); if (m_verticalAlignment != alignment) { m_verticalAlignment = alignment; if (alignment == QLatin1String("Text.AlignTop")) emit removeProperty(QLatin1String("verticalAlignment")); else emit propertyChanged(QLatin1String("verticalAlignment"), alignment); } } ContextPaneTextWidget::~ContextPaneTextWidget() { delete ui; } void ContextPaneTextWidget::changeEvent(QEvent *e) { QWidget::changeEvent(e); switch (e->type()) { case QEvent::LanguageChange: ui->retranslateUi(this); break; default: break; } } void ContextPaneTextWidget::timerEvent(QTimerEvent *event) { if (event->timerId() == m_fontSizeTimer) { killTimer(m_fontSizeTimer); m_fontSizeTimer = -1; int value = ui->fontSizeSpinBox->value(); if (ui->fontSizeSpinBox->isPointSize()) emit propertyChanged(QLatin1String("font.pointSize"), value); else emit propertyChanged(QLatin1String("font.pixelSize"), value); } } } //QmlDesigner <|endoftext|>
<commit_before>#ifndef __STAN__PROB__DISTRIBUTIONS__UNIVARIATE__CONTINUOUS__SCALED_INV_CHI_SQUARE_HPP__ #define __STAN__PROB__DISTRIBUTIONS__UNIVARIATE__CONTINUOUS__SCALED_INV_CHI_SQUARE_HPP__ #include <stan/agrad.hpp> #include <stan/math/error_handling.hpp> #include <stan/math/special_functions.hpp> #include <stan/meta/traits.hpp> #include <stan/prob/constants.hpp> #include <stan/prob/traits.hpp> #include <stan/prob/internal_math.hpp> namespace stan { namespace prob { /** * The log of a scaled inverse chi-squared density for y with the * specified degrees of freedom parameter and scale parameter. * \f{eqnarray*}{ y &\sim& \mbox{\sf{Inv-}}\chi^2(\nu, s^2) \\ \log (p (y \,|\, \nu, s)) &=& \log \left( \frac{(\nu / 2)^{\nu / 2}}{\Gamma (\nu / 2)} s^\nu y^{- (\nu / 2 + 1)} \exp^{-\nu s^2 / (2y)} \right) \\ &=& \frac{\nu}{2} \log(\frac{\nu}{2}) - \log (\Gamma (\nu / 2)) + \nu \log(s) - (\frac{\nu}{2} + 1) \log(y) - \frac{\nu s^2}{2y} \\ & & \mathrm{ where } \; y > 0 \f} * @param y A scalar variable. * @param nu Degrees of freedom. * @param s Scale parameter. * @throw std::domain_error if nu is not greater than 0 * @throw std::domain_error if s is not greater than 0. * @throw std::domain_error if y is not greater than 0. * @tparam T_y Type of scalar. * @tparam T_dof Type of degrees of freedom. */ template <bool propto, typename T_y, typename T_dof, typename T_scale, class Policy> typename return_type<T_y,T_dof,T_scale>::type scaled_inv_chi_square_log(const T_y& y, const T_dof& nu, const T_scale& s, const Policy&) { static const char* function = "stan::prob::scaled_inv_chi_square_log(%1%)"; using stan::math::check_finite; using stan::math::check_positive; using stan::math::check_not_nan; using stan::math::check_consistent_sizes; using stan::math::value_of; // check if any vectors are zero length if (!(stan::length(y) && stan::length(nu) && stan::length(s))) return 0.0; typename return_type<T_y,T_dof,T_scale>::type logp(0.0); if (!check_not_nan(function, y, "Random variable", &logp, Policy())) return logp; if (!check_finite(function, nu, "Degrees of freedom parameter", &logp, Policy())) return logp; if (!check_positive(function, nu, "Degrees of freedom parameter", &logp, Policy())) return logp; if (!check_finite(function, s, "Scale parameter", &logp, Policy())) return logp; if (!check_positive(function, s, "Scale parameter", &logp, Policy())) return logp; if (!(check_consistent_sizes(function, y,nu,s, "Random variable","Degrees of freedom parameter","Scale parameter", &logp, Policy()))) return logp; // check if no variables are involved and prop-to if (!include_summand<propto,T_y,T_dof,T_scale>::value) return 0.0; VectorView<const T_y> y_vec(y); VectorView<const T_dof> nu_vec(nu); VectorView<const T_scale> s_vec(s); size_t N = max_size(y, nu, s); for (size_t n = 0; n < N; n++) { if (value_of(y_vec[n]) <= 0) return LOG_ZERO; } using stan::math::multiply_log; using stan::math::square; for (size_t n = 0; n < N; n++) { if (include_summand<propto,T_dof>::value) { typename return_type<T_dof>::type half_nu = 0.5 * nu_vec[n]; logp += multiply_log(half_nu,half_nu) - lgamma(half_nu); } if (include_summand<propto,T_dof,T_scale>::value) logp += nu_vec[n] * log(s_vec[n]); if (include_summand<propto,T_dof,T_y>::value) logp -= multiply_log(nu_vec[n]*0.5+1.0, y_vec[n]); if (include_summand<propto,T_dof,T_y,T_scale>::value) logp -= nu_vec[n] * 0.5 * square(s_vec[n]) / y_vec[n]; } return logp; } template <bool propto, typename T_y, typename T_dof, typename T_scale> inline typename return_type<T_y,T_dof,T_scale>::type scaled_inv_chi_square_log(const T_y& y, const T_dof& nu, const T_scale& s) { return scaled_inv_chi_square_log<propto>(y,nu,s, stan::math::default_policy()); } template <typename T_y, typename T_dof, typename T_scale, class Policy> inline typename return_type<T_y,T_dof,T_scale>::type scaled_inv_chi_square_log(const T_y& y, const T_dof& nu, const T_scale& s, const Policy&) { return scaled_inv_chi_square_log<false>(y,nu,s,Policy()); } template <typename T_y, typename T_dof, typename T_scale> inline typename return_type<T_y,T_dof,T_scale>::type scaled_inv_chi_square_log(const T_y& y, const T_dof& nu, const T_scale& s) { return scaled_inv_chi_square_log<false>(y,nu,s, stan::math::default_policy()); } /** * The CDF of a scaled inverse chi-squared density for y with the * specified degrees of freedom parameter and scale parameter. * * @param y A scalar variable. * @param nu Degrees of freedom. * @param s Scale parameter. * @throw std::domain_error if nu is not greater than 0 * @throw std::domain_error if s is not greater than 0. * @throw std::domain_error if y is not greater than 0. * @tparam T_y Type of scalar. * @tparam T_dof Type of degrees of freedom. */ template <typename T_y, typename T_dof, typename T_scale, class Policy> typename return_type<T_y, T_dof, T_scale>::type scaled_inv_chi_square_cdf(const T_y& y, const T_dof& nu, const T_scale& s, const Policy&) { static const char* function = "stan::prob::scaled_inv_chi_square_log(%1%)"; using stan::math::check_finite; using stan::math::check_positive; using stan::math::check_not_nan; using stan::math::check_consistent_sizes; using boost::math::tools::promote_args; double P(1.0); if (!check_not_nan(function, y, "Random variable", &P, Policy())) return P; if (!check_positive(function, y, "Random variable", &P, Policy())) return P; if (!check_finite(function, nu, "Degrees of freedom parameter", &P, Policy())) return P; if (!check_positive(function, nu, "Degrees of freedom parameter", &P, Policy())) return P; if (!check_finite(function, s, "Scale parameter", &P, Policy())) return P; if (!check_positive(function, s, "Scale parameter", &P, Policy())) return P; if (!(check_consistent_sizes(function, y, nu, s, "Random variable", "Degrees of freedom parameter", "Scale parameter", &P, Policy()))) return P; // Wrap arguments in vectors VectorView<const T_y> y_vec(y); VectorView<const T_dof> nu_vec(nu); VectorView<const T_scale> s_vec(s); size_t N = max_size(y, nu, s); agrad::OperandsAndPartials<T_y, T_dof, T_scale> operands_and_partials(y, nu, s); std::fill(operands_and_partials.all_partials, operands_and_partials.all_partials + operands_and_partials.nvaris, 0.0); // Compute CDF and its gradients using stan::math::value_of; using boost::math::gamma_p_derivative; using boost::math::gamma_q; using boost::math::digamma; using boost::math::tgamma; // Cache a few expensive function calls if nu is a parameter DoubleVectorView<!is_constant_struct<T_dof>::value, T_dof> gamma_vec(stan::length(nu)); DoubleVectorView<!is_constant_struct<T_dof>::value, T_dof> digamma_vec(stan::length(nu)); if (!is_constant_struct<T_dof>::value) { for (size_t i = 0; i < stan::length(nu); i++) { const double half_nu_dbl = 0.5 * value_of(nu_vec[i]); gamma_vec[i] = tgamma(half_nu_dbl); digamma_vec[i] = digamma(half_nu_dbl); } } // Compute vectorized CDF and gradient for (size_t n = 0; n < N; n++) { // Pull out values const double y_dbl = value_of(y_vec[n]); const double y_inv_dbl = 1.0 / y_dbl; const double half_nu_dbl = 0.5 * value_of(nu_vec[n]); const double s_dbl = value_of(s_vec[n]); const double half_s2_overx_dbl = 0.5 * s_dbl * s_dbl * y_inv_dbl; const double half_nu_s2_overx_dbl = 2.0 * half_nu_dbl * half_s2_overx_dbl; // Compute const double Pn = gamma_q(half_nu_dbl, half_nu_s2_overx_dbl); P *= Pn; if (!is_constant_struct<T_y>::value) operands_and_partials.d_x1[n] += half_nu_s2_overx_dbl * y_inv_dbl * gamma_p_derivative(half_nu_dbl, half_nu_s2_overx_dbl) / Pn; if (!is_constant_struct<T_dof>::value) operands_and_partials.d_x2[n] += (0.5 * stan::math::gradRegIncGamma(half_nu_dbl, half_nu_s2_overx_dbl, gamma_vec[n], digamma_vec[n]) - half_s2_overx_dbl * gamma_p_derivative(half_nu_dbl, half_nu_s2_overx_dbl) ) / Pn; if (!is_constant_struct<T_scale>::value) operands_and_partials.d_x3[n] += - 2.0 * half_nu_dbl * s_dbl * y_inv_dbl * gamma_p_derivative(half_nu_dbl, half_nu_s2_overx_dbl) / Pn; } for (size_t n = 0; n < N; n++) { if (!is_constant_struct<T_y>::value) operands_and_partials.d_x1[n] *= P; if (!is_constant_struct<T_dof>::value) operands_and_partials.d_x2[n] *= P; if (!is_constant_struct<T_scale>::value) operands_and_partials.d_x3[n] *= P; } return operands_and_partials.to_var(P); } template <typename T_y, typename T_dof, typename T_scale> inline typename return_type<T_y, T_dof, T_scale>::type scaled_inv_chi_square_cdf(const T_y& y, const T_dof& nu, const T_scale& s) { return scaled_inv_chi_square_cdf(y, nu, s, stan::math::default_policy()); } } } #endif <commit_msg>refactoring scaled_inv_chi_square distribution<commit_after>#ifndef __STAN__PROB__DISTRIBUTIONS__UNIVARIATE__CONTINUOUS__SCALED_INV_CHI_SQUARE_HPP__ #define __STAN__PROB__DISTRIBUTIONS__UNIVARIATE__CONTINUOUS__SCALED_INV_CHI_SQUARE_HPP__ #include <stan/agrad.hpp> #include <stan/math/error_handling.hpp> #include <stan/math/special_functions.hpp> #include <stan/meta/traits.hpp> #include <stan/prob/constants.hpp> #include <stan/prob/traits.hpp> #include <stan/prob/internal_math.hpp> namespace stan { namespace prob { /** * The log of a scaled inverse chi-squared density for y with the * specified degrees of freedom parameter and scale parameter. * \f{eqnarray*}{ y &\sim& \mbox{\sf{Inv-}}\chi^2(\nu, s^2) \\ \log (p (y \,|\, \nu, s)) &=& \log \left( \frac{(\nu / 2)^{\nu / 2}}{\Gamma (\nu / 2)} s^\nu y^{- (\nu / 2 + 1)} \exp^{-\nu s^2 / (2y)} \right) \\ &=& \frac{\nu}{2} \log(\frac{\nu}{2}) - \log (\Gamma (\nu / 2)) + \nu \log(s) - (\frac{\nu}{2} + 1) \log(y) - \frac{\nu s^2}{2y} \\ & & \mathrm{ where } \; y > 0 \f} * @param y A scalar variable. * @param nu Degrees of freedom. * @param s Scale parameter. * @throw std::domain_error if nu is not greater than 0 * @throw std::domain_error if s is not greater than 0. * @throw std::domain_error if y is not greater than 0. * @tparam T_y Type of scalar. * @tparam T_dof Type of degrees of freedom. */ template <bool propto, typename T_y, typename T_dof, typename T_scale, class Policy> typename return_type<T_y,T_dof,T_scale>::type scaled_inv_chi_square_log(const T_y& y, const T_dof& nu, const T_scale& s, const Policy&) { static const char* function = "stan::prob::scaled_inv_chi_square_log(%1%)"; using stan::math::check_finite; using stan::math::check_positive; using stan::math::check_not_nan; using stan::math::check_consistent_sizes; using stan::math::value_of; // check if any vectors are zero length if (!(stan::length(y) && stan::length(nu) && stan::length(s))) return 0.0; typename return_type<T_y,T_dof,T_scale>::type logp(0.0); if (!check_not_nan(function, y, "Random variable", &logp, Policy())) return logp; if (!check_finite(function, nu, "Degrees of freedom parameter", &logp, Policy())) return logp; if (!check_positive(function, nu, "Degrees of freedom parameter", &logp, Policy())) return logp; if (!check_finite(function, s, "Scale parameter", &logp, Policy())) return logp; if (!check_positive(function, s, "Scale parameter", &logp, Policy())) return logp; if (!(check_consistent_sizes(function, y,nu,s, "Random variable","Degrees of freedom parameter","Scale parameter", &logp, Policy()))) return logp; // check if no variables are involved and prop-to if (!include_summand<propto,T_y,T_dof,T_scale>::value) return 0.0; VectorView<const T_y> y_vec(y); VectorView<const T_dof> nu_vec(nu); VectorView<const T_scale> s_vec(s); size_t N = max_size(y, nu, s); for (size_t n = 0; n < N; n++) { if (value_of(y_vec[n]) <= 0) return LOG_ZERO; } using stan::math::multiply_log; using stan::math::square; for (size_t n = 0; n < N; n++) { if (include_summand<propto,T_dof>::value) { typename return_type<T_dof>::type half_nu = 0.5 * nu_vec[n]; logp += multiply_log(half_nu,half_nu) - lgamma(half_nu); } if (include_summand<propto,T_dof,T_scale>::value) logp += nu_vec[n] * log(s_vec[n]); if (include_summand<propto,T_dof,T_y>::value) logp -= multiply_log(nu_vec[n]*0.5+1.0, y_vec[n]); if (include_summand<propto,T_dof,T_y,T_scale>::value) logp -= nu_vec[n] * 0.5 * square(s_vec[n]) / y_vec[n]; } return logp; } template <bool propto, typename T_y, typename T_dof, typename T_scale> inline typename return_type<T_y,T_dof,T_scale>::type scaled_inv_chi_square_log(const T_y& y, const T_dof& nu, const T_scale& s) { return scaled_inv_chi_square_log<propto>(y,nu,s, stan::math::default_policy()); } template <typename T_y, typename T_dof, typename T_scale, class Policy> inline typename return_type<T_y,T_dof,T_scale>::type scaled_inv_chi_square_log(const T_y& y, const T_dof& nu, const T_scale& s, const Policy&) { return scaled_inv_chi_square_log<false>(y,nu,s,Policy()); } template <typename T_y, typename T_dof, typename T_scale> inline typename return_type<T_y,T_dof,T_scale>::type scaled_inv_chi_square_log(const T_y& y, const T_dof& nu, const T_scale& s) { return scaled_inv_chi_square_log<false>(y,nu,s, stan::math::default_policy()); } /** * The CDF of a scaled inverse chi-squared density for y with the * specified degrees of freedom parameter and scale parameter. * * @param y A scalar variable. * @param nu Degrees of freedom. * @param s Scale parameter. * @throw std::domain_error if nu is not greater than 0 * @throw std::domain_error if s is not greater than 0. * @throw std::domain_error if y is not greater than 0. * @tparam T_y Type of scalar. * @tparam T_dof Type of degrees of freedom. */ template <typename T_y, typename T_dof, typename T_scale, class Policy> typename return_type<T_y, T_dof, T_scale>::type scaled_inv_chi_square_cdf(const T_y& y, const T_dof& nu, const T_scale& s, const Policy&) { static const char* function = "stan::prob::scaled_inv_chi_square_log(%1%)"; using stan::math::check_finite; using stan::math::check_positive; using stan::math::check_not_nan; using stan::math::check_consistent_sizes; using boost::math::tools::promote_args; double P(1.0); if (!check_not_nan(function, y, "Random variable", &P, Policy())) return P; if (!check_positive(function, y, "Random variable", &P, Policy())) return P; if (!check_finite(function, nu, "Degrees of freedom parameter", &P, Policy())) return P; if (!check_positive(function, nu, "Degrees of freedom parameter", &P, Policy())) return P; if (!check_finite(function, s, "Scale parameter", &P, Policy())) return P; if (!check_positive(function, s, "Scale parameter", &P, Policy())) return P; if (!(check_consistent_sizes(function, y, nu, s, "Random variable", "Degrees of freedom parameter", "Scale parameter", &P, Policy()))) return P; // Wrap arguments in vectors VectorView<const T_y> y_vec(y); VectorView<const T_dof> nu_vec(nu); VectorView<const T_scale> s_vec(s); size_t N = max_size(y, nu, s); agrad::OperandsAndPartials<T_y, T_dof, T_scale> operands_and_partials(y, nu, s); std::fill(operands_and_partials.all_partials, operands_and_partials.all_partials + operands_and_partials.nvaris, 0.0); // Compute CDF and its gradients using stan::math::value_of; using boost::math::gamma_p_derivative; using boost::math::gamma_q; using boost::math::digamma; using boost::math::tgamma; // Cache a few expensive function calls if nu is a parameter DoubleVectorView<!is_constant_struct<T_dof>::value,is_vector<T_dof>::value> gamma_vec(stan::length(nu)); DoubleVectorView<!is_constant_struct<T_dof>::value,is_vector<T_dof>::value> digamma_vec(stan::length(nu)); if (!is_constant_struct<T_dof>::value) { for (size_t i = 0; i < stan::length(nu); i++) { const double half_nu_dbl = 0.5 * value_of(nu_vec[i]); gamma_vec[i] = tgamma(half_nu_dbl); digamma_vec[i] = digamma(half_nu_dbl); } } // Compute vectorized CDF and gradient for (size_t n = 0; n < N; n++) { // Pull out values const double y_dbl = value_of(y_vec[n]); const double y_inv_dbl = 1.0 / y_dbl; const double half_nu_dbl = 0.5 * value_of(nu_vec[n]); const double s_dbl = value_of(s_vec[n]); const double half_s2_overx_dbl = 0.5 * s_dbl * s_dbl * y_inv_dbl; const double half_nu_s2_overx_dbl = 2.0 * half_nu_dbl * half_s2_overx_dbl; // Compute const double Pn = gamma_q(half_nu_dbl, half_nu_s2_overx_dbl); P *= Pn; if (!is_constant_struct<T_y>::value) operands_and_partials.d_x1[n] += half_nu_s2_overx_dbl * y_inv_dbl * gamma_p_derivative(half_nu_dbl, half_nu_s2_overx_dbl) / Pn; if (!is_constant_struct<T_dof>::value) operands_and_partials.d_x2[n] += (0.5 * stan::math::gradRegIncGamma(half_nu_dbl, half_nu_s2_overx_dbl, gamma_vec[n], digamma_vec[n]) - half_s2_overx_dbl * gamma_p_derivative(half_nu_dbl, half_nu_s2_overx_dbl) ) / Pn; if (!is_constant_struct<T_scale>::value) operands_and_partials.d_x3[n] += - 2.0 * half_nu_dbl * s_dbl * y_inv_dbl * gamma_p_derivative(half_nu_dbl, half_nu_s2_overx_dbl) / Pn; } for (size_t n = 0; n < N; n++) { if (!is_constant_struct<T_y>::value) operands_and_partials.d_x1[n] *= P; if (!is_constant_struct<T_dof>::value) operands_and_partials.d_x2[n] *= P; if (!is_constant_struct<T_scale>::value) operands_and_partials.d_x3[n] *= P; } return operands_and_partials.to_var(P); } template <typename T_y, typename T_dof, typename T_scale> inline typename return_type<T_y, T_dof, T_scale>::type scaled_inv_chi_square_cdf(const T_y& y, const T_dof& nu, const T_scale& s) { return scaled_inv_chi_square_cdf(y, nu, s, stan::math::default_policy()); } } } #endif <|endoftext|>
<commit_before>/* * NotebookAlternateEngines.cpp * * Copyright (C) 2009-16 by RStudio, Inc. * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #include "SessionRmdNotebook.hpp" #include "SessionExecuteChunkOperation.hpp" #include "NotebookCache.hpp" #include "NotebookAlternateEngines.hpp" #include <boost/algorithm/string.hpp> #include <core/StringUtils.hpp> #include <core/Algorithm.hpp> #include <core/Exec.hpp> #include <core/json/JsonRpc.hpp> #include <r/RExec.hpp> using namespace rstudio::core; namespace rstudio { namespace session { namespace modules { namespace rmarkdown { namespace notebook { namespace { class ChunkExecCompletedScope : boost::noncopyable { public: ChunkExecCompletedScope(const std::string& docId, const std::string& chunkId) : docId_(docId), chunkId_(chunkId) { } ~ChunkExecCompletedScope() { events().onChunkExecCompleted( docId_, chunkId_, notebookCtxId()); } private: std::string docId_; std::string chunkId_; }; Error prepareCacheConsoleOutputFile(const std::string& docId, const std::string& chunkId, const std::string& nbCtxId, FilePath* pChunkOutputFile) { // forward declare error Error error; // prepare chunk directory FilePath cachePath = notebook::chunkOutputPath( docId, chunkId, notebook::ContextExact); error = cachePath.resetDirectory(); if (error) return error; // prepare cache console output file *pChunkOutputFile = notebook::chunkOutputFile(docId, chunkId, nbCtxId, ChunkOutputText); return Success(); } void chunkConsoleOutputHandler(module_context::ConsoleOutputType type, const std::string& output, const FilePath& targetPath) { using namespace module_context; Error error = appendConsoleOutput( type == ConsoleOutputNormal ? kChunkConsoleOutput : kChunkConsoleError, output, targetPath); if (error) LOG_ERROR(error); } void reportChunkExecutionError(const std::string& docId, const std::string& chunkId, const std::string& nbCtxId, const std::string& message, const FilePath& targetPath) { // emit chunk error chunkConsoleOutputHandler( module_context::ConsoleOutputError, message, targetPath); // forward failure to chunk enqueueChunkOutput( docId, chunkId, nbCtxId, 0, // no ordinal needed ChunkOutputText, targetPath); } Error executeRcppEngineChunk(const std::string& docId, const std::string& chunkId, const std::string& nbCtxId, const std::string& code, const std::map<std::string, std::string>& options) { // forward declare error Error error; // always ensure we emit a 'execution complete' event on exit ChunkExecCompletedScope execScope(docId, chunkId); // prepare cache output file (use tempfile on failure) FilePath targetPath = module_context::tempFile("rcpp-cache", ""); error = prepareCacheConsoleOutputFile(docId, chunkId, nbCtxId, &targetPath); if (error) LOG_ERROR(error); // capture console output, error boost::signals::scoped_connection consoleHandler = module_context::events().onConsoleOutput.connect( boost::bind(chunkConsoleOutputHandler, _1, _2, targetPath)); // call Rcpp::sourceCpp on code std::string escaped = boost::regex_replace( code, boost::regex("(\\\\|\")"), "\\\\$1"); std::string execCode = "Rcpp::sourceCpp(code = \"" + escaped + "\")"; // write input code to cache error = appendConsoleOutput( kChunkConsoleInput, code, targetPath); if (error) LOG_ERROR(error); // execute code (output captured on success; on failure we // explicitly forward the error message returned) error = r::exec::executeString(execCode); if (error) { chunkConsoleOutputHandler(module_context::ConsoleOutputError, r::endUserErrorMessage(error), targetPath); } // forward success / failure to chunk enqueueChunkOutput( docId, chunkId, nbCtxId, 0, // no ordinal needed ChunkOutputText, targetPath); return error; } void reportStanExecutionError(const std::string& docId, const std::string& chunkId, const std::string& nbCtxId, const FilePath& targetPath) { std::string message = "engine.opts$x must be a character string providing a " "name for the returned `stanmodel` object"; reportChunkExecutionError(docId, chunkId, nbCtxId, message, targetPath); } Error executeStanEngineChunk(const std::string& docId, const std::string& chunkId, const std::string& nbCtxId, const std::string& code, const std::map<std::string, std::string>& options) { // forward-declare error Error error; // ensure we always emit an execution complete event on exit ChunkExecCompletedScope execScope(docId, chunkId); // prepare console output file -- use tempfile on failure FilePath targetPath = module_context::tempFile("stan-cache-", ""); error = prepareCacheConsoleOutputFile(docId, chunkId, nbCtxId, &targetPath); if (error) LOG_ERROR(error); // capture console output, error boost::signals::scoped_connection consoleHandler = module_context::events().onConsoleOutput.connect( boost::bind(chunkConsoleOutputHandler, _1, _2, targetPath)); // write code to file FilePath tempFile = module_context::tempFile("stan-", ".stan"); error = writeStringToFile(tempFile, code); if (error) { reportChunkExecutionError( docId, chunkId, nbCtxId, r::endUserErrorMessage(error), targetPath); LOG_ERROR(error); return Success(); } RemoveOnExitScope removeOnExitScope(tempFile, ERROR_LOCATION); // ensure existence of 'engine.opts' with 'x' parameter if (!options.count("engine.opts")) { reportStanExecutionError(docId, chunkId, nbCtxId, targetPath); return Success(); } // evaluate engine options (so we can pass them through to stan call) r::sexp::Protect protect; SEXP engineOptsSEXP = R_NilValue; error = r::exec::evaluateString( options.at("engine.opts"), &engineOptsSEXP, &protect); if (error) { reportStanExecutionError(docId, chunkId, nbCtxId, targetPath); return Success(); } // construct call to 'stan_model' r::exec::RFunction fStanEngine("rstan:::stan_model"); std::vector<std::string> engineOptsNames; error = r::sexp::getNames(engineOptsSEXP, &engineOptsNames); if (error) { reportStanExecutionError(docId, chunkId, nbCtxId, targetPath); return Success(); } // build parameters std::string modelName; for (std::size_t i = 0, n = r::sexp::length(engineOptsSEXP); i < n; ++i) { // skip 'x' engine option (this is the variable we wish to assign to // after evaluating the stan model) if (engineOptsNames[i] == "x") { modelName = r::sexp::asString(VECTOR_ELT(engineOptsSEXP, i)); continue; } fStanEngine.addParam( engineOptsNames[i], VECTOR_ELT(engineOptsSEXP, i)); } // if no model name was set, return error message if (modelName.empty()) { reportStanExecutionError(docId, chunkId, nbCtxId, targetPath); return Success(); } // if the 'file' option was not set, set it explicitly if (!core::algorithm::contains(engineOptsNames, "file")) fStanEngine.addParam("file", string_utils::utf8ToSystem(tempFile.absolutePath())); // evaluate stan_model call SEXP stanModelSEXP = R_NilValue; error = fStanEngine.call(&stanModelSEXP, &protect); if (error) { std::string msg = r::endUserErrorMessage(error); reportChunkExecutionError(docId, chunkId, nbCtxId, msg, targetPath); return Success(); } // assign in global env on success if (stanModelSEXP != R_NilValue) { r::exec::RFunction assign("base:::assign"); assign.addParam("x", modelName); assign.addParam("value", stanModelSEXP); error = assign.call(); if (error) { std::string msg = r::endUserErrorMessage(error); reportChunkExecutionError(docId, chunkId, nbCtxId, msg, targetPath); LOG_ERROR(error); return Success(); } } // forward success / failure to chunk enqueueChunkOutput( docId, chunkId, notebookCtxId(), 0, // no ordinal needed ChunkOutputText, targetPath); return Success(); } Error executeSqlEngineChunk(const std::string& docId, const std::string& chunkId, const std::string& nbCtxId, const std::string& code, const json::Object& options) { Error error; // ensure we always emit an execution complete event on exit ChunkExecCompletedScope execScope(docId, chunkId); FilePath targetPath = notebook::chunkOutputFile(docId, chunkId, nbCtxId, ChunkOutputData); // run sql and save result error = r::exec::RFunction( ".rs.runSqlForDataCapture", code, string_utils::utf8ToSystem(targetPath.absolutePath()), options).call(); if (error) { std::string message = "Failed to execute SQL chunk"; reportChunkExecutionError(docId, chunkId, nbCtxId, message, targetPath); return Success(); } // forward success / failure to chunk enqueueChunkOutput( docId, chunkId, notebookCtxId(), 0, // no ordinal needed ChunkOutputData, targetPath); return Success(); } Error interruptEngineChunk(const json::JsonRpcRequest& request, json::JsonRpcResponse* pResponse) { std::string docId, chunkId; Error error = json::readParams(request.params, &docId, &chunkId); if (error) { LOG_ERROR(error); return error; } interruptChunk(docId, chunkId); return Success(); } } // anonymous namespace Error executeAlternateEngineChunk(const std::string& docId, const std::string& chunkId, const std::string& nbCtxId, const std::string& engine, const std::string& code, const json::Object& jsonChunkOptions) { // read json chunk options std::map<std::string, std::string> options; for (json::Object::const_iterator it = jsonChunkOptions.begin(); it != jsonChunkOptions.end(); ++it) { if (it->second.type() == json::StringType) options[it->first] = it->second.get_str(); } // handle Rcpp specially if (engine == "Rcpp") return executeRcppEngineChunk(docId, chunkId, nbCtxId, code, options); else if (engine == "stan") return executeStanEngineChunk(docId, chunkId, nbCtxId, code, options); else if (engine == "sql") return executeSqlEngineChunk(docId, chunkId, nbCtxId, code, jsonChunkOptions); runChunk(docId, chunkId, nbCtxId, engine, code); return Success(); } Error initAlternateEngines() { using namespace module_context; ExecBlock initBlock; initBlock.addFunctions() (bind(registerRpcMethod, "interrupt_chunk", interruptEngineChunk)); return initBlock.execute(); } } // namespace notebook } // namespace rmarkdown } // namespace modules } // namespace session } // namespace rstudio <commit_msg>check for DBI version in SQL engine<commit_after>/* * NotebookAlternateEngines.cpp * * Copyright (C) 2009-16 by RStudio, Inc. * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #include "SessionRmdNotebook.hpp" #include "SessionExecuteChunkOperation.hpp" #include "NotebookCache.hpp" #include "NotebookAlternateEngines.hpp" #include <boost/algorithm/string.hpp> #include <core/StringUtils.hpp> #include <core/Algorithm.hpp> #include <core/Exec.hpp> #include <core/json/JsonRpc.hpp> #include <r/RExec.hpp> using namespace rstudio::core; namespace rstudio { namespace session { namespace modules { namespace rmarkdown { namespace notebook { namespace { class ChunkExecCompletedScope : boost::noncopyable { public: ChunkExecCompletedScope(const std::string& docId, const std::string& chunkId) : docId_(docId), chunkId_(chunkId) { } ~ChunkExecCompletedScope() { events().onChunkExecCompleted( docId_, chunkId_, notebookCtxId()); } private: std::string docId_; std::string chunkId_; }; Error prepareCacheConsoleOutputFile(const std::string& docId, const std::string& chunkId, const std::string& nbCtxId, FilePath* pChunkOutputFile) { // forward declare error Error error; // prepare chunk directory FilePath cachePath = notebook::chunkOutputPath( docId, chunkId, notebook::ContextExact); error = cachePath.resetDirectory(); if (error) return error; // prepare cache console output file *pChunkOutputFile = notebook::chunkOutputFile(docId, chunkId, nbCtxId, ChunkOutputText); return Success(); } void chunkConsoleOutputHandler(module_context::ConsoleOutputType type, const std::string& output, const FilePath& targetPath) { using namespace module_context; Error error = appendConsoleOutput( type == ConsoleOutputNormal ? kChunkConsoleOutput : kChunkConsoleError, output, targetPath); if (error) LOG_ERROR(error); } void reportChunkExecutionError(const std::string& docId, const std::string& chunkId, const std::string& nbCtxId, const std::string& message, const FilePath& targetPath) { // emit chunk error chunkConsoleOutputHandler( module_context::ConsoleOutputError, message, targetPath); // forward failure to chunk enqueueChunkOutput( docId, chunkId, nbCtxId, 0, // no ordinal needed ChunkOutputText, targetPath); } Error executeRcppEngineChunk(const std::string& docId, const std::string& chunkId, const std::string& nbCtxId, const std::string& code, const std::map<std::string, std::string>& options) { // forward declare error Error error; // always ensure we emit a 'execution complete' event on exit ChunkExecCompletedScope execScope(docId, chunkId); // prepare cache output file (use tempfile on failure) FilePath targetPath = module_context::tempFile("rcpp-cache", ""); error = prepareCacheConsoleOutputFile(docId, chunkId, nbCtxId, &targetPath); if (error) LOG_ERROR(error); // capture console output, error boost::signals::scoped_connection consoleHandler = module_context::events().onConsoleOutput.connect( boost::bind(chunkConsoleOutputHandler, _1, _2, targetPath)); // call Rcpp::sourceCpp on code std::string escaped = boost::regex_replace( code, boost::regex("(\\\\|\")"), "\\\\$1"); std::string execCode = "Rcpp::sourceCpp(code = \"" + escaped + "\")"; // write input code to cache error = appendConsoleOutput( kChunkConsoleInput, code, targetPath); if (error) LOG_ERROR(error); // execute code (output captured on success; on failure we // explicitly forward the error message returned) error = r::exec::executeString(execCode); if (error) { chunkConsoleOutputHandler(module_context::ConsoleOutputError, r::endUserErrorMessage(error), targetPath); } // forward success / failure to chunk enqueueChunkOutput( docId, chunkId, nbCtxId, 0, // no ordinal needed ChunkOutputText, targetPath); return error; } void reportStanExecutionError(const std::string& docId, const std::string& chunkId, const std::string& nbCtxId, const FilePath& targetPath) { std::string message = "engine.opts$x must be a character string providing a " "name for the returned `stanmodel` object"; reportChunkExecutionError(docId, chunkId, nbCtxId, message, targetPath); } Error executeStanEngineChunk(const std::string& docId, const std::string& chunkId, const std::string& nbCtxId, const std::string& code, const std::map<std::string, std::string>& options) { // forward-declare error Error error; // ensure we always emit an execution complete event on exit ChunkExecCompletedScope execScope(docId, chunkId); // prepare console output file -- use tempfile on failure FilePath targetPath = module_context::tempFile("stan-cache-", ""); error = prepareCacheConsoleOutputFile(docId, chunkId, nbCtxId, &targetPath); if (error) LOG_ERROR(error); // capture console output, error boost::signals::scoped_connection consoleHandler = module_context::events().onConsoleOutput.connect( boost::bind(chunkConsoleOutputHandler, _1, _2, targetPath)); // write code to file FilePath tempFile = module_context::tempFile("stan-", ".stan"); error = writeStringToFile(tempFile, code); if (error) { reportChunkExecutionError( docId, chunkId, nbCtxId, r::endUserErrorMessage(error), targetPath); LOG_ERROR(error); return Success(); } RemoveOnExitScope removeOnExitScope(tempFile, ERROR_LOCATION); // ensure existence of 'engine.opts' with 'x' parameter if (!options.count("engine.opts")) { reportStanExecutionError(docId, chunkId, nbCtxId, targetPath); return Success(); } // evaluate engine options (so we can pass them through to stan call) r::sexp::Protect protect; SEXP engineOptsSEXP = R_NilValue; error = r::exec::evaluateString( options.at("engine.opts"), &engineOptsSEXP, &protect); if (error) { reportStanExecutionError(docId, chunkId, nbCtxId, targetPath); return Success(); } // construct call to 'stan_model' r::exec::RFunction fStanEngine("rstan:::stan_model"); std::vector<std::string> engineOptsNames; error = r::sexp::getNames(engineOptsSEXP, &engineOptsNames); if (error) { reportStanExecutionError(docId, chunkId, nbCtxId, targetPath); return Success(); } // build parameters std::string modelName; for (std::size_t i = 0, n = r::sexp::length(engineOptsSEXP); i < n; ++i) { // skip 'x' engine option (this is the variable we wish to assign to // after evaluating the stan model) if (engineOptsNames[i] == "x") { modelName = r::sexp::asString(VECTOR_ELT(engineOptsSEXP, i)); continue; } fStanEngine.addParam( engineOptsNames[i], VECTOR_ELT(engineOptsSEXP, i)); } // if no model name was set, return error message if (modelName.empty()) { reportStanExecutionError(docId, chunkId, nbCtxId, targetPath); return Success(); } // if the 'file' option was not set, set it explicitly if (!core::algorithm::contains(engineOptsNames, "file")) fStanEngine.addParam("file", string_utils::utf8ToSystem(tempFile.absolutePath())); // evaluate stan_model call SEXP stanModelSEXP = R_NilValue; error = fStanEngine.call(&stanModelSEXP, &protect); if (error) { std::string msg = r::endUserErrorMessage(error); reportChunkExecutionError(docId, chunkId, nbCtxId, msg, targetPath); return Success(); } // assign in global env on success if (stanModelSEXP != R_NilValue) { r::exec::RFunction assign("base:::assign"); assign.addParam("x", modelName); assign.addParam("value", stanModelSEXP); error = assign.call(); if (error) { std::string msg = r::endUserErrorMessage(error); reportChunkExecutionError(docId, chunkId, nbCtxId, msg, targetPath); LOG_ERROR(error); return Success(); } } // forward success / failure to chunk enqueueChunkOutput( docId, chunkId, notebookCtxId(), 0, // no ordinal needed ChunkOutputText, targetPath); return Success(); } Error executeSqlEngineChunk(const std::string& docId, const std::string& chunkId, const std::string& nbCtxId, const std::string& code, const json::Object& options) { Error error; // ensure we always emit an execution complete event on exit ChunkExecCompletedScope execScope(docId, chunkId); FilePath targetPath = notebook::chunkOutputFile(docId, chunkId, nbCtxId, ChunkOutputData); // check package dependencies if (!module_context::isPackageVersionInstalled("DBI", "0.4")) { std::string message = "Executing SQL chunks requires version 0.4 or " "later of the DBI package"; reportChunkExecutionError(docId, chunkId, nbCtxId, message, targetPath); return Success(); } // run sql and save result error = r::exec::RFunction( ".rs.runSqlForDataCapture", code, string_utils::utf8ToSystem(targetPath.absolutePath()), options).call(); if (error) { std::string message = "Failed to execute SQL chunk"; reportChunkExecutionError(docId, chunkId, nbCtxId, message, targetPath); return Success(); } // forward success / failure to chunk enqueueChunkOutput( docId, chunkId, notebookCtxId(), 0, // no ordinal needed ChunkOutputData, targetPath); return Success(); } Error interruptEngineChunk(const json::JsonRpcRequest& request, json::JsonRpcResponse* pResponse) { std::string docId, chunkId; Error error = json::readParams(request.params, &docId, &chunkId); if (error) { LOG_ERROR(error); return error; } interruptChunk(docId, chunkId); return Success(); } } // anonymous namespace Error executeAlternateEngineChunk(const std::string& docId, const std::string& chunkId, const std::string& nbCtxId, const std::string& engine, const std::string& code, const json::Object& jsonChunkOptions) { // read json chunk options std::map<std::string, std::string> options; for (json::Object::const_iterator it = jsonChunkOptions.begin(); it != jsonChunkOptions.end(); ++it) { if (it->second.type() == json::StringType) options[it->first] = it->second.get_str(); } // handle Rcpp specially if (engine == "Rcpp") return executeRcppEngineChunk(docId, chunkId, nbCtxId, code, options); else if (engine == "stan") return executeStanEngineChunk(docId, chunkId, nbCtxId, code, options); else if (engine == "sql") return executeSqlEngineChunk(docId, chunkId, nbCtxId, code, jsonChunkOptions); runChunk(docId, chunkId, nbCtxId, engine, code); return Success(); } Error initAlternateEngines() { using namespace module_context; ExecBlock initBlock; initBlock.addFunctions() (bind(registerRpcMethod, "interrupt_chunk", interruptEngineChunk)); return initBlock.execute(); } } // namespace notebook } // namespace rmarkdown } // namespace modules } // namespace session } // namespace rstudio <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: chips/p9/procedures/hwp/memory/lib/mcbist/address.H $ */ /* */ /* IBM CONFIDENTIAL */ /* */ /* EKB Project */ /* */ /* COPYRIGHT 2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* The source code for this program is not published or otherwise */ /* divested of its trade secrets, irrespective of what has been */ /* deposited with the U.S. Copyright Office. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file address.H /// @brief Class for mcbist related addresses (addresses below the hash translation) /// // *HWP HWP Owner: Brian Silver <[email protected]> // *HWP HWP Backup: Craig Hamilton <[email protected]> // *HWP Team: Memory // *HWP Level: 2 // *HWP Consumed by: HB:FSP #ifndef _MSS_MCBIST_ADDRESS_H_ #define _MSS_MCBIST_ADDRESS_H_ #include <fapi2.H> namespace mss { namespace mcbist { /// /// @class address /// @brief Represents a physical address in memory /// @note /// 0:1 port select /// 2 dimm select /// 3:4 mrank(0 to 1) /// 5:7 srank(0 to 2) /// 8:25 row(0 to 17) /// 26:32 col(3 to 9) /// 33:35 bank(0 to 2) /// 36:37 bank_group(0 to 1) /// class address { public: address() = default; /// /// @brief Construct an address from a uint64_t (scom'ed value) /// @param[in] i_value representing an address; say from a trap register /// /// @note This assumes input has the same bit layout as this address /// structure, and this is presently not the case for the trap registers (3/16). /// These are presently unused, however. There is an open defect against the /// design team to correct this. address( const uint64_t i_value ): iv_address(i_value) { } /// /// @brief Conversion operator to uint64_t /// inline operator uint64_t() const { return iv_address; } /// /// @brief Conversion operator to uint64_t reference /// inline operator uint64_t& () { return iv_address; } /// /// @brief Set the port value for an address /// @param[in] i_value the value to set /// inline void set_port( const uint64_t i_value ) { iv_address.insertFromRight<PORT, PORT_LEN>(i_value); } /// /// @brief Get the port value for an address /// @return right-aligned uint64_t representing the value /// inline uint64_t get_port() { uint64_t l_value = 0; iv_address.extractToRight<PORT, PORT_LEN>(l_value); return l_value; } /// /// @brief Set the DIMM value for an address /// @param[in] i_value the value to set /// @note 0 is the DIMM[0] != 0 is DIMM[1] /// inline void set_dimm( const uint64_t i_value ) { iv_address.writeBit<DIMM>(i_value); } /// /// @brief Get the DIMM value for an address /// @return right-aligned uint64_t representing the vaule /// inline uint64_t get_dimm() { bool l_value = iv_address.getBit<DIMM>(); return (l_value == true ? 1 : 0); } /// /// @brief Set the master rank value for an address /// @param[in] i_value the value to set /// inline void set_master_rank( const uint64_t i_value ) { iv_address.insertFromRight<MRANK, MRANK_LEN>(i_value); } /// /// @brief Get the master rank value for an address /// @return right-aligned uint64_t representing the value /// inline uint64_t get_master_rank() { uint64_t l_value = 0; iv_address.extractToRight<MRANK, MRANK_LEN>(l_value); return l_value; } /// /// @brief Set the slave rank value for an address /// @param[in] i_value the value to set /// inline void set_slave_rank( const uint64_t i_value ) { iv_address.insertFromRight<SRANK, SRANK_LEN>(i_value); } /// /// @brief Get the slave rank value for an address /// @return right-aligned uint64_t representing the value /// inline uint64_t get_slave_rank() { uint64_t l_value = 0; iv_address.extractToRight<SRANK, SRANK_LEN>(l_value); return l_value; } /// /// @brief Set the row value for an address /// @param[in] i_value the value to set /// inline void set_row( const uint64_t i_value ) { iv_address.insertFromRight<ROW, ROW_LEN>(i_value); } /// /// @brief Get the row value for an address /// @return right-aligned uint64_t representing the value /// inline uint64_t get_row() { uint64_t l_value = 0; iv_address.extractToRight<ROW, ROW_LEN>(l_value); return l_value; } /// /// @brief Set the column value for an address /// @param[in] i_value the value to set /// inline void set_column( const uint64_t i_value ) { iv_address.insertFromRight<COL, COL_LEN>(i_value); } /// /// @brief Get the column value for an address /// @return right-aligned uint64_t representing the value /// inline uint64_t get_column() { uint64_t l_value = 0; iv_address.extractToRight<COL, COL_LEN>(l_value); return l_value; } /// /// @brief Set the bank value for an address /// @param[in] i_value the value to set /// inline void set_bank( const uint64_t i_value ) { iv_address.insertFromRight<BANK, BANK_LEN>(i_value); } /// /// @brief Get the bank value for an address /// @return right-aligned uint64_t representing the value /// inline uint64_t get_bank() { uint64_t l_value = 0; iv_address.extractToRight<BANK, BANK_LEN>(l_value); return l_value; } /// /// @brief Set the bank group value for an address /// @param[in] i_value the value to set /// inline void set_bank_group( const uint64_t i_value ) { iv_address.insertFromRight<BANK_GROUP, BANK_GROUP_LEN>(i_value); } /// /// @brief Get the bank group value for an address /// @return right-aligned uint64_t representing the value /// inline uint64_t get_bank_group() { uint64_t l_value = 0; iv_address.extractToRight<BANK_GROUP, BANK_GROUP_LEN>(l_value); return l_value; } private: /// Start and length bits for address bit fields enum start_and_length { PORT = 0, ///< 0:1 port select PORT_LEN = 2, DIMM = 2, ///< 2 dimm select MRANK = 3, ///< 3:4 mrank(0 to 1) MRANK_LEN = 2, SRANK = 5, ///< 5:7 srank(0 to 2) SRANK_LEN = 3, ROW = 8, ///< 8:25 row(0 to 17) ROW_LEN = 18, COL = 26, ///< 26:32 col(3 to 9) COL_LEN = 7, BANK = 33, ///< 33:35 bank(0 to 2) BANK_LEN = 3, BANK_GROUP = 36, ///< 36:37 bank_group(0 to 1) BANK_GROUP_LEN = 2, }; // We use a fapi2 buffer as it has static compile-time support fapi2::buffer<uint64_t> iv_address; }; } // namespace } // namespace #endif <commit_msg>Add address::get_mrank_range(), get_srank_range()<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: chips/p9/procedures/hwp/memory/lib/mcbist/address.H $ */ /* */ /* IBM CONFIDENTIAL */ /* */ /* EKB Project */ /* */ /* COPYRIGHT 2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* The source code for this program is not published or otherwise */ /* divested of its trade secrets, irrespective of what has been */ /* deposited with the U.S. Copyright Office. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file address.H /// @brief Class for mcbist related addresses (addresses below the hash translation) /// // *HWP HWP Owner: Brian Silver <[email protected]> // *HWP HWP Backup: Andre Marin <[email protected]> // *HWP Team: Memory // *HWP Level: 2 // *HWP Consumed by: HB:FSP #ifndef _MSS_MCBIST_ADDRESS_H_ #define _MSS_MCBIST_ADDRESS_H_ #include <fapi2.H> #include <utility> namespace mss { namespace mcbist { /// /// @class address /// @brief Represents a physical address in memory /// @note /// 0:1 port select /// 2 dimm select /// 3:4 mrank(0 to 1) /// 5:7 srank(0 to 2) /// 8:25 row(0 to 17) /// 26:32 col(3 to 9) /// 33:35 bank(0 to 2) /// 36:37 bank_group(0 to 1) /// class address { public: // first is the start bit of the field, second is the length typedef std::pair<uint64_t, uint64_t> field; constexpr static field PORT = {0, 2}; constexpr static field DIMM = {2, 1}; constexpr static field MRANK = {3, 2}; constexpr static field SRANK = {5, 3}; constexpr static field ROW = {8, 18}; constexpr static field COL = {26, 7}; constexpr static field BANK = {33, 3}; constexpr static field BANK_GROUP = {36, 2}; constexpr static field LAST_VALID = BANK_GROUP; address() = default; /// /// @brief Construct an address from a uint64_t (scom'ed value) /// @param[in] i_value representing an address; say from a trap register /// /// @note This assumes input has the same bit layout as this address /// structure, and this is presently not the case for the trap registers (3/16). /// These are presently unused, however. There is an open defect against the /// design team to correct this. address( const uint64_t i_value ): iv_address(i_value) { } /// /// @brief Conversion operator to uint64_t /// inline operator uint64_t() const { return iv_address; } /// /// @brief Conversion operator to uint64_t reference /// inline operator uint64_t& () { return iv_address; } /// /// @brief Set a field for an address /// @tparam F the field to set /// @param[in] i_value the value to set /// template< const field& F > inline void set_field( const uint64_t i_value ) { iv_address.insertFromRight<F.first, F.second>(i_value); } /// /// @brief Get a field from an address /// @tparam F the field to get /// @return right-aligned uint64_t representing the value /// template< const field& F > inline uint64_t get_field() { uint64_t l_value = 0; iv_address.extractToRight<F.first, F.second>(l_value); return l_value; } /// /// @brief Get a range of addresses. /// @tparam[in] F the left-most valid field. So, if the address was for master rank, /// the left-most valid field would be MRANK /// @param[out] o_end representing an address to end at /// @note this pointer is the start address /// template< const field& F > inline void get_range( address& o_end ) const { constexpr uint64_t START = F.first + F.second; constexpr uint64_t LEN = (LAST_VALID.first + LAST_VALID.second) - START; // All we need to do is fill in the bits to the right of the last valid field o_end.iv_address = iv_address; o_end.iv_address.setBit<START, LEN>(); } /// /// @brief Get a range of addresses given a master rank /// @param[in] i_start representing an address to start from /// @param[out] o_end representing an address to end at /// inline static void get_mrank_range( const address& i_start, address& o_end ) { i_start.get_range<MRANK>(o_end); } /// /// @brief Get a range of addresses given a master rank /// @param[in] i_port representing the port for the starting address /// @param[in] i_dimm representing the dimm for the starting address /// @param[in] i_mrank representing the master rank for the starting address /// @param[out] o_start representing an address to start from /// @param[out] o_end representing an address to end at /// inline static void get_mrank_range( const uint64_t i_port, const uint64_t i_dimm, const uint64_t i_mrank, address& o_start, address& o_end ) { o_start.set_port(i_port); o_start.set_dimm(i_dimm); o_start.set_master_rank(i_mrank); get_mrank_range(o_start, o_end); } /// /// @brief Get a range of addresses given a slave rank /// @param[in] i_start representing an address to start from /// @param[out] o_end representing an address to end at /// inline static void get_srank_range( const address& i_start, address& o_end ) { i_start.get_range<SRANK>(o_end); } /// /// @brief Get a range of addresses given a slave rank /// @param[in] i_port representing the port for the starting address /// @param[in] i_dimm representing the dimm for the starting address /// @param[in] i_mrank representing the master rank for the starting address /// @param[in] i_srank representing the slave rank for the starting address /// @param[out] o_start representing an address to start from /// @param[out] o_end representing an address to end at /// inline static void get_srank_range( const uint64_t i_port, const uint64_t i_dimm, const uint64_t i_mrank, const uint64_t i_srank, address& o_start, address& o_end ) { o_start.set_port(i_port); o_start.set_dimm(i_dimm); o_start.set_master_rank(i_mrank); o_start.set_slave_rank(i_srank); get_srank_range(o_start, o_end); } /// /// @brief Set the port value for an address /// @param[in] i_value the value to set /// inline void set_port( const uint64_t i_value ) { set_field<PORT>(i_value); } /// /// @brief Get the port value for an address /// @return right-aligned uint64_t representing the value /// inline uint64_t get_port() { return get_field<PORT>(); } /// /// @brief Set the DIMM value for an address /// @param[in] i_value the value to set /// @note 0 is the DIMM[0] != 0 is DIMM[1] /// inline void set_dimm( const uint64_t i_value ) { set_field<DIMM>(i_value); } /// /// @brief Get the DIMM value for an address /// @return right-aligned uint64_t representing the vaule /// inline uint64_t get_dimm() { return (get_field<DIMM>() == true ? 1 : 0); } /// /// @brief Set the master rank value for an address /// @param[in] i_value the value to set /// inline void set_master_rank( const uint64_t i_value ) { set_field<MRANK>(i_value); } /// /// @brief Get the master rank value for an address /// @return right-aligned uint64_t representing the value /// inline uint64_t get_master_rank() { return get_field<MRANK>(); } /// /// @brief Set the slave rank value for an address /// @param[in] i_value the value to set /// inline void set_slave_rank( const uint64_t i_value ) { set_field<SRANK>(i_value); } /// /// @brief Get the slave rank value for an address /// @return right-aligned uint64_t representing the value /// inline uint64_t get_slave_rank() { return get_field<SRANK>(); } /// /// @brief Set the row value for an address /// @param[in] i_value the value to set /// inline void set_row( const uint64_t i_value ) { set_field<ROW>(i_value); } /// /// @brief Get the row value for an address /// @return right-aligned uint64_t representing the value /// inline uint64_t get_row() { return get_field<ROW>(); } /// /// @brief Set the column value for an address /// @param[in] i_value the value to set /// inline void set_column( const uint64_t i_value ) { set_field<COL>(i_value); } /// /// @brief Get the column value for an address /// @return right-aligned uint64_t representing the value /// inline uint64_t get_column() { return get_field<COL>(); } /// /// @brief Set the bank value for an address /// @param[in] i_value the value to set /// inline void set_bank( const uint64_t i_value ) { set_field<BANK>(i_value); } /// /// @brief Get the bank value for an address /// @return right-aligned uint64_t representing the value /// inline uint64_t get_bank() { return get_field<BANK>(); } /// /// @brief Set the bank group value for an address /// @param[in] i_value the value to set /// inline void set_bank_group( const uint64_t i_value ) { set_field<BANK_GROUP>(i_value); } /// /// @brief Get the bank group value for an address /// @return right-aligned uint64_t representing the value /// inline uint64_t get_bank_group() { return get_field<BANK_GROUP>(); } private: // We use a fapi2 buffer as it has static compile-time support fapi2::buffer<uint64_t> iv_address; }; } // namespace } // namespace #endif <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/lib/p9_common_poweronoff.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file p9_common_poweronoff.H /// @brief common procedure for power on/off /// // *HWP HWP Owner : David Du <[email protected]> // *HWP Backup HWP Owner : Greg Still <[email protected]> // *HWP FW Owner : Sangeetha T S <[email protected]> // *HWP Team : PM // *HWP Consumed by : SBE:SGPE:CME // *HWP Level : 2 #ifndef __P9_COMMON_POWERONOFF_H__ #define __P9_COMMON_POWERONOFF_H__ #include <fapi2.H> namespace p9power { enum powerOperation_t { POWER_ON = 0x0, POWER_OFF = 0xFF, POWER_ON_VDD = 0x1, POWER_OFF_VDD = 0xFE }; // For SBE, the initial power-on times are not overly time critical so they are // hardcoded for the delay necessary when running with the fastest nest (2.4GHz). // When these same values are used with slower nest frequencies, the delays will // get longer (more conservative). // // For istep 15, the delay settings are computed based on the setting of // ATTR_FREQ_PB // // pfet_delay = (1/nest_frequency_mhz)*1000*4 (PPM clock period in ns) * // 2^(15-pfet_delay_value). // // or // // pfet_delay // 2^(15-pfet_delay_value) = ------------------------------ // (1/nest_frequency_mhz)*1000*4 // // pfet_delay * nest_frequency_mhz // 2^(15-pfet_delay_value = ------------------------------ // 1000*4 // // ( pfet_delay * nest_frequency_mhz) // 15-pfet_delay_value = log2( ------------------------------) // ( 1000*4 ) // // ( pfet_delay * nest_frequency_mhz) // pfet_delay_value = 15 - log2( ------------------------------) // ( 1000*4 ) // // ( pfet_delay * nest_frequency_mhz) // logexp = ( ------------------------------) // ( 1000*4 ) // // = pfet_delay * nest_frequency_mhz / (1000 * 4) // = pfet_delay * (nest_frequency_mhz / (1000 * 4)) // = pfet_delay * (2400 / (1000 * 4)) // = pfet_delay * (.6) // // For core delay of 250ns per step, logexp = 250 * .6 = 150 // --> log2(150) = 8 (rounded up to next integer) // -- > pfet_delay_value = 15 - 8 = 7 // // For EQ delay of 500ns per step, logexp = 500 * .6 = 300 // --> log2(150) = 9 (rounded up to next integer) // -- > pfet_delay_value = 15 - 9 = 6 enum pfetDelays { PFET_DELAY_POWERDOWN_EQ = 0x1, PFET_DELAY_POWERDOWN_CORE = 0x1, #ifndef PRODUCT_DEFAULT_PFET_DELAYS PFET_DELAY_POWERUP_EQ = 0x1, PFET_DELAY_POWERUP_CORE = 0x1 #else PFET_DELAY_POWERUP_EQ = 0x6, PFET_DELAY_POWERUP_CORE = 0x7 #endif }; } // namespace /// @typedef p9_common_poweronoff_FP_t /// function pointer typedef definition for HWP call support /// @todo: consider template solution here typedef fapi2::ReturnCode (*p9_common_poweronoff_FP_t) ( const fapi2::Target < fapi2::TARGET_TYPE_EQ | fapi2::TARGET_TYPE_CORE > &, const p9power::powerOperation_t i_operation); /// @brief common procedure for power on/off /// /// @param [in] i_target TARGET_TYPE_EQ|TARGET_TYPE_CORE target /// @param [in] i_operation ENUM(ON,OFF) /// /// @attr /// @attritem ATTR_PFET_TIMING - EX target, uint32 /// /// @retval FAPI_RC_SUCCESS template <fapi2::TargetType K> fapi2::ReturnCode p9_common_poweronoff( const fapi2::Target<K>& i_target, const p9power::powerOperation_t i_operation); #endif // __P9_COMMON_POWERONOFF_H__ <commit_msg>Cache HWP: DD1 VCS Workaround<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/lib/p9_common_poweronoff.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file p9_common_poweronoff.H /// @brief common procedure for power on/off /// // *HWP HWP Owner : David Du <[email protected]> // *HWP Backup HWP Owner : Greg Still <[email protected]> // *HWP FW Owner : Sangeetha T S <[email protected]> // *HWP Team : PM // *HWP Consumed by : SBE:SGPE:CME // *HWP Level : 2 #ifndef __P9_COMMON_POWERONOFF_H__ #define __P9_COMMON_POWERONOFF_H__ #include <fapi2.H> namespace p9power { enum powerOperation_t { POWER_ON = 0x0, POWER_OFF = 0xFF, POWER_ON_VDD = 0x1, POWER_OFF_VDD = 0xFE, POWER_ON_VCS = 0x2, POWER_OFF_VCS = 0xFD }; // For SBE, the initial power-on times are not overly time critical so they are // hardcoded for the delay necessary when running with the fastest nest (2.4GHz). // When these same values are used with slower nest frequencies, the delays will // get longer (more conservative). // // For istep 15, the delay settings are computed based on the setting of // ATTR_FREQ_PB // // pfet_delay = (1/nest_frequency_mhz)*1000*4 (PPM clock period in ns) * // 2^(15-pfet_delay_value). // // or // // pfet_delay // 2^(15-pfet_delay_value) = ------------------------------ // (1/nest_frequency_mhz)*1000*4 // // pfet_delay * nest_frequency_mhz // 2^(15-pfet_delay_value = ------------------------------ // 1000*4 // // ( pfet_delay * nest_frequency_mhz) // 15-pfet_delay_value = log2( ------------------------------) // ( 1000*4 ) // // ( pfet_delay * nest_frequency_mhz) // pfet_delay_value = 15 - log2( ------------------------------) // ( 1000*4 ) // // ( pfet_delay * nest_frequency_mhz) // logexp = ( ------------------------------) // ( 1000*4 ) // // = pfet_delay * nest_frequency_mhz / (1000 * 4) // = pfet_delay * (nest_frequency_mhz / (1000 * 4)) // = pfet_delay * (2400 / (1000 * 4)) // = pfet_delay * (.6) // // For core delay of 250ns per step, logexp = 250 * .6 = 150 // --> log2(150) = 8 (rounded up to next integer) // -- > pfet_delay_value = 15 - 8 = 7 // // For EQ delay of 500ns per step, logexp = 500 * .6 = 300 // --> log2(150) = 9 (rounded up to next integer) // -- > pfet_delay_value = 15 - 9 = 6 enum pfetDelays { PFET_DELAY_POWERDOWN_EQ = 0x1, PFET_DELAY_POWERDOWN_CORE = 0x1, #ifndef PRODUCT_DEFAULT_PFET_DELAYS PFET_DELAY_POWERUP_EQ = 0x1, PFET_DELAY_POWERUP_CORE = 0x1 #else PFET_DELAY_POWERUP_EQ = 0x6, PFET_DELAY_POWERUP_CORE = 0x7 #endif }; } // namespace /// @typedef p9_common_poweronoff_FP_t /// function pointer typedef definition for HWP call support /// @todo: consider template solution here typedef fapi2::ReturnCode (*p9_common_poweronoff_FP_t) ( const fapi2::Target < fapi2::TARGET_TYPE_EQ | fapi2::TARGET_TYPE_CORE > &, const p9power::powerOperation_t i_operation); /// @brief common procedure for power on/off /// /// @param [in] i_target TARGET_TYPE_EQ|TARGET_TYPE_CORE target /// @param [in] i_operation ENUM(ON,OFF) /// /// @attr /// @attritem ATTR_PFET_TIMING - EX target, uint32 /// /// @retval FAPI_RC_SUCCESS template <fapi2::TargetType K> fapi2::ReturnCode p9_common_poweronoff( const fapi2::Target<K>& i_target, const p9power::powerOperation_t i_operation); #endif // __P9_COMMON_POWERONOFF_H__ <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/pm/p9_cpu_special_wakeup.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file : p9_cpu_special_wakeup.C /// @brief : HWP to perform special wakeup of core, EQ or EX. // *HWP HW Owner : Greg Still <[email protected]> // *HWP FW Owner : Prem S Jha <[email protected]> // *HWP Team : PM // *HWP Level : 1 // *HWP Consumed by : OCC:FSP:HOST // --------------------------------------------------------------------- // Includes // --------------------------------------------------------------------- #include <p9_cpu_special_wakeup.H> using namespace p9specialWakeup; enum { NUM_SPCWKUP_ENTITIES = 4, NUM_SPCWKUP_OPS = 3, }; fapi2::ReturnCode p9_cpu_special_wakeup( const FAPI2_WAKEUP_CHIPLET& i_chipletTarget, const PROC_SPCWKUP_OPS i_operation, const PROC_SPCWKUP_ENTITY i_entity ) { FAPI_DBG("Entering p9_cpu_special_wakeup"); FAPI_DBG("Exit p9_cpu_special_wakeup" ); return fapi2::FAPI2_RC_SUCCESS; } <commit_msg>Level 2 p9_cpu_special_wakeup<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/pm/p9_cpu_special_wakeup.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file : p9_cpu_special_wakeup_core.C /// @brief : HWP to perform special wakeup of a core // *HWP HW Owner : Greg Still <[email protected]> // *HWP FW Owner : Prem S Jha <[email protected]> // *HWP Team : PM // *HWP Level : 2 // *HWP Consumed by : OCC:FSP:HOST:CRO // ----------------------------------------------------------------------------- // Includes // ----------------------------------------------------------------------------- #include <p9_cpu_special_wakeup.H> /// ---------------------------------------------------------------------------- /// /// @brief Sets a normal core chiplet into special wakeup state. /// @note Code added as a workaround to fix HB-CI failure. Will /// be removed eventually. /// fapi2::ReturnCode p9_cpu_special_wakeup( const fapi2::Target < fapi2::TARGET_TYPE_CORE>& i_target, const p9specialWakeup::PROC_SPCWKUP_OPS i_operation, const p9specialWakeup::PROC_SPCWKUP_ENTITY i_entity ) { FAPI_DBG("> p9_cpu_special_wakeup"); FAPI_INF("< p9_cpu_special_wakeup" ); return fapi2::FAPI2_RC_SUCCESS; } <|endoftext|>
<commit_before>#include "sub_thruster_library/t200_thruster.h" //#include "sub_thruster_library/seabotix_thruster.h" #include "sub_thruster_library/generic_thruster.h" #include <json/json.h> #include <ros/ros.h> #include <diagnostic_msgs/DiagnosticStatus.h> #include <diagnostic_msgs/SelfTest.h> #include <iostream> #include <fstream> //TODO: Determine module name at runtime (needs some capemgr fuckery) #define SUB_SECTION_NAME "COMPUTE" inline const std::string BoolToString(const bool b); //http://stackoverflow.com/a/29798 class ThrusterManager { ros::NodeHandle nh_; ros::Subscriber command_subscriber; ros::Publisher diagnostics_output; sub_trajectory::ThrusterCmd savedMsg; ros::AsyncSpinner spinner; std::map<int, GenericThruster> thrusterMap; public: ThrusterManager() : spinner(1) { for(int i = 0; i < 8; i++) { savedMsg.cmd.push_back(0.0); } command_subscriber = nh_.subscribe("/thrusters/cmd_vel", 1000, &ThrusterManager::thrusterCb, this); diagnostics_output = nh_.advertise<diagnostic_msgs::DiagnosticStatus>("/diagnostics", 1000); //thrusterMap[0] = T200Thruster(1, 0x2D); //thrusterMap[1] = T200Thruster(1, 0x2E); //This should keep a reference? The copy disabling thing should keep us safe } void init() { if(spinner.canStart()) spinner.start(); else return; ifstream configFile("config.json"); if(!ifstream.is_open()){ ROS_ERROR("%s thruster controller couldn't open config file", SUB_SECTION_NAME); return; } Json::Reader reader; Json::Value obj; reader.parse(configFile, obj); Json::Value& thrustersJson = obj[SUB_SECTION_NAME]; for(int i = 0; i < thrustersJson.size(); i++) { int thrusterID = thrustersJson[i]["ID"].asInt(); int thrusterType = thrustersJson[i]["Type"].asInt(); int thrusterAddress = thrustersJson[i]["Address"].asInt(); thrusterMap[thrusterID] = T200Thruster(1, thrusterAddress); } //TODO: Iterate through the thruster param and build thruster objects. //No fucking idea how you build things from JSON in C++ but ROS does it somehow. ros::Rate rate(4); while(ros::ok()) { //Publish diagnostic data here diagnostic_msgs::DiagnosticStatus status; status.name = "Thrusters"; status.hardware_id = "Thrusters"; for(auto& thruster : thrusterMap) { iter.second.updateStatus(); if (thrusterOk(iter.second) && status.level != status.ERROR) status.level = status.OK; else status.level = status.ERROR; PushDiagData(status, iter.second, std::to_string(iter.first)); iter.second.setVelocity(savedMsg.cmd.at(iter.first)); } diagnostics_output.publish(status); rate.sleep(); } spinner.stop(); } bool thrusterOk (GenericThruster & thruster) { return thruster.isAlive() && thruster.inLimits(); } void PushDiagData(diagnostic_msgs::DiagnosticStatus & statusmsg, GenericThruster & thruster, std::string thrusterName) { diagnostic_msgs::KeyValue thrusterValue; thrusterValue.key = "Thruster Type"; thrusterValue.value = thruster.getType(); statusmsg.values.push_back(thrusterValue); thrusterValue.key = thrusterName + " Alive"; thrusterValue.value = BoolToString(thruster.isAlive()); statusmsg.values.push_back(thrusterValue); thrusterValue.key = thrusterName + " Voltage"; thrusterValue.value = std::to_string(thruster.getVoltage()); statusmsg.values.push_back(thrusterValue); thrusterValue.key = thrusterName + " Current"; thrusterValue.value = std::to_string(thruster.getCurrent()); statusmsg.values.push_back(thrusterValue); thrusterValue.key = thrusterName + " Temperature"; thrusterValue.value = std::to_string(thruster.getTemperature()); statusmsg.values.push_back(thrusterValue); } void thrusterCb(const sub_trajectory::ThrusterCmd &msg) { savedMsg = msg; } float magnitude(float x, float y) //return the magnitude of a 2d vector { return sqrt(x*x + y*y); } }; int main(int argc, char** argv) { ros::init(argc, argv, "thruster_driver"); ThrusterManager tc; tc.init(); return 0; } inline const std::string BoolToString(const bool b) { return b ? "true" : "false"; } <commit_msg>Changed to single-thread ros spinning, added self-test function<commit_after>#include "sub_thruster_library/t200_thruster.h" //#include "sub_thruster_library/seabotix_thruster.h" #include "sub_thruster_library/generic_thruster.h" #include <json/json.h> #include <ros/ros.h> #include <diagnostic_msgs/DiagnosticStatus.h> #include <diagnostic_msgs/SelfTest.h> //TODO: implement self tests #include <iostream> #include <fstream> //TODO: Determine module name at runtime (needs some capemgr fuckery) #define SUB_SECTION_NAME "COMPUTE" inline const std::string BoolToString(const bool b); //http://stackoverflow.com/a/29798 class ThrusterManager { ros::NodeHandle nh_; ros::Subscriber command_subscriber; ros::Publisher diagnostics_output; sub_trajectory::ThrusterCmd savedMsg; std::map<int, GenericThruster> thrusterMap; public: ThrusterManager() : spinner(1) { for(int i = 0; i < 8; i++) { savedMsg.cmd.push_back(0.0); } command_subscriber = nh_.subscribe("/thrusters/cmd_vel", 1000, &ThrusterManager::thrusterCb, this); diagnostics_output = nh_.advertise<diagnostic_msgs::DiagnosticStatus>("/diagnostics", 1000); //thrusterMap[0] = T200Thruster(1, 0x2D); //thrusterMap[1] = T200Thruster(1, 0x2E); //This should keep a reference? The copy disabling thing should keep us safe } void init() { ifstream configFile("config.json"); if(!ifstream.is_open()){ ROS_ERROR("%s thruster controller couldn't open config file", SUB_SECTION_NAME); return; } Json::Reader reader; Json::Value obj; reader.parse(configFile, obj); Json::Value& thrustersJson = obj[SUB_SECTION_NAME]; for(int i = 0; i < thrustersJson.size(); i++) { int thrusterID = thrustersJson[i]["ID"].asInt(); int thrusterType = thrustersJson[i]["Type"].asInt(); //TODO: support for multiple thruster types int thrusterAddress = thrustersJson[i]["Address"].asInt(); try{ thrusterMap[thrusterID] = T200Thruster(1, thrusterAddress); } catch(I2CException e){ //If we get here there's a bus problem //Publish an error message for the diagnostic system to do something about diagnostic_msgs::DiagnosticStatus status; status.name = "Thrusters"; status.hardware_id = "Thrusters"; status.level = status.ERROR; diagnostics_output.publish(status); ros::spinOnce(); } else { } } } void spin() { ros::Rate rate(4); while(ros::ok()) { //Publish diagnostic data here diagnostic_msgs::DiagnosticStatus status; status.name = "Thrusters"; status.hardware_id = "Thrusters"; //TODO: Different hardware ID/section based on sub section name? for(auto& thruster : thrusterMap) { try { iter.second.updateStatus(); iter.second.setVelocity(savedMsg.cmd.at(iter.first)); } catch(I2CException e) { //Publish an error message for the diagnostic system to do something about diagnostic_msgs::DiagnosticStatus status; status.name = "Thrusters"; status.hardware_id = "Thrusters"; status.level = status.ERROR; diagnostics_output.publish(status); ros::spinOnce(); } if (thrusterOk(iter.second) && status.level != status.ERROR) status.level = status.OK; else status.level = status.ERROR; PushDiagData(status, iter.second, std::to_string(iter.first)); } diagnostics_output.publish(status); ros::spinOnce(); rate.sleep(); } } bool thrusterOk (GenericThruster & thruster) { return thruster.isAlive() && thruster.inLimits(); } void PushDiagData(diagnostic_msgs::DiagnosticStatus & statusmsg, GenericThruster & thruster, std::string thrusterName) { diagnostic_msgs::KeyValue thrusterValue; thrusterValue.key = "Thruster Type"; thrusterValue.value = thruster.getType(); statusmsg.values.push_back(thrusterValue); thrusterValue.key = thrusterName + " Alive"; thrusterValue.value = BoolToString(thruster.isAlive()); statusmsg.values.push_back(thrusterValue); thrusterValue.key = thrusterName + " Voltage"; thrusterValue.value = std::to_string(thruster.getVoltage()); statusmsg.values.push_back(thrusterValue); thrusterValue.key = thrusterName + " Current"; thrusterValue.value = std::to_string(thruster.getCurrent()); statusmsg.values.push_back(thrusterValue); thrusterValue.key = thrusterName + " Temperature"; thrusterValue.value = std::to_string(thruster.getTemperature()); statusmsg.values.push_back(thrusterValue); } void thrusterCb(const sub_trajectory::ThrusterCmd &msg) { savedMsg = msg; } //Self test function void testThrusterConnections(diagnostic_updater::DiagnosticStatusWrapper& status) { ifstream configFile("config.json"); if(!ifstream.is_open()){ ROS_ERROR("%s thruster controller couldn't open config file", SUB_SECTION_NAME); status.summary(diagnostic_msgs::DiagnosticStatus::ERROR, "Config file didn't load"); return; } Json::Reader reader; Json::Value obj; reader.parse(configFile, obj); Json::Value& thrustersJson = obj[SUB_SECTION_NAME]; for(int i = 0; i < thrustersJson.size(); i++) { int thrusterID = thrustersJson[i]["ID"].asInt(); int thrusterType = thrustersJson[i]["Type"].asInt(); //TODO: support for multiple thruster types int thrusterAddress = thrustersJson[i]["Address"].asInt(); try{ T200Thruster(1, thrusterAddress); } catch(I2CException e){ status.summary(diagnostic_msgs::DiagnosticStatus::ERROR, "Thruster couldn't connect"); status.add("Fail id", thrusterAddress); //TODO: What if multiple thrusters fail } } } }; int main(int argc, char** argv) { ros::init(argc, argv, "thruster_driver"); ThrusterManager tc; tc.init(); tc.spin(); return 0; } inline const std::string BoolToString(const bool b) { return b ? "true" : "false"; } <|endoftext|>
<commit_before>#include "ElectricFieldReaderInitModule.hpp" #include <fstream> #include <limits> #include <memory> #include <new> #include <stdexcept> #include <string> #include <utility> #include <Math/Vector3D.h> #include <TH2F.h> #include "core/config/exceptions.h" #include "core/geometry/PixelDetectorModel.hpp" #include "core/utils/log.h" #include "core/utils/unit.h" // use the allpix namespace within this file using namespace allpix; // constructor to load the module ElectricFieldReaderInitModule::ElectricFieldReaderInitModule(Configuration config, Messenger*, std::shared_ptr<Detector> detector) : Module(config, detector), config_(std::move(config)), detector_(std::move(detector)) {} // init method that reads the electric field from the file void ElectricFieldReaderInitModule::init() { try { // get field LOG(TRACE) << "Reading electric field file"; auto field_data = get_by_file_name(config_.getPath("file_name", true), *detector_.get()); // set detector field detector_->setElectricField(field_data.first, field_data.second); // produce debug histograms if needed if(config_.get<bool>("output_plots", false)) { LOG(TRACE) << "Creating output plots"; auto steps = config_.get<size_t>("output_plots_steps", 5000); auto project = config_.get<char>("output_plots_project", 'x'); if(project != 'x' && project != 'y' && project != 'z') { throw InvalidValueError(config_, "output_plots_project", "can only project on x, y or z axis"); } auto model = detector_->getModel(); double min1, max1; double min2, max2; if(project == 'x') { min1 = model->getSensorMinY(); max1 = model->getSensorMinY() + model->getSensorSizeY(); min2 = model->getSensorMinZ(); max2 = model->getSensorMinZ() + model->getSensorSizeZ(); } else if(project == 'y') { min1 = model->getSensorMinX(); max1 = model->getSensorMinX() + model->getSensorSizeX(); min2 = model->getSensorMinZ(); max2 = model->getSensorMinZ() + model->getSensorSizeZ(); } else { min1 = model->getSensorMinX(); max1 = model->getSensorMinX() + model->getSensorSizeX(); min2 = model->getSensorMinY(); max2 = model->getSensorMinY() + model->getSensorSizeY(); } auto histogram = new TH2F("field", ("Electric field for " + detector_->getName()).c_str(), static_cast<int>(steps), min1, max1, static_cast<int>(steps), min2, max2); double x = 0, y = 0, z = 0; if(project == 'x') { x = model->getSensorMinX() + config_.get<double>("output_plots_projection_percentage", 0.5) * model->getSensorSizeX(); } else if(project == 'y') { y = model->getSensorMinY() + config_.get<double>("output_plots_projection_percentage", 0.5) * model->getSensorSizeY(); } else { z = model->getSensorMinZ() + config_.get<double>("output_plots_projection_percentage", 0.5) * model->getSensorSizeZ(); } for(size_t j = 0; j < steps; ++j) { if(project == 'x') { y = model->getSensorMinY() + ((static_cast<double>(j) + 0.5) / static_cast<double>(steps)) * model->getSensorSizeY(); } else if(project == 'y') { x = model->getSensorMinX() + ((static_cast<double>(j) + 0.5) / static_cast<double>(steps)) * model->getSensorSizeX(); } else { x = model->getSensorMinX() + ((static_cast<double>(j) + 0.5) / static_cast<double>(steps)) * model->getSensorSizeX(); } for(size_t k = 0; k < steps; ++k) { if(project == 'x') { z = model->getSensorMinZ() + ((static_cast<double>(k) + 0.5) / static_cast<double>(steps)) * model->getSensorSizeZ(); } else if(project == 'y') { z = model->getSensorMinZ() + ((static_cast<double>(k) + 0.5) / static_cast<double>(steps)) * model->getSensorSizeZ(); } else { y = model->getSensorMinY() + ((static_cast<double>(k) + 0.5) / static_cast<double>(steps)) * model->getSensorSizeY(); } // get field strength and fill histogram auto field_strength = std::sqrt(detector_->getElectricField(ROOT::Math::XYZPoint(x, y, z)).Mag2()); // fill histogram if(project == 'x') { histogram->Fill(y, z, field_strength); } else if(project == 'y') { histogram->Fill(x, z, field_strength); } else { histogram->Fill(x, y, field_strength); } } } // write histogram histogram->Write(); } } catch(std::invalid_argument& e) { throw InvalidValueError(config_, "file_name", e.what()); } catch(std::runtime_error& e) { throw InvalidValueError(config_, "file_name", e.what()); } catch(std::bad_alloc& e) { throw InvalidValueError(config_, "file_name", "file too large"); } } // check if the detector matches the file inline static void check_detector_match(Detector& detector, double thickness, double xpixsz, double ypixsz) { auto model = std::dynamic_pointer_cast<PixelDetectorModel>(detector.getModel()); // do a few simple checks for pixel detector models if(model != nullptr) { if(std::fabs(thickness - model->getSensorSizeZ()) > std::numeric_limits<double>::epsilon()) { LOG(WARNING) << "Thickness of sensor in file is " << thickness << " but in the model it is " << model->getSensorSizeZ(); } if(std::fabs(xpixsz - model->getPixelSizeX()) > std::numeric_limits<double>::epsilon() || std::fabs(ypixsz - model->getPixelSizeY()) > std::numeric_limits<double>::epsilon()) { LOG(WARNING) << "Pixel size is (" << xpixsz << "," << ypixsz << ") but in the model it is (" << model->getPixelSizeX() << "," << model->getPixelSizeY() << ")"; } } } // get the electric field from file name (reusing the same if catched earlier) std::map<std::string, ElectricFieldReaderInitModule::FieldData> ElectricFieldReaderInitModule::field_map_; ElectricFieldReaderInitModule::FieldData ElectricFieldReaderInitModule::get_by_file_name(const std::string& file_name, Detector& detector) { // search in cache (NOTE: the path reached here is always a canonical name) auto iter = field_map_.find(file_name); if(iter != field_map_.end()) { // FIXME: check detector match here as well return iter->second; } // load file std::ifstream file(file_name); std::string header; std::getline(file, header); LOG(TRACE) << "Header of file " << file_name << " is " << header; // read the header std::string tmp; file >> tmp >> tmp; // ignore the init seed and cluster length file >> tmp >> tmp >> tmp; // ignore the incident pion direction file >> tmp >> tmp >> tmp; // ignore the magnetic field (specify separately) double thickness, xpixsz, ypixsz; file >> thickness >> xpixsz >> ypixsz; thickness = Units::get(thickness, "um"); xpixsz = Units::get(xpixsz, "um"); ypixsz = Units::get(ypixsz, "um"); file >> tmp >> tmp >> tmp >> tmp; // ignore temperature, flux, rhe (?) and new_drde (?) size_t xsize, ysize, zsize; file >> xsize >> ysize >> zsize; file >> tmp; // check if electric field matches chip check_detector_match(detector, thickness, xpixsz, ypixsz); if(file.fail()) { throw std::runtime_error("invalid data or unexpected end of file"); } auto field = std::make_shared<std::vector<double>>(); field->resize(xsize * ysize * zsize * 3); // loop through all the field data for(size_t i = 0; i < xsize * ysize * zsize; ++i) { if(file.eof()) { throw std::runtime_error("unexpected end of file"); } // get index of electric field size_t xind, yind, zind; file >> xind >> yind >> zind; if(file.fail() || xind > xsize || yind > ysize || zind > zsize) { throw std::runtime_error("invalid data"); } xind--; yind--; zind--; // loop through components of electric field for(size_t j = 0; j < 3; ++j) { double input; file >> input; // set the electric field at a position (*field)[xind * ysize * zsize * 3 + yind * zsize * 3 + zind * 3 + j] = Units::get(input, "V/cm"); } } return std::make_pair(field, std::array<size_t, 3>{{xsize, ysize, zsize}}); } <commit_msg>add units to electric field reader<commit_after>#include "ElectricFieldReaderInitModule.hpp" #include <fstream> #include <limits> #include <memory> #include <new> #include <stdexcept> #include <string> #include <utility> #include <Math/Vector3D.h> #include <TH2F.h> #include "core/config/exceptions.h" #include "core/geometry/PixelDetectorModel.hpp" #include "core/utils/log.h" #include "core/utils/unit.h" // use the allpix namespace within this file using namespace allpix; // constructor to load the module ElectricFieldReaderInitModule::ElectricFieldReaderInitModule(Configuration config, Messenger*, std::shared_ptr<Detector> detector) : Module(config, detector), config_(std::move(config)), detector_(std::move(detector)) {} // init method that reads the electric field from the file void ElectricFieldReaderInitModule::init() { try { // get field LOG(TRACE) << "Reading electric field file"; auto field_data = get_by_file_name(config_.getPath("file_name", true), *detector_.get()); // set detector field detector_->setElectricField(field_data.first, field_data.second); // produce debug histograms if needed if(config_.get<bool>("output_plots", false)) { LOG(TRACE) << "Creating output plots"; auto steps = config_.get<size_t>("output_plots_steps", 5000); auto project = config_.get<char>("output_plots_project", 'x'); if(project != 'x' && project != 'y' && project != 'z') { throw InvalidValueError(config_, "output_plots_project", "can only project on x, y or z axis"); } auto model = detector_->getModel(); double min1, max1; double min2, max2; if(project == 'x') { min1 = model->getSensorMinY(); max1 = model->getSensorMinY() + model->getSensorSizeY(); min2 = model->getSensorMinZ(); max2 = model->getSensorMinZ() + model->getSensorSizeZ(); } else if(project == 'y') { min1 = model->getSensorMinX(); max1 = model->getSensorMinX() + model->getSensorSizeX(); min2 = model->getSensorMinZ(); max2 = model->getSensorMinZ() + model->getSensorSizeZ(); } else { min1 = model->getSensorMinX(); max1 = model->getSensorMinX() + model->getSensorSizeX(); min2 = model->getSensorMinY(); max2 = model->getSensorMinY() + model->getSensorSizeY(); } auto histogram = new TH2F("field", ("Electric field for " + detector_->getName()).c_str(), static_cast<int>(steps), min1, max1, static_cast<int>(steps), min2, max2); double x = 0, y = 0, z = 0; if(project == 'x') { x = model->getSensorMinX() + config_.get<double>("output_plots_projection_percentage", 0.5) * model->getSensorSizeX(); } else if(project == 'y') { y = model->getSensorMinY() + config_.get<double>("output_plots_projection_percentage", 0.5) * model->getSensorSizeY(); } else { z = model->getSensorMinZ() + config_.get<double>("output_plots_projection_percentage", 0.5) * model->getSensorSizeZ(); } for(size_t j = 0; j < steps; ++j) { if(project == 'x') { y = model->getSensorMinY() + ((static_cast<double>(j) + 0.5) / static_cast<double>(steps)) * model->getSensorSizeY(); } else if(project == 'y') { x = model->getSensorMinX() + ((static_cast<double>(j) + 0.5) / static_cast<double>(steps)) * model->getSensorSizeX(); } else { x = model->getSensorMinX() + ((static_cast<double>(j) + 0.5) / static_cast<double>(steps)) * model->getSensorSizeX(); } for(size_t k = 0; k < steps; ++k) { if(project == 'x') { z = model->getSensorMinZ() + ((static_cast<double>(k) + 0.5) / static_cast<double>(steps)) * model->getSensorSizeZ(); } else if(project == 'y') { z = model->getSensorMinZ() + ((static_cast<double>(k) + 0.5) / static_cast<double>(steps)) * model->getSensorSizeZ(); } else { y = model->getSensorMinY() + ((static_cast<double>(k) + 0.5) / static_cast<double>(steps)) * model->getSensorSizeY(); } // get field strength and fill histogram auto field_strength = std::sqrt(detector_->getElectricField(ROOT::Math::XYZPoint(x, y, z)).Mag2()); // fill histogram if(project == 'x') { histogram->Fill(y, z, field_strength); } else if(project == 'y') { histogram->Fill(x, z, field_strength); } else { histogram->Fill(x, y, field_strength); } } } // write histogram histogram->Write(); } } catch(std::invalid_argument& e) { throw InvalidValueError(config_, "file_name", e.what()); } catch(std::runtime_error& e) { throw InvalidValueError(config_, "file_name", e.what()); } catch(std::bad_alloc& e) { throw InvalidValueError(config_, "file_name", "file too large"); } } // check if the detector matches the file inline static void check_detector_match(Detector& detector, double thickness, double xpixsz, double ypixsz) { auto model = std::dynamic_pointer_cast<PixelDetectorModel>(detector.getModel()); // do a few simple checks for pixel detector models if(model != nullptr) { if(std::fabs(thickness - model->getSensorSizeZ()) > std::numeric_limits<double>::epsilon()) { LOG(WARNING) << "Thickness of sensor in file is " << Units::display(thickness, "um") << " but in the model it is " << Units::display(model->getSensorSizeZ(), "um"); } if(std::fabs(xpixsz - model->getPixelSizeX()) > std::numeric_limits<double>::epsilon() || std::fabs(ypixsz - model->getPixelSizeY()) > std::numeric_limits<double>::epsilon()) { LOG(WARNING) << "Pixel size is (" << Units::display(xpixsz, {"um", "mm"}) << "," << Units::display(ypixsz, {"um", "mm"}) << ") but in the model it is (" << Units::display(model->getPixelSizeX(), {"um", "mm"}) << "," << Units::display(model->getPixelSizeY(), {"um", "mm"}) << ")"; } } } // get the electric field from file name (reusing the same if catched earlier) std::map<std::string, ElectricFieldReaderInitModule::FieldData> ElectricFieldReaderInitModule::field_map_; ElectricFieldReaderInitModule::FieldData ElectricFieldReaderInitModule::get_by_file_name(const std::string& file_name, Detector& detector) { // search in cache (NOTE: the path reached here is always a canonical name) auto iter = field_map_.find(file_name); if(iter != field_map_.end()) { // FIXME: check detector match here as well return iter->second; } // load file std::ifstream file(file_name); std::string header; std::getline(file, header); LOG(TRACE) << "Header of file " << file_name << " is " << header; // read the header std::string tmp; file >> tmp >> tmp; // ignore the init seed and cluster length file >> tmp >> tmp >> tmp; // ignore the incident pion direction file >> tmp >> tmp >> tmp; // ignore the magnetic field (specify separately) double thickness, xpixsz, ypixsz; file >> thickness >> xpixsz >> ypixsz; thickness = Units::get(thickness, "um"); xpixsz = Units::get(xpixsz, "um"); ypixsz = Units::get(ypixsz, "um"); file >> tmp >> tmp >> tmp >> tmp; // ignore temperature, flux, rhe (?) and new_drde (?) size_t xsize, ysize, zsize; file >> xsize >> ysize >> zsize; file >> tmp; // check if electric field matches chip check_detector_match(detector, thickness, xpixsz, ypixsz); if(file.fail()) { throw std::runtime_error("invalid data or unexpected end of file"); } auto field = std::make_shared<std::vector<double>>(); field->resize(xsize * ysize * zsize * 3); // loop through all the field data for(size_t i = 0; i < xsize * ysize * zsize; ++i) { if(file.eof()) { throw std::runtime_error("unexpected end of file"); } // get index of electric field size_t xind, yind, zind; file >> xind >> yind >> zind; if(file.fail() || xind > xsize || yind > ysize || zind > zsize) { throw std::runtime_error("invalid data"); } xind--; yind--; zind--; // loop through components of electric field for(size_t j = 0; j < 3; ++j) { double input; file >> input; // set the electric field at a position (*field)[xind * ysize * zsize * 3 + yind * zsize * 3 + zind * 3 + j] = Units::get(input, "V/cm"); } } return std::make_pair(field, std::array<size_t, 3>{{xsize, ysize, zsize}}); } <|endoftext|>
<commit_before>/** * @author Koen Wolters <[email protected]> */ #include "DetectorHistogrammerModule.hpp" #include <memory> #include <string> #include <utility> #include <TApplication.h> #include <TFile.h> #include "core/geometry/PixelDetectorModel.hpp" #include "core/messenger/Messenger.hpp" #include "core/utils/log.h" using namespace allpix; DetectorHistogrammerModule::DetectorHistogrammerModule(Configuration config, Messenger* messenger, std::shared_ptr<Detector> detector) : Module(detector), config_(std::move(config)), detector_(std::move(detector)), pixels_message_(nullptr) { // fetch deposit for single module messenger->bindSingle(this, &DetectorHistogrammerModule::pixels_message_); } DetectorHistogrammerModule::~DetectorHistogrammerModule() = default; // create histograms void DetectorHistogrammerModule::init() { // get detector model auto model = std::dynamic_pointer_cast<PixelDetectorModel>(detector_->getModel()); if(model == nullptr) { // FIXME: exception can be more appropriate here LOG(ERROR) << "Detector " << detector_->getName() << " is not a PixelDetectorModel: ignored as other types are currently unsupported!"; return; } // create histogram LOG(INFO) << "Creating histograms"; std::string histogram_name = "histogram_" + detector_->getName(); std::string histogram_title = "Histogram for " + detector_->getName(); histogram = new TH2I(histogram_name.c_str(), histogram_title.c_str(), model->getNPixelsX(), 0, model->getNPixelsX(), model->getNPixelsY(), 0, model->getNPixelsY()); // create cluster size plot std::string cluster_size_name = "cluster_" + detector_->getName(); std::string cluster_size_title = "Cluster size for " + detector_->getName(); cluster_size = new TH1I(cluster_size_name.c_str(), cluster_size_title.c_str(), model->getNPixelsX() * model->getNPixelsY(), 0, model->getNPixelsX() * model->getNPixelsY()); } // fill the histograms void DetectorHistogrammerModule::run() { // check if we got any deposits if(pixels_message_ == nullptr) { LOG(WARNING) << "Detector " << detector_->getName() << " did not get any deposits... skipping!"; return; } LOG(DEBUG) << "got charges in " << pixels_message_->getData().size() << " pixels"; // fill 2d histogram for(auto& pixel_charge : pixels_message_->getData()) { auto pixel = pixel_charge.getPixel(); auto charge = pixel_charge.getCharge(); histogram->Fill(pixel.x(), pixel.y(), charge); } // fill cluster histogram cluster_size->Fill(static_cast<double>(pixels_message_->getData().size())); } // create file and write the histograms to it void DetectorHistogrammerModule::finalize() { // create root file std::string file_name = config_.get<std::string>("file_prefix") + "_" + detector_->getName() + ".root"; TFile file(file_name.c_str(), "RECREATE"); // write histograms LOG(INFO) << "Writing histograms to file"; histogram->Write(); cluster_size->Write(); // close the file file.Close(); } <commit_msg>set better histogram options<commit_after>/** * @author Koen Wolters <[email protected]> */ #include "DetectorHistogrammerModule.hpp" #include <memory> #include <string> #include <utility> #include <TApplication.h> #include <TFile.h> #include "core/geometry/PixelDetectorModel.hpp" #include "core/messenger/Messenger.hpp" #include "core/utils/log.h" using namespace allpix; DetectorHistogrammerModule::DetectorHistogrammerModule(Configuration config, Messenger* messenger, std::shared_ptr<Detector> detector) : Module(detector), config_(std::move(config)), detector_(std::move(detector)), pixels_message_(nullptr) { // fetch deposit for single module messenger->bindSingle(this, &DetectorHistogrammerModule::pixels_message_); } DetectorHistogrammerModule::~DetectorHistogrammerModule() = default; // create histograms void DetectorHistogrammerModule::init() { // get detector model auto model = std::dynamic_pointer_cast<PixelDetectorModel>(detector_->getModel()); if(model == nullptr) { // FIXME: exception can be more appropriate here LOG(ERROR) << "Detector " << detector_->getName() << " is not a PixelDetectorModel: ignored as other types are currently unsupported!"; return; } // create histogram LOG(INFO) << "Creating histograms"; std::string histogram_name = "histogram_" + detector_->getName(); std::string histogram_title = "Histogram for " + detector_->getName(); histogram = new TH2I(histogram_name.c_str(), histogram_title.c_str(), model->getNPixelsX(), 0, model->getNPixelsX(), model->getNPixelsY(), 0, model->getNPixelsY()); // create cluster size plot std::string cluster_size_name = "cluster_" + detector_->getName(); std::string cluster_size_title = "Cluster size for " + detector_->getName(); cluster_size = new TH1I(cluster_size_name.c_str(), cluster_size_title.c_str(), model->getNPixelsX() * model->getNPixelsY(), 0, model->getNPixelsX() * model->getNPixelsY()); } // fill the histograms void DetectorHistogrammerModule::run() { // check if we got any deposits if(pixels_message_ == nullptr) { LOG(WARNING) << "Detector " << detector_->getName() << " did not get any deposits... skipping!"; return; } LOG(DEBUG) << "got charges in " << pixels_message_->getData().size() << " pixels"; // fill 2d histogram for(auto& pixel_charge : pixels_message_->getData()) { auto pixel = pixel_charge.getPixel(); auto charge = pixel_charge.getCharge(); histogram->Fill(pixel.x(), pixel.y(), charge); } // fill cluster histogram cluster_size->Fill(static_cast<double>(pixels_message_->getData().size())); } // create file and write the histograms to it void DetectorHistogrammerModule::finalize() { // set more useful spacing maximum for cluster size histogram int xmax = static_cast<int>(std::ceil(cluster_size->GetBinCenter(cluster_size->FindLastBinAbove()) + 1)); cluster_size->GetXaxis()->SetRange(0, xmax); // set default drawing option histogram histogram->SetOption("colz"); // create root file std::string file_name = config_.get<std::string>("file_prefix") + "_" + detector_->getName() + ".root"; TFile file(file_name.c_str(), "RECREATE"); // write histograms LOG(INFO) << "Writing histograms to file"; histogram->Write(); cluster_size->Write(); // close the file file.Close(); } <|endoftext|>
<commit_before>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/compiler/mlir/tensorflow/utils/compile_mlir_util.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/StringRef.h" #include "mlir/Dialect/StandardOps/IR/Ops.h" // TF:llvm-project #include "mlir/IR/Function.h" // TF:llvm-project #include "mlir/IR/MLIRContext.h" // TF:llvm-project #include "mlir/IR/OpDefinition.h" // TF:llvm-project #include "mlir/IR/StandardTypes.h" // TF:llvm-project #include "mlir/Parser.h" // TF:llvm-project #include "mlir/Pass/Pass.h" // TF:llvm-project #include "mlir/Pass/PassManager.h" // TF:llvm-project #include "mlir/Transforms/Passes.h" // TF:llvm-project #include "tensorflow/compiler/mlir/tensorflow/transforms/passes.h" #include "tensorflow/compiler/mlir/tensorflow/transforms/shape_inference.h" #include "tensorflow/compiler/mlir/tensorflow/utils/bridge_logger.h" #include "tensorflow/compiler/mlir/tensorflow/utils/convert_type.h" #include "tensorflow/compiler/mlir/tensorflow/utils/dump_mlir_util.h" #include "tensorflow/compiler/mlir/tensorflow/utils/error_util.h" #include "tensorflow/compiler/mlir/tensorflow/utils/translate_utils.h" #include "tensorflow/compiler/mlir/xla/mlir_hlo_to_hlo.h" #include "tensorflow/compiler/mlir/xla/transforms/passes.h" #include "tensorflow/compiler/mlir/xla/type_to_shape.h" #include "tensorflow/compiler/tf2xla/shape_util.h" #include "tensorflow/core/platform/logging.h" namespace tensorflow { namespace { // Parses the MLIR module from the mlir_module_string. Status ParseMlirModule(llvm::StringRef mlir_module_string, mlir::MLIRContext* mlir_context, mlir::OwningModuleRef* mlir_module) { TF_RET_CHECK(!mlir_module_string.empty()) << "unexpected empty serialized MLIR module string"; TF_RET_CHECK(mlir_module) << "unexpected null MLIR module pointer"; // Make sure we catch any error reported by MLIR and forward it to the TF // error reporting system. mlir::StatusScopedDiagnosticHandler error_handler(mlir_context); // Parse the module. *mlir_module = mlir::parseSourceString(mlir_module_string, mlir_context); if (!*mlir_module) { return error_handler.Combine( errors::InvalidArgument("could not parse MLIR module")); } return Status::OK(); } // Converts arg_shapes to xla::Shape's and store into xla_input_shapes. Status GetXlaInputShapes( mlir::ModuleOp module, llvm::ArrayRef<TensorShape> arg_shapes, const xla::CustomShapeRepresentationFn shape_representation_fn, std::vector<xla::Shape>* xla_input_shapes) { xla_input_shapes->clear(); mlir::FuncOp main_func = module.lookupSymbol<mlir::FuncOp>("main"); mlir::FunctionType func_type = main_func.getType(); int num_args = func_type.getNumInputs(); xla_input_shapes->reserve(num_args); std::vector<xla::Shape> individual_arg_shapes; individual_arg_shapes.reserve(num_args); for (int i = 0; i < num_args; ++i) { individual_arg_shapes.emplace_back(); xla::Shape& xla_shape = individual_arg_shapes.back(); DataType dtype; TF_RETURN_IF_ERROR(ConvertToDataType(func_type.getInput(i), &dtype)); TF_ASSIGN_OR_RETURN(xla_shape, shape_representation_fn(arg_shapes[i], dtype)); } xla_input_shapes->push_back( xla::ShapeUtil::MakeTupleShape(individual_arg_shapes)); return Status::OK(); } // Calculates computation output shape and build OutputDescription for each // output based on static shapes in MLIR module Status GetOutputInfo( mlir::ModuleOp module, const xla::CustomShapeRepresentationFn shape_representation_fn, xla::Shape* xla_output_shape, std::vector<XlaCompiler::OutputDescription>* outputs) { mlir::FuncOp main_func = module.lookupSymbol<mlir::FuncOp>("main"); mlir::FunctionType func_type = main_func.getType(); outputs->clear(); outputs->reserve(func_type.getNumResults()); std::vector<xla::Shape> shapes; shapes.reserve(func_type.getNumResults()); for (mlir::Type type : func_type.getResults()) { TF_ASSIGN_OR_RETURN(xla::Shape shape, TypeToShape(type, shape_representation_fn)); auto tensor_type = type.dyn_cast<mlir::RankedTensorType>(); shapes.push_back(shape); // Construct OutputDescription for result. outputs->emplace_back(); XlaCompiler::OutputDescription& out_desc = outputs->back(); TF_RETURN_IF_ERROR(ConvertToDataType(tensor_type, &out_desc.type)); // TODO(ycao): Support constant output. out_desc.is_constant = false; TF_RETURN_IF_ERROR(XLAShapeToTensorShape(shape, &out_desc.shape)); // Input_index is only meaningful for resource output. Since MLIR-based // TF-Compiler bridge doesn't support resource output yet. Setting it to // meaningless value -1. // TODO(ycao): Support resource-type output. out_desc.input_index = -1; // MLIR-based TF-Compiler bridge doesn't support tensorlist output yet. // TODO(ycao): Support tensorlist-type output. out_desc.is_tensor_list = false; } // XLA computation always uses Tuple shape. *xla_output_shape = xla::ShapeUtil::MakeTupleShape(shapes); return Status::OK(); } // Gets information about how computation updates Tensorflow resources. // TODO(ycao): Implement logic to compute resource updates when we need to // support graphs with resource updates in MLIR-based TF compiler bridge. void GetResourceUpdatesForMlir( std::vector<XlaCompiler::ResourceUpdate>* resource_updates) { resource_updates->clear(); } // Creates a vector that maps from the parameters of the XLA computation to // their original argument positions. // MLIR-based TF-Compiler bridge doesn't have constant analysis yet, thus no // inputs are known constants. Therefore, the input mapping between input to // computation arguments is a trivial in-order 1-1 mapping. // TODO(ycao): Support computation with compile-time constant, which requires // non-trivial input mapping as implemented now. void GetInputMappingForMlir(int num_inputs, std::vector<int>* input_mapping) { input_mapping->resize(num_inputs, 0); std::iota(input_mapping->begin(), input_mapping->end(), 0); } // Refine MLIR types based on new shape information. Status RefineShapes(llvm::ArrayRef<TensorShape> arg_shapes, mlir::ModuleOp module) { auto producer_or = GetTfGraphProducerVersion(module); if (!producer_or.ok()) return producer_or.status(); int64_t producer_version = producer_or.ValueOrDie(); llvm::SmallVector<int64_t, 16> shape_backing; llvm::SmallVector<llvm::ArrayRef<int64_t>, 4> arg_shapes_copy; { // Convert arg_shapes to a mlir friendly format. size_t count = 0; for (const TensorShape& shape : arg_shapes) { count += shape.dims(); } shape_backing.resize(count); arg_shapes_copy.reserve(arg_shapes.size()); size_t offset = 0; for (const TensorShape& shape : arg_shapes) { size_t start = offset; for (tensorflow::TensorShapeDim dim : shape) { shape_backing[offset] = dim.size; ++offset; } if (offset == start) { arg_shapes_copy.push_back(llvm::ArrayRef<int64_t>()); } else { arg_shapes_copy.push_back( llvm::ArrayRef<int64_t>(&shape_backing[start], offset - start)); } } } auto main_func = module.lookupSymbol<mlir::FuncOp>("main"); mlir::StatusScopedDiagnosticHandler error_handler(module.getContext()); mlir::LogicalResult result = mlir::TF::InferShapeForFunction( main_func, arg_shapes_copy, producer_version); if (failed(result)) { return error_handler.Combine( errors::Internal("MLIR Shape refinement failed")); } return Status::OK(); } } // namespace Status ConvertMLIRToXlaComputation(mlir::ModuleOp module_op, xla::XlaComputation* xla_computation, bool use_tuple_args, bool return_tuple) { mlir::PassManager tf2xla(module_op.getContext()); tf2xla.addNestedPass<mlir::FuncOp>(mlir::createCanonicalizerPass()); tf2xla.addPass(mlir::TFDevice::CreateDecomposeResourceOpsPass()); tf2xla.addPass(mlir::TF::CreatePromoteResourcesToArgsPass()); // LegalizeTFControlFlow encapsulates arguments for control flow operations // with a tuple argument which break the assumption of resource lifting // inside PromoteResourcesToArgs. tf2xla.addPass(mlir::xla_hlo::createLegalizeTFControlFlowPass()); // We need to run LegalizeTFPass 2 times because first // LegalizeTFPass(allow_partial_conversion=true) can expose more graph pruning // and canonicalization opportunities that are necessary for the second // LegalizeTFPass(allow_partial_conversion=false) invocation. tf2xla.addNestedPass<mlir::FuncOp>(mlir::xla_hlo::createLegalizeTFPass(true)); tf2xla.addNestedPass<mlir::FuncOp>(mlir::createCanonicalizerPass()); tf2xla.addNestedPass<mlir::FuncOp>( mlir::xla_hlo::createLegalizeTFPass(false)); if (VLOG_IS_ON(1)) tf2xla.enableIRPrinting(std::make_unique<tensorflow::BridgeLoggerConfig>()); // Make sure we catch any error reported by MLIR and forward it to the TF // error reporting system. Report a generic error if pass manager failed // without emitting a diagnostic. mlir::StatusScopedDiagnosticHandler error_handler(module_op.getContext()); if (failed(tf2xla.run(module_op))) { return error_handler.Combine( errors::Internal("MLIR TF to XLA legalization failed")); } if (VLOG_IS_ON(1)) tensorflow::DumpMlirOpToFile("mlir_compile_legalize_hlo", module_op); xla::HloProto hlo_proto; TF_RETURN_IF_ERROR(mlir::ConvertMlirHloToHlo(module_op, &hlo_proto, use_tuple_args, return_tuple)); *xla_computation = xla::XlaComputation(hlo_proto.hlo_module()); return Status::OK(); } Status CompileSerializedMlirToXlaHlo( llvm::StringRef mlir_module_string, llvm::ArrayRef<TensorShape> arg_shapes, const XlaCompiler::ShapeRepresentationFn shape_representation_fn, XlaCompiler::CompilationResult* compilation_result) { mlir::MLIRContext mlir_context; mlir::OwningModuleRef mlir_module; TF_RETURN_IF_ERROR( ParseMlirModule(mlir_module_string, &mlir_context, &mlir_module)); auto module_op = mlir_module.get(); if (VLOG_IS_ON(1)) tensorflow::DumpMlirOpToFile("mlir_compile_before", module_op); // Use arg_shapes to improve the mlir type information of `main` in module_op. TF_RETURN_IF_ERROR(RefineShapes(arg_shapes, module_op)); if (VLOG_IS_ON(1)) tensorflow::DumpMlirOpToFile("mlir_compile_shape_refiner", module_op); // Convert MLIR module to XLA HLO proto contained in XlaComputation. compilation_result->computation = std::make_shared<xla::XlaComputation>(); TF_RETURN_IF_ERROR(ConvertMLIRToXlaComputation( module_op, compilation_result->computation.get(), /*use_tuple_args=*/true, /*return_tuple=*/true)); // Construct mapping from XlaComputation's arg to input edges of execute // node. GetInputMappingForMlir(arg_shapes.size(), &compilation_result->input_mapping); auto shape_representation_fn_no_fast_memory = [shape_representation_fn](const TensorShape& shape, DataType dtype) { return shape_representation_fn(shape, dtype, /*use_fast_memory=*/false); }; // Compute all input shapes. TF_RETURN_IF_ERROR(GetXlaInputShapes(module_op, arg_shapes, shape_representation_fn_no_fast_memory, &compilation_result->xla_input_shapes)); // Compute all output descriptions. TF_RETURN_IF_ERROR(GetOutputInfo( module_op, shape_representation_fn_no_fast_memory, &compilation_result->xla_output_shape, &compilation_result->outputs)); // Compute what resource variables need to be updated after XlaComputation's // execution. GetResourceUpdatesForMlir(&compilation_result->resource_updates); if (VLOG_IS_ON(1)) tensorflow::DumpMlirOpToFile("mlir_compile_after", module_op); return Status::OK(); } } // namespace tensorflow <commit_msg>Remove graph pruning from the HLO lowering pipeline<commit_after>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/compiler/mlir/tensorflow/utils/compile_mlir_util.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/StringRef.h" #include "mlir/Dialect/StandardOps/IR/Ops.h" // TF:llvm-project #include "mlir/IR/Function.h" // TF:llvm-project #include "mlir/IR/MLIRContext.h" // TF:llvm-project #include "mlir/IR/OpDefinition.h" // TF:llvm-project #include "mlir/IR/StandardTypes.h" // TF:llvm-project #include "mlir/Parser.h" // TF:llvm-project #include "mlir/Pass/Pass.h" // TF:llvm-project #include "mlir/Pass/PassManager.h" // TF:llvm-project #include "mlir/Transforms/Passes.h" // TF:llvm-project #include "tensorflow/compiler/mlir/tensorflow/transforms/passes.h" #include "tensorflow/compiler/mlir/tensorflow/transforms/shape_inference.h" #include "tensorflow/compiler/mlir/tensorflow/utils/bridge_logger.h" #include "tensorflow/compiler/mlir/tensorflow/utils/convert_type.h" #include "tensorflow/compiler/mlir/tensorflow/utils/dump_mlir_util.h" #include "tensorflow/compiler/mlir/tensorflow/utils/error_util.h" #include "tensorflow/compiler/mlir/tensorflow/utils/translate_utils.h" #include "tensorflow/compiler/mlir/xla/mlir_hlo_to_hlo.h" #include "tensorflow/compiler/mlir/xla/transforms/passes.h" #include "tensorflow/compiler/mlir/xla/type_to_shape.h" #include "tensorflow/compiler/tf2xla/shape_util.h" #include "tensorflow/core/platform/logging.h" namespace tensorflow { namespace { // Parses the MLIR module from the mlir_module_string. Status ParseMlirModule(llvm::StringRef mlir_module_string, mlir::MLIRContext* mlir_context, mlir::OwningModuleRef* mlir_module) { TF_RET_CHECK(!mlir_module_string.empty()) << "unexpected empty serialized MLIR module string"; TF_RET_CHECK(mlir_module) << "unexpected null MLIR module pointer"; // Make sure we catch any error reported by MLIR and forward it to the TF // error reporting system. mlir::StatusScopedDiagnosticHandler error_handler(mlir_context); // Parse the module. *mlir_module = mlir::parseSourceString(mlir_module_string, mlir_context); if (!*mlir_module) { return error_handler.Combine( errors::InvalidArgument("could not parse MLIR module")); } return Status::OK(); } // Converts arg_shapes to xla::Shape's and store into xla_input_shapes. Status GetXlaInputShapes( mlir::ModuleOp module, llvm::ArrayRef<TensorShape> arg_shapes, const xla::CustomShapeRepresentationFn shape_representation_fn, std::vector<xla::Shape>* xla_input_shapes) { xla_input_shapes->clear(); mlir::FuncOp main_func = module.lookupSymbol<mlir::FuncOp>("main"); mlir::FunctionType func_type = main_func.getType(); int num_args = func_type.getNumInputs(); xla_input_shapes->reserve(num_args); std::vector<xla::Shape> individual_arg_shapes; individual_arg_shapes.reserve(num_args); for (int i = 0; i < num_args; ++i) { individual_arg_shapes.emplace_back(); xla::Shape& xla_shape = individual_arg_shapes.back(); DataType dtype; TF_RETURN_IF_ERROR(ConvertToDataType(func_type.getInput(i), &dtype)); TF_ASSIGN_OR_RETURN(xla_shape, shape_representation_fn(arg_shapes[i], dtype)); } xla_input_shapes->push_back( xla::ShapeUtil::MakeTupleShape(individual_arg_shapes)); return Status::OK(); } // Calculates computation output shape and build OutputDescription for each // output based on static shapes in MLIR module Status GetOutputInfo( mlir::ModuleOp module, const xla::CustomShapeRepresentationFn shape_representation_fn, xla::Shape* xla_output_shape, std::vector<XlaCompiler::OutputDescription>* outputs) { mlir::FuncOp main_func = module.lookupSymbol<mlir::FuncOp>("main"); mlir::FunctionType func_type = main_func.getType(); outputs->clear(); outputs->reserve(func_type.getNumResults()); std::vector<xla::Shape> shapes; shapes.reserve(func_type.getNumResults()); for (mlir::Type type : func_type.getResults()) { TF_ASSIGN_OR_RETURN(xla::Shape shape, TypeToShape(type, shape_representation_fn)); auto tensor_type = type.dyn_cast<mlir::RankedTensorType>(); shapes.push_back(shape); // Construct OutputDescription for result. outputs->emplace_back(); XlaCompiler::OutputDescription& out_desc = outputs->back(); TF_RETURN_IF_ERROR(ConvertToDataType(tensor_type, &out_desc.type)); // TODO(ycao): Support constant output. out_desc.is_constant = false; TF_RETURN_IF_ERROR(XLAShapeToTensorShape(shape, &out_desc.shape)); // Input_index is only meaningful for resource output. Since MLIR-based // TF-Compiler bridge doesn't support resource output yet. Setting it to // meaningless value -1. // TODO(ycao): Support resource-type output. out_desc.input_index = -1; // MLIR-based TF-Compiler bridge doesn't support tensorlist output yet. // TODO(ycao): Support tensorlist-type output. out_desc.is_tensor_list = false; } // XLA computation always uses Tuple shape. *xla_output_shape = xla::ShapeUtil::MakeTupleShape(shapes); return Status::OK(); } // Gets information about how computation updates Tensorflow resources. // TODO(ycao): Implement logic to compute resource updates when we need to // support graphs with resource updates in MLIR-based TF compiler bridge. void GetResourceUpdatesForMlir( std::vector<XlaCompiler::ResourceUpdate>* resource_updates) { resource_updates->clear(); } // Creates a vector that maps from the parameters of the XLA computation to // their original argument positions. // MLIR-based TF-Compiler bridge doesn't have constant analysis yet, thus no // inputs are known constants. Therefore, the input mapping between input to // computation arguments is a trivial in-order 1-1 mapping. // TODO(ycao): Support computation with compile-time constant, which requires // non-trivial input mapping as implemented now. void GetInputMappingForMlir(int num_inputs, std::vector<int>* input_mapping) { input_mapping->resize(num_inputs, 0); std::iota(input_mapping->begin(), input_mapping->end(), 0); } // Refine MLIR types based on new shape information. Status RefineShapes(llvm::ArrayRef<TensorShape> arg_shapes, mlir::ModuleOp module) { auto producer_or = GetTfGraphProducerVersion(module); if (!producer_or.ok()) return producer_or.status(); int64_t producer_version = producer_or.ValueOrDie(); llvm::SmallVector<int64_t, 16> shape_backing; llvm::SmallVector<llvm::ArrayRef<int64_t>, 4> arg_shapes_copy; { // Convert arg_shapes to a mlir friendly format. size_t count = 0; for (const TensorShape& shape : arg_shapes) { count += shape.dims(); } shape_backing.resize(count); arg_shapes_copy.reserve(arg_shapes.size()); size_t offset = 0; for (const TensorShape& shape : arg_shapes) { size_t start = offset; for (tensorflow::TensorShapeDim dim : shape) { shape_backing[offset] = dim.size; ++offset; } if (offset == start) { arg_shapes_copy.push_back(llvm::ArrayRef<int64_t>()); } else { arg_shapes_copy.push_back( llvm::ArrayRef<int64_t>(&shape_backing[start], offset - start)); } } } auto main_func = module.lookupSymbol<mlir::FuncOp>("main"); mlir::StatusScopedDiagnosticHandler error_handler(module.getContext()); mlir::LogicalResult result = mlir::TF::InferShapeForFunction( main_func, arg_shapes_copy, producer_version); if (failed(result)) { return error_handler.Combine( errors::Internal("MLIR Shape refinement failed")); } return Status::OK(); } } // namespace Status ConvertMLIRToXlaComputation(mlir::ModuleOp module_op, xla::XlaComputation* xla_computation, bool use_tuple_args, bool return_tuple) { mlir::PassManager tf2xla(module_op.getContext()); tf2xla.addNestedPass<mlir::FuncOp>(mlir::createCanonicalizerPass()); tf2xla.addPass(mlir::TFDevice::CreateDecomposeResourceOpsPass()); tf2xla.addPass(mlir::TF::CreatePromoteResourcesToArgsPass()); // LegalizeTFControlFlow encapsulates arguments for control flow operations // with a tuple argument which break the assumption of resource lifting // inside PromoteResourcesToArgs. tf2xla.addPass(mlir::xla_hlo::createLegalizeTFControlFlowPass()); // We need to run LegalizeTFPass 2 times because first // LegalizeTFPass(allow_partial_conversion=true) can expose more graph pruning // and canonicalization opportunities that are necessary for the second // LegalizeTFPass(allow_partial_conversion=false) invocation. tf2xla.addNestedPass<mlir::FuncOp>(mlir::xla_hlo::createLegalizeTFPass(true)); tf2xla.addPass(mlir::tf_executor::CreateTFExecutorGraphPruningPass()); tf2xla.addNestedPass<mlir::FuncOp>(mlir::createCanonicalizerPass()); tf2xla.addNestedPass<mlir::FuncOp>( mlir::xla_hlo::createLegalizeTFPass(false)); if (VLOG_IS_ON(1)) tf2xla.enableIRPrinting(std::make_unique<tensorflow::BridgeLoggerConfig>()); // Make sure we catch any error reported by MLIR and forward it to the TF // error reporting system. Report a generic error if pass manager failed // without emitting a diagnostic. mlir::StatusScopedDiagnosticHandler error_handler(module_op.getContext()); if (failed(tf2xla.run(module_op))) { return error_handler.Combine( errors::Internal("MLIR TF to XLA legalization failed")); } if (VLOG_IS_ON(1)) tensorflow::DumpMlirOpToFile("mlir_compile_legalize_hlo", module_op); xla::HloProto hlo_proto; TF_RETURN_IF_ERROR(mlir::ConvertMlirHloToHlo(module_op, &hlo_proto, use_tuple_args, return_tuple)); *xla_computation = xla::XlaComputation(hlo_proto.hlo_module()); return Status::OK(); } Status CompileSerializedMlirToXlaHlo( llvm::StringRef mlir_module_string, llvm::ArrayRef<TensorShape> arg_shapes, const XlaCompiler::ShapeRepresentationFn shape_representation_fn, XlaCompiler::CompilationResult* compilation_result) { mlir::MLIRContext mlir_context; mlir::OwningModuleRef mlir_module; TF_RETURN_IF_ERROR( ParseMlirModule(mlir_module_string, &mlir_context, &mlir_module)); auto module_op = mlir_module.get(); if (VLOG_IS_ON(1)) tensorflow::DumpMlirOpToFile("mlir_compile_before", module_op); // Use arg_shapes to improve the mlir type information of `main` in module_op. TF_RETURN_IF_ERROR(RefineShapes(arg_shapes, module_op)); if (VLOG_IS_ON(1)) tensorflow::DumpMlirOpToFile("mlir_compile_shape_refiner", module_op); // Convert MLIR module to XLA HLO proto contained in XlaComputation. compilation_result->computation = std::make_shared<xla::XlaComputation>(); TF_RETURN_IF_ERROR(ConvertMLIRToXlaComputation( module_op, compilation_result->computation.get(), /*use_tuple_args=*/true, /*return_tuple=*/true)); // Construct mapping from XlaComputation's arg to input edges of execute // node. GetInputMappingForMlir(arg_shapes.size(), &compilation_result->input_mapping); auto shape_representation_fn_no_fast_memory = [shape_representation_fn](const TensorShape& shape, DataType dtype) { return shape_representation_fn(shape, dtype, /*use_fast_memory=*/false); }; // Compute all input shapes. TF_RETURN_IF_ERROR(GetXlaInputShapes(module_op, arg_shapes, shape_representation_fn_no_fast_memory, &compilation_result->xla_input_shapes)); // Compute all output descriptions. TF_RETURN_IF_ERROR(GetOutputInfo( module_op, shape_representation_fn_no_fast_memory, &compilation_result->xla_output_shape, &compilation_result->outputs)); // Compute what resource variables need to be updated after XlaComputation's // execution. GetResourceUpdatesForMlir(&compilation_result->resource_updates); if (VLOG_IS_ON(1)) tensorflow::DumpMlirOpToFile("mlir_compile_after", module_op); return Status::OK(); } } // namespace tensorflow <|endoftext|>
<commit_before>#pragma once #include "core_configuration/core_configuration.hpp" #include "counter_chunk_value.hpp" #include "counter_direction.hpp" #include "counter_entry.hpp" #include "options.hpp" #include "types/absolute_time_duration.hpp" #include "types/pointing_motion.hpp" #include <algorithm> #include <deque> #include <nod/nod.hpp> #include <numeric> #include <optional> #include <pqrs/dispatcher.hpp> #include <pqrs/osx/chrono.hpp> #include <pqrs/sign.hpp> namespace krbn { namespace manipulator { namespace manipulators { namespace mouse_motion_to_scroll { class counter final : pqrs::dispatcher::extra::dispatcher_client { public: using chunk_accumulated_values_entry_t = std::pair<pqrs::dispatcher::time_point, int>; using chunk_accumulated_values_t = std::deque<std::pair<pqrs::dispatcher::time_point, int>>; static constexpr int timer_interval = 20; // Signals (invoked from the dispatcher thread) nod::signal<void(const pointing_motion&)> scroll_event_arrived; // Methods counter(std::weak_ptr<pqrs::dispatcher::dispatcher> weak_dispatcher, const core_configuration::details::complex_modifications_parameters& parameters, const options& options) : dispatcher_client(weak_dispatcher), parameters_(parameters), options_(options), counter_direction_(counter_direction::none), total_x_(0), total_y_(0), momentum_x_(0), momentum_y_(0), momentum_count_(0), momentum_wait_(0), timer_(*this) { } ~counter(void) { detach_from_dispatcher([this] { timer_.stop(); }); } void update(const pointing_motion& motion, pqrs::dispatcher::time_point time_point) { enqueue_to_dispatcher([this, motion, time_point] { entries_.emplace_back(motion.get_x(), motion.get_y(), time_point); timer_.start( [this] { bool continue_timer = false; continue_timer |= process_entries(); continue_timer |= scroll(); if (!continue_timer) { timer_.stop(); } }, std::chrono::milliseconds(timer_interval)); }); } void async_reset(void) { enqueue_to_dispatcher([this] { entries_.empty(); last_entry_time_point_ = std::nullopt; last_scroll_time_point_ = std::nullopt; counter_direction_ = counter_direction::none; chunk_accumulated_values_x_.clear(); chunk_accumulated_values_y_.clear(); total_x_ = 0; total_y_ = 0; momentum_x_ = 0; momentum_y_ = 0; momentum_count_ = 0; momentum_wait_ = 0; }); } private: bool process_entries(void) { if (entries_.empty()) { return false; } auto recent_time_duration_milliseconds = options_.get_recent_time_duration_milliseconds(); auto front_time_point = entries_.front().get_time_point(); if (when_now() - front_time_point <= recent_time_duration_milliseconds) { return true; } erase_chunk_accumulated_values(chunk_accumulated_values_x_, front_time_point); erase_chunk_accumulated_values(chunk_accumulated_values_y_, front_time_point); bool initial = false; if (chunk_accumulated_values_x_.empty() && chunk_accumulated_values_y_.empty()) { initial = true; counter_direction_ = counter_direction::none; } // Accumulate chunk_x,chunk_y counter_chunk_value chunk_x; counter_chunk_value chunk_y; while (!entries_.empty()) { auto t = entries_.front().get_time_point(); auto duration = t - front_time_point; if (duration <= recent_time_duration_milliseconds) { auto x = entries_.front().get_x(); auto y = entries_.front().get_y(); chunk_x.add(x); chunk_y.add(y); last_entry_time_point_ = t; entries_.pop_front(); } else { break; } } auto x = chunk_x.make_accumulated_value(); auto y = chunk_y.make_accumulated_value(); // Update chunk_accumulated_values_* chunk_accumulated_values_x_.push_back(std::make_pair(front_time_point, x)); chunk_accumulated_values_y_.push_back(std::make_pair(front_time_point, y)); // Reset direction { auto recent_chunks_total_x = accumulate_abs_chunk_accumulated_values(chunk_accumulated_values_x_); auto recent_chunks_total_y = accumulate_abs_chunk_accumulated_values(chunk_accumulated_values_y_); if (counter_direction_ == counter_direction::horizontal) { if (recent_chunks_total_y > recent_chunks_total_x) { counter_direction_ = counter_direction::none; } } else if (counter_direction_ == counter_direction::vertical) { if (recent_chunks_total_x > recent_chunks_total_y) { counter_direction_ = counter_direction::none; } } } // Set direction if (counter_direction_ == counter_direction::none) { if (chunk_x.get_abs_total() > chunk_y.get_abs_total()) { counter_direction_ = counter_direction::horizontal; } else { counter_direction_ = counter_direction::vertical; } total_x_ = 0; total_y_ = 0; momentum_x_ = 0; momentum_y_ = 0; momentum_minus_ = options_.get_threshold(); } // Apply direction if (counter_direction_ == counter_direction::horizontal) { y = 0; } else if (counter_direction_ == counter_direction::vertical) { x = 0; } // Reset if sign is changed. if (x != 0 && pqrs::make_sign(total_x_) != pqrs::make_sign(x)) { // Keep total_abs_x_ total_x_ = 0; momentum_x_ = 0; momentum_minus_ = options_.get_threshold(); initial = true; } if (y != 0 && pqrs::make_sign(total_y_) != pqrs::make_sign(y)) { // Keep total_abs_y_ total_y_ = 0; momentum_y_ = 0; momentum_minus_ = options_.get_threshold(); initial = true; } // Multiply x,y double multiplier = parameters_.make_mouse_motion_to_scroll_speed_rate() * options_.get_speed_multiplier(); x *= multiplier; y *= multiplier; // Modify total_* total_x_ += x; total_y_ += y; if (total_x_ == 0 && total_y_ == 0) { return true; } // Enlarge total_x, total_y if initial event if (initial) { int least_value = options_.get_threshold(); #if 0 std::cout << "least_value " << least_value << std::endl; #endif if (least_value == 0) { least_value = 1; } if (0 < total_x_) { total_x_ = std::max(total_x_, least_value); } else if (total_x_ < 0) { total_x_ = std::min(total_x_, -least_value); } if (0 < total_y_) { total_y_ = std::max(total_y_, least_value); } else if (total_y_ < 0) { total_y_ = std::min(total_y_, -least_value); } } // Update momentum values { auto value = static_cast<double>(std::max(std::abs(total_x_), std::abs(total_y_))); value /= options_.get_threshold(); if (value > 10) { value = 10; } auto minus = static_cast<int>(static_cast<double>(options_.get_threshold()) / std::pow(value, 4)); if (minus <= 0) { minus = 1; } momentum_minus_ = std::min(momentum_minus_, minus); #if 0 std::cout << "total_x_ " << total_x_ << std::endl; std::cout << "total_y_ " << total_y_ << std::endl; std::cout << "value " << value << std::endl; std::cout << "pow " << std::pow(value, 4) << std::endl; std::cout << "minus " << minus << std::endl; std::cout << "momentum_minus_ " << momentum_minus_ << std::endl; #endif } last_scroll_time_point_ = std::nullopt; momentum_count_ = 0; momentum_wait_ = 0; return true; } bool scroll(void) { if (momentum_wait_ > 0) { --momentum_wait_; return true; } ++momentum_count_; if (momentum_count_ == 0) { return false; } auto now = when_now(); if (last_scroll_time_point_ && now - *last_scroll_time_point_ > options_.get_scroll_event_interval_milliseconds_threshold()) { return false; } double scale = (1.0 / momentum_count_); if (!options_.get_momentum_scroll_enabled() && momentum_count_ > 1) { scale = 0; } int dx = round_up(total_x_ * scale); int dy = round_up(total_y_ * scale); momentum_x_ += dx; momentum_y_ += dy; auto x = convert(momentum_x_); auto y = convert(momentum_y_); #if 0 std::cout << "scale: " << scale << std::endl; std::cout << "tx,ty: " << total_x_ << "," << total_y_ << std::endl; std::cout << "dx,dy: " << dx << "," << dy << std::endl; std::cout << "mx,my: " << momentum_x_ << "," << momentum_y_ << std::endl; std::cout << "x,y: " << x << "," << y << std::endl; #endif if (x != 0 || y != 0) { pointing_motion motion(0, 0, -y, x); enqueue_to_dispatcher([this, motion] { scroll_event_arrived(motion); }); last_scroll_time_point_ = now; } reduce(total_x_, momentum_minus_); reduce(total_y_, momentum_minus_); if (total_x_ == 0 && total_y_ == 0) { return false; } if (options_.get_momentum_scroll_enabled()) { momentum_wait_ = std::min(momentum_count_, 10); } return true; } void erase_chunk_accumulated_values(chunk_accumulated_values_t& chunk_accumulated_values, pqrs::dispatcher::time_point time_point) const { auto threshold = options_.get_recent_time_duration_milliseconds() * options_.get_direction_lock_threshold(); chunk_accumulated_values.erase(std::remove_if(std::begin(chunk_accumulated_values), std::end(chunk_accumulated_values), [time_point, threshold](auto&& p) { return (time_point - p.first) > threshold; }), std::end(chunk_accumulated_values)); } int accumulate_abs_chunk_accumulated_values(const chunk_accumulated_values_t& chunk_accumulated_values) const { return std::accumulate(std::begin(chunk_accumulated_values), std::end(chunk_accumulated_values), 0, [](auto&& a, auto&& b) { return a + std::abs(b.second); }); } int round_up(double value) const { if (value > 0) { return std::ceil(value); } else if (value < 0) { return std::ceil(value) - 1; } return 0; } int convert(int& value) const { int result = 0; int threshold = options_.get_threshold(); while (value >= threshold) { value -= threshold; ++result; if (options_.get_momentum_scroll_enabled()) { break; } } while (value <= -threshold) { value += threshold; --result; if (options_.get_momentum_scroll_enabled()) { break; } } return result; } void reduce(int& value, int amount) const { if (value > 0) { value -= std::min(amount, value); } else if (value < 0) { value += std::min(amount, -value); } } const core_configuration::details::complex_modifications_parameters parameters_; const options options_; std::deque<counter_entry> entries_; std::optional<pqrs::dispatcher::time_point> last_entry_time_point_; std::optional<pqrs::dispatcher::time_point> last_scroll_time_point_; counter_direction counter_direction_; chunk_accumulated_values_t chunk_accumulated_values_x_; chunk_accumulated_values_t chunk_accumulated_values_y_; int total_x_; int total_y_; int momentum_x_; int momentum_y_; int momentum_minus_; int momentum_count_; int momentum_wait_; pqrs::dispatcher::extra::timer timer_; }; } // namespace mouse_motion_to_scroll } // namespace manipulators } // namespace manipulator } // namespace krbn <commit_msg>Fix mouse_motion_to_scroll::counter::async_reset<commit_after>#pragma once #include "core_configuration/core_configuration.hpp" #include "counter_chunk_value.hpp" #include "counter_direction.hpp" #include "counter_entry.hpp" #include "options.hpp" #include "types/absolute_time_duration.hpp" #include "types/pointing_motion.hpp" #include <algorithm> #include <deque> #include <nod/nod.hpp> #include <numeric> #include <optional> #include <pqrs/dispatcher.hpp> #include <pqrs/osx/chrono.hpp> #include <pqrs/sign.hpp> namespace krbn { namespace manipulator { namespace manipulators { namespace mouse_motion_to_scroll { class counter final : pqrs::dispatcher::extra::dispatcher_client { public: using chunk_accumulated_values_entry_t = std::pair<pqrs::dispatcher::time_point, int>; using chunk_accumulated_values_t = std::deque<std::pair<pqrs::dispatcher::time_point, int>>; static constexpr int timer_interval = 20; // Signals (invoked from the dispatcher thread) nod::signal<void(const pointing_motion&)> scroll_event_arrived; // Methods counter(std::weak_ptr<pqrs::dispatcher::dispatcher> weak_dispatcher, const core_configuration::details::complex_modifications_parameters& parameters, const options& options) : dispatcher_client(weak_dispatcher), parameters_(parameters), options_(options), counter_direction_(counter_direction::none), total_x_(0), total_y_(0), momentum_x_(0), momentum_y_(0), momentum_count_(0), momentum_wait_(0), timer_(*this) { } ~counter(void) { detach_from_dispatcher([this] { timer_.stop(); }); } void update(const pointing_motion& motion, pqrs::dispatcher::time_point time_point) { enqueue_to_dispatcher([this, motion, time_point] { entries_.emplace_back(motion.get_x(), motion.get_y(), time_point); timer_.start( [this] { bool continue_timer = false; continue_timer |= process_entries(); continue_timer |= scroll(); if (!continue_timer) { timer_.stop(); } }, std::chrono::milliseconds(timer_interval)); }); } void async_reset(void) { enqueue_to_dispatcher([this] { entries_.clear(); last_entry_time_point_ = std::nullopt; last_scroll_time_point_ = std::nullopt; counter_direction_ = counter_direction::none; chunk_accumulated_values_x_.clear(); chunk_accumulated_values_y_.clear(); total_x_ = 0; total_y_ = 0; momentum_x_ = 0; momentum_y_ = 0; momentum_count_ = 0; momentum_wait_ = 0; }); } private: bool process_entries(void) { if (entries_.empty()) { return false; } auto recent_time_duration_milliseconds = options_.get_recent_time_duration_milliseconds(); auto front_time_point = entries_.front().get_time_point(); if (when_now() - front_time_point <= recent_time_duration_milliseconds) { return true; } erase_chunk_accumulated_values(chunk_accumulated_values_x_, front_time_point); erase_chunk_accumulated_values(chunk_accumulated_values_y_, front_time_point); bool initial = false; if (chunk_accumulated_values_x_.empty() && chunk_accumulated_values_y_.empty()) { initial = true; counter_direction_ = counter_direction::none; } // Accumulate chunk_x,chunk_y counter_chunk_value chunk_x; counter_chunk_value chunk_y; while (!entries_.empty()) { auto t = entries_.front().get_time_point(); auto duration = t - front_time_point; if (duration <= recent_time_duration_milliseconds) { auto x = entries_.front().get_x(); auto y = entries_.front().get_y(); chunk_x.add(x); chunk_y.add(y); last_entry_time_point_ = t; entries_.pop_front(); } else { break; } } auto x = chunk_x.make_accumulated_value(); auto y = chunk_y.make_accumulated_value(); // Update chunk_accumulated_values_* chunk_accumulated_values_x_.push_back(std::make_pair(front_time_point, x)); chunk_accumulated_values_y_.push_back(std::make_pair(front_time_point, y)); // Reset direction { auto recent_chunks_total_x = accumulate_abs_chunk_accumulated_values(chunk_accumulated_values_x_); auto recent_chunks_total_y = accumulate_abs_chunk_accumulated_values(chunk_accumulated_values_y_); if (counter_direction_ == counter_direction::horizontal) { if (recent_chunks_total_y > recent_chunks_total_x) { counter_direction_ = counter_direction::none; } } else if (counter_direction_ == counter_direction::vertical) { if (recent_chunks_total_x > recent_chunks_total_y) { counter_direction_ = counter_direction::none; } } } // Set direction if (counter_direction_ == counter_direction::none) { if (chunk_x.get_abs_total() > chunk_y.get_abs_total()) { counter_direction_ = counter_direction::horizontal; } else { counter_direction_ = counter_direction::vertical; } total_x_ = 0; total_y_ = 0; momentum_x_ = 0; momentum_y_ = 0; momentum_minus_ = options_.get_threshold(); } // Apply direction if (counter_direction_ == counter_direction::horizontal) { y = 0; } else if (counter_direction_ == counter_direction::vertical) { x = 0; } // Reset if sign is changed. if (x != 0 && pqrs::make_sign(total_x_) != pqrs::make_sign(x)) { // Keep total_abs_x_ total_x_ = 0; momentum_x_ = 0; momentum_minus_ = options_.get_threshold(); initial = true; } if (y != 0 && pqrs::make_sign(total_y_) != pqrs::make_sign(y)) { // Keep total_abs_y_ total_y_ = 0; momentum_y_ = 0; momentum_minus_ = options_.get_threshold(); initial = true; } // Multiply x,y double multiplier = parameters_.make_mouse_motion_to_scroll_speed_rate() * options_.get_speed_multiplier(); x *= multiplier; y *= multiplier; // Modify total_* total_x_ += x; total_y_ += y; if (total_x_ == 0 && total_y_ == 0) { return true; } // Enlarge total_x, total_y if initial event if (initial) { int least_value = options_.get_threshold(); #if 0 std::cout << "least_value " << least_value << std::endl; #endif if (least_value == 0) { least_value = 1; } if (0 < total_x_) { total_x_ = std::max(total_x_, least_value); } else if (total_x_ < 0) { total_x_ = std::min(total_x_, -least_value); } if (0 < total_y_) { total_y_ = std::max(total_y_, least_value); } else if (total_y_ < 0) { total_y_ = std::min(total_y_, -least_value); } } // Update momentum values { auto value = static_cast<double>(std::max(std::abs(total_x_), std::abs(total_y_))); value /= options_.get_threshold(); if (value > 10) { value = 10; } auto minus = static_cast<int>(static_cast<double>(options_.get_threshold()) / std::pow(value, 4)); if (minus <= 0) { minus = 1; } momentum_minus_ = std::min(momentum_minus_, minus); #if 0 std::cout << "total_x_ " << total_x_ << std::endl; std::cout << "total_y_ " << total_y_ << std::endl; std::cout << "value " << value << std::endl; std::cout << "pow " << std::pow(value, 4) << std::endl; std::cout << "minus " << minus << std::endl; std::cout << "momentum_minus_ " << momentum_minus_ << std::endl; #endif } last_scroll_time_point_ = std::nullopt; momentum_count_ = 0; momentum_wait_ = 0; return true; } bool scroll(void) { if (momentum_wait_ > 0) { --momentum_wait_; return true; } ++momentum_count_; if (momentum_count_ == 0) { return false; } auto now = when_now(); if (last_scroll_time_point_ && now - *last_scroll_time_point_ > options_.get_scroll_event_interval_milliseconds_threshold()) { return false; } double scale = (1.0 / momentum_count_); if (!options_.get_momentum_scroll_enabled() && momentum_count_ > 1) { scale = 0; } int dx = round_up(total_x_ * scale); int dy = round_up(total_y_ * scale); momentum_x_ += dx; momentum_y_ += dy; auto x = convert(momentum_x_); auto y = convert(momentum_y_); #if 0 std::cout << "scale: " << scale << std::endl; std::cout << "tx,ty: " << total_x_ << "," << total_y_ << std::endl; std::cout << "dx,dy: " << dx << "," << dy << std::endl; std::cout << "mx,my: " << momentum_x_ << "," << momentum_y_ << std::endl; std::cout << "x,y: " << x << "," << y << std::endl; #endif if (x != 0 || y != 0) { pointing_motion motion(0, 0, -y, x); enqueue_to_dispatcher([this, motion] { scroll_event_arrived(motion); }); last_scroll_time_point_ = now; } reduce(total_x_, momentum_minus_); reduce(total_y_, momentum_minus_); if (total_x_ == 0 && total_y_ == 0) { return false; } if (options_.get_momentum_scroll_enabled()) { momentum_wait_ = std::min(momentum_count_, 10); } return true; } void erase_chunk_accumulated_values(chunk_accumulated_values_t& chunk_accumulated_values, pqrs::dispatcher::time_point time_point) const { auto threshold = options_.get_recent_time_duration_milliseconds() * options_.get_direction_lock_threshold(); chunk_accumulated_values.erase(std::remove_if(std::begin(chunk_accumulated_values), std::end(chunk_accumulated_values), [time_point, threshold](auto&& p) { return (time_point - p.first) > threshold; }), std::end(chunk_accumulated_values)); } int accumulate_abs_chunk_accumulated_values(const chunk_accumulated_values_t& chunk_accumulated_values) const { return std::accumulate(std::begin(chunk_accumulated_values), std::end(chunk_accumulated_values), 0, [](auto&& a, auto&& b) { return a + std::abs(b.second); }); } int round_up(double value) const { if (value > 0) { return std::ceil(value); } else if (value < 0) { return std::ceil(value) - 1; } return 0; } int convert(int& value) const { int result = 0; int threshold = options_.get_threshold(); while (value >= threshold) { value -= threshold; ++result; if (options_.get_momentum_scroll_enabled()) { break; } } while (value <= -threshold) { value += threshold; --result; if (options_.get_momentum_scroll_enabled()) { break; } } return result; } void reduce(int& value, int amount) const { if (value > 0) { value -= std::min(amount, value); } else if (value < 0) { value += std::min(amount, -value); } } const core_configuration::details::complex_modifications_parameters parameters_; const options options_; std::deque<counter_entry> entries_; std::optional<pqrs::dispatcher::time_point> last_entry_time_point_; std::optional<pqrs::dispatcher::time_point> last_scroll_time_point_; counter_direction counter_direction_; chunk_accumulated_values_t chunk_accumulated_values_x_; chunk_accumulated_values_t chunk_accumulated_values_y_; int total_x_; int total_y_; int momentum_x_; int momentum_y_; int momentum_minus_; int momentum_count_; int momentum_wait_; pqrs::dispatcher::extra::timer timer_; }; } // namespace mouse_motion_to_scroll } // namespace manipulators } // namespace manipulator } // namespace krbn <|endoftext|>
<commit_before>#define _LOG_PROB_ poisson_log_log #include <stan/prob/distributions/univariate/discrete/poisson.hpp> #include <test/agrad/distributions/distribution_test_fixture.hpp> #include <test/agrad/distributions/distribution_tests_1_discrete_1_param.hpp> using std::vector; using std::numeric_limits; using stan::agrad::var; class AgradDistributionsPoissonLog : public AgradDistributionTest { public: void valid_values(vector<vector<double> >& parameters) { using std::log; vector<double> param(2); param[0] = 17; // n param[1] = log(13.0); // lambda parameters.push_back(param); param[0] = 192; // n param[1] = log(42.0); // lambda parameters.push_back(param); param[0] = 0; // n param[1] = log(3.0); // lambda parameters.push_back(param); /*param[0] = 0; // n param[1] = std::numeric_limits<double>::infinity(); // lambda parameters.push_back(param);*/ /* param[0] = 1; // n param[1] = 0.0; // lambda parameters.push_back(param);*/ } void invalid_values(vector<size_t>& index, vector<double>& value) { // n index.push_back(0U); value.push_back(-1); } template <class T_log_rate> var log_prob(const int n, const T_log_rate& alpha) { using std::exp; using boost::math::lgamma; using stan::math::multiply_log; using stan::prob::LOG_ZERO; using stan::prob::include_summand; var logp(0); if (log(alpha) == 0) return n == 0 ? 0 : LOG_ZERO; if (std::isinf(log(alpha))) return LOG_ZERO; if (include_summand<true>::value) logp -= lgamma(n + 1.0); if (include_summand<true,T_log_rate>::value) logp += n * alpha - exp(alpha); return logp; } }; INSTANTIATE_TYPED_TEST_CASE_P(AgradDistributionsPoissonLog, AgradDistributionTestFixture, AgradDistributionsPoissonLog); <commit_msg>updated agrad distro test for Daniel's new framework<commit_after>#define _LOG_PROB_ poisson_log_log #include <stan/prob/distributions/univariate/discrete/poisson.hpp> #include <test/agrad/distributions/distribution_test_fixture.hpp> #include <test/agrad/distributions/distribution_tests_1_discrete_1_param.hpp> using std::vector; using std::numeric_limits; using stan::agrad::var; class AgradDistributionsPoisson : public AgradDistributionTest { public: void valid_values(vector<vector<double> >& parameters) { vector<double> param(2); param[0] = 17; // n param[1] = log(13.0); // alpha parameters.push_back(param); param[0] = 192; // n param[1] = log(42.0); // alpha parameters.push_back(param); param[0] = 0; // n param[1] = log(3.0); // alpha parameters.push_back(param); /*param[0] = 0; // n param[1] = std::numeric_limits<double>::infinity(); // alpha parameters.push_back(param);*/ /* param[0] = 1; // n param[1] = 0.0; // alpha parameters.push_back(param);*/ } void invalid_values(vector<size_t>& index, vector<double>& value) { // n index.push_back(0U); value.push_back(-1); } template <class T_n=int, class T_rate, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9> var log_prob(const T_n& n, const T_rate& alpha, const T2&, const T3&, const T4&, const T5&, const T6&, const T7&, const T8&, const T9&) { using std::exp; using boost::math::lgamma; using stan::math::multiply_log; using stan::prob::LOG_ZERO; using stan::prob::include_summand; var logp(0); if (alpha == -std::numeric_limits<double>::infinity()) return n == 0 ? 0 : LOG_ZERO; if (alpha == std::numeric_limits<double>::infinity()) return LOG_ZERO; if (include_summand<true>::value) logp -= lgamma(n + 1.0); if (include_summand<true,T_rate>::value) logp += n * alpha - exp(alpha); return logp; } }; INSTANTIATE_TYPED_TEST_CASE_P(AgradDistributionsPoisson, AgradDistributionTestFixture, AgradDistributionsPoisson); <|endoftext|>
<commit_before>/* * Copyright 2004-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <thrift/lib/cpp2/transport/http2/common/HTTP2RoutingHandler.h> #include <gflags/gflags.h> #include <proxygen/httpserver/HTTPServerAcceptor.h> #include <proxygen/httpserver/HTTPServerOptions.h> #include <proxygen/httpserver/RequestHandler.h> #include <proxygen/httpserver/RequestHandlerAdaptor.h> #include <proxygen/lib/http/codec/HTTPCodec.h> #include <proxygen/lib/http/codec/HTTPSettings.h> #include <proxygen/lib/http/session/HTTPDefaultSessionCodecFactory.h> #include <proxygen/lib/http/session/HTTPDownstreamSession.h> #include <proxygen/lib/http/session/HTTPSession.h> #include <proxygen/lib/http/session/SimpleController.h> #include <thrift/lib/cpp2/transport/http2/common/H2ChannelFactory.h> #include <thrift/lib/cpp2/transport/http2/server/ThriftRequestHandler.h> #include <wangle/acceptor/ManagedConnection.h> #include <limits> DECLARE_uint32(force_channel_version); DEFINE_uint32(stream_timeout_ms, 1000, "Stream timeout in milliseconds"); namespace apache { namespace thrift { using std::chrono::milliseconds; namespace { // Class for managing lifetime of objects supporting an HTTP2 session. class HTTP2RoutingSessionManager : public proxygen::HTTPSession::InfoCallback, public proxygen::SimpleController { public: HTTP2RoutingSessionManager( std::unique_ptr<proxygen::HTTPServerAcceptor> acceptor, ThriftProcessor* processor) : proxygen::HTTPSession::InfoCallback(), proxygen::SimpleController(acceptor.get()), processor_(processor), negotiatedChannelVersion_(FLAGS_force_channel_version) { acceptor_ = std::move(acceptor); if (FLAGS_force_channel_version > 0) { // This prevents the inspection of the HTTP2 header for the channel // version. stableId_ = 0; } else { stableId_ = std::numeric_limits<proxygen::HTTPCodec::StreamID>::max(); } } ~HTTP2RoutingSessionManager() = default; proxygen::HTTPDownstreamSession* createSession( folly::AsyncTransportWrapper::UniquePtr sock, folly::SocketAddress* peerAddress, std::unique_ptr<proxygen::HTTPCodec> h2codec, wangle::TransportInfo const& tinfo) { // Obtain the proper routing address folly::SocketAddress localAddress; try { sock->getLocalAddress(&localAddress); } catch (...) { VLOG(3) << "couldn't get local address for socket"; localAddress = folly::SocketAddress("0.0.0.0", 0); } VLOG(4) << "Created new session for peer " << *peerAddress; // Create the DownstreamSession. Note that "this" occurs twice // because it acts as both a controller as well as a info // callback. auto session = new proxygen::HTTPDownstreamSession( proxygen::WheelTimerInstance(milliseconds(FLAGS_stream_timeout_ms)), std::move(sock), localAddress, *peerAddress, this, std::move(h2codec), tinfo, this); return session; } // begin HTTPSession::InfoCallback methods // We do not override onDestroy() to self destroy because this object // doubles as both the InfoCallback and the SimpleController. The // session destructor calls onDestroy() first and then detachSession() // so we self destroy at detachSession(). void onSettings( const proxygen::HTTPSessionBase&, const proxygen::SettingsList& settings) override { if (FLAGS_force_channel_version > 0) { // Do not use the negotiated settings. return; } for (auto& setting : settings) { if (setting.id == proxygen::SettingsId::THRIFT_CHANNEL_ID_DEPRECATED || setting.id == proxygen::SettingsId::THRIFT_CHANNEL_ID) { negotiatedChannelVersion_ = std::min(setting.value, kMaxSupportedChannelVersion); VLOG(3) << "Peer channel version is " << setting.value << "; " << "Negotiated channel version is " << negotiatedChannelVersion_; } } if (negotiatedChannelVersion_ == 0) { // Did not receive a channel version, assuming legacy peer. negotiatedChannelVersion_ = 1; } } // end HTTPSession::InfoCallback methods // begin SimpleController methods proxygen::HTTPTransactionHandler* getRequestHandler( proxygen::HTTPTransaction& txn, proxygen::HTTPMessage* msg) override { folly::SocketAddress clientAddr, vipAddr; txn.getPeerAddress(clientAddr); txn.getLocalAddress(vipAddr); msg->setClientAddress(clientAddr); msg->setDstAddress(vipAddr); // This checks that the SETTINGS frame arrives before the first RPC. DCHECK(negotiatedChannelVersion_ > 0); // Determine channel version for this HTTP2 stream. uint32_t version = negotiatedChannelVersion_; if (UNLIKELY(txn.getID() < stableId_)) { auto val = msg->getHeaders().rawGet(kChannelVersionKey); try { version = folly::to<int>(val); } catch (const std::exception& ex) { LOG(WARNING) << "Channel version not set properly in header: " << val; // This could be from a legacy client. version = 1; } DCHECK(version == 1 || version == negotiatedChannelVersion_); if (version == negotiatedChannelVersion_) { stableId_ = txn.getID(); } } proxygen::RequestHandler* handler = new ThriftRequestHandler(processor_, version); return new proxygen::RequestHandlerAdaptor(handler); } void detachSession(const proxygen::HTTPSessionBase*) override { VLOG(4) << "HTTP2RoutingSessionManager::detachSession"; // Session destroyed, so self destroy. delete this; } // end SimpleController methods private: // Supporting objects for HTTP2 session managed by the callback. std::unique_ptr<proxygen::HTTPServerAcceptor> acceptor_; ThriftProcessor* processor_; // The negotiated channel version - 0 means negotiation has not // taken place yet. Negotiation is completed when the server // receives a header with a non-zero channel version. uint32_t negotiatedChannelVersion_; // The stream id after which the server can assume that the channel // version will be the negotiated version. proxygen::HTTPCodec::StreamID stableId_; }; } // anonymous namespace void HTTP2RoutingHandler::stopListening() { listening_ = false; } bool HTTP2RoutingHandler::canAcceptConnection( const std::vector<uint8_t>& bytes) { return listening_ && /* * HTTP/2.0 requests start with the following sequence: * Octal: 0x505249202a20485454502f322e300d0a0d0a534d0d0a0d0a * String: "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n" * * For more, see: https://tools.ietf.org/html/rfc7540#section-3.5 */ ((bytes[0] == 0x50 && bytes[1] == 0x52 && bytes[2] == 0x49) || /* * HTTP requests start with the following sequence: * Octal: "0x485454502f..." * String: "HTTP/X.X" * * For more, see: https://tools.ietf.org/html/rfc2616#section-3 */ (bytes[0] == 0x48 && bytes[1] == 0x54 && bytes[2] == 0x54)); } bool HTTP2RoutingHandler::canAcceptEncryptedConnection( const std::string& protocolName) { return listening_ && (protocolName == "h2" || protocolName == "http"); } void HTTP2RoutingHandler::handleConnection( wangle::ConnectionManager* connectionManager, folly::AsyncTransportWrapper::UniquePtr sock, folly::SocketAddress const* peerAddress, wangle::TransportInfo const& tinfo, std::shared_ptr<Cpp2Worker>) { // Create the DownstreamSession manager. auto ipConfig = proxygen::HTTPServer::IPConfig( *peerAddress, proxygen::HTTPServer::Protocol::HTTP2); auto acceptorConfig = proxygen::HTTPServerAcceptor::makeConfig(ipConfig, *options_); auto acceptor = proxygen::HTTPServerAcceptor::make(acceptorConfig, *options_); auto sessionManager = new HTTP2RoutingSessionManager(std::move(acceptor), processor_); // Get the HTTP2 Codec auto codecFactory = proxygen::HTTPDefaultSessionCodecFactory(acceptorConfig); auto h2codec = codecFactory.getCodec("h2", proxygen::TransportDirection::DOWNSTREAM); // Create the DownstreamSession // A const_cast is needed to match wangle and proxygen APIs auto session = sessionManager->createSession( std::move(sock), const_cast<folly::SocketAddress*>(peerAddress), std::move(h2codec), tinfo); // Set HTTP2 priorities flag on session object. session->setHTTP2PrioritiesEnabled(acceptorConfig.HTTP2PrioritiesEnabled); /* if (acceptorConfig.maxConcurrentIncomingStreams) { session->setMaxConcurrentIncomingStreams( acceptorConfig.maxConcurrentIncomingStreams); } */ // TODO: Improve the way max incoming streams is set session->setMaxConcurrentIncomingStreams(100000); // Set flow control parameters. session->setFlowControl( acceptorConfig.initialReceiveWindow, acceptorConfig.receiveStreamWindowSize, acceptorConfig.receiveSessionWindowSize); if (acceptorConfig.writeBufferLimit > 0) { session->setWriteBufferLimit(acceptorConfig.writeBufferLimit); } session->setEgressSettings( {{proxygen::SettingsId::THRIFT_CHANNEL_ID_DEPRECATED, kMaxSupportedChannelVersion}, {proxygen::SettingsId::THRIFT_CHANNEL_ID, kMaxSupportedChannelVersion}}); // Route the connection. connectionManager->addConnection(session); session->startNow(); auto observer = serverConfigs_.getObserver(); if (observer) { observer->connAccepted(); observer->activeConnections( connectionManager->getNumConnections() * serverConfigs_.getNumIOWorkerThreads()); } } } // namespace thrift } // namespace apache <commit_msg>Allow codec factory to handle ssl w/ plaintext acceptors<commit_after>/* * Copyright 2004-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <thrift/lib/cpp2/transport/http2/common/HTTP2RoutingHandler.h> #include <gflags/gflags.h> #include <proxygen/httpserver/HTTPServerAcceptor.h> #include <proxygen/httpserver/HTTPServerOptions.h> #include <proxygen/httpserver/RequestHandler.h> #include <proxygen/httpserver/RequestHandlerAdaptor.h> #include <proxygen/lib/http/codec/HTTPCodec.h> #include <proxygen/lib/http/codec/HTTPSettings.h> #include <proxygen/lib/http/session/HTTPDefaultSessionCodecFactory.h> #include <proxygen/lib/http/session/HTTPDownstreamSession.h> #include <proxygen/lib/http/session/HTTPSession.h> #include <proxygen/lib/http/session/SimpleController.h> #include <thrift/lib/cpp2/transport/http2/common/H2ChannelFactory.h> #include <thrift/lib/cpp2/transport/http2/server/ThriftRequestHandler.h> #include <wangle/acceptor/ManagedConnection.h> #include <limits> DECLARE_uint32(force_channel_version); DEFINE_uint32(stream_timeout_ms, 1000, "Stream timeout in milliseconds"); namespace apache { namespace thrift { using std::chrono::milliseconds; namespace { // Class for managing lifetime of objects supporting an HTTP2 session. class HTTP2RoutingSessionManager : public proxygen::HTTPSession::InfoCallback, public proxygen::SimpleController { public: HTTP2RoutingSessionManager( std::unique_ptr<proxygen::HTTPServerAcceptor> acceptor, ThriftProcessor* processor) : proxygen::HTTPSession::InfoCallback(), proxygen::SimpleController(acceptor.get()), processor_(processor), negotiatedChannelVersion_(FLAGS_force_channel_version) { acceptor_ = std::move(acceptor); if (FLAGS_force_channel_version > 0) { // This prevents the inspection of the HTTP2 header for the channel // version. stableId_ = 0; } else { stableId_ = std::numeric_limits<proxygen::HTTPCodec::StreamID>::max(); } } ~HTTP2RoutingSessionManager() = default; proxygen::HTTPDownstreamSession* createSession( folly::AsyncTransportWrapper::UniquePtr sock, folly::SocketAddress* peerAddress, std::unique_ptr<proxygen::HTTPCodec> h2codec, wangle::TransportInfo const& tinfo) { // Obtain the proper routing address folly::SocketAddress localAddress; try { sock->getLocalAddress(&localAddress); } catch (...) { VLOG(3) << "couldn't get local address for socket"; localAddress = folly::SocketAddress("0.0.0.0", 0); } VLOG(4) << "Created new session for peer " << *peerAddress; // Create the DownstreamSession. Note that "this" occurs twice // because it acts as both a controller as well as a info // callback. auto session = new proxygen::HTTPDownstreamSession( proxygen::WheelTimerInstance(milliseconds(FLAGS_stream_timeout_ms)), std::move(sock), localAddress, *peerAddress, this, std::move(h2codec), tinfo, this); return session; } // begin HTTPSession::InfoCallback methods // We do not override onDestroy() to self destroy because this object // doubles as both the InfoCallback and the SimpleController. The // session destructor calls onDestroy() first and then detachSession() // so we self destroy at detachSession(). void onSettings( const proxygen::HTTPSessionBase&, const proxygen::SettingsList& settings) override { if (FLAGS_force_channel_version > 0) { // Do not use the negotiated settings. return; } for (auto& setting : settings) { if (setting.id == proxygen::SettingsId::THRIFT_CHANNEL_ID_DEPRECATED || setting.id == proxygen::SettingsId::THRIFT_CHANNEL_ID) { negotiatedChannelVersion_ = std::min(setting.value, kMaxSupportedChannelVersion); VLOG(3) << "Peer channel version is " << setting.value << "; " << "Negotiated channel version is " << negotiatedChannelVersion_; } } if (negotiatedChannelVersion_ == 0) { // Did not receive a channel version, assuming legacy peer. negotiatedChannelVersion_ = 1; } } // end HTTPSession::InfoCallback methods // begin SimpleController methods proxygen::HTTPTransactionHandler* getRequestHandler( proxygen::HTTPTransaction& txn, proxygen::HTTPMessage* msg) override { folly::SocketAddress clientAddr, vipAddr; txn.getPeerAddress(clientAddr); txn.getLocalAddress(vipAddr); msg->setClientAddress(clientAddr); msg->setDstAddress(vipAddr); // This checks that the SETTINGS frame arrives before the first RPC. DCHECK(negotiatedChannelVersion_ > 0); // Determine channel version for this HTTP2 stream. uint32_t version = negotiatedChannelVersion_; if (UNLIKELY(txn.getID() < stableId_)) { auto val = msg->getHeaders().rawGet(kChannelVersionKey); try { version = folly::to<int>(val); } catch (const std::exception& ex) { LOG(WARNING) << "Channel version not set properly in header: " << val; // This could be from a legacy client. version = 1; } DCHECK(version == 1 || version == negotiatedChannelVersion_); if (version == negotiatedChannelVersion_) { stableId_ = txn.getID(); } } proxygen::RequestHandler* handler = new ThriftRequestHandler(processor_, version); return new proxygen::RequestHandlerAdaptor(handler); } void detachSession(const proxygen::HTTPSessionBase*) override { VLOG(4) << "HTTP2RoutingSessionManager::detachSession"; // Session destroyed, so self destroy. delete this; } // end SimpleController methods private: // Supporting objects for HTTP2 session managed by the callback. std::unique_ptr<proxygen::HTTPServerAcceptor> acceptor_; ThriftProcessor* processor_; // The negotiated channel version - 0 means negotiation has not // taken place yet. Negotiation is completed when the server // receives a header with a non-zero channel version. uint32_t negotiatedChannelVersion_; // The stream id after which the server can assume that the channel // version will be the negotiated version. proxygen::HTTPCodec::StreamID stableId_; }; } // anonymous namespace void HTTP2RoutingHandler::stopListening() { listening_ = false; } bool HTTP2RoutingHandler::canAcceptConnection( const std::vector<uint8_t>& bytes) { return listening_ && /* * HTTP/2.0 requests start with the following sequence: * Octal: 0x505249202a20485454502f322e300d0a0d0a534d0d0a0d0a * String: "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n" * * For more, see: https://tools.ietf.org/html/rfc7540#section-3.5 */ ((bytes[0] == 0x50 && bytes[1] == 0x52 && bytes[2] == 0x49) || /* * HTTP requests start with the following sequence: * Octal: "0x485454502f..." * String: "HTTP/X.X" * * For more, see: https://tools.ietf.org/html/rfc2616#section-3 */ (bytes[0] == 0x48 && bytes[1] == 0x54 && bytes[2] == 0x54)); } bool HTTP2RoutingHandler::canAcceptEncryptedConnection( const std::string& protocolName) { return listening_ && (protocolName == "h2" || protocolName == "http"); } void HTTP2RoutingHandler::handleConnection( wangle::ConnectionManager* connectionManager, folly::AsyncTransportWrapper::UniquePtr sock, folly::SocketAddress const* peerAddress, wangle::TransportInfo const& tinfo, std::shared_ptr<Cpp2Worker>) { // Create the DownstreamSession manager. auto ipConfig = proxygen::HTTPServer::IPConfig( *peerAddress, proxygen::HTTPServer::Protocol::HTTP2); auto acceptorConfig = proxygen::HTTPServerAcceptor::makeConfig(ipConfig, *options_); auto acceptor = proxygen::HTTPServerAcceptor::make(acceptorConfig, *options_); auto sessionManager = new HTTP2RoutingSessionManager(std::move(acceptor), processor_); // Get the HTTP2 Codec auto codecFactory = proxygen::HTTPDefaultSessionCodecFactory(acceptorConfig); auto h2codec = codecFactory.getCodec( "h2", proxygen::TransportDirection::DOWNSTREAM, // a non empty security protocol is assumed to be TLS !sock->getSecurityProtocol().empty()); // Create the DownstreamSession // A const_cast is needed to match wangle and proxygen APIs auto session = sessionManager->createSession( std::move(sock), const_cast<folly::SocketAddress*>(peerAddress), std::move(h2codec), tinfo); // Set HTTP2 priorities flag on session object. session->setHTTP2PrioritiesEnabled(acceptorConfig.HTTP2PrioritiesEnabled); /* if (acceptorConfig.maxConcurrentIncomingStreams) { session->setMaxConcurrentIncomingStreams( acceptorConfig.maxConcurrentIncomingStreams); } */ // TODO: Improve the way max incoming streams is set session->setMaxConcurrentIncomingStreams(100000); // Set flow control parameters. session->setFlowControl( acceptorConfig.initialReceiveWindow, acceptorConfig.receiveStreamWindowSize, acceptorConfig.receiveSessionWindowSize); if (acceptorConfig.writeBufferLimit > 0) { session->setWriteBufferLimit(acceptorConfig.writeBufferLimit); } session->setEgressSettings( {{proxygen::SettingsId::THRIFT_CHANNEL_ID_DEPRECATED, kMaxSupportedChannelVersion}, {proxygen::SettingsId::THRIFT_CHANNEL_ID, kMaxSupportedChannelVersion}}); // Route the connection. connectionManager->addConnection(session); session->startNow(); auto observer = serverConfigs_.getObserver(); if (observer) { observer->connAccepted(); observer->activeConnections( connectionManager->getNumConnections() * serverConfigs_.getNumIOWorkerThreads()); } } } // namespace thrift } // namespace apache <|endoftext|>
<commit_before>/*========================================================================= Library: TubeTK Copyright 2010 Kitware Inc. 28 Corporate Drive, Clifton Park, NY, 12065, USA. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =========================================================================*/ #include <itkIdentityTransform.h> #include <itkImageFileReader.h> #include <itkMutualInformationImageToImageMetric.h> #include <itkNormalizedCorrelationImageToImageMetric.h> #include <itkNormalizeImageFilter.h> #include "ComputeImageSimilarityMetricsCLP.h" template< class TPixel, unsigned int VDimension > int DoIt( int argc, char * argv[] ); // Must follow include of "...CLP.h" and forward declaration of int DoIt( ... ). #include "tubeCLIHelperFunctions.h" template< class TPixel, unsigned int VDimension > int DoIt( int argc, char * argv[] ) { PARSE_ARGS; typedef TPixel PixelType; typedef itk::Image< PixelType, VDimension > ImageType; typedef itk::ImageFileReader< ImageType > ReaderType; typename ReaderType::Pointer reader1 = ReaderType::New(); typename ReaderType::Pointer reader2 = ReaderType::New(); //read input image reader1->SetFileName( inputVolume1.c_str() ); reader2->SetFileName( inputVolume2.c_str() ); try { reader1->Update(); } catch( itk::ExceptionObject & err ) { std::cerr << "ExceptionObject caught, image reader 1 !" << std::endl; std::cerr << err << std::endl; return EXIT_FAILURE; } try { reader2->Update(); } catch( itk::ExceptionObject & err ) { std::cerr << "ExceptionObject caught, image reader2 !" << std::endl; std::cerr << err << std::endl; return EXIT_FAILURE; } typename ImageType::Pointer image1 = reader1->GetOutput(); typename ImageType::Pointer image2 = reader2->GetOutput(); typedef itk::NormalizeImageFilter< ImageType, ImageType > NormFilterType; typename NormFilterType::Pointer norm1 = NormFilterType::New(); norm1->SetInput( image1 ); norm1->Update(); image1 = norm1->GetOutput(); typename NormFilterType::Pointer norm2 = NormFilterType::New(); norm2->SetInput( image2 ); norm2->Update(); image2 = norm2->GetOutput(); typedef itk::IdentityTransform< double, VDimension > TransformType; typename TransformType::Pointer transform = TransformType::New(); typedef itk::LinearInterpolateImageFunction< ImageType, double > InterpolatorType; typename InterpolatorType::Pointer interpolator = InterpolatorType::New(); interpolator->SetInputImage( image2 ); typedef itk::ImageToImageMetric< ImageType, ImageType > MetricType; typename MetricType::Pointer metric; if( !correlation ) { typedef itk::MutualInformationImageToImageMetric< ImageType, ImageType > MIMetricType; metric = MIMetricType::New(); } else { typedef itk::NormalizedCorrelationImageToImageMetric< ImageType, ImageType > CorMetricType; metric = CorMetricType::New(); } typename ImageType::SizeType size = image1->GetLargestPossibleRegion(). GetSize(); metric->SetFixedImage( image1 ); metric->SetMovingImage( image2 ); metric->SetFixedImageRegion( image1->GetLargestPossibleRegion() ); metric->SetTransform( transform ); metric->SetInterpolator( interpolator ); metric->SetNumberOfSpatialSamples( size[0]*size[1]*samplingRate ); metric->Initialize(); metric->MultiThreadingInitialize(); if( !correlation ) { std::cout << metric->GetValue( transform->GetParameters() ) << std::endl; } else { std::cout << -metric->GetValue( transform->GetParameters() ) << std::endl; } return EXIT_SUCCESS; } int main( int argc, char * argv[] ) { PARSE_ARGS; return tube::ParseArgsAndCallDoIt( inputVolume1, argc, argv ); } <commit_msg>Made ComputeImageSimilarityMetrics CLI to use shadow class for logic<commit_after>/*========================================================================= Library: TubeTK Copyright 2010 Kitware Inc. 28 Corporate Drive, Clifton Park, NY, 12065, USA. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =========================================================================*/ // ITK includes #include <itkImageFileReader.h> // TubeTK includes #include "tubeComputeImageSimilarityMetrics.h" #include "tubeMessage.h" #include "ComputeImageSimilarityMetricsCLP.h" template< class TPixel, unsigned int VDimension > int DoIt( int argc, char * argv[] ); // Must follow include of "...CLP.h" and forward declaration of int DoIt( ... ). #include "tubeCLIHelperFunctions.h" template< class TPixel, unsigned int VDimension > int DoIt( int argc, char * argv[] ) { PARSE_ARGS; // typedefs typedef TPixel PixelType; typedef itk::Image< PixelType, VDimension > ImageType; typedef itk::ImageFileReader< ImageType > ReaderType; typedef tube::ComputeImageSimilarityMetrics< ImageType > FilterType; // read input image 1 typename ReaderType::Pointer reader1 = ReaderType::New(); try { reader1->SetFileName( inputVolume1.c_str() ); reader1->Update(); } catch( itk::ExceptionObject & err ) { tube::ErrorMessage( "Error reading input image 1: " + std::string(err.GetDescription()) ); return EXIT_FAILURE; } // read input image 2 typename ReaderType::Pointer reader2 = ReaderType::New(); try { reader2->SetFileName( inputVolume2.c_str() ); reader2->Update(); } catch( itk::ExceptionObject & err ) { tube::ErrorMessage( "Error reading input image 2: " + std::string(err.GetDescription()) ); return EXIT_FAILURE; } // compute image similarity typename FilterType::Pointer similarityCalculator = FilterType::New(); similarityCalculator->SetInput1( reader1->GetOutput() ); similarityCalculator->SetInput2( reader2->GetOutput() ); similarityCalculator->SetSamplingRate( samplingRate ); similarityCalculator->SetUseCorrelation( correlation ); std::cout << similarityCalculator->GetOutput() << std::endl; return EXIT_SUCCESS; } int main( int argc, char * argv[] ) { PARSE_ARGS; return tube::ParseArgsAndCallDoIt( inputVolume1, argc, argv ); } <|endoftext|>
<commit_before>/* * Copyright(c) Sophist Solutions, Inc. 1990-2015. All rights reserved */ #include "../../StroikaPreComp.h" #if qPlatform_Windows #include <windows.h> #include <shellapi.h> #include <shlobj.h> #elif qPlatform_POSIX #include <unistd.h> #endif #include "../../Characters/StringBuilder.h" #include "../../Containers/Set.h" #if qPlatform_Windows #include "../../Execution/Platform/Windows/Exception.h" #include "../../Execution/Platform/Windows/HRESULTErrorException.h" #endif #include "../../Execution/ErrNoException.h" #include "../../IO/FileAccessException.h" #include "../../IO/FileBusyException.h" #include "../../IO/FileFormatException.h" #include "../../Memory/SmallStackBuffer.h" #include "FileUtils.h" #include "FileSystem.h" using namespace Stroika::Foundation; using namespace Stroika::Foundation::Characters; using namespace Stroika::Foundation::Containers; using namespace Stroika::Foundation::Execution; using namespace Stroika::Foundation::IO; using namespace Stroika::Foundation::IO::FileSystem; #if qPlatform_Windows using Execution::Platform::Windows::ThrowIfFalseGetLastError; using Execution::Platform::Windows::ThrowIfZeroGetLastError; #endif // Comment this in to turn on aggressive noisy DbgTrace in this module //#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1 /* ******************************************************************************** **************************** FileSystem::FileSystem **************************** ******************************************************************************** */ IO::FileSystem::FileSystem IO::FileSystem::FileSystem::Default () { static IO::FileSystem::FileSystem sThe_; return sThe_; } bool IO::FileSystem::FileSystem::Access (const String& fileFullPath, FileAccessMode accessMode) const { #if qPlatform_Windows if ((accessMode & FileAccessMode::eRead) == FileAccessMode::eRead) { DWORD attribs = ::GetFileAttributesW (fileFullPath.c_str ()); if (attribs == INVALID_FILE_ATTRIBUTES) { return false; } } if ((accessMode & FileAccessMode::eWrite) == FileAccessMode::eWrite) { DWORD attribs = ::GetFileAttributesW (fileFullPath.c_str ()); if ((attribs == INVALID_FILE_ATTRIBUTES) or (attribs & FILE_ATTRIBUTE_READONLY)) { return false; } } return true; #elif qPlatform_POSIX // Not REALLY right - but an OK hack for now... -- LGP 2011-09-26 //http://linux.die.net/man/2/access if ((accessMode & FileAccessMode::eRead) == FileAccessMode::eRead) { if (access (fileFullPath.AsSDKString().c_str (), R_OK) != 0) { return false; } } if ((accessMode & FileAccessMode::eWrite) == FileAccessMode::eWrite) { if (access (fileFullPath.AsSDKString().c_str (), W_OK) != 0) { return false; } } return true; #else AssertNotImplemented (); return false; #endif } void IO::FileSystem::FileSystem::CheckAccess (const String& fileFullPath, FileAccessMode accessMode) { // quick hack - not fully implemented - but since advsiory only - not too important... if (not Access (fileFullPath, accessMode)) { // FOR NOW - MIMIC OLD CODE - BUT FIX TO CHECK READ AND WRITE (AND BOTH) ACCESS DEPENDING ON ARGS) -- LGP 2009-08-15 Execution::DoThrow (FileAccessException (fileFullPath, accessMode)); } } void IO::FileSystem::FileSystem::CheckFileAccess (const String& fileFullPath, bool checkCanRead, bool checkCanWrite) { if (checkCanRead and checkCanWrite) { CheckAccess (fileFullPath, IO::FileAccessMode::eReadWrite); } else if (checkCanRead) { CheckAccess (fileFullPath, IO::FileAccessMode::eRead); } else if (checkCanWrite) { CheckAccess (fileFullPath, IO::FileAccessMode::eWrite); } } String IO::FileSystem::FileSystem::ResolveShortcut (const String& path2FileOrShortcut) { #if qPlatform_Windows // @todo WRONG semantics if file doesnt exist. Wed should raise an exception here. // But OK if not a shortcut. THEN just rutn the givne file // // // NB: this requires COM, and for now - I don't want the support module depending on the COM module, // so just allow this to fail if COM isn't initialized. // -- LGP 2007-09-23 // { SHFILEINFO info; memset (&info, 0, sizeof (info)); if (::SHGetFileInfo (path2FileOrShortcut.AsSDKString ().c_str (), 0, &info, sizeof (info), SHGFI_ATTRIBUTES) == 0) { return path2FileOrShortcut; } // not a shortcut? if (!(info.dwAttributes & SFGAO_LINK)) { return path2FileOrShortcut; } } // obtain the IShellLink interface IShellLink* psl = nullptr; IPersistFile* ppf = nullptr; try { if (FAILED (::CoCreateInstance (CLSID_ShellLink, nullptr, CLSCTX_INPROC_SERVER, IID_IShellLink, (LPVOID*)&psl))) { return path2FileOrShortcut; } if (SUCCEEDED (psl->QueryInterface (IID_IPersistFile, (LPVOID*)&ppf))) { if (SUCCEEDED (ppf->Load (path2FileOrShortcut.c_str (), STGM_READ))) { // Resolve the link, this may post UI to find the link if (SUCCEEDED (psl->Resolve(0, SLR_NO_UI))) { TCHAR path[MAX_PATH + 1]; memset (path, 0, sizeof (path)); if (SUCCEEDED (psl->GetPath (path, NEltsOf (path), nullptr, 0))) { ppf->Release (); ppf = nullptr; psl->Release (); psl = nullptr; return String::FromSDKString (path); } } } } } catch (...) { if (ppf != nullptr) { ppf->Release (); } if (psl != nullptr) { psl->Release (); } Execution::DoReThrow (); } if (ppf != nullptr) { ppf->Release (); } if (psl != nullptr) { psl->Release (); } return path2FileOrShortcut; #else Memory::SmallStackBuffer<Characters::SDKChar> buf (1024); ssize_t n; while ( (n = ::readlink (path2FileOrShortcut.AsSDKString ().c_str (), buf, buf.GetSize ())) == buf.GetSize ()) { buf.GrowToSize (buf.GetSize () * 2); } if (n < 0) { auto e = errno; if (e == EINVAL) { // According to http://linux.die.net/man/2/readlink - this means the target is not a shortcut which is OK return path2FileOrShortcut; } else { Execution::errno_ErrorException::DoThrow (e); } } Assert (n <= buf.GetSize ()); // could leave no room for NUL-byte, but not needed constexpr bool kWorkaroundBuggyCentos5ReturnsNulBytesInBuf_ = true; if (kWorkaroundBuggyCentos5ReturnsNulBytesInBuf_) { const Characters::SDKChar* b = buf.begin (); const Characters::SDKChar* e = b + n; const Characters::SDKChar* i = find (b, e, '\0'); if (i != e) { size_t newN = i - buf.begin (); Assert (newN < n); n = newN; } } return String::FromSDKString (SDKString (buf.begin (), buf.begin () + n)); #endif } String IO::FileSystem::FileSystem::CanonicalizeName (const String& path2FileOrShortcut, bool throwIfComponentsNotFound) { #if qPlatform_POSIX // We used to call canonicalize_file_name() - but this doesnt work with AIX 7.1/g++4.9.2, and // according to http://man7.org/linux/man-pages/man3/canonicalize_file_name.3.html: // The call canonicalize_file_name(path) is equivalent to the call: // realpath(path, NULL) char* tmp { ::realpath (path2FileOrShortcut.AsSDKString ().c_str (), nullptr) }; if (tmp == nullptr) { errno_ErrorException::DoThrow (errno); } String result { String::FromNarrowSDKString (tmp) }; free (tmp); return result; #elif qPlatform_Windows // @todo LARGELY UNSTED ROUGH DRAFT - 2015-05-11 /* * Note: PathCanonicalize has lots of problems, PathCanonicalizeCh, and * PathCchCanonicalizeEx is better, but only works with windows 8 or later. */ using Characters::StringBuilder; String tmp = ResolveShortcut (path2FileOrShortcut); StringBuilder sb; Components c = GetPathComponents (path2FileOrShortcut); if (c.fAbsolutePath == Components::eAbsolutePath) { // use UNC notation sb += L"\\\\?"; if (c.fDriveLetter) { sb += *c.fDriveLetter; } else if (c.fServerAndShare) { sb += c.fServerAndShare->fServer + L"\\" + c.fServerAndShare->fShare; } else { Execution::DoThrow (Execution::StringException (L"for absolute path need drive letter or server/share")); } } else { if (c.fDriveLetter) { sb += *c.fDriveLetter + L":"; } } bool prefixWIthSlash = false; for (String i : c.fPath) { if (prefixWIthSlash) { sb += L"\\"; } sb += i; prefixWIthSlash = true; } return sb.str (); #else AssertNotImplemented (); return path2FileOrShortcut; #endif } String IO::FileSystem::FileSystem::CanonicalizeName (const String& path2FileOrShortcut, const String& relativeToDirectory, bool throwIfComponentsNotFound) { AssertNotImplemented (); return path2FileOrShortcut; } IO::FileSystem::FileSystem::Components IO::FileSystem::FileSystem::GetPathComponents (const String& fileName) { // @todo LARGELY UNSTED ROUGH DRAFT - 2015-05-11 // See http://en.wikipedia.org/wiki/Path_%28computing%29 to write this #if 0 //windows C: \user\docs\Letter.txt / user / docs / Letter.txt C: Letter.txt \\Server01\user\docs\Letter.txt \\ ? \UNC\Server01\user\docs\Letter.txt \\ ? \C : \user\docs\Letter.txt C : \user\docs\somefile.ext : alternate_stream_name . / inthisdir .. / .. / greatgrandparent #endif #if 0 // unix / home / user / docs / Letter.txt . / inthisdir .. / .. / greatgrandparent ~ / .rcinfo #endif IO::FileSystem::FileSystem::Components result; using Traversal::Iterator; using Characters::Character; #if qPlatform_Windows bool isUNCName = fileName.length () > 2 and fileName.StartsWith (L"\\\\"); bool isAbsolutePath = fileName.length () >= 1 and fileName.StartsWith (L"\\"); #else #endif #if qPlatform_Windows const Set<Character> kSlashChars_ = { '\\', '/' }; #else const Set<Character> kSlashChars_ = { '/' }; #endif Sequence<String> rawComponents = fileName.Tokenize (kSlashChars_, false); Iterator<String> i = rawComponents.begin (); #if qPlatform_Windows if (isUNCName) { // work todo } #endif for (; i != rawComponents.end (); ++i) { result.fPath.Append (*i); } AssertNotImplemented (); return result; } FileOffset_t IO::FileSystem::FileSystem::GetFileSize (const String& fileName) { #if qPlatform_Windows WIN32_FILE_ATTRIBUTE_DATA fileAttrData; (void)::memset (&fileAttrData, 0, sizeof (fileAttrData)); Execution::Platform::Windows::ThrowIfFalseGetLastError (::GetFileAttributesExW (fileName.c_str (), GetFileExInfoStandard, &fileAttrData)); return fileAttrData.nFileSizeLow + (static_cast<FileOffset_t> (fileAttrData.nFileSizeHigh) << 32); #else AssertNotImplemented (); return 0; #endif } DateTime IO::FileSystem::FileSystem::GetFileLastModificationDate (const String& fileName) { #if qPlatform_Windows WIN32_FILE_ATTRIBUTE_DATA fileAttrData; (void)::memset (&fileAttrData, 0, sizeof (fileAttrData)); ThrowIfFalseGetLastError (::GetFileAttributesExW (fileName.c_str (), GetFileExInfoStandard, &fileAttrData)); return DateTime (fileAttrData.ftLastWriteTime); #else AssertNotImplemented (); return DateTime (); #endif } DateTime IO::FileSystem::FileSystem::GetFileLastAccessDate (const String& fileName) { #if qPlatform_Windows WIN32_FILE_ATTRIBUTE_DATA fileAttrData; (void)::memset (&fileAttrData, 0, sizeof (fileAttrData)); ThrowIfFalseGetLastError (::GetFileAttributesExW (fileName.c_str (), GetFileExInfoStandard, &fileAttrData)); return DateTime (fileAttrData.ftLastAccessTime); #else AssertNotImplemented (); return DateTime (); #endif } void IO::FileSystem::FileSystem::RemoveFile (const String& fileName) { #if qPlatform_Windows && qTargetPlatformSDKUseswchar_t Execution::ThrowErrNoIfNegative (::_wunlink (fileName.c_str ())); #else Execution::ThrowErrNoIfNegative (::unlink (fileName.AsNarrowSDKString ().c_str ())); #endif } void IO::FileSystem::FileSystem::RemoveFileIf (const String& fileName) { #if qPlatform_Windows && qTargetPlatformSDKUseswchar_t int r = ::_wunlink (fileName.c_str ()); #else int r = ::unlink (fileName.AsNarrowSDKString ().c_str ()); #endif if (r < 0) { if (errno != ENOENT) { errno_ErrorException::DoThrow (errno); } } } String IO::FileSystem::FileSystem::GetCurrentDirectory () const { #if qPlatform_POSIX SDKChar buf[PATH_MAX]; Execution::ThrowErrNoIfNull (::getcwd (buf, NEltsOf (buf))); return String::FromSDKString (buf); #elif qPlatform_Windows SDKChar buf[MAX_PATH]; ThrowIfZeroGetLastError (::GetCurrentDirectory (NEltsOf (buf), buf)); return String::FromSDKString (buf); #else AssertNotReached (); #endif } void IO::FileSystem::FileSystem::SetCurrentDirectory (const String& newDir) { #if qPlatform_POSIX Execution::ThrowErrNoIfNegative (::chdir (newDir.AsNarrowSDKString ().c_str ())); #elif qPlatform_Windows ::SetCurrentDirectory(newDir.AsSDKString ().c_str ()); #else AssertNotReached (); #endif } <commit_msg>Comments<commit_after>/* * Copyright(c) Sophist Solutions, Inc. 1990-2015. All rights reserved */ #include "../../StroikaPreComp.h" #if qPlatform_Windows #include <windows.h> #include <shellapi.h> #include <shlobj.h> #elif qPlatform_POSIX #include <unistd.h> #endif #include "../../Characters/StringBuilder.h" #include "../../Containers/Set.h" #if qPlatform_Windows #include "../../Execution/Platform/Windows/Exception.h" #include "../../Execution/Platform/Windows/HRESULTErrorException.h" #endif #include "../../Execution/ErrNoException.h" #include "../../IO/FileAccessException.h" #include "../../IO/FileBusyException.h" #include "../../IO/FileFormatException.h" #include "../../Memory/SmallStackBuffer.h" #include "FileUtils.h" #include "FileSystem.h" using namespace Stroika::Foundation; using namespace Stroika::Foundation::Characters; using namespace Stroika::Foundation::Containers; using namespace Stroika::Foundation::Execution; using namespace Stroika::Foundation::IO; using namespace Stroika::Foundation::IO::FileSystem; #if qPlatform_Windows using Execution::Platform::Windows::ThrowIfFalseGetLastError; using Execution::Platform::Windows::ThrowIfZeroGetLastError; #endif // Comment this in to turn on aggressive noisy DbgTrace in this module //#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1 /* ******************************************************************************** **************************** FileSystem::FileSystem **************************** ******************************************************************************** */ IO::FileSystem::FileSystem IO::FileSystem::FileSystem::Default () { static IO::FileSystem::FileSystem sThe_; return sThe_; } bool IO::FileSystem::FileSystem::Access (const String& fileFullPath, FileAccessMode accessMode) const { #if qPlatform_Windows if ((accessMode & FileAccessMode::eRead) == FileAccessMode::eRead) { DWORD attribs = ::GetFileAttributesW (fileFullPath.c_str ()); if (attribs == INVALID_FILE_ATTRIBUTES) { return false; } } if ((accessMode & FileAccessMode::eWrite) == FileAccessMode::eWrite) { DWORD attribs = ::GetFileAttributesW (fileFullPath.c_str ()); if ((attribs == INVALID_FILE_ATTRIBUTES) or (attribs & FILE_ATTRIBUTE_READONLY)) { return false; } } return true; #elif qPlatform_POSIX // Not REALLY right - but an OK hack for now... -- LGP 2011-09-26 //http://linux.die.net/man/2/access if ((accessMode & FileAccessMode::eRead) == FileAccessMode::eRead) { if (access (fileFullPath.AsSDKString().c_str (), R_OK) != 0) { return false; } } if ((accessMode & FileAccessMode::eWrite) == FileAccessMode::eWrite) { if (access (fileFullPath.AsSDKString().c_str (), W_OK) != 0) { return false; } } return true; #else AssertNotImplemented (); return false; #endif } void IO::FileSystem::FileSystem::CheckAccess (const String& fileFullPath, FileAccessMode accessMode) { // quick hack - not fully implemented - but since advsiory only - not too important... if (not Access (fileFullPath, accessMode)) { // FOR NOW - MIMIC OLD CODE - BUT FIX TO CHECK READ AND WRITE (AND BOTH) ACCESS DEPENDING ON ARGS) -- LGP 2009-08-15 Execution::DoThrow (FileAccessException (fileFullPath, accessMode)); } } void IO::FileSystem::FileSystem::CheckFileAccess (const String& fileFullPath, bool checkCanRead, bool checkCanWrite) { if (checkCanRead and checkCanWrite) { CheckAccess (fileFullPath, IO::FileAccessMode::eReadWrite); } else if (checkCanRead) { CheckAccess (fileFullPath, IO::FileAccessMode::eRead); } else if (checkCanWrite) { CheckAccess (fileFullPath, IO::FileAccessMode::eWrite); } } String IO::FileSystem::FileSystem::ResolveShortcut (const String& path2FileOrShortcut) { #if qPlatform_Windows // @todo WRONG semantics if file doesnt exist. Wed should raise an exception here. // But OK if not a shortcut. THEN just rutn the givne file // // // NB: this requires COM, and for now - I don't want the support module depending on the COM module, // so just allow this to fail if COM isn't initialized. // -- LGP 2007-09-23 // { SHFILEINFO info; memset (&info, 0, sizeof (info)); if (::SHGetFileInfo (path2FileOrShortcut.AsSDKString ().c_str (), 0, &info, sizeof (info), SHGFI_ATTRIBUTES) == 0) { return path2FileOrShortcut; } // not a shortcut? if (!(info.dwAttributes & SFGAO_LINK)) { return path2FileOrShortcut; } } // obtain the IShellLink interface IShellLink* psl = nullptr; IPersistFile* ppf = nullptr; try { if (FAILED (::CoCreateInstance (CLSID_ShellLink, nullptr, CLSCTX_INPROC_SERVER, IID_IShellLink, (LPVOID*)&psl))) { return path2FileOrShortcut; } if (SUCCEEDED (psl->QueryInterface (IID_IPersistFile, (LPVOID*)&ppf))) { if (SUCCEEDED (ppf->Load (path2FileOrShortcut.c_str (), STGM_READ))) { // Resolve the link, this may post UI to find the link if (SUCCEEDED (psl->Resolve(0, SLR_NO_UI))) { TCHAR path[MAX_PATH + 1]; memset (path, 0, sizeof (path)); if (SUCCEEDED (psl->GetPath (path, NEltsOf (path), nullptr, 0))) { ppf->Release (); ppf = nullptr; psl->Release (); psl = nullptr; return String::FromSDKString (path); } } } } } catch (...) { if (ppf != nullptr) { ppf->Release (); } if (psl != nullptr) { psl->Release (); } Execution::DoReThrow (); } if (ppf != nullptr) { ppf->Release (); } if (psl != nullptr) { psl->Release (); } return path2FileOrShortcut; #else Memory::SmallStackBuffer<Characters::SDKChar> buf (1024); ssize_t n; while ( (n = ::readlink (path2FileOrShortcut.AsSDKString ().c_str (), buf, buf.GetSize ())) == buf.GetSize ()) { buf.GrowToSize (buf.GetSize () * 2); } if (n < 0) { auto e = errno; if (e == EINVAL) { // According to http://linux.die.net/man/2/readlink - this means the target is not a shortcut which is OK return path2FileOrShortcut; } else { Execution::errno_ErrorException::DoThrow (e); } } Assert (n <= buf.GetSize ()); // could leave no room for NUL-byte, but not needed constexpr bool kWorkaroundBuggyCentos5ReturnsNulBytesInBuf_ = true; if (kWorkaroundBuggyCentos5ReturnsNulBytesInBuf_) { const Characters::SDKChar* b = buf.begin (); const Characters::SDKChar* e = b + n; const Characters::SDKChar* i = find (b, e, '\0'); if (i != e) { size_t newN = i - buf.begin (); Assert (newN < n); n = newN; } } return String::FromSDKString (SDKString (buf.begin (), buf.begin () + n)); #endif } String IO::FileSystem::FileSystem::CanonicalizeName (const String& path2FileOrShortcut, bool throwIfComponentsNotFound) { #if qPlatform_POSIX // We used to call canonicalize_file_name() - but this doesnt work with AIX 7.1/g++4.9.2, and // according to http://man7.org/linux/man-pages/man3/canonicalize_file_name.3.html: // The call canonicalize_file_name(path) is equivalent to the call: // realpath(path, NULL) char* tmp { ::realpath (path2FileOrShortcut.AsSDKString ().c_str (), nullptr) }; if (tmp == nullptr) { errno_ErrorException::DoThrow (errno); } String result { String::FromNarrowSDKString (tmp) }; free (tmp); return result; #elif qPlatform_Windows // @todo MaYBE USE GetFinalPathNameByHandle // https://msdn.microsoft.com/en-us/library/windows/desktop/aa364962(v=vs.85).aspx // EXCEPT REQUIRES OPEN? // @todo LARGELY UNSTED ROUGH DRAFT - 2015-05-11 /* * Note: PathCanonicalize has lots of problems, PathCanonicalizeCh, and * PathCchCanonicalizeEx is better, but only works with windows 8 or later. */ using Characters::StringBuilder; String tmp = ResolveShortcut (path2FileOrShortcut); StringBuilder sb; Components c = GetPathComponents (path2FileOrShortcut); if (c.fAbsolutePath == Components::eAbsolutePath) { // use UNC notation sb += L"\\\\?"; if (c.fDriveLetter) { sb += *c.fDriveLetter; } else if (c.fServerAndShare) { sb += c.fServerAndShare->fServer + L"\\" + c.fServerAndShare->fShare; } else { Execution::DoThrow (Execution::StringException (L"for absolute path need drive letter or server/share")); } } else { if (c.fDriveLetter) { sb += *c.fDriveLetter + L":"; } } bool prefixWIthSlash = false; for (String i : c.fPath) { if (prefixWIthSlash) { sb += L"\\"; } sb += i; prefixWIthSlash = true; } return sb.str (); #else AssertNotImplemented (); return path2FileOrShortcut; #endif } String IO::FileSystem::FileSystem::CanonicalizeName (const String& path2FileOrShortcut, const String& relativeToDirectory, bool throwIfComponentsNotFound) { AssertNotImplemented (); return path2FileOrShortcut; } IO::FileSystem::FileSystem::Components IO::FileSystem::FileSystem::GetPathComponents (const String& fileName) { // @todo LARGELY UNSTED ROUGH DRAFT - 2015-05-11 // See http://en.wikipedia.org/wiki/Path_%28computing%29 to write this #if 0 //windows C: \user\docs\Letter.txt / user / docs / Letter.txt C: Letter.txt \\Server01\user\docs\Letter.txt \\ ? \UNC\Server01\user\docs\Letter.txt \\ ? \C : \user\docs\Letter.txt C : \user\docs\somefile.ext : alternate_stream_name . / inthisdir .. / .. / greatgrandparent #endif #if 0 // unix / home / user / docs / Letter.txt . / inthisdir .. / .. / greatgrandparent ~ / .rcinfo #endif IO::FileSystem::FileSystem::Components result; using Traversal::Iterator; using Characters::Character; #if qPlatform_Windows bool isUNCName = fileName.length () > 2 and fileName.StartsWith (L"\\\\"); bool isAbsolutePath = fileName.length () >= 1 and fileName.StartsWith (L"\\"); #else #endif #if qPlatform_Windows const Set<Character> kSlashChars_ = { '\\', '/' }; #else const Set<Character> kSlashChars_ = { '/' }; #endif Sequence<String> rawComponents = fileName.Tokenize (kSlashChars_, false); Iterator<String> i = rawComponents.begin (); #if qPlatform_Windows if (isUNCName) { // work todo } #endif for (; i != rawComponents.end (); ++i) { result.fPath.Append (*i); } AssertNotImplemented (); return result; } FileOffset_t IO::FileSystem::FileSystem::GetFileSize (const String& fileName) { #if qPlatform_Windows WIN32_FILE_ATTRIBUTE_DATA fileAttrData; (void)::memset (&fileAttrData, 0, sizeof (fileAttrData)); Execution::Platform::Windows::ThrowIfFalseGetLastError (::GetFileAttributesExW (fileName.c_str (), GetFileExInfoStandard, &fileAttrData)); return fileAttrData.nFileSizeLow + (static_cast<FileOffset_t> (fileAttrData.nFileSizeHigh) << 32); #else AssertNotImplemented (); return 0; #endif } DateTime IO::FileSystem::FileSystem::GetFileLastModificationDate (const String& fileName) { #if qPlatform_Windows WIN32_FILE_ATTRIBUTE_DATA fileAttrData; (void)::memset (&fileAttrData, 0, sizeof (fileAttrData)); ThrowIfFalseGetLastError (::GetFileAttributesExW (fileName.c_str (), GetFileExInfoStandard, &fileAttrData)); return DateTime (fileAttrData.ftLastWriteTime); #else AssertNotImplemented (); return DateTime (); #endif } DateTime IO::FileSystem::FileSystem::GetFileLastAccessDate (const String& fileName) { #if qPlatform_Windows WIN32_FILE_ATTRIBUTE_DATA fileAttrData; (void)::memset (&fileAttrData, 0, sizeof (fileAttrData)); ThrowIfFalseGetLastError (::GetFileAttributesExW (fileName.c_str (), GetFileExInfoStandard, &fileAttrData)); return DateTime (fileAttrData.ftLastAccessTime); #else AssertNotImplemented (); return DateTime (); #endif } void IO::FileSystem::FileSystem::RemoveFile (const String& fileName) { #if qPlatform_Windows && qTargetPlatformSDKUseswchar_t Execution::ThrowErrNoIfNegative (::_wunlink (fileName.c_str ())); #else Execution::ThrowErrNoIfNegative (::unlink (fileName.AsNarrowSDKString ().c_str ())); #endif } void IO::FileSystem::FileSystem::RemoveFileIf (const String& fileName) { #if qPlatform_Windows && qTargetPlatformSDKUseswchar_t int r = ::_wunlink (fileName.c_str ()); #else int r = ::unlink (fileName.AsNarrowSDKString ().c_str ()); #endif if (r < 0) { if (errno != ENOENT) { errno_ErrorException::DoThrow (errno); } } } String IO::FileSystem::FileSystem::GetCurrentDirectory () const { #if qPlatform_POSIX SDKChar buf[PATH_MAX]; Execution::ThrowErrNoIfNull (::getcwd (buf, NEltsOf (buf))); return String::FromSDKString (buf); #elif qPlatform_Windows SDKChar buf[MAX_PATH]; ThrowIfZeroGetLastError (::GetCurrentDirectory (NEltsOf (buf), buf)); return String::FromSDKString (buf); #else AssertNotReached (); #endif } void IO::FileSystem::FileSystem::SetCurrentDirectory (const String& newDir) { #if qPlatform_POSIX Execution::ThrowErrNoIfNegative (::chdir (newDir.AsNarrowSDKString ().c_str ())); #elif qPlatform_Windows ::SetCurrentDirectory(newDir.AsSDKString ().c_str ()); #else AssertNotReached (); #endif } <|endoftext|>
<commit_before>/* Copyright (c) 2010-2012 Delft University of Technology. * * This software is protected by national and international copyright. * Any unauthorized use, reproduction or modification is unlawful and * will be prosecuted. Commercial and non-private application of the * software in any form is strictly prohibited unless otherwise granted * by the authors. * * The code is provided without any warranty; without even the implied * warranty of merchantibility or fitness for a particular purpose. * * Changelog * YYMMDD Author Comment * 101203 E. Iorfida First creation of the code. * 101208 E. Iorfida Fulfillment of the code with the elliptical case. * 101208 E. Iorfida Modified punctuation. * 101215 E. Iorfida Added tolerance, added parabolic, circular and hyperbolic * cases. * 101217 E. Iorfida Added computeAbsoluteValue( ) in the errors computation, * modified punctuation. * 101219 J. Melman Put gravitational parameters in one place, changed first right * ascension to 15.0 * pi / 8.0, thereby exposing a possible * error. * 110107 E. Iorfida orbitalConversionBookExampleUnitTest.test added to this file, * to have a unique unit test file for the conversion code. Also * some punctuation modifications have been made. * 110109 J. Melman Included test for semi-latus rectum of circular case. Gave the * orbital angles less trivial values, and not almost exclusively * in the first quadrant. * 110111 E. Iorfida Updated to the new format of unitTest file and added hyperbolic * equatorial case. * 110204 K. Kumar Removed "vector" from naming. * 110216 K. Kumar Added unit tests for new orbital element conversion functions. * 110310 K. Kumar Changed right ascension of ascending node to longitude of * ascending node. * 110510 K. Kumar Updated to use new orbital element conversion functions and * removed dynamic memory allocation. * * References * http://www.astro.uu.nl/~strous/AA/en/reken/kepler.html, last accessed: 16th February, 2011. * Vallado, D. A., McClain, W. D. Fundamentals of astrodynamics and applications, 2nd Edition, * Kluwer Academic Publishers, The Netherlands, 2004. * Fortescue, P. W., et al. Spacecraft systems engineering, Third Edition, * Wiley, England, 2003. * */ // Temporary notes (move to class/function doxygen): // Test runs code and verifies result against expected value. // If the tested code is erroneous, the test function returns a boolean // true; if the code is correct, the function returns a boolean false. // #include <cmath> #include <iostream> #include <limits> #include <TudatCore/Astrodynamics/BasicAstrodynamics/orbitalElementConversions.h> #include <TudatCore/Astrodynamics/BasicAstrodynamics/unitConversions.h> #include "Tudat/Astrodynamics/BasicAstrodynamics/convertMeanAnomalyToEccentricAnomaly.h" #include "Tudat/Astrodynamics/BasicAstrodynamics/convertMeanAnomalyToHyperbolicEccentricAnomaly.h" #include "Tudat/Astrodynamics/Bodies/celestialBody.h" #include "Tudat/Astrodynamics/Bodies/planet.h" #include "Tudat/Astrodynamics/Gravitation/gravityFieldModel.h" #include "Tudat/Astrodynamics/Gravitation/sphericalHarmonicsGravityField.h" #include "Tudat/Mathematics/RootFindingMethods/newtonRaphson.h" //! Test orbital element conversion code. int main( ) { // Using declarations. using std::cerr; using std::endl; using std::fabs; using std::pow; using tudat::orbital_element_conversions::convertCartesianToKeplerianElements; using tudat::orbital_element_conversions::convertKeplerianToCartesianElements; using tudat::orbital_element_conversions::ConvertMeanAnomalyToEccentricAnomaly; using tudat::orbital_element_conversions::ConvertMeanAnomalyToHyperbolicEccentricAnomaly; using namespace tudat; // Test of orbital element conversion methods imeplemented in Tudat. // Test 1: Test of mean anomaly to eccentric anomaly conversion. // Initialize unit test result to false. bool isOrbitalElementConversionErroneous = false; // Test 1: Test of mean anomaly to eccentric anomaly conversion. // Source: ( Vallado, 2004 ). // Set tolerance for conversion. double toleranceOrbitalElementConversion = 1e-8; // Set eccentricity. double eccentricity = 0.01671; // Set mean anomaly. double meanAnomaly = unit_conversions::convertDegreesToRadians( 60.0 ); // Create Newton-Raphson object. NewtonRaphson newtonRaphson; // Create object for mean anomaly to eccentric anomaly conversion. orbital_element_conversions::ConvertMeanAnomalyToEccentricAnomaly convertMeanAnomalyToEccentricAnomaly( eccentricity, meanAnomaly, &newtonRaphson ); // Compute eccentric anomaly. double eccentricAnomaly = convertMeanAnomalyToEccentricAnomaly.convert( ); // Check if computed eccentric anomaly is equal to reference value. if ( fabs( eccentricAnomaly - 1.061789204 ) > toleranceOrbitalElementConversion ) { isOrbitalElementConversionErroneous = true; cerr << "The conversion of mean anomaly to eccentric anomaly is " << "erroneous as the computed eccentric anomaly after applying the conversion ( " << unit_conversions::convertRadiansToDegrees( eccentricAnomaly ) << " ) does not match the expected value of the eccentric anomaly ( " << unit_conversions::convertRadiansToDegrees( 1.061789204 ) << " ) " << endl; } // Return test result. // If test is successful return false; if test fails, return true. if ( isOrbitalElementConversionErroneous ) { cerr << "testOrbitalElementConversions failed!" << endl; } return isOrbitalElementConversionErroneous; } <commit_msg>Removed old (superfluous) orbital elements unit test (issue #409).<commit_after><|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 "MiniAppManager.h" // CTK #include "ctkCommandLineParser.h" #include <mitkIOUtil.h> #include <mitkRegistrationWrapper.h> #include <mitkImage.h> #include <mitkImageCast.h> #include <mitkITKImageImport.h> #include <mitkDiffusionImage.h> #include "mitkNrrdDiffusionImageWriter.h" // ITK #include <itksys/SystemTools.hxx> #include <itkDirectory.h> typedef std::vector<std::string> FileListType; static std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems) { std::stringstream ss(s); std::string item; while (std::getline(ss, item, delim)) { elems.push_back(item); } return elems; } static std::vector<std::string> split(const std::string &s, char delim) { std::vector < std::string > elems; return split(s, delim, elems); } /// Create list of all files in provided folder ending with same postfix static FileListType CreateFileList(std::string folder , std::string postfix) { itk::Directory::Pointer dir = itk::Directory::New(); FileListType fileList; if( dir->Load(folder.c_str() ) ) { int n = dir->GetNumberOfFiles(); for(int r=0;r<n;r++) { std::string filename = dir->GetFile( r ); if (filename == "." || filename == "..") continue; filename = folder + filename; if (!itksys::SystemTools::FileExists( filename.c_str())) continue; if (filename.substr(filename.length() -postfix.length() ) == postfix) fileList.push_back(filename); } } return fileList; } /// Add '_reg' tag to file name static std::string GetSavePath(std::string outputFolder, std::string fileName) { std::string fileType = itksys::SystemTools::GetFilenameExtension(fileName); std::string fileStem = itksys::SystemTools::GetFilenameWithoutExtension(fileName); std::string savePathAndFileName = outputFolder +fileStem + "_reg" + fileType; return savePathAndFileName; } /// Build a derived file name from moving images e.g. xxx_T2.nrrd becomes xxx_GTV.nrrd static FileListType CreateDerivedFileList(std::string baseFN, std::string baseSuffix, std::vector<std::string> derivedPatterns) { FileListType files; for (unsigned int i=0; i < derivedPatterns.size(); i++) { std::string derResourceSuffix = derivedPatterns.at(i); std::string derivedResourceFilename = baseFN.substr(0,baseFN.length() -baseSuffix.length()) + derResourceSuffix; MITK_INFO <<" Looking for file: " << derivedResourceFilename; if (!itksys::SystemTools::FileExists(derivedResourceFilename.c_str())) { MITK_INFO << "CreateDerivedFileList: File does not exit. Skipping entry."; continue; } files.push_back(derivedResourceFilename); } return files; } /// Save images according to file type static void SaveImage(std::string fileName, mitk::Image* image, std::string fileType ) { MITK_INFO << "----Save to " << fileName; if (fileType == "dwi") // IOUtil does not handle dwi files properly Bug 15772 { mitk::NrrdDiffusionImageWriter< short >::Pointer dwiwriter = mitk::NrrdDiffusionImageWriter< short >::New(); dwiwriter->SetInput( dynamic_cast<mitk::DiffusionImage<short>* > (image)); dwiwriter->SetFileName( fileName ); try { dwiwriter->Update(); } catch( const itk::ExceptionObject& e) { MITK_ERROR << "Caught exception: " << e.what(); mitkThrow() << "Failed with exception from subprocess!"; } } else { mitk::IOUtil::SaveImage(image, fileName); } } /// Copy derived resources from first time step. Append _reg tag, but leave data untouched. static void CopyResources(FileListType fileList, std::string outputPath) { for (unsigned int j=0; j < fileList.size(); j++) { std::string derivedResourceFilename = fileList.at(j); std::string fileType = itksys::SystemTools::GetFilenameExtension(derivedResourceFilename); std::string fileStem = itksys::SystemTools::GetFilenameWithoutExtension(derivedResourceFilename); std::string savePathAndFileName = outputPath +fileStem + "_reg." + fileType; MITK_INFO << "Copy resource " << savePathAndFileName; mitk::Image::Pointer resImage = mitk::IOUtil::LoadImage(derivedResourceFilename); mitk::IOUtil::SaveImage(resImage, savePathAndFileName); } } int BatchedFolderRegistration( int argc, char* argv[] ) { ctkCommandLineParser parser; parser.setArgumentPrefix("--","-"); // Add command line argument names parser.addArgument("help", "h",ctkCommandLineParser::Bool, "Show this help text"); parser.addArgument("xml", "x",ctkCommandLineParser::Bool, "Print a XML description of this modules command line interface"); //parser.addArgument("usemask", "u", QVariant::Bool, "Use segmentations (derived resources) to exclude areas from registration metrics"); parser.addArgument("input", "i", ctkCommandLineParser::String, "Input folder",us::Any(),false); parser.addArgument("output", "o", ctkCommandLineParser::String, "Output folder (ending with /)",us::Any(),false); parser.addArgument("fixed", "f", ctkCommandLineParser::String, "Suffix for fixed image",us::Any(),false); parser.addArgument("moving", "m", ctkCommandLineParser::String, "Suffix for moving images",us::Any(),false); parser.addArgument("derived", "d", ctkCommandLineParser::String, "Derived resources suffixes (replaces suffix for moving images); comma separated",us::Any(),true); parser.addArgument("silent", "s", ctkCommandLineParser::Bool, "No xml progress output."); // Feature currently disabled //parser.addArgument("resample", "r", QVariant::String, "Reference Image for resampling (optional), is not applied to tensor data"); map<string, us::Any> parsedArgs = parser.parseArguments(argc, argv); // Handle special arguments bool silent = false; { if (parsedArgs.size() == 0) { MITK_ERROR << "Missig arguements" ; return EXIT_FAILURE; } if (parsedArgs.count("xml")) { MITK_ERROR << "This is to be handled by shell script"; return EXIT_SUCCESS; } if (parsedArgs.count("silent")) silent = true; // Show a help message if ( parsedArgs.count("help") || parsedArgs.count("h")) { std::cout << parser.helpText(); return EXIT_SUCCESS; } } std::string outputPath = us::any_cast<string>(parsedArgs["output"]); std::string refPattern = us::any_cast<string>(parsedArgs["fixed"]); std::string inputPath = us::any_cast<string>(parsedArgs["input"]); std::string movingImgPattern = us::any_cast<string>(parsedArgs["moving"]); //QString resampleReference = parsedArgs["resample"].toString(); //bool maskTumor = parsedArgs["usemask"].toBool(); // if derived sources pattern is provided, populate QStringList with possible filename postfixes std::vector<std::string> derPatterns; if (parsedArgs.count("derived") || parsedArgs.count("d") ) { std::string arg = us::any_cast<string>(parsedArgs["derived"]); derPatterns = split(arg ,','); } MITK_INFO << "Input Folder : " << inputPath; MITK_INFO << "Looking for reference image ..."; FileListType referenceFileList = CreateFileList(inputPath,refPattern); if (referenceFileList.size() != 1) { MITK_ERROR << "None or more than one possible reference images (" << refPattern <<") found. Exiting." << referenceFileList.size(); MITK_INFO << "Choose a fixed arguement that is unique in the given folder!"; return EXIT_FAILURE; } std::string referenceFileName = referenceFileList.at(0); MITK_INFO << "Loading Reference (fixed) image: " << referenceFileName; mitk::Image::Pointer refImage = mitk::IOUtil::LoadImage(referenceFileName); if (refImage.IsNull()) MITK_ERROR << "Loaded fixed image is NULL"; // Copy reference image to destination std::string savePathAndFileName = GetSavePath(outputPath, referenceFileName); mitk::IOUtil::SaveImage(refImage, savePathAndFileName); // Copy all derived resources also to output folder, adding _reg suffix referenceFileList = CreateDerivedFileList(referenceFileName, movingImgPattern,derPatterns); CopyResources(referenceFileList, outputPath); std::string derivedResourceFilename; mitk::Image::Pointer referenceMask = NULL; // union of all segmentations if (!silent) { // XML Output to report progress std::cout << "<filter-start>"; std::cout << "<filter-name>Batched Registration</filter-name>"; std::cout << "<filter-comment>Starting registration ... </filter-comment>"; std::cout << "</filter-start>"; } // Now iterate over all files and register them to the reference image, // also register derived resources based on file patterns // ------------------------------------------------------------------------------ // Create File list FileListType movingImagesList = CreateFileList(inputPath, movingImgPattern); // TODO Reactivate Resampling Feature // mitk::Image::Pointer resampleImage = NULL; // if (QFileInfo(resampleReference).isFile()) // { // resampleImage = mitk::IOUtil::LoadImage(resampleReference.toStdString()); // } for (unsigned int i =0; i < movingImagesList.size(); i++) { std::string fileMorphName = movingImagesList.at(i); if (fileMorphName == referenceFileName) { // do not process reference image again continue; } MITK_INFO << "Processing image " << fileMorphName; // 1 Register morphological file to reference image if (!itksys::SystemTools::FileExists(fileMorphName.c_str())) { MITK_WARN << "File does not exit. Skipping entry."; continue; } // Origin of images is cancelled // TODO make this optional!! double transf[6]; double offset[3]; { mitk::Image::Pointer movingImage = mitk::IOUtil::LoadImage(fileMorphName); if (movingImage.IsNull()) MITK_ERROR << "Loaded moving image is NULL"; // Store transformation, apply it to morph file MITK_INFO << "----------Registering moving image to reference----------"; mitk::RegistrationWrapper::GetTransformation(refImage, movingImage, transf, offset, referenceMask); mitk::RegistrationWrapper::ApplyTransformationToImage(movingImage, transf,offset, NULL); // , resampleImage savePathAndFileName = GetSavePath(outputPath, fileMorphName); std::string fileType = itksys::SystemTools::GetFilenameExtension(fileMorphName); SaveImage(savePathAndFileName,movingImage,fileType ); } if (!silent) { std::cout << "<filter-progress-text progress=\"" << (float)i / (float)movingImagesList.size() << "\" >.</filter-progress-text>"; } // Now parse all derived resource and apply the above calculated transformation to them // ------------------------------------------------------------------------------------ FileListType fList = CreateDerivedFileList(fileMorphName, movingImgPattern,derPatterns); if (fList.size() > 0) MITK_INFO << "----------DERIVED RESOURCES ---------"; for (unsigned int j=0; j < fList.size(); j++) { derivedResourceFilename = fList.at(j); MITK_INFO << "----Processing derived resource " << derivedResourceFilename << " ..."; mitk::Image::Pointer derivedMovingResource = mitk::IOUtil::LoadImage(derivedResourceFilename); // Apply transformation to derived resource, treat derived resource as binary mitk::RegistrationWrapper::ApplyTransformationToImage(derivedMovingResource, transf,offset, NULL, true); savePathAndFileName = GetSavePath(outputPath, derivedResourceFilename); std::string fileType = itksys::SystemTools::GetFilenameExtension(derivedResourceFilename); SaveImage(savePathAndFileName,derivedMovingResource,fileType ); } } if (!silent) std::cout << "<filter-end/>"; return EXIT_SUCCESS; } RegisterDiffusionMiniApp(BatchedFolderRegistration); <commit_msg>correct handling of dwi file endings<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 "MiniAppManager.h" // CTK #include "ctkCommandLineParser.h" #include <mitkIOUtil.h> #include <mitkRegistrationWrapper.h> #include <mitkImage.h> #include <mitkImageCast.h> #include <mitkITKImageImport.h> #include <mitkDiffusionImage.h> #include "mitkNrrdDiffusionImageWriter.h" // ITK #include <itksys/SystemTools.hxx> #include <itkDirectory.h> typedef std::vector<std::string> FileListType; static std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems) { std::stringstream ss(s); std::string item; while (std::getline(ss, item, delim)) { elems.push_back(item); } return elems; } static std::vector<std::string> split(const std::string &s, char delim) { std::vector < std::string > elems; return split(s, delim, elems); } /// Create list of all files in provided folder ending with same postfix static FileListType CreateFileList(std::string folder , std::string postfix) { itk::Directory::Pointer dir = itk::Directory::New(); FileListType fileList; if( dir->Load(folder.c_str() ) ) { int n = dir->GetNumberOfFiles(); for(int r=0;r<n;r++) { std::string filename = dir->GetFile( r ); if (filename == "." || filename == "..") continue; filename = folder + filename; if (!itksys::SystemTools::FileExists( filename.c_str())) continue; if (filename.substr(filename.length() -postfix.length() ) == postfix) fileList.push_back(filename); } } return fileList; } /// Add '_reg' tag to file name static std::string GetSavePath(std::string outputFolder, std::string fileName) { std::string fileType = itksys::SystemTools::GetFilenameExtension(fileName); std::string fileStem = itksys::SystemTools::GetFilenameWithoutExtension(fileName); std::string savePathAndFileName = outputFolder +fileStem + "_reg" + fileType; return savePathAndFileName; } /// Build a derived file name from moving images e.g. xxx_T2.nrrd becomes xxx_GTV.nrrd static FileListType CreateDerivedFileList(std::string baseFN, std::string baseSuffix, std::vector<std::string> derivedPatterns) { FileListType files; for (unsigned int i=0; i < derivedPatterns.size(); i++) { std::string derResourceSuffix = derivedPatterns.at(i); std::string derivedResourceFilename = baseFN.substr(0,baseFN.length() -baseSuffix.length()) + derResourceSuffix; MITK_INFO <<" Looking for file: " << derivedResourceFilename; if (!itksys::SystemTools::FileExists(derivedResourceFilename.c_str())) { MITK_INFO << "CreateDerivedFileList: File does not exit. Skipping entry."; continue; } files.push_back(derivedResourceFilename); } return files; } /// Save images according to file type static void SaveImage(std::string fileName, mitk::Image* image, std::string fileType ) { MITK_INFO << "----Save to " << fileName; if (fileType == "dwi") // IOUtil does not handle dwi files properly Bug 15772 { mitk::NrrdDiffusionImageWriter< short >::Pointer dwiwriter = mitk::NrrdDiffusionImageWriter< short >::New(); dwiwriter->SetInput( dynamic_cast<mitk::DiffusionImage<short>* > (image)); dwiwriter->SetFileName( fileName ); try { dwiwriter->Update(); } catch( const itk::ExceptionObject& e) { MITK_ERROR << "Caught exception: " << e.what(); mitkThrow() << "Failed with exception from subprocess!"; } } else { mitk::IOUtil::SaveImage(image, fileName); } } /// Copy derived resources from first time step. Append _reg tag, but leave data untouched. static void CopyResources(FileListType fileList, std::string outputPath) { for (unsigned int j=0; j < fileList.size(); j++) { std::string derivedResourceFilename = fileList.at(j); std::string fileType = itksys::SystemTools::GetFilenameExtension(derivedResourceFilename); std::string fileStem = itksys::SystemTools::GetFilenameWithoutExtension(derivedResourceFilename); std::string savePathAndFileName = outputPath +fileStem + "_reg." + fileType; MITK_INFO << "Copy resource " << savePathAndFileName; mitk::Image::Pointer resImage = mitk::IOUtil::LoadImage(derivedResourceFilename); mitk::IOUtil::SaveImage(resImage, savePathAndFileName); } } int BatchedFolderRegistration( int argc, char* argv[] ) { ctkCommandLineParser parser; parser.setArgumentPrefix("--","-"); // Add command line argument names parser.addArgument("help", "h",ctkCommandLineParser::Bool, "Show this help text"); parser.addArgument("xml", "x",ctkCommandLineParser::Bool, "Print a XML description of this modules command line interface"); //parser.addArgument("usemask", "u", QVariant::Bool, "Use segmentations (derived resources) to exclude areas from registration metrics"); parser.addArgument("input", "i", ctkCommandLineParser::String, "Input folder",us::Any(),false); parser.addArgument("output", "o", ctkCommandLineParser::String, "Output folder (ending with /)",us::Any(),false); parser.addArgument("fixed", "f", ctkCommandLineParser::String, "Suffix for fixed image",us::Any(),false); parser.addArgument("moving", "m", ctkCommandLineParser::String, "Suffix for moving images",us::Any(),false); parser.addArgument("derived", "d", ctkCommandLineParser::String, "Derived resources suffixes (replaces suffix for moving images); comma separated",us::Any(),true); parser.addArgument("silent", "s", ctkCommandLineParser::Bool, "No xml progress output."); // Feature currently disabled //parser.addArgument("resample", "r", QVariant::String, "Reference Image for resampling (optional), is not applied to tensor data"); map<string, us::Any> parsedArgs = parser.parseArguments(argc, argv); // Handle special arguments bool silent = false; { if (parsedArgs.size() == 0) { MITK_ERROR << "Missig arguements" ; return EXIT_FAILURE; } if (parsedArgs.count("xml")) { MITK_ERROR << "This is to be handled by shell script"; return EXIT_SUCCESS; } if (parsedArgs.count("silent")) silent = true; // Show a help message if ( parsedArgs.count("help") || parsedArgs.count("h")) { std::cout << parser.helpText(); return EXIT_SUCCESS; } } std::string outputPath = us::any_cast<string>(parsedArgs["output"]); std::string refPattern = us::any_cast<string>(parsedArgs["fixed"]); std::string inputPath = us::any_cast<string>(parsedArgs["input"]); std::string movingImgPattern = us::any_cast<string>(parsedArgs["moving"]); //QString resampleReference = parsedArgs["resample"].toString(); //bool maskTumor = parsedArgs["usemask"].toBool(); // if derived sources pattern is provided, populate QStringList with possible filename postfixes std::vector<std::string> derPatterns; if (parsedArgs.count("derived") || parsedArgs.count("d") ) { std::string arg = us::any_cast<string>(parsedArgs["derived"]); derPatterns = split(arg ,','); } MITK_INFO << "Input Folder : " << inputPath; MITK_INFO << "Looking for reference image ..."; FileListType referenceFileList = CreateFileList(inputPath,refPattern); if (referenceFileList.size() != 1) { MITK_ERROR << "None or more than one possible reference images (" << refPattern <<") found. Exiting." << referenceFileList.size(); MITK_INFO << "Choose a fixed arguement that is unique in the given folder!"; return EXIT_FAILURE; } std::string referenceFileName = referenceFileList.at(0); MITK_INFO << "Loading Reference (fixed) image: " << referenceFileName; mitk::Image::Pointer refImage = mitk::IOUtil::LoadImage(referenceFileName); if (refImage.IsNull()) MITK_ERROR << "Loaded fixed image is NULL"; // Copy reference image to destination std::string savePathAndFileName = GetSavePath(outputPath, referenceFileName); mitk::IOUtil::SaveImage(refImage, savePathAndFileName); // Copy all derived resources also to output folder, adding _reg suffix referenceFileList = CreateDerivedFileList(referenceFileName, movingImgPattern,derPatterns); CopyResources(referenceFileList, outputPath); std::string derivedResourceFilename; mitk::Image::Pointer referenceMask = NULL; // union of all segmentations if (!silent) { // XML Output to report progress std::cout << "<filter-start>"; std::cout << "<filter-name>Batched Registration</filter-name>"; std::cout << "<filter-comment>Starting registration ... </filter-comment>"; std::cout << "</filter-start>"; } // Now iterate over all files and register them to the reference image, // also register derived resources based on file patterns // ------------------------------------------------------------------------------ // Create File list FileListType movingImagesList = CreateFileList(inputPath, movingImgPattern); // TODO Reactivate Resampling Feature // mitk::Image::Pointer resampleImage = NULL; // if (QFileInfo(resampleReference).isFile()) // { // resampleImage = mitk::IOUtil::LoadImage(resampleReference.toStdString()); // } for (unsigned int i =0; i < movingImagesList.size(); i++) { std::string fileMorphName = movingImagesList.at(i); if (fileMorphName == referenceFileName) { // do not process reference image again continue; } MITK_INFO << "Processing image " << fileMorphName; // 1 Register morphological file to reference image if (!itksys::SystemTools::FileExists(fileMorphName.c_str())) { MITK_WARN << "File does not exit. Skipping entry."; continue; } // Origin of images is cancelled // TODO make this optional!! double transf[6]; double offset[3]; { mitk::Image::Pointer movingImage = mitk::IOUtil::LoadImage(fileMorphName); if (movingImage.IsNull()) MITK_ERROR << "Loaded moving image is NULL"; // Store transformation, apply it to morph file MITK_INFO << "----------Registering moving image to reference----------"; mitk::RegistrationWrapper::GetTransformation(refImage, movingImage, transf, offset, referenceMask); mitk::RegistrationWrapper::ApplyTransformationToImage(movingImage, transf,offset, NULL); // , resampleImage savePathAndFileName = GetSavePath(outputPath, fileMorphName); std::string fileType = itksys::SystemTools::GetFilenameExtension(fileMorphName); if (fileType == ".dwi") fileType = "dwi"; SaveImage(savePathAndFileName,movingImage,fileType ); } if (!silent) { std::cout << "<filter-progress-text progress=\"" << (float)i / (float)movingImagesList.size() << "\" >.</filter-progress-text>"; } // Now parse all derived resource and apply the above calculated transformation to them // ------------------------------------------------------------------------------------ FileListType fList = CreateDerivedFileList(fileMorphName, movingImgPattern,derPatterns); if (fList.size() > 0) MITK_INFO << "----------DERIVED RESOURCES ---------"; for (unsigned int j=0; j < fList.size(); j++) { derivedResourceFilename = fList.at(j); MITK_INFO << "----Processing derived resource " << derivedResourceFilename << " ..."; mitk::Image::Pointer derivedMovingResource = mitk::IOUtil::LoadImage(derivedResourceFilename); // Apply transformation to derived resource, treat derived resource as binary mitk::RegistrationWrapper::ApplyTransformationToImage(derivedMovingResource, transf,offset, NULL, true); savePathAndFileName = GetSavePath(outputPath, derivedResourceFilename); std::string fileType = itksys::SystemTools::GetFilenameExtension(derivedResourceFilename); SaveImage(savePathAndFileName,derivedMovingResource,fileType ); } } if (!silent) std::cout << "<filter-end/>"; return EXIT_SUCCESS; } RegisterDiffusionMiniApp(BatchedFolderRegistration); <|endoftext|>
<commit_before>// // Copyright (c) articy Software GmbH & Co. KG. All rights reserved. // #include "Slate/GV/SArticyGlobalVariables.h" #include "ArticyEditorStyle.h" #include "ArticyPluginSettings.h" #include "Widgets/Input/SNumericEntryBox.h" #include "Widgets/Input/SSearchBox.h" #include "Widgets/Input/SCheckBox.h" #include "Widgets/Layout/SScrollBox.h" #include "Widgets/Layout/SBox.h" #include "Editor.h" #include "ScopedTransaction.h" #define LOCTEXT_NAMESPACE "ArticyGlobalVariables" #if ENGINE_MAJOR_VERSION >= 5 using SplitterSlotType = SSplitter::FSlot::FSlotArguments::WidgetArgsType; using HorizontalBoxSlotType = SHorizontalBox::FSlot::FSlotArguments; #else using SplitterSlotType = SSplitter::FSlot; using HorizontalBoxSlotType = SHorizontalBox::FSlot; #endif void SArticyVariableSet::Construct(const FArguments& Args, TWeakObjectPtr<UArticyBaseVariableSet> InVariableSet) { VariableSet = InVariableSet; ensure(VariableSet.IsValid()); SizeData = Args._SizeData; VariableContainer = SNew(SVerticalBox); NamespaceExpansion = SNew(SExpandableArea) .InitiallyCollapsed(Args._bInitiallyCollapsed) .BorderBackgroundColor(FLinearColor(0.7f, 0.7f, 0.7f)) .HeaderContent() [ SNew(SHorizontalBox) + SHorizontalBox::Slot() .FillWidth(1.f) [ SNew(STextBlock) .Text(FText::FromString(VariableSet->GetName())) .TextStyle(FArticyEditorStyle::Get(), TEXT("ArticyImporter.GlobalVariables.Namespace")) ] ] .BodyContent() [ VariableContainer.ToSharedRef() ]; BuildVariableWidgets(); ChildSlot [ NamespaceExpansion.ToSharedRef() ]; } void SArticyVariableSet::SetExpanded(bool bInExpanded) const { NamespaceExpansion->SetExpanded(bInExpanded); } bool SArticyVariableSet::IsExpanded() const { return NamespaceExpansion->IsExpanded(); } void SArticyVariableSet::BuildVariableWidgets() { if (bVariableWidgetsBuilt) { return; } TArray<UArticyVariable*> SortedVars = VariableSet->Variables; SortedVars.Sort([](const UArticyVariable& LHS, const UArticyVariable& RHS) { return LHS.GetName().Compare(RHS.GetName(), ESearchCase::IgnoreCase) < 0 ? true : false; }); for (UArticyVariable* Var : SortedVars) { TSharedRef<SSplitter> LocalSplitter = SNew(SSplitter); // left variable slot LocalSplitter->AddSlot() .Value(SizeData->LeftColumnWidth) .OnSlotResized(SizeData->OnWidthChanged) [ SNew(STextBlock).Text_Lambda([Var]() { return FText::FromString(Var->GetName()); }) ]; // right variable slot SplitterSlotType& RightVariableSlot = LocalSplitter->AddSlot() .Value(SizeData->RightColumnWidth) .OnSlotResized(SizeData->OnWidthChanged); TSharedRef<SHorizontalBox> ConstrainBox = SNew(SHorizontalBox); HorizontalBoxSlotType& InnerVarSlot = ConstrainBox->AddSlot().AutoWidth(); RightVariableSlot [ SNew(SBox) .MinDesiredWidth(150.f) .MaxDesiredWidth(300.f) [ ConstrainBox ] ]; if (Var->GetClass() == UArticyString::StaticClass()) { UArticyString* StringVar = Cast<UArticyString>(Var); InnerVarSlot [ SNew(SEditableTextBox) .MinDesiredWidth(30.f) .Text_Lambda([StringVar]() { return FText::FromString(StringVar->Get()); }) .OnTextCommitted_Lambda([StringVar](const FText& Text, ETextCommit::Type CommitType) { if(StringVar->Get().Equals(Text.ToString())) { return; } const FScopedTransaction Transaction(LOCTEXT("ModifyGV", "Modified GV")); StringVar->Modify(); *StringVar = Text.ToString(); }) ]; } else if (Var->GetClass() == UArticyInt::StaticClass()) { UArticyInt* IntVar = Cast<UArticyInt>(Var); InnerVarSlot [ SNew(SNumericEntryBox<int32>) .AllowSpin(true) .MaxSliderValue(TOptional<int32>()) .MinSliderValue(TOptional<int32>()) .MinDesiredValueWidth(80.f) .OnBeginSliderMovement_Lambda([=]() { bSliderMoving = true; GEditor->BeginTransaction(TEXT("Articy GV"), FText::FromString(TEXT("Modify Articy GV by Slider")), IntVar); }) .OnEndSliderMovement_Lambda([=](int32 Value) { bSliderMoving = false; IntVar->Modify(); *IntVar = Value; GEditor->EndTransaction(); }) .Value_Lambda([IntVar]() { return IntVar->Get(); }) // on value changed is only used for slider value updates .OnValueChanged(this, &SArticyVariableSet::OnValueChanged, IntVar) .OnValueCommitted_Lambda([=](int32 Value, ETextCommit::Type Type) { if (bSliderMoving || Value == IntVar->Get()) { return; } const FScopedTransaction Transaction(LOCTEXT("ModifyGV", "Modified GV")); IntVar->Modify(); *IntVar = Value; }) ]; } else if (Var->GetClass() == UArticyBool::StaticClass()) { UArticyBool* BoolVar = Cast<UArticyBool>(Var); InnerVarSlot [ SNew(SCheckBox) .IsChecked_Lambda([BoolVar]() { return BoolVar->Get() ? ECheckBoxState::Checked : ECheckBoxState::Unchecked; }) .OnCheckStateChanged_Lambda([BoolVar](const ECheckBoxState& State) { if(*BoolVar == (State == ECheckBoxState::Checked)) { return; } const FScopedTransaction Transaction(TEXT("ArticyGV"),LOCTEXT("ModifyGV", "Modified GV"), BoolVar); bool bSavedInTranactionBuffer = BoolVar->Modify(); *BoolVar = State == ECheckBoxState::Checked; }) ]; } VariableWidgetMapping.Add(Var, LocalSplitter); VariableContainer->AddSlot() .AutoHeight() .Padding(25.f, 5.f, 5.f, 5.f) [ LocalSplitter ]; } bVariableWidgetsBuilt = true; } void SArticyVariableSet::UpdateVisibility(const UArticyVariable* Variable, EVisibility InVisibility) { if(VariableWidgetMapping.Contains(Variable)) { TWeakPtr<SWidget> VarWidget = VariableWidgetMapping[Variable]; VarWidget.Pin()->SetVisibility(InVisibility); } } TArray<UArticyVariable*> SArticyVariableSet::GetVariables() { return VariableSet->GetVariables(); } void SArticyGlobalVariables::Construct(const FArguments& Args, TWeakObjectPtr<UArticyGlobalVariables> GV) { VariableFilter = MakeShareable(new FFrontendFilter_ArticyVariable); FrontendFilters = MakeShareable(new FArticyVariableFilterCollectionType); FrontendFilters->OnChanged().AddSP(this, &SArticyGlobalVariables::OnFrontendFiltersChanged); GlobalVariables = GV; SizeData.RightColumnWidth = TAttribute<float>(this, &SArticyGlobalVariables::OnGetRightColumnWidth); SizeData.LeftColumnWidth = TAttribute<float>(this, &SArticyGlobalVariables::OnGetLeftColumnWidth); SizeData.OnWidthChanged = SSplitter::FOnSlotResized::CreateSP(this, &SArticyGlobalVariables::OnSetColumnWidth); bInitiallyCollapsed = Args._bInitiallyCollapsed; TSharedRef<SVerticalBox> ParentWidget = SNew(SVerticalBox); SetContainer = SNew(SVerticalBox); TSharedRef<SScrollBox> ScrollBox = SNew(SScrollBox).ScrollBarAlwaysVisible(true) + SScrollBox::Slot() [ SetContainer.ToSharedRef() ]; if(GlobalVariables.IsValid()) { UpdateDisplayedGlobalVariables(GlobalVariables); } TSharedRef<SSearchBox> SearchBox = SNew(SSearchBox) .OnTextChanged(this, &SArticyGlobalVariables::OnSearchBoxChanged) .OnTextCommitted(this, &SArticyGlobalVariables::OnSearchBoxCommitted) .DelayChangeNotificationsWhileTyping(true); ParentWidget->AddSlot().AutoHeight()[SearchBox]; ParentWidget->AddSlot().FillHeight(1.f)[ScrollBox]; ChildSlot [ ParentWidget ]; //FrontendFilters->Add(VariableFilter); } void SArticyGlobalVariables::UpdateDisplayedGlobalVariables(TWeakObjectPtr<UArticyGlobalVariables> InGV) { VariableSetWidgets.Empty(); SetContainer->ClearChildren(); if(!InGV.IsValid()) { return; } TArray<UArticyBaseVariableSet*> SortedSets = InGV->GetVariableSets(); SortedSets.Sort([](const UArticyBaseVariableSet& LHS, const UArticyBaseVariableSet& RHS) { return LHS.GetName().Compare(RHS.GetName(), ESearchCase::IgnoreCase) < 0 ? true : false; }); for (UArticyBaseVariableSet* Set : SortedSets) { TSharedRef<SArticyVariableSet> VarSetWidget = SNew(SArticyVariableSet, Set) .bInitiallyCollapsed(bInitiallyCollapsed) .SizeData(&SizeData); VariableSetWidgets.Add(VarSetWidget); SetContainer->AddSlot().AutoHeight() [ VarSetWidget ]; } // retrigger the currently active filters FrontendFilters->OnChanged().Broadcast(); } void SArticyGlobalVariables::OnSearchBoxChanged(const FText& InSearchText) { SetSearchBoxText(InSearchText); } void SArticyGlobalVariables::OnSearchBoxCommitted(const FText& InSearchText, ETextCommit::Type CommitInfo) { SetSearchBoxText(InSearchText); } void SArticyGlobalVariables::SetSearchBoxText(const FText& InSearchText) { // Update the filter text only if it has actually changed, including case sensitivity (as operators are case sensitive) if (!InSearchText.ToString().Equals(VariableFilter->GetRawFilterText().ToString(), ESearchCase::CaseSensitive)) { VariableFilter->SetRawFilterText(InSearchText); // add or remove the filter depending on whether the search field has content or not if (InSearchText.IsEmpty() && FrontendFilters->Num() > 0) { FrontendFilters->Remove(VariableFilter); RestoreExpansionStates(); } else if(!InSearchText.IsEmpty() && FrontendFilters->Num() == 0) { CacheExpansionStates(); FrontendFilters->Add(VariableFilter); } } } void SArticyGlobalVariables::OnFrontendFiltersChanged() { if(FrontendFilters->Num() > 0) { bShouldForceExpand = true; } else { bShouldForceExpand = false; } for(TSharedPtr<SArticyVariableSet> SetWidget : VariableSetWidgets) { uint32 NumVisible = 0; TArray<UArticyVariable*> Vars = SetWidget->GetVariables(); for(UArticyVariable* Var : Vars) { const UArticyVariable* VarTmp = Var; if(TestAgainstFrontendFilters(Var)) { SetWidget->UpdateVisibility(VarTmp, EVisibility::Visible); NumVisible++; } else { SetWidget->UpdateVisibility(VarTmp, EVisibility::Collapsed); } } if(NumVisible > 0) { if(bShouldForceExpand) { SetWidget->SetExpanded(true); } SetWidget->SetVisibility(EVisibility::Visible); } else { SetWidget->SetVisibility(EVisibility::Collapsed); } } } bool SArticyGlobalVariables::TestAgainstFrontendFilters(const UArticyVariable* Item) const { if (FrontendFilters.IsValid() && !FrontendFilters->PassesAllFilters(Item)) { return false; } return true; } void SArticyGlobalVariables::CacheExpansionStates() { for(TSharedPtr<SArticyVariableSet>& SetWidget : VariableSetWidgets) { ExpansionCache.Add(SetWidget, SetWidget->IsExpanded()); } } void SArticyGlobalVariables::RestoreExpansionStates() { // restore the previous expansion state from the forced expansion for (auto It = ExpansionCache.CreateIterator(); It; ++It) { It.Key()->SetExpanded(It.Value()); } } #undef LOCTEXT_NAMESPACE<commit_msg>Fixed global variables editor for UE5<commit_after>// // Copyright (c) articy Software GmbH & Co. KG. All rights reserved. // #include "Slate/GV/SArticyGlobalVariables.h" #include "ArticyEditorStyle.h" #include "ArticyPluginSettings.h" #include "Widgets/Input/SNumericEntryBox.h" #include "Widgets/Input/SSearchBox.h" #include "Widgets/Input/SCheckBox.h" #include "Widgets/Layout/SScrollBox.h" #include "Widgets/Layout/SBox.h" #include "Editor.h" #include "ScopedTransaction.h" #define LOCTEXT_NAMESPACE "ArticyGlobalVariables" #if ENGINE_MAJOR_VERSION >= 5 using SplitterSlotType = SSplitter::FScopedWidgetSlotArguments; using HorizontalBoxSlotType = SHorizontalBox::FScopedWidgetSlotArguments; #else using SplitterSlotType = SSplitter::FSlot&; using HorizontalBoxSlotType = SHorizontalBox::FSlot&; #endif void SArticyVariableSet::Construct(const FArguments& Args, TWeakObjectPtr<UArticyBaseVariableSet> InVariableSet) { VariableSet = InVariableSet; ensure(VariableSet.IsValid()); SizeData = Args._SizeData; VariableContainer = SNew(SVerticalBox); NamespaceExpansion = SNew(SExpandableArea) .InitiallyCollapsed(Args._bInitiallyCollapsed) .BorderBackgroundColor(FLinearColor(0.7f, 0.7f, 0.7f)) .HeaderContent() [ SNew(SHorizontalBox) + SHorizontalBox::Slot() .FillWidth(1.f) [ SNew(STextBlock) .Text(FText::FromString(VariableSet->GetName())) .TextStyle(FArticyEditorStyle::Get(), TEXT("ArticyImporter.GlobalVariables.Namespace")) ] ] .BodyContent() [ VariableContainer.ToSharedRef() ]; BuildVariableWidgets(); ChildSlot [ NamespaceExpansion.ToSharedRef() ]; } void SArticyVariableSet::SetExpanded(bool bInExpanded) const { NamespaceExpansion->SetExpanded(bInExpanded); } bool SArticyVariableSet::IsExpanded() const { return NamespaceExpansion->IsExpanded(); } void SArticyVariableSet::BuildVariableWidgets() { if (bVariableWidgetsBuilt) { return; } TArray<UArticyVariable*> SortedVars = VariableSet->Variables; SortedVars.Sort([](const UArticyVariable& LHS, const UArticyVariable& RHS) { return LHS.GetName().Compare(RHS.GetName(), ESearchCase::IgnoreCase) < 0 ? true : false; }); for (UArticyVariable* Var : SortedVars) { TSharedRef<SSplitter> LocalSplitter = SNew(SSplitter); // left variable slot LocalSplitter->AddSlot() .Value(SizeData->LeftColumnWidth) .OnSlotResized(SizeData->OnWidthChanged) [ SNew(STextBlock).Text_Lambda([Var]() { return FText::FromString(Var->GetName()); }) ]; // right variable slot SplitterSlotType RightVariableSlot = LocalSplitter->AddSlot(); RightVariableSlot.Value(SizeData->RightColumnWidth); RightVariableSlot.OnSlotResized(SizeData->OnWidthChanged); TSharedRef<SHorizontalBox> ConstrainBox = SNew(SHorizontalBox); HorizontalBoxSlotType InnerVarSlot = ConstrainBox->AddSlot(); InnerVarSlot.AutoWidth(); RightVariableSlot [ SNew(SBox) .MinDesiredWidth(150.f) .MaxDesiredWidth(300.f) [ ConstrainBox ] ]; if (Var->GetClass() == UArticyString::StaticClass()) { UArticyString* StringVar = Cast<UArticyString>(Var); InnerVarSlot [ SNew(SEditableTextBox) .MinDesiredWidth(30.f) .Text_Lambda([StringVar]() { return FText::FromString(StringVar->Get()); }) .OnTextCommitted_Lambda([StringVar](const FText& Text, ETextCommit::Type CommitType) { if(StringVar->Get().Equals(Text.ToString())) { return; } const FScopedTransaction Transaction(LOCTEXT("ModifyGV", "Modified GV")); StringVar->Modify(); *StringVar = Text.ToString(); }) ]; } else if (Var->GetClass() == UArticyInt::StaticClass()) { UArticyInt* IntVar = Cast<UArticyInt>(Var); InnerVarSlot [ SNew(SNumericEntryBox<int32>) .AllowSpin(true) .MaxSliderValue(TOptional<int32>()) .MinSliderValue(TOptional<int32>()) .MinDesiredValueWidth(80.f) .OnBeginSliderMovement_Lambda([=]() { bSliderMoving = true; GEditor->BeginTransaction(TEXT("Articy GV"), FText::FromString(TEXT("Modify Articy GV by Slider")), IntVar); }) .OnEndSliderMovement_Lambda([=](int32 Value) { bSliderMoving = false; IntVar->Modify(); *IntVar = Value; GEditor->EndTransaction(); }) .Value_Lambda([IntVar]() { return IntVar->Get(); }) // on value changed is only used for slider value updates .OnValueChanged(this, &SArticyVariableSet::OnValueChanged, IntVar) .OnValueCommitted_Lambda([=](int32 Value, ETextCommit::Type Type) { if (bSliderMoving || Value == IntVar->Get()) { return; } const FScopedTransaction Transaction(LOCTEXT("ModifyGV", "Modified GV")); IntVar->Modify(); *IntVar = Value; }) ]; } else if (Var->GetClass() == UArticyBool::StaticClass()) { UArticyBool* BoolVar = Cast<UArticyBool>(Var); InnerVarSlot [ SNew(SCheckBox) .IsChecked_Lambda([BoolVar]() { return BoolVar->Get() ? ECheckBoxState::Checked : ECheckBoxState::Unchecked; }) .OnCheckStateChanged_Lambda([BoolVar](const ECheckBoxState& State) { if(*BoolVar == (State == ECheckBoxState::Checked)) { return; } const FScopedTransaction Transaction(TEXT("ArticyGV"),LOCTEXT("ModifyGV", "Modified GV"), BoolVar); bool bSavedInTranactionBuffer = BoolVar->Modify(); *BoolVar = State == ECheckBoxState::Checked; }) ]; } VariableWidgetMapping.Add(Var, LocalSplitter); VariableContainer->AddSlot() .AutoHeight() .Padding(25.f, 5.f, 5.f, 5.f) [ LocalSplitter ]; } bVariableWidgetsBuilt = true; } void SArticyVariableSet::UpdateVisibility(const UArticyVariable* Variable, EVisibility InVisibility) { if(VariableWidgetMapping.Contains(Variable)) { TWeakPtr<SWidget> VarWidget = VariableWidgetMapping[Variable]; VarWidget.Pin()->SetVisibility(InVisibility); } } TArray<UArticyVariable*> SArticyVariableSet::GetVariables() { return VariableSet->GetVariables(); } void SArticyGlobalVariables::Construct(const FArguments& Args, TWeakObjectPtr<UArticyGlobalVariables> GV) { VariableFilter = MakeShareable(new FFrontendFilter_ArticyVariable); FrontendFilters = MakeShareable(new FArticyVariableFilterCollectionType); FrontendFilters->OnChanged().AddSP(this, &SArticyGlobalVariables::OnFrontendFiltersChanged); GlobalVariables = GV; SizeData.RightColumnWidth = TAttribute<float>(this, &SArticyGlobalVariables::OnGetRightColumnWidth); SizeData.LeftColumnWidth = TAttribute<float>(this, &SArticyGlobalVariables::OnGetLeftColumnWidth); SizeData.OnWidthChanged = SSplitter::FOnSlotResized::CreateSP(this, &SArticyGlobalVariables::OnSetColumnWidth); bInitiallyCollapsed = Args._bInitiallyCollapsed; TSharedRef<SVerticalBox> ParentWidget = SNew(SVerticalBox); SetContainer = SNew(SVerticalBox); TSharedRef<SScrollBox> ScrollBox = SNew(SScrollBox).ScrollBarAlwaysVisible(true) + SScrollBox::Slot() [ SetContainer.ToSharedRef() ]; if(GlobalVariables.IsValid()) { UpdateDisplayedGlobalVariables(GlobalVariables); } TSharedRef<SSearchBox> SearchBox = SNew(SSearchBox) .OnTextChanged(this, &SArticyGlobalVariables::OnSearchBoxChanged) .OnTextCommitted(this, &SArticyGlobalVariables::OnSearchBoxCommitted) .DelayChangeNotificationsWhileTyping(true); ParentWidget->AddSlot().AutoHeight()[SearchBox]; ParentWidget->AddSlot().FillHeight(1.f)[ScrollBox]; ChildSlot [ ParentWidget ]; //FrontendFilters->Add(VariableFilter); } void SArticyGlobalVariables::UpdateDisplayedGlobalVariables(TWeakObjectPtr<UArticyGlobalVariables> InGV) { VariableSetWidgets.Empty(); SetContainer->ClearChildren(); if(!InGV.IsValid()) { return; } TArray<UArticyBaseVariableSet*> SortedSets = InGV->GetVariableSets(); SortedSets.Sort([](const UArticyBaseVariableSet& LHS, const UArticyBaseVariableSet& RHS) { return LHS.GetName().Compare(RHS.GetName(), ESearchCase::IgnoreCase) < 0 ? true : false; }); for (UArticyBaseVariableSet* Set : SortedSets) { TSharedRef<SArticyVariableSet> VarSetWidget = SNew(SArticyVariableSet, Set) .bInitiallyCollapsed(bInitiallyCollapsed) .SizeData(&SizeData); VariableSetWidgets.Add(VarSetWidget); SetContainer->AddSlot().AutoHeight() [ VarSetWidget ]; } // retrigger the currently active filters FrontendFilters->OnChanged().Broadcast(); } void SArticyGlobalVariables::OnSearchBoxChanged(const FText& InSearchText) { SetSearchBoxText(InSearchText); } void SArticyGlobalVariables::OnSearchBoxCommitted(const FText& InSearchText, ETextCommit::Type CommitInfo) { SetSearchBoxText(InSearchText); } void SArticyGlobalVariables::SetSearchBoxText(const FText& InSearchText) { // Update the filter text only if it has actually changed, including case sensitivity (as operators are case sensitive) if (!InSearchText.ToString().Equals(VariableFilter->GetRawFilterText().ToString(), ESearchCase::CaseSensitive)) { VariableFilter->SetRawFilterText(InSearchText); // add or remove the filter depending on whether the search field has content or not if (InSearchText.IsEmpty() && FrontendFilters->Num() > 0) { FrontendFilters->Remove(VariableFilter); RestoreExpansionStates(); } else if(!InSearchText.IsEmpty() && FrontendFilters->Num() == 0) { CacheExpansionStates(); FrontendFilters->Add(VariableFilter); } } } void SArticyGlobalVariables::OnFrontendFiltersChanged() { if(FrontendFilters->Num() > 0) { bShouldForceExpand = true; } else { bShouldForceExpand = false; } for(TSharedPtr<SArticyVariableSet> SetWidget : VariableSetWidgets) { uint32 NumVisible = 0; TArray<UArticyVariable*> Vars = SetWidget->GetVariables(); for(UArticyVariable* Var : Vars) { const UArticyVariable* VarTmp = Var; if(TestAgainstFrontendFilters(Var)) { SetWidget->UpdateVisibility(VarTmp, EVisibility::Visible); NumVisible++; } else { SetWidget->UpdateVisibility(VarTmp, EVisibility::Collapsed); } } if(NumVisible > 0) { if(bShouldForceExpand) { SetWidget->SetExpanded(true); } SetWidget->SetVisibility(EVisibility::Visible); } else { SetWidget->SetVisibility(EVisibility::Collapsed); } } } bool SArticyGlobalVariables::TestAgainstFrontendFilters(const UArticyVariable* Item) const { if (FrontendFilters.IsValid() && !FrontendFilters->PassesAllFilters(Item)) { return false; } return true; } void SArticyGlobalVariables::CacheExpansionStates() { for(TSharedPtr<SArticyVariableSet>& SetWidget : VariableSetWidgets) { ExpansionCache.Add(SetWidget, SetWidget->IsExpanded()); } } void SArticyGlobalVariables::RestoreExpansionStates() { // restore the previous expansion state from the forced expansion for (auto It = ExpansionCache.CreateIterator(); It; ++It) { It.Key()->SetExpanded(It.Value()); } } #undef LOCTEXT_NAMESPACE<|endoftext|>
<commit_before>/* This file is part of the PhantomJS project from Ofi Labs. Copyright (C) 2011 Ariya Hidayat <[email protected]> Copyright (C) 2011 Ivan De Marino <[email protected]> Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the <organization> 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 <COPYRIGHT HOLDER> 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 <QDateTime> #include <QList> #include <QDesktopServices> #include <QNetworkRequest> #include <QNetworkReply> #include <QNetworkDiskCache> #include <QAuthenticator> #include "networkaccessmanager.h" #include "networkreplyproxy.h" #include "cookiejar.h" #include "terminal.h" static const char *toString(QNetworkAccessManager::Operation op) { const char *str = 0; switch (op) { case QNetworkAccessManager::HeadOperation: str = "HEAD"; break; case QNetworkAccessManager::GetOperation: str = "GET"; break; case QNetworkAccessManager::PutOperation: str = "PUT"; break; case QNetworkAccessManager::PostOperation: str = "POST"; break; case QNetworkAccessManager::DeleteOperation: str = "DELETE"; break; default: str = "?"; break; } return str; } // public: NetworkAccessManager::NetworkAccessManager(QObject *parent, bool diskCacheEnabled, QString cookieFile, bool ignoreSslErrors, QString authUser, QString authPass) : QNetworkAccessManager(parent) , m_networkDiskCache(0) , m_ignoreSslErrors(ignoreSslErrors) , m_authUser(authUser) , m_authPass(authPass) , m_idCounter(0) { if (!cookieFile.isEmpty()) { setCookieJar(new CookieJar(cookieFile)); } if (diskCacheEnabled) { m_networkDiskCache = new QNetworkDiskCache(); m_networkDiskCache->setCacheDirectory(QDesktopServices::storageLocation(QDesktopServices::CacheLocation)); setCache(m_networkDiskCache); } connect(this, SIGNAL(authenticationRequired(QNetworkReply*,QAuthenticator*)), SLOT(provideAuthenication(QNetworkReply*,QAuthenticator*))); connect(this, SIGNAL(finished(QNetworkReply*)), SLOT(handleFinished(QNetworkReply*))); } NetworkAccessManager::~NetworkAccessManager() { if (m_networkDiskCache) delete m_networkDiskCache; } // protected: QNetworkReply *NetworkAccessManager::createRequest(Operation op, const QNetworkRequest & req, QIODevice * outgoingData) { // Pass duty to the superclass - Nothing special to do here (yet?) QNetworkReply *reply = QNetworkAccessManager::createRequest(op, req, outgoingData); if(m_ignoreSslErrors) { reply->ignoreSslErrors(); } QVariantList headers; foreach (QByteArray headerName, req.rawHeaderList()) { QVariantMap header; header["name"] = QString::fromUtf8(headerName); header["value"] = QString::fromUtf8(req.rawHeader(headerName)); headers += header; } m_idCounter++; m_ids[reply] = m_idCounter; QVariantMap data; data["id"] = m_idCounter; data["url"] = req.url().toString(); data["method"] = toString(op); data["headers"] = headers; data["time"] = QDateTime::currentDateTime(); connect(reply, SIGNAL(readyRead()), this, SLOT(handleStarted())); emit resourceRequested(data); return new NetworkReplyProxy(this, reply); } void NetworkAccessManager::handleStarted() { QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender()); if (!reply) return; if (m_started.contains(reply)) return; m_started += reply; QVariantList headers; foreach (QByteArray headerName, reply->rawHeaderList()) { QVariantMap header; header["name"] = QString::fromUtf8(headerName); header["value"] = QString::fromUtf8(reply->rawHeader(headerName)); headers += header; } QVariantMap data; data["stage"] = "start"; data["id"] = m_ids.value(reply); data["url"] = reply->url().toString(); data["status"] = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute); data["statusText"] = reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute); data["contentType"] = reply->header(QNetworkRequest::ContentTypeHeader); data["bodySize"] = reply->size(); data["redirectURL"] = reply->header(QNetworkRequest::LocationHeader); data["headers"] = headers; data["time"] = QDateTime::currentDateTime(); emit resourceReceived(data); } void NetworkAccessManager::handleFinished(QNetworkReply *reply) { QVariantList headers; foreach (QByteArray headerName, reply->rawHeaderList()) { QVariantMap header; header["name"] = QString::fromUtf8(headerName); header["value"] = QString::fromUtf8(reply->rawHeader(headerName)); headers += header; } QVariantMap data; data["stage"] = "end"; data["id"] = m_ids.value(reply); data["url"] = reply->url().toString(); data["status"] = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute); data["statusText"] = reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute); data["contentType"] = reply->header(QNetworkRequest::ContentTypeHeader); data["redirectURL"] = reply->header(QNetworkRequest::LocationHeader); data["headers"] = headers; data["time"] = QDateTime::currentDateTime(); NetworkReplyProxy *nrp = qobject_cast<NetworkReplyProxy*>(reply); data["text"] = nrp->body(); m_ids.remove(reply); m_started.remove(reply); emit resourceReceived(data); } void NetworkAccessManager::provideAuthenication(QNetworkReply *reply, QAuthenticator *ator) { ator->setUser(m_authUser); ator->setPassword(m_authPass); } <commit_msg>Removing unnecessary Terminal include<commit_after>/* This file is part of the PhantomJS project from Ofi Labs. Copyright (C) 2011 Ariya Hidayat <[email protected]> Copyright (C) 2011 Ivan De Marino <[email protected]> Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the <organization> 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 <COPYRIGHT HOLDER> 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 <QDateTime> #include <QList> #include <QDesktopServices> #include <QNetworkRequest> #include <QNetworkReply> #include <QNetworkDiskCache> #include <QAuthenticator> #include "networkaccessmanager.h" #include "networkreplyproxy.h" #include "cookiejar.h" static const char *toString(QNetworkAccessManager::Operation op) { const char *str = 0; switch (op) { case QNetworkAccessManager::HeadOperation: str = "HEAD"; break; case QNetworkAccessManager::GetOperation: str = "GET"; break; case QNetworkAccessManager::PutOperation: str = "PUT"; break; case QNetworkAccessManager::PostOperation: str = "POST"; break; case QNetworkAccessManager::DeleteOperation: str = "DELETE"; break; default: str = "?"; break; } return str; } // public: NetworkAccessManager::NetworkAccessManager(QObject *parent, bool diskCacheEnabled, QString cookieFile, bool ignoreSslErrors, QString authUser, QString authPass) : QNetworkAccessManager(parent) , m_networkDiskCache(0) , m_ignoreSslErrors(ignoreSslErrors) , m_authUser(authUser) , m_authPass(authPass) , m_idCounter(0) { if (!cookieFile.isEmpty()) { setCookieJar(new CookieJar(cookieFile)); } if (diskCacheEnabled) { m_networkDiskCache = new QNetworkDiskCache(); m_networkDiskCache->setCacheDirectory(QDesktopServices::storageLocation(QDesktopServices::CacheLocation)); setCache(m_networkDiskCache); } connect(this, SIGNAL(authenticationRequired(QNetworkReply*,QAuthenticator*)), SLOT(provideAuthenication(QNetworkReply*,QAuthenticator*))); connect(this, SIGNAL(finished(QNetworkReply*)), SLOT(handleFinished(QNetworkReply*))); } NetworkAccessManager::~NetworkAccessManager() { if (m_networkDiskCache) delete m_networkDiskCache; } // protected: QNetworkReply *NetworkAccessManager::createRequest(Operation op, const QNetworkRequest & req, QIODevice * outgoingData) { // Pass duty to the superclass - Nothing special to do here (yet?) QNetworkReply *reply = QNetworkAccessManager::createRequest(op, req, outgoingData); if(m_ignoreSslErrors) { reply->ignoreSslErrors(); } QVariantList headers; foreach (QByteArray headerName, req.rawHeaderList()) { QVariantMap header; header["name"] = QString::fromUtf8(headerName); header["value"] = QString::fromUtf8(req.rawHeader(headerName)); headers += header; } m_idCounter++; m_ids[reply] = m_idCounter; QVariantMap data; data["id"] = m_idCounter; data["url"] = req.url().toString(); data["method"] = toString(op); data["headers"] = headers; data["time"] = QDateTime::currentDateTime(); connect(reply, SIGNAL(readyRead()), this, SLOT(handleStarted())); emit resourceRequested(data); return new NetworkReplyProxy(this, reply); } void NetworkAccessManager::handleStarted() { QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender()); if (!reply) return; if (m_started.contains(reply)) return; m_started += reply; QVariantList headers; foreach (QByteArray headerName, reply->rawHeaderList()) { QVariantMap header; header["name"] = QString::fromUtf8(headerName); header["value"] = QString::fromUtf8(reply->rawHeader(headerName)); headers += header; } QVariantMap data; data["stage"] = "start"; data["id"] = m_ids.value(reply); data["url"] = reply->url().toString(); data["status"] = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute); data["statusText"] = reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute); data["contentType"] = reply->header(QNetworkRequest::ContentTypeHeader); data["bodySize"] = reply->size(); data["redirectURL"] = reply->header(QNetworkRequest::LocationHeader); data["headers"] = headers; data["time"] = QDateTime::currentDateTime(); emit resourceReceived(data); } void NetworkAccessManager::handleFinished(QNetworkReply *reply) { QVariantList headers; foreach (QByteArray headerName, reply->rawHeaderList()) { QVariantMap header; header["name"] = QString::fromUtf8(headerName); header["value"] = QString::fromUtf8(reply->rawHeader(headerName)); headers += header; } QVariantMap data; data["stage"] = "end"; data["id"] = m_ids.value(reply); data["url"] = reply->url().toString(); data["status"] = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute); data["statusText"] = reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute); data["contentType"] = reply->header(QNetworkRequest::ContentTypeHeader); data["redirectURL"] = reply->header(QNetworkRequest::LocationHeader); data["headers"] = headers; data["time"] = QDateTime::currentDateTime(); NetworkReplyProxy *nrp = qobject_cast<NetworkReplyProxy*>(reply); data["text"] = nrp->body(); m_ids.remove(reply); m_started.remove(reply); emit resourceReceived(data); } void NetworkAccessManager::provideAuthenication(QNetworkReply *reply, QAuthenticator *ator) { ator->setUser(m_authUser); ator->setPassword(m_authPass); } <|endoftext|>
<commit_before>/************************************************************************** * * Copyright 2011 Jose Fonseca * All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * **************************************************************************/ #include <assert.h> #include <iostream> #include "glproc.hpp" #include "glws.hpp" namespace glws { bool checkExtension(const char *extName, const char *extString) { assert(extName); if (!extString) { return false; } const char *p = extString; const char *q = extName; char c; do { c = *p++; if (c == '\0' || c == ' ') { if (q && *q == '\0') { return true; } else { q = extName; } } else { if (q && *q == c) { ++q; } else { q = 0; } } } while (c); return false; } void Drawable::copySubBuffer(int x, int y, int width, int height) { std::cerr << "warning: copySubBuffer not yet implemented\n"; } void Context::initialize(void) { assert(!initialized); extensions.getCurrentContextExtensions(profile); /* Ensure we got a matching profile. * * In particular on MacOSX, there is no way to specify specific versions, so this is all we can do. * * Also, see if OpenGL ES can be handled through ARB_ES*_compatibility. */ glprofile::Profile expectedProfile = profile; glprofile::Profile currentProfile = glprofile::getCurrentContextProfile(); if (!currentProfile.matches(expectedProfile)) { if (expectedProfile.api == glprofile::API_GLES && currentProfile.api == glprofile::API_GL && ((expectedProfile.major == 2 && extensions.has("GL_ARB_ES2_compatibility")) || (expectedProfile.major == 3 && extensions.has("GL_ARB_ES3_compatibility")))) { std::cerr << "warning: context mismatch:" << " expected " << expectedProfile << "," << " but got " << currentProfile << " with GL_ARB_ES" << expectedProfile.major << "_compatibility\n"; } else { std::cerr << "error: context mismatch: expected " << expectedProfile << ", but got " << currentProfile << "\n"; exit(1); } } initialized = true; } } /* namespace glws */ <commit_msg>glws: Add missing stdlib.h include.<commit_after>/************************************************************************** * * Copyright 2011 Jose Fonseca * All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * **************************************************************************/ #include <assert.h> #include <stdlib.h> #include <iostream> #include "glproc.hpp" #include "glws.hpp" namespace glws { bool checkExtension(const char *extName, const char *extString) { assert(extName); if (!extString) { return false; } const char *p = extString; const char *q = extName; char c; do { c = *p++; if (c == '\0' || c == ' ') { if (q && *q == '\0') { return true; } else { q = extName; } } else { if (q && *q == c) { ++q; } else { q = 0; } } } while (c); return false; } void Drawable::copySubBuffer(int x, int y, int width, int height) { std::cerr << "warning: copySubBuffer not yet implemented\n"; } void Context::initialize(void) { assert(!initialized); extensions.getCurrentContextExtensions(profile); /* Ensure we got a matching profile. * * In particular on MacOSX, there is no way to specify specific versions, so this is all we can do. * * Also, see if OpenGL ES can be handled through ARB_ES*_compatibility. */ glprofile::Profile expectedProfile = profile; glprofile::Profile currentProfile = glprofile::getCurrentContextProfile(); if (!currentProfile.matches(expectedProfile)) { if (expectedProfile.api == glprofile::API_GLES && currentProfile.api == glprofile::API_GL && ((expectedProfile.major == 2 && extensions.has("GL_ARB_ES2_compatibility")) || (expectedProfile.major == 3 && extensions.has("GL_ARB_ES3_compatibility")))) { std::cerr << "warning: context mismatch:" << " expected " << expectedProfile << "," << " but got " << currentProfile << " with GL_ARB_ES" << expectedProfile.major << "_compatibility\n"; } else { std::cerr << "error: context mismatch: expected " << expectedProfile << ", but got " << currentProfile << "\n"; exit(1); } } initialized = true; } } /* namespace glws */ <|endoftext|>
<commit_before>#include "opencv2/opencv.hpp" #include <iostream> using namespace cv; using namespace std; // From wikipedia: // // def RL_deconvolution(observed, psf, iterations): // # initial estimate is arbitrary - uniform 50% grey works fine // latent_est = 0.5*np.ones(observed.shape) // # create an inverse psf // psf_hat = psf[::-1,::-1] // # iterate towards ML estimate for the latent image // for i in np.arange(iterations): // est_conv = cv2.filter2D(latent_est,-1,psf) // relative_blur = observed/est_conv; // error_est = cv2.filter2D(relative_blur,-1,psf_hat) // latent_est = latent_est * error_est // return latent_est Mat RL_deconvolution(Mat observed, Mat psf, int iterations) { // Uniform grey starting estimation Mat latent_est = Mat(observed.size(), CV_64FC1, 0.5); // Flip the point spread function (NOT the inverse) Mat psf_hat = Mat(psf.size(), CV_64FC1); int psf_row_max = psf.rows - 1; int psf_col_max = psf.cols - 1; for (int row = 0; row <= psf_row_max; row++) { for (int col = 0; col <= psf_col_max; col++) { psf_hat.at<double>(psf_row_max - row, psf_col_max - col) = psf.at<double>(row, col); } } Mat est_conv; Mat relative_blur; Mat error_est; // Iterate for (int i=0; i<iterations; i++) { filter2D(latent_est, est_conv, -1, psf); // Element-wise division relative_blur = observed.mul(1.0/est_conv); filter2D(relative_blur, error_est, -1, psf_hat); // Element-wise multiplication latent_est = latent_est.mul(error_est); } return latent_est; } int main( int argc, const char** argv ) { if (argc != 3) { cout << "Usage: " << argv[0] << " image iterations" << "\n"; return -1; } int iterations = atoi(argv[2]); // Read the original image Mat original_image; original_image = imread(argv[1], CV_LOAD_IMAGE_UNCHANGED); // This is a hack, assumes too much int divisor; switch (original_image.elemSize()) { case 1: divisor = 255; break; case 2: divisor = 65535; break; default: return -2; } // From here on, use 64-bit floats // Convert original_image to float Mat float_image; original_image.convertTo(float_image, CV_64FC1); float_image *= 1.0/divisor; namedWindow("Float", CV_WINDOW_AUTOSIZE); imshow("Float", float_image); // Calculate a gaussian blur psf. double sigma_row = 9.0; double sigma_col = 5.0; int psf_size = 5; double mean_row = 0.0; double mean_col = psf_size/2.0; double sum = 0.0; double temp; Mat psf = Mat(Size(psf_size, psf_size), CV_64FC1, 0.0); for (int j = 0; j<psf.rows; j++) { for (int k = 0; k<psf.cols; k++) { temp = exp( -0.5 * ( pow((j - mean_row) / sigma_row, 2.0) + pow((k - mean_col) / sigma_col, 2.0))) / (2* M_PI * sigma_row * sigma_col); sum += temp; psf.at<double>(j,k) = temp; } } // Normalise the psf. for (int row = 0; row<psf.rows; row++) { // cout << row << " "; for (int col = 0; col<psf.cols; col++) { psf.at<double>(row, col) /= sum; // cout << psf.at<double>(row, col) << " "; } // cout << "\n"; } // Blur the float_image with the psf. Mat blurred_float; blurred_float = float_image.clone(); filter2D(float_image, blurred_float, -1, psf); namedWindow("BlurredFloat", CV_WINDOW_AUTOSIZE); imshow("BlurredFloat", blurred_float); Mat estimation = RL_deconvolution(blurred_float, psf, iterations); namedWindow("Estimation", CV_WINDOW_AUTOSIZE); imshow("Estimation", estimation); waitKey(0); //wait infinite time for a keypress destroyWindow("Float"); destroyWindow("BlurredFloat"); destroyWindow("Estimation"); return 0; }<commit_msg>Handle multi-channel images<commit_after>#include "opencv2/opencv.hpp" #include <iostream> using namespace cv; using namespace std; // From wikipedia: // // def RL_deconvolution(observed, psf, iterations): // # initial estimate is arbitrary - uniform 50% grey works fine // latent_est = 0.5*np.ones(observed.shape) // # create an inverse psf // psf_hat = psf[::-1,::-1] // # iterate towards ML estimate for the latent image // for i in np.arange(iterations): // est_conv = cv2.filter2D(latent_est,-1,psf) // relative_blur = observed/est_conv; // error_est = cv2.filter2D(relative_blur,-1,psf_hat) // latent_est = latent_est * error_est // return latent_est static int image_type; Mat RL_deconvolution(Mat observed, Mat psf, int iterations) { Scalar grey; // Uniform grey starting estimation switch (image_type) { case CV_64FC1: grey = Scalar(0.5); case CV_64FC3: grey = Scalar(0.5, 0.5, 0.5); } Mat latent_est = Mat(observed.size(), image_type, grey); // Flip the point spread function (NOT the inverse) Mat psf_hat = Mat(psf.size(), CV_64FC1); int psf_row_max = psf.rows - 1; int psf_col_max = psf.cols - 1; for (int row = 0; row <= psf_row_max; row++) { for (int col = 0; col <= psf_col_max; col++) { psf_hat.at<double>(psf_row_max - row, psf_col_max - col) = psf.at<double>(row, col); } } Mat est_conv; Mat relative_blur; Mat error_est; // Iterate for (int i=0; i<iterations; i++) { filter2D(latent_est, est_conv, -1, psf); // Element-wise division relative_blur = observed.mul(1.0/est_conv); filter2D(relative_blur, error_est, -1, psf_hat); // Element-wise multiplication latent_est = latent_est.mul(error_est); } return latent_est; } int main( int argc, const char** argv ) { if (argc != 3) { cout << "Usage: " << argv[0] << " image iterations" << "\n"; return -1; } int iterations = atoi(argv[2]); // Read the original image Mat original_image; original_image = imread(argv[1], CV_LOAD_IMAGE_UNCHANGED); int num_channels = original_image.channels(); switch (num_channels) { case 1: image_type = CV_64FC1; break; case 3: image_type = CV_64FC3; break; default: return -2; } // This is a hack, assumes too much int divisor; switch (original_image.elemSize() / num_channels) { case 1: divisor = 255; break; case 2: divisor = 65535; break; default: return -3; } // From here on, use 64-bit floats // Convert original_image to float Mat float_image; original_image.convertTo(float_image, image_type); float_image *= 1.0/divisor; namedWindow("Float", CV_WINDOW_AUTOSIZE); imshow("Float", float_image); // Calculate a gaussian blur psf. double sigma_row = 9.0; double sigma_col = 5.0; int psf_size = 5; double mean_row = 0.0; double mean_col = psf_size/2.0; double sum = 0.0; double temp; Mat psf = Mat(Size(psf_size, psf_size), CV_64FC1, 0.0); for (int j = 0; j<psf.rows; j++) { for (int k = 0; k<psf.cols; k++) { temp = exp( -0.5 * ( pow((j - mean_row) / sigma_row, 2.0) + pow((k - mean_col) / sigma_col, 2.0))) / (2* M_PI * sigma_row * sigma_col); sum += temp; psf.at<double>(j,k) = temp; } } // Normalise the psf. for (int row = 0; row<psf.rows; row++) { // cout << row << " "; for (int col = 0; col<psf.cols; col++) { psf.at<double>(row, col) /= sum; // cout << psf.at<double>(row, col) << " "; } // cout << "\n"; } // Blur the float_image with the psf. Mat blurred_float; blurred_float = float_image.clone(); filter2D(float_image, blurred_float, -1, psf); namedWindow("BlurredFloat", CV_WINDOW_AUTOSIZE); imshow("BlurredFloat", blurred_float); Mat estimation = RL_deconvolution(blurred_float, psf, iterations); namedWindow("Estimation", CV_WINDOW_AUTOSIZE); imshow("Estimation", estimation); waitKey(0); //wait infinite time for a keypress destroyWindow("Float"); destroyWindow("BlurredFloat"); destroyWindow("Estimation"); return 0; }<|endoftext|>
<commit_before>#include "rltk.hpp" #include <SFML/Graphics.hpp> namespace rltk { void run(std::function<void(double)> on_tick, const int window_width, const int window_height, const std::string window_title) { sf::RenderWindow window(sf::VideoMode(window_width, window_height, sf::Style::Titlebar | sf::Style::Resize | sf::Style::Close), window_title); double duration_ms = 0.0; while (window.isOpen()) { clock_t start_time = clock(); sf::Event event; while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) window.close(); } window.clear(); on_tick(duration_ms); window.display(); duration_ms = ((clock() - start_time) * 1000.0) / CLOCKS_PER_SEC; } } } <commit_msg>Window moved to a unique_ptr<commit_after>#include "rltk.hpp" #include <SFML/Graphics.hpp> #include <memory> namespace rltk { std::unique_ptr<sf::RenderWindow> main_window; void run(std::function<void(double)> on_tick, const int window_width, const int window_height, const std::string window_title) { std::make_unique<sf::RenderWindow>(sf::VideoMode(window_width, window_height, sf::Style::Titlebar | sf::Style::Resize | sf::Style::Close), window_title); main_window->setVerticalSyncEnabled(true); double duration_ms = 0.0; while (main_window->isOpen()) { clock_t start_time = clock(); sf::Event event; while (main_window->pollEvent(event)) { if (event.type == sf::Event::Closed) { main_window->close(); } } main_window->clear(); sf::Vector2u size_pixels = main_window->getSize(); on_tick(duration_ms); main_window->display(); duration_ms = ((clock() - start_time) * 1000.0) / CLOCKS_PER_SEC; } } } <|endoftext|>
<commit_before>//===----------------------------------------------------------------------===// // // Peloton // // aggregate_plan.cpp // // Identification: src/planner/aggregate_plan.cpp // // Copyright (c) 2015-17, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include "planner/aggregate_plan.h" namespace peloton { namespace planner { void AggregatePlan::PerformBinding(BindingContext &binding_context) { BindingContext input_context; const auto &children = GetChildren(); PL_ASSERT(children.size() == 1); children[0]->PerformBinding(input_context); // First get bindings for the grouping keys for (oid_t gb_col_id : GetGroupbyColIds()) { auto *ai = input_context.Find(gb_col_id); LOG_DEBUG("Grouping col %u binds to AI %p", gb_col_id, ai); PL_ASSERT(ai != nullptr); groupby_ais_.push_back(ai); } const auto &aggregates = GetUniqueAggTerms(); // Now let the aggregate expressions do their bindings for (oid_t i = 0; i < aggregates.size(); i++) { auto &term = const_cast<planner::AggregatePlan::AggTerm &>(aggregates[i]); auto *term_exp = const_cast<expression::AbstractExpression *>(aggregates[i].expression); if (term_exp != nullptr) { term_exp->PerformBinding(input_context); term.agg_ai.nullable = term_exp->IsNullable(); } } // Handle the projection by creating to binding contexts, the first being // input context we receive, and the next being all the aggregates this // plan produces. BindingContext agg_ctx; for (oid_t i = 0; i < aggregates.size(); i++) { const auto &agg_ai = aggregates[i].agg_ai; LOG_DEBUG("Binding aggregate at position %u to AI %p", i, &agg_ai); agg_ctx.BindNew(i, &agg_ai); } // Do projection (if one exists) if (GetProjectInfo() != nullptr) { std::vector<BindingContext *> inputs = {&input_context, &agg_ctx}; GetProjectInfo()->PerformRebinding(binding_context, inputs); } // Let the predicate do its binding (if one exists) const auto *predicate = GetPredicate(); if (predicate != nullptr) { const_cast<expression::AbstractExpression *>(predicate) ->PerformBinding(binding_context); } } } // namespace planner } // namespace peloton<commit_msg>Fixes for valgrind<commit_after>//===----------------------------------------------------------------------===// // // Peloton // // aggregate_plan.cpp // // Identification: src/planner/aggregate_plan.cpp // // Copyright (c) 2015-17, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include "planner/aggregate_plan.h" namespace peloton { namespace planner { void AggregatePlan::PerformBinding(BindingContext &binding_context) { BindingContext input_context; const auto &children = GetChildren(); PL_ASSERT(children.size() == 1); children[0]->PerformBinding(input_context); // First get bindings for the grouping keys for (oid_t gb_col_id : GetGroupbyColIds()) { auto *ai = input_context.Find(gb_col_id); LOG_DEBUG("Grouping col %u binds to AI %p", gb_col_id, ai); PL_ASSERT(ai != nullptr); groupby_ais_.push_back(ai); } const auto &aggregates = GetUniqueAggTerms(); // Now let the aggregate expressions do their bindings for (oid_t i = 0; i < aggregates.size(); i++) { auto &term = const_cast<planner::AggregatePlan::AggTerm &>(aggregates[i]); auto *term_exp = const_cast<expression::AbstractExpression *>(aggregates[i].expression); if (term_exp != nullptr) { term_exp->PerformBinding(input_context); term.agg_ai.nullable = term_exp->IsNullable(); term.agg_ai.type = term_exp->GetValueType(); } else { term.agg_ai.type = type::Type::TypeId::BIGINT; } } // Handle the projection by creating to binding contexts, the first being // input context we receive, and the next being all the aggregates this // plan produces. BindingContext agg_ctx; for (oid_t i = 0; i < aggregates.size(); i++) { const auto &agg_ai = aggregates[i].agg_ai; LOG_DEBUG("Binding aggregate at position %u to AI %p", i, &agg_ai); agg_ctx.BindNew(i, &agg_ai); } // Do projection (if one exists) if (GetProjectInfo() != nullptr) { std::vector<BindingContext *> inputs = {&input_context, &agg_ctx}; GetProjectInfo()->PerformRebinding(binding_context, inputs); } // Let the predicate do its binding (if one exists) const auto *predicate = GetPredicate(); if (predicate != nullptr) { const_cast<expression::AbstractExpression *>(predicate) ->PerformBinding(binding_context); } } } // namespace planner } // namespace peloton<|endoftext|>
<commit_before>/* kopetecommand.cpp - Command Copyright (c) 2003 by Jason Keirstead <[email protected]> Copyright (c) 2005 by Michel Hermier <[email protected]> Kopete (c) 2002-2005 by the Kopete developers <[email protected]> ************************************************************************* * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Lesser General Public * * License as published by the Free Software Foundation; either * * version 2 of the License, or (at your option) any later version. * * * ************************************************************************* */ #include "kopetecommand.h" #include "kopetechatsessionmanager.h" #include "kopeteview.h" #include "kopeteuiglobal.h" #include <kauthorized.h> #include <kdebug.h> #include <kinputdialog.h> #include <klocale.h> #include <kmessagebox.h> #include <qstringlist.h> class Kopete::Command::Private { public: QString command; QString help; QString formatString; uint minArgs; int maxArgs; bool processing; Kopete::Command::Types types; }; Kopete::Command::Command( QObject *parent, const QString &command, const char* handlerSlot, const QString &help, Kopete::CommandHandler::CommandType type, const QString &formatString, uint minArgs, int maxArgs, const KShortcut &cut, const QString &pix ) : KAction( command[0].toUpper() + command.right( command.length() - 1).toLower(), pix, cut, this, SLOT(slotAction()) ,0l, (command.toLower() + QString::fromLatin1("_command")).toLatin1()) , d(new Private) { connect(parent,SIGNAL(destroyed()),this,SLOT(deleteLater())); init( command, handlerSlot, help, type, formatString, minArgs, maxArgs ); } Kopete::Command::~Command() { delete d; } void Kopete::Command::init( const QString &command, const char* slot, const QString &help, Kopete::CommandHandler::CommandType type, const QString &formatString, uint minArgs, int maxArgs ) { m_command = command; m_help = help; m_type = type; m_formatString = formatString; m_minArgs = minArgs; m_maxArgs = maxArgs; m_processing = false; if(m_type == Kopete::CommandHandler::Normal ) { QObject::connect(this, SIGNAL( handleCommand(const QString &, Kopete::ChatSession *)), parent(), slot ); } } void Kopete::Command::slotAction() { Kopete::ChatSession *manager = Kopete::ChatSessionManager::self()->activeView()->msgManager(); QString args; if( m_minArgs > 0 ) { args = KInputDialog::getText( i18n("Enter Arguments"), i18n("Enter the arguments to %1:").arg(m_command) ); if( args.isNull() ) return; } processCommand( args, manager, true ); } void Kopete::Command::processCommand( const QString &args, Kopete::ChatSession *manager, bool gui ) { QStringList mArgs = Kopete::CommandHandler::parseArguments( args ); if( m_processing ) { printError( i18n("Alias \"%1\" expands to itself.").arg( text() ), manager, gui ); } else if( mArgs.count() < m_minArgs ) { printError( i18n("\"%1\" requires at least %n argument.", "\"%1\" requires at least %n arguments.", m_minArgs) .arg( text() ), manager, gui ); } else if( m_maxArgs > -1 && (int)mArgs.count() > m_maxArgs ) { printError( i18n("\"%1\" has a maximum of %n argument.", "\"%1\" has a maximum of %n arguments.", m_minArgs) .arg( text() ), manager, gui ); } else if( !KAuthorized::authorizeKAction( name() ) ) { printError( i18n("You are not authorized to perform the command \"%1\".").arg(text()), manager, gui ); } else { m_processing = true; if( m_type == Kopete::CommandHandler::UserAlias || m_type == Kopete::CommandHandler::SystemAlias ) { QString formatString = m_formatString; // Translate %s to the whole string and %n to current nickname formatString.replace( QString::fromLatin1("%n"), manager->myself()->nickName() ); formatString.replace( QString::fromLatin1("%s"), args ); // Translate %1..%N to word1..wordN while( mArgs.count() > 0 ) { formatString = formatString.arg( mArgs.front() ); mArgs.pop_front(); } kdDebug(14010) << "New Command after processing alias: " << formatString << endl; Kopete::CommandHandler::commandHandler()->processMessage( QString::fromLatin1("/") + formatString, manager ); } else { emit( handleCommand( args, manager ) ); } m_processing = false; } } void Kopete::Command::printError( const QString &error, Kopete::ChatSession *manager, bool gui ) const { if( gui ) { KMessageBox::error( Kopete::UI::Global::mainWidget(), error, i18n("Command Error") ); } else { Kopete::Message msg( manager->myself(), manager->members(), error, Kopete::Message::Internal, Kopete::Message::PlainText ); manager->appendMessage( msg ); } } #include "kopetecommand.moc" <commit_msg>Fix signal connections<commit_after>/* kopetecommand.cpp - Command Copyright (c) 2003 by Jason Keirstead <[email protected]> Copyright (c) 2005 by Michel Hermier <[email protected]> Kopete (c) 2002-2005 by the Kopete developers <[email protected]> ************************************************************************* * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Lesser General Public * * License as published by the Free Software Foundation; either * * version 2 of the License, or (at your option) any later version. * * * ************************************************************************* */ #include "kopetecommand.h" #include "kopetechatsessionmanager.h" #include "kopeteview.h" #include "kopeteuiglobal.h" #include <kauthorized.h> #include <kdebug.h> #include <kinputdialog.h> #include <klocale.h> #include <kmessagebox.h> #include <qstringlist.h> class Kopete::Command::Private { public: QString command; QString help; QString formatString; uint minArgs; int maxArgs; bool processing; Kopete::Command::Types types; QObject* parent; }; Kopete::Command::Command( QObject *parent, const QString &command, const char* handlerSlot, const QString &help, Kopete::CommandHandler::CommandType type, const QString &formatString, uint minArgs, int maxArgs, const KShortcut &cut, const QString &pix ) : KAction( command[0].toUpper() + command.right( command.length() - 1).toLower(), pix, cut, 0l,0l ,0l, (command.toLower() + QString::fromLatin1("_command")).toLatin1()) , d(new Private) { d->parent = parent; connect(this, SIGNAL(activated()),this, SLOT(slotAction())); connect(parent,SIGNAL(destroyed()),this,SLOT(deleteLater())); init( command, handlerSlot, help, type, formatString, minArgs, maxArgs ); } Kopete::Command::~Command() { delete d; } void Kopete::Command::init( const QString &command, const char* slot, const QString &help, Kopete::CommandHandler::CommandType type, const QString &formatString, uint minArgs, int maxArgs ) { m_command = command; m_help = help; m_type = type; m_formatString = formatString; m_minArgs = minArgs; m_maxArgs = maxArgs; m_processing = false; if(m_type == Kopete::CommandHandler::Normal ) { QObject::connect(this, SIGNAL( handleCommand(const QString &, Kopete::ChatSession *)), d->parent, slot ); } } void Kopete::Command::slotAction() { Kopete::ChatSession *manager = Kopete::ChatSessionManager::self()->activeView()->msgManager(); QString args; if( m_minArgs > 0 ) { args = KInputDialog::getText( i18n("Enter Arguments"), i18n("Enter the arguments to %1:").arg(m_command) ); if( args.isNull() ) return; } processCommand( args, manager, true ); } void Kopete::Command::processCommand( const QString &args, Kopete::ChatSession *manager, bool gui ) { QStringList mArgs = Kopete::CommandHandler::parseArguments( args ); if( m_processing ) { printError( i18n("Alias \"%1\" expands to itself.").arg( text() ), manager, gui ); } else if( mArgs.count() < m_minArgs ) { printError( i18n("\"%1\" requires at least %n argument.", "\"%1\" requires at least %n arguments.", m_minArgs) .arg( text() ), manager, gui ); } else if( m_maxArgs > -1 && (int)mArgs.count() > m_maxArgs ) { printError( i18n("\"%1\" has a maximum of %n argument.", "\"%1\" has a maximum of %n arguments.", m_minArgs) .arg( text() ), manager, gui ); } else if( !KAuthorized::authorizeKAction( name() ) ) { printError( i18n("You are not authorized to perform the command \"%1\".").arg(text()), manager, gui ); } else { m_processing = true; if( m_type == Kopete::CommandHandler::UserAlias || m_type == Kopete::CommandHandler::SystemAlias ) { QString formatString = m_formatString; // Translate %s to the whole string and %n to current nickname formatString.replace( QString::fromLatin1("%n"), manager->myself()->nickName() ); formatString.replace( QString::fromLatin1("%s"), args ); // Translate %1..%N to word1..wordN while( mArgs.count() > 0 ) { formatString = formatString.arg( mArgs.front() ); mArgs.pop_front(); } kdDebug(14010) << "New Command after processing alias: " << formatString << endl; Kopete::CommandHandler::commandHandler()->processMessage( QString::fromLatin1("/") + formatString, manager ); } else { emit( handleCommand( args, manager ) ); } m_processing = false; } } void Kopete::Command::printError( const QString &error, Kopete::ChatSession *manager, bool gui ) const { if( gui ) { KMessageBox::error( Kopete::UI::Global::mainWidget(), error, i18n("Command Error") ); } else { Kopete::Message msg( manager->myself(), manager->members(), error, Kopete::Message::Internal, Kopete::Message::PlainText ); manager->appendMessage( msg ); } } #include "kopetecommand.moc" <|endoftext|>
<commit_before>#include "memstorage.h" #include "utils.h" #include "compression.h" #include <limits> #include <algorithm> #include <map> using namespace memseries; using namespace memseries::compression; using namespace memseries::storage; using memseries::utils::Range; struct Chunk { uint8_t *_buffer; Range times; Range flags; Range values; CopmressedWriter c_writer; size_t count; Meas first; Time minTime,maxTime; Chunk(size_t size, Meas first_m): count(0), first(first_m) { minTime=std::numeric_limits<Time>::max(); maxTime=std::numeric_limits<Time>::min(); _buffer=new uint8_t[size*3+3]; times=Range{_buffer,_buffer+sizeof(uint8_t)*size}; flags=Range{times.end+1,times.end+sizeof(uint8_t)*size}; values=Range{flags.end+1,flags.end+sizeof(uint8_t)*size}; using compression::BinaryBuffer; c_writer = compression::CopmressedWriter( BinaryBuffer(times), BinaryBuffer(values), BinaryBuffer(flags)); c_writer.append(first); minTime=std::min(minTime,first_m.time); maxTime=std::max(maxTime,first_m.time); } ~Chunk(){ delete[] _buffer; } bool append(const Meas&m) { auto t_f = this->c_writer.append(m); if (!t_f) { return false; }else{ count++; minTime=std::min(minTime,m.time); maxTime=std::max(maxTime,m.time); return true; } } bool is_full()const { return c_writer.is_full(); } }; typedef std::shared_ptr<Chunk> Chunk_Ptr; typedef std::vector<Chunk_Ptr> ChuncksVector; //TODO replace to ChunksList; typedef std::map<Id, ChuncksVector> ChunkMap; class InnerReader: public Reader{ public: struct ReadChunk { size_t count; Chunk_Ptr chunk; ReadChunk()=default; ReadChunk(const ReadChunk&other){ count=other.count; chunk=other.chunk; } ReadChunk&operator=(const ReadChunk&other){ if(this!=&other){ count=other.count; chunk=other.chunk; } return *this; } }; InnerReader(memseries::Flag flag, memseries::Time from, memseries::Time to): _chunks{}, _flag(flag), _from(from), _to(to), _tp_readed(false) { is_time_point_reader = false; end=false; } void add(Chunk_Ptr c, size_t count){ ReadChunk rc; rc.chunk = c; rc.count = count; this->_chunks[c->first.id].push_back(rc); } void add_tp(Chunk_Ptr c, size_t count){ ReadChunk rc; rc.chunk = c; rc.count = count; this->_tp_chunks[c->first.id].push_back(rc); } bool isEnd() const override{ return this->end && this->_tp_readed; //TODO replace //return this->_chunks.size() == 0 && this->_tp_chunks.size() == 0; } void readNext(storage::ReaderClb*clb) override { if (!_tp_readed) { this->readTimePoint(clb); } for (auto ch : _chunks) { for (size_t i = 0; i < ch.second.size(); i++) { auto cur_ch=ch.second[i].chunk; CopmressedReader crr(BinaryBuffer(cur_ch->times), BinaryBuffer(cur_ch->values), BinaryBuffer(cur_ch->flags), cur_ch->first); if (check_meas(ch.second[i].chunk->first)) { auto sub=ch.second[i].chunk->first; clb->call(sub); } for (size_t j = 0; j < ch.second[i].count; j++) { auto sub = crr.read(); sub.id = ch.second[i].chunk->first.id; if (check_meas(sub)) { clb->call(sub); } } } } end=true; //TODO replace //_chunks.clear(); } void readTimePoint(storage::ReaderClb*clb){ std::list<InnerReader::ReadChunk> to_read_chunks{}; for (auto ch : _tp_chunks) { auto candidate = ch.second.front(); for (size_t i = 0; i < ch.second.size(); i++) { auto cur_chunk=ch.second[i].chunk; if (candidate.chunk->first.time < cur_chunk->first.time){ candidate = ch.second[i]; } } to_read_chunks.push_back(candidate); } for (auto ch : to_read_chunks) { CopmressedReader crr(BinaryBuffer(ch.chunk->times), BinaryBuffer(ch.chunk->values), BinaryBuffer(ch.chunk->flags), ch.chunk->first); Meas candidate; candidate = ch.chunk->first; for (size_t i = 0; i < ch.count; i++) { auto sub = crr.read(); sub.id = ch.chunk->first.id; if ((sub.time <= _from) && (sub.time >= candidate.time)) { candidate = sub; } } if (candidate.time <= _from) { clb->call(candidate); } } _tp_readed = true; //TODO replace // _tp_chunks.clear(); } bool is_time_point_reader; bool check_meas(const Meas&m)const{ using utils::inInterval; if ((in_filter(_flag, m.flag))&&(inInterval(_from, _to, m.time))) { return true; } return false; } typedef std::vector<ReadChunk> ReadChuncksVector; typedef std::map<Id, ReadChuncksVector> ReadChunkMap; ReadChunkMap _chunks; ReadChunkMap _tp_chunks; memseries::Flag _flag; memseries::Time _from; memseries::Time _to; bool _tp_readed; //TODO remove end var bool end; }; class MemoryStorage::Private { public: Private(size_t size): _size(size), _min_time(std::numeric_limits<memseries::Time>::max()), _max_time(std::numeric_limits<memseries::Time>::min()) {} ~Private(){ _chuncks.clear(); } Time minTime(){return _min_time;} Time maxTime(){return _max_time;} Chunk_Ptr getFreeChunk(memseries::Id id){ Chunk_Ptr resulted_chunk=nullptr; auto ch_iter=_chuncks.find(id); if (ch_iter != _chuncks.end()) { for (size_t i = 0; i < ch_iter->second.size(); i++) { if (!ch_iter->second[i]->is_full()) { resulted_chunk = ch_iter->second[i]; break; } } }else { this->_chuncks[id] = ChuncksVector{}; } return resulted_chunk; } append_result append(const Meas& value){ Chunk_Ptr chunk=this->getFreeChunk(value.id); bool need_sort = false; if (chunk == nullptr) { chunk = std::make_shared<Chunk>(_size, value); this->_chuncks[value.id].push_back(chunk); need_sort = true; } else { if (!chunk->append(value)) { chunk = std::make_shared<Chunk>(_size, value); this->_chuncks[value.id].push_back(chunk); need_sort = true; } } if (need_sort){ std::sort(this->_chuncks[value.id].begin(), this->_chuncks[value.id].end(), [](const Chunk_Ptr &l, const Chunk_Ptr &r) {return l->first.time < r->first.time; }); } _min_time = std::min(_min_time, value.time); _max_time = std::max(_max_time, value.time); return memseries::append_result(1, 0); } append_result append(const Meas::PMeas begin, const size_t size){ memseries::append_result result{}; for (size_t i = 0; i < size; i++) { result = result + append(begin[i]); } return result; } std::shared_ptr<InnerReader> readInterval(const IdArray &ids, Flag flag, Time from, Time to){ auto res= this->readInTimePoint(ids,flag,from); res->_from=from; res->_to=to; res->_flag=flag; for (auto ch : _chuncks) { if ((ids.size() != 0) && (std::find(ids.begin(), ids.end(), ch.first) == ids.end())) { continue; } for (size_t i = 0; i < ch.second.size(); i++) { Chunk_Ptr cur_chunk = ch.second[i]; if ((utils::inInterval(from,to,cur_chunk->minTime))|| (utils::inInterval(from,to,cur_chunk->maxTime))){ res->add(cur_chunk, cur_chunk->count); } } } res->is_time_point_reader=false; return res; } std::shared_ptr<InnerReader> readInTimePoint(const IdArray &ids, Flag flag, Time time_point){ auto res = std::make_shared<InnerReader>(flag, time_point, 0); for (auto ch : _chuncks) { if ((ids.size() != 0) && (std::find(ids.begin(), ids.end(), ch.first) == ids.end())) { continue; } for (size_t i = 0; i < ch.second.size(); i++) { Chunk_Ptr cur_chunk = ch.second[i]; if(cur_chunk->minTime<time_point){ res->add_tp(cur_chunk, cur_chunk->count); } } } res->is_time_point_reader = true; return res; } size_t size()const { return _size; } size_t chunks_size()const { return _chuncks.size(); } protected: size_t _size; ChunkMap _chuncks; Time _min_time,_max_time; }; MemoryStorage::MemoryStorage(size_t size) :_Impl(new MemoryStorage::Private(size)){ } MemoryStorage::~MemoryStorage(){ } Time MemoryStorage::minTime(){ return _Impl->minTime(); } Time MemoryStorage::maxTime(){ return _Impl->maxTime(); } append_result MemoryStorage::append(const memseries::Meas &value){ return _Impl->append(value); } append_result MemoryStorage::append(const memseries::Meas::PMeas begin, const size_t size){ return _Impl->append(begin,size); } Reader_ptr MemoryStorage::readInterval(const memseries::IdArray &ids, memseries::Flag flag, memseries::Time from, memseries::Time to){ return _Impl->readInterval(ids,flag,from,to); } Reader_ptr MemoryStorage::readInTimePoint(const memseries::IdArray &ids, memseries::Flag flag, memseries::Time time_point){ return _Impl->readInTimePoint(ids,flag,time_point); } size_t MemoryStorage::size()const { return _Impl->size(); } size_t MemoryStorage::chunks_size()const { return _Impl->chunks_size(); } <commit_msg>debug code.<commit_after>#include "memstorage.h" #include "utils.h" #include "compression.h" #include <limits> #include <algorithm> #include <map> using namespace memseries; using namespace memseries::compression; using namespace memseries::storage; using memseries::utils::Range; struct Chunk { uint8_t *_buffer; Range times; Range flags; Range values; CopmressedWriter c_writer; size_t count; Meas first; Time minTime,maxTime; Chunk(size_t size, Meas first_m): count(0), first(first_m) { minTime=std::numeric_limits<Time>::max(); maxTime=std::numeric_limits<Time>::min(); _buffer=new uint8_t[size*3+3]; times=Range{_buffer,_buffer+sizeof(uint8_t)*size}; flags=Range{times.end+1,times.end+sizeof(uint8_t)*size}; values=Range{flags.end+1,flags.end+sizeof(uint8_t)*size}; using compression::BinaryBuffer; c_writer = compression::CopmressedWriter( BinaryBuffer(times), BinaryBuffer(values), BinaryBuffer(flags)); c_writer.append(first); minTime=std::min(minTime,first_m.time); maxTime=std::max(maxTime,first_m.time); } ~Chunk(){ delete[] _buffer; } bool append(const Meas&m) { auto t_f = this->c_writer.append(m); if (!t_f) { return false; }else{ count++; minTime=std::min(minTime,m.time); maxTime=std::max(maxTime,m.time); return true; } } bool is_full()const { return c_writer.is_full(); } }; typedef std::shared_ptr<Chunk> Chunk_Ptr; typedef std::vector<Chunk_Ptr> ChuncksVector; //TODO replace to ChunksList; typedef std::map<Id, ChuncksVector> ChunkMap; class InnerReader: public Reader{ public: struct ReadChunk { size_t count; Chunk_Ptr chunk; ReadChunk()=default; ReadChunk(const ReadChunk&other){ count=other.count; chunk=other.chunk; } ReadChunk&operator=(const ReadChunk&other){ if(this!=&other){ count=other.count; chunk=other.chunk; } return *this; } }; InnerReader(memseries::Flag flag, memseries::Time from, memseries::Time to): _chunks{}, _flag(flag), _from(from), _to(to), _tp_readed(false) { is_time_point_reader = false; end=false; } void add(Chunk_Ptr c, size_t count){ ReadChunk rc; rc.chunk = c; rc.count = count; this->_chunks[c->first.id].push_back(rc); } void add_tp(Chunk_Ptr c, size_t count){ ReadChunk rc; rc.chunk = c; rc.count = count; this->_tp_chunks[c->first.id].push_back(rc); } bool isEnd() const override{ return this->end && this->_tp_readed; //TODO replace //return this->_chunks.size() == 0 && this->_tp_chunks.size() == 0; } void readNext(storage::ReaderClb*clb) override { if (!_tp_readed) { this->readTimePoint(clb); } for (auto ch : _chunks) { for (size_t i = 0; i < ch.second.size(); i++) { auto cur_ch=ch.second[i].chunk; CopmressedReader crr(BinaryBuffer(cur_ch->times), BinaryBuffer(cur_ch->values), BinaryBuffer(cur_ch->flags), cur_ch->first); if (check_meas(ch.second[i].chunk->first)) { auto sub=ch.second[i].chunk->first; clb->call(sub); } for (size_t j = 0; j < ch.second[i].count; j++) { auto sub = crr.read(); sub.id = ch.second[i].chunk->first.id; if (check_meas(sub)) { clb->call(sub); } } } } end=true; //TODO replace //_chunks.clear(); } void readTimePoint(storage::ReaderClb*clb){ std::list<InnerReader::ReadChunk> to_read_chunks{}; for (auto ch : _tp_chunks) { auto candidate = ch.second.front(); for (size_t i = 0; i < ch.second.size(); i++) { auto cur_chunk=ch.second[i].chunk; if (candidate.chunk->first.time < cur_chunk->first.time){ candidate = ch.second[i]; } } to_read_chunks.push_back(candidate); } for (auto ch : to_read_chunks) { CopmressedReader crr(BinaryBuffer(ch.chunk->times), BinaryBuffer(ch.chunk->values), BinaryBuffer(ch.chunk->flags), ch.chunk->first); Meas candidate; candidate = ch.chunk->first; for (size_t i = 0; i < ch.count; i++) { auto sub = crr.read(); sub.id = ch.chunk->first.id; if ((sub.time <= _from) && (sub.time >= candidate.time)) { candidate = sub; } } if (candidate.time <= _from) { clb->call(candidate); } } _tp_readed = true; //TODO replace // _tp_chunks.clear(); } bool is_time_point_reader; bool check_meas(const Meas&m)const{ using utils::inInterval; if ((in_filter(_flag, m.flag))&&(inInterval(_from, _to, m.time))) { return true; } return false; } typedef std::vector<ReadChunk> ReadChuncksVector; typedef std::map<Id, ReadChuncksVector> ReadChunkMap; ReadChunkMap _chunks; ReadChunkMap _tp_chunks; memseries::Flag _flag; memseries::Time _from; memseries::Time _to; bool _tp_readed; //TODO remove end var bool end; }; class MemoryStorage::Private { public: Private(size_t size): _size(size), _min_time(std::numeric_limits<memseries::Time>::max()), _max_time(std::numeric_limits<memseries::Time>::min()) {} ~Private(){ _chuncks.clear(); } Time minTime(){return _min_time;} Time maxTime(){return _max_time;} Chunk_Ptr getFreeChunk(memseries::Id id){ Chunk_Ptr resulted_chunk=nullptr; auto ch_iter=_chuncks.find(id); if (ch_iter != _chuncks.end()) { for (size_t i = 0; i < ch_iter->second.size(); i++) { if (!ch_iter->second[i]->is_full()) { resulted_chunk = ch_iter->second[i]; break; } } }else { this->_chuncks[id] = ChuncksVector{}; } return resulted_chunk; } append_result append(const Meas& value){ Chunk_Ptr chunk=this->getFreeChunk(value.id); bool need_sort = false; if (chunk == nullptr) { chunk = std::make_shared<Chunk>(_size, value); this->_chuncks[value.id].push_back(chunk); need_sort = true; } else { if (!chunk->append(value)) { chunk = std::make_shared<Chunk>(_size, value); this->_chuncks[value.id].push_back(chunk); need_sort = true; } } if (need_sort){ std::sort(this->_chuncks[value.id].begin(), this->_chuncks[value.id].end(), [](const Chunk_Ptr &l, const Chunk_Ptr &r) {return l->first.time < r->first.time; }); } CopmressedReader crr(BinaryBuffer(chunk->times), BinaryBuffer(chunk->values), BinaryBuffer(chunk->flags), chunk->first); for (size_t j = 0; j < chunk->count; j++) { auto sub = crr.read(); sub.id = chunk->first.id; } _min_time = std::min(_min_time, value.time); _max_time = std::max(_max_time, value.time); return memseries::append_result(1, 0); } append_result append(const Meas::PMeas begin, const size_t size){ memseries::append_result result{}; for (size_t i = 0; i < size; i++) { result = result + append(begin[i]); } return result; } std::shared_ptr<InnerReader> readInterval(const IdArray &ids, Flag flag, Time from, Time to){ auto res= this->readInTimePoint(ids,flag,from); res->_from=from; res->_to=to; res->_flag=flag; for (auto ch : _chuncks) { if ((ids.size() != 0) && (std::find(ids.begin(), ids.end(), ch.first) == ids.end())) { continue; } for (size_t i = 0; i < ch.second.size(); i++) { Chunk_Ptr cur_chunk = ch.second[i]; if ((utils::inInterval(from,to,cur_chunk->minTime))|| (utils::inInterval(from,to,cur_chunk->maxTime))){ res->add(cur_chunk, cur_chunk->count); } } } res->is_time_point_reader=false; return res; } std::shared_ptr<InnerReader> readInTimePoint(const IdArray &ids, Flag flag, Time time_point){ auto res = std::make_shared<InnerReader>(flag, time_point, 0); for (auto ch : _chuncks) { if ((ids.size() != 0) && (std::find(ids.begin(), ids.end(), ch.first) == ids.end())) { continue; } for (size_t i = 0; i < ch.second.size(); i++) { Chunk_Ptr cur_chunk = ch.second[i]; if(cur_chunk->minTime<time_point){ res->add_tp(cur_chunk, cur_chunk->count); } } } res->is_time_point_reader = true; return res; } size_t size()const { return _size; } size_t chunks_size()const { return _chuncks.size(); } protected: size_t _size; ChunkMap _chuncks; Time _min_time,_max_time; }; MemoryStorage::MemoryStorage(size_t size) :_Impl(new MemoryStorage::Private(size)){ } MemoryStorage::~MemoryStorage(){ } Time MemoryStorage::minTime(){ return _Impl->minTime(); } Time MemoryStorage::maxTime(){ return _Impl->maxTime(); } append_result MemoryStorage::append(const memseries::Meas &value){ return _Impl->append(value); } append_result MemoryStorage::append(const memseries::Meas::PMeas begin, const size_t size){ return _Impl->append(begin,size); } Reader_ptr MemoryStorage::readInterval(const memseries::IdArray &ids, memseries::Flag flag, memseries::Time from, memseries::Time to){ return _Impl->readInterval(ids,flag,from,to); } Reader_ptr MemoryStorage::readInTimePoint(const memseries::IdArray &ids, memseries::Flag flag, memseries::Time time_point){ return _Impl->readInTimePoint(ids,flag,time_point); } size_t MemoryStorage::size()const { return _Impl->size(); } size_t MemoryStorage::chunks_size()const { return _Impl->chunks_size(); } <|endoftext|>
<commit_before>// Ceres Solver - A fast non-linear least squares minimizer // Copyright 2010, 2011, 2012 Google Inc. All rights reserved. // http://code.google.com/p/ceres-solver/ // // 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 Google 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. // // Author: [email protected] (Sameer Agarwal) #define EIGEN_CACHEFRIENDLY_PRODUCT_THRESHOLD 10 #include "ceres/partitioned_matrix_view.h" #include <algorithm> #include <cstring> #include <vector> #include <glog/logging.h> #include "ceres/block_sparse_matrix.h" #include "ceres/block_structure.h" #include "ceres/internal/eigen.h" namespace ceres { namespace internal { PartitionedMatrixView::PartitionedMatrixView( const BlockSparseMatrixBase& matrix, int num_col_blocks_a) : matrix_(matrix), num_col_blocks_e_(num_col_blocks_a) { const CompressedRowBlockStructure* bs = matrix_.block_structure(); CHECK_NOTNULL(bs); num_col_blocks_f_ = bs->cols.size() - num_col_blocks_a; // Compute the number of row blocks in E. The number of row blocks // in E maybe less than the number of row blocks in the input matrix // as some of the row blocks at the bottom may not have any // e_blocks. For a definition of what an e_block is, please see // explicit_schur_complement_solver.h num_row_blocks_e_ = 0; for (int r = 0; r < bs->rows.size(); ++r) { const vector<Cell>& cells = bs->rows[r].cells; if (cells[0].block_id < num_col_blocks_a) { ++num_row_blocks_e_; } } // Compute the number of columns in E and F. num_cols_e_ = 0; num_cols_f_ = 0; for (int c = 0; c < bs->cols.size(); ++c) { const Block& block = bs->cols[c]; if (c < num_col_blocks_a) { num_cols_e_ += block.size; } else { num_cols_f_ += block.size; } } CHECK_EQ(num_cols_e_ + num_cols_f_, matrix_.num_cols()); } PartitionedMatrixView::~PartitionedMatrixView() { } // The next four methods don't seem to be particularly cache // friendly. This is an artifact of how the BlockStructure of the // input matrix is constructed. These methods will benefit from // multithreading as well as improved data layout. void PartitionedMatrixView::RightMultiplyE(const double* x, double* y) const { const CompressedRowBlockStructure* bs = matrix_.block_structure(); // Iterate over the first num_row_blocks_e_ row blocks, and multiply // by the first cell in each row block. for (int r = 0; r < num_row_blocks_e_; ++r) { const double* row_values = matrix_.RowBlockValues(r); const Cell& cell = bs->rows[r].cells[0]; const int row_block_pos = bs->rows[r].block.position; const int row_block_size = bs->rows[r].block.size; const int col_block_id = cell.block_id; const int col_block_pos = bs->cols[col_block_id].position; const int col_block_size = bs->cols[col_block_id].size; ConstVectorRef xref(x + col_block_pos, col_block_size); VectorRef yref(y + row_block_pos, row_block_size); ConstMatrixRef m(row_values + cell.position, row_block_size, col_block_size); yref += m.lazyProduct(xref); } } void PartitionedMatrixView::RightMultiplyF(const double* x, double* y) const { const CompressedRowBlockStructure* bs = matrix_.block_structure(); // Iterate over row blocks, and if the row block is in E, then // multiply by all the cells except the first one which is of type // E. If the row block is not in E (i.e its in the bottom // num_row_blocks - num_row_blocks_e row blocks), then all the cells // are of type F and multiply by them all. for (int r = 0; r < bs->rows.size(); ++r) { const int row_block_pos = bs->rows[r].block.position; const int row_block_size = bs->rows[r].block.size; VectorRef yref(y + row_block_pos, row_block_size); const vector<Cell>& cells = bs->rows[r].cells; for (int c = (r < num_row_blocks_e_) ? 1 : 0; c < cells.size(); ++c) { const double* row_values = matrix_.RowBlockValues(r); const int col_block_id = cells[c].block_id; const int col_block_pos = bs->cols[col_block_id].position; const int col_block_size = bs->cols[col_block_id].size; ConstVectorRef xref(x + col_block_pos - num_cols_e(), col_block_size); ConstMatrixRef m(row_values + cells[c].position, row_block_size, col_block_size); yref += m.lazyProduct(xref); } } } void PartitionedMatrixView::LeftMultiplyE(const double* x, double* y) const { const CompressedRowBlockStructure* bs = matrix_.block_structure(); // Iterate over the first num_row_blocks_e_ row blocks, and multiply // by the first cell in each row block. for (int r = 0; r < num_row_blocks_e_; ++r) { const Cell& cell = bs->rows[r].cells[0]; const double* row_values = matrix_.RowBlockValues(r); const int row_block_pos = bs->rows[r].block.position; const int row_block_size = bs->rows[r].block.size; const int col_block_id = cell.block_id; const int col_block_pos = bs->cols[col_block_id].position; const int col_block_size = bs->cols[col_block_id].size; ConstVectorRef xref(x + row_block_pos, row_block_size); VectorRef yref(y + col_block_pos, col_block_size); ConstMatrixRef m(row_values + cell.position, row_block_size, col_block_size); yref += m.transpose().lazyProduct(xref); } } void PartitionedMatrixView::LeftMultiplyF(const double* x, double* y) const { const CompressedRowBlockStructure* bs = matrix_.block_structure(); // Iterate over row blocks, and if the row block is in E, then // multiply by all the cells except the first one which is of type // E. If the row block is not in E (i.e its in the bottom // num_row_blocks - num_row_blocks_e row blocks), then all the cells // are of type F and multiply by them all. for (int r = 0; r < bs->rows.size(); ++r) { const int row_block_pos = bs->rows[r].block.position; const int row_block_size = bs->rows[r].block.size; ConstVectorRef xref(x + row_block_pos, row_block_size); const vector<Cell>& cells = bs->rows[r].cells; for (int c = (r < num_row_blocks_e_) ? 1 : 0; c < cells.size(); ++c) { const double* row_values = matrix_.RowBlockValues(r); const int col_block_id = cells[c].block_id; const int col_block_pos = bs->cols[col_block_id].position; const int col_block_size = bs->cols[col_block_id].size; VectorRef yref(y + col_block_pos - num_cols_e(), col_block_size); ConstMatrixRef m(row_values + cells[c].position, row_block_size, col_block_size); yref += m.transpose().lazyProduct(xref); } } } // Given a range of columns blocks of a matrix m, compute the block // structure of the block diagonal of the matrix m(:, // start_col_block:end_col_block)'m(:, start_col_block:end_col_block) // and return a BlockSparseMatrix with the this block structure. The // caller owns the result. BlockSparseMatrix* PartitionedMatrixView::CreateBlockDiagonalMatrixLayout( int start_col_block, int end_col_block) const { const CompressedRowBlockStructure* bs = matrix_.block_structure(); CompressedRowBlockStructure* block_diagonal_structure = new CompressedRowBlockStructure; int block_position = 0; int diagonal_cell_position = 0; // Iterate over the column blocks, creating a new diagonal block for // each column block. for (int c = start_col_block; c < end_col_block; ++c) { const Block& block = bs->cols[c]; block_diagonal_structure->cols.push_back(Block()); Block& diagonal_block = block_diagonal_structure->cols.back(); diagonal_block.size = block.size; diagonal_block.position = block_position; block_diagonal_structure->rows.push_back(CompressedRow()); CompressedRow& row = block_diagonal_structure->rows.back(); row.block = diagonal_block; row.cells.push_back(Cell()); Cell& cell = row.cells.back(); cell.block_id = c - start_col_block; cell.position = diagonal_cell_position; block_position += block.size; diagonal_cell_position += block.size * block.size; } // Build a BlockSparseMatrix with the just computed block // structure. return new BlockSparseMatrix(block_diagonal_structure); } BlockSparseMatrix* PartitionedMatrixView::CreateBlockDiagonalEtE() const { BlockSparseMatrix* block_diagonal = CreateBlockDiagonalMatrixLayout(0, num_col_blocks_e_); UpdateBlockDiagonalEtE(block_diagonal); return block_diagonal; } BlockSparseMatrix* PartitionedMatrixView::CreateBlockDiagonalFtF() const { BlockSparseMatrix* block_diagonal = CreateBlockDiagonalMatrixLayout( num_col_blocks_e_, num_col_blocks_e_ + num_col_blocks_f_); UpdateBlockDiagonalFtF(block_diagonal); return block_diagonal; } // Similar to the code in RightMultiplyE, except instead of the matrix // vector multiply its an outer product. // // block_diagonal = block_diagonal(E'E) void PartitionedMatrixView::UpdateBlockDiagonalEtE( BlockSparseMatrix* block_diagonal) const { const CompressedRowBlockStructure* bs = matrix_.block_structure(); const CompressedRowBlockStructure* block_diagonal_structure = block_diagonal->block_structure(); block_diagonal->SetZero(); for (int r = 0; r < num_row_blocks_e_ ; ++r) { const double* row_values = matrix_.RowBlockValues(r); const Cell& cell = bs->rows[r].cells[0]; const int row_block_size = bs->rows[r].block.size; const int block_id = cell.block_id; const int col_block_size = bs->cols[block_id].size; ConstMatrixRef m(row_values + cell.position, row_block_size, col_block_size); const int cell_position = block_diagonal_structure->rows[block_id].cells[0].position; MatrixRef(block_diagonal->mutable_values() + cell_position, col_block_size, col_block_size).noalias() += m.transpose() * m; } } // Similar to the code in RightMultiplyF, except instead of the matrix // vector multiply its an outer product. // // block_diagonal = block_diagonal(F'F) void PartitionedMatrixView::UpdateBlockDiagonalFtF( BlockSparseMatrix* block_diagonal) const { const CompressedRowBlockStructure* bs = matrix_.block_structure(); const CompressedRowBlockStructure* block_diagonal_structure = block_diagonal->block_structure(); block_diagonal->SetZero(); for (int r = 0; r < bs->rows.size(); ++r) { const int row_block_size = bs->rows[r].block.size; const vector<Cell>& cells = bs->rows[r].cells; const double* row_values = matrix_.RowBlockValues(r); for (int c = (r < num_row_blocks_e_) ? 1 : 0; c < cells.size(); ++c) { const int col_block_id = cells[c].block_id; const int col_block_size = bs->cols[col_block_id].size; ConstMatrixRef m(row_values + cells[c].position, row_block_size, col_block_size); const int diagonal_block_id = col_block_id - num_col_blocks_e_; const int cell_position = block_diagonal_structure->rows[diagonal_block_id].cells[0].position; MatrixRef(block_diagonal->mutable_values() + cell_position, col_block_size, col_block_size).noalias() += m.transpose() * m; } } } } // namespace internal } // namespace ceres <commit_msg>Comment formatting<commit_after>// Ceres Solver - A fast non-linear least squares minimizer // Copyright 2010, 2011, 2012 Google Inc. All rights reserved. // http://code.google.com/p/ceres-solver/ // // 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 Google 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. // // Author: [email protected] (Sameer Agarwal) #define EIGEN_CACHEFRIENDLY_PRODUCT_THRESHOLD 10 #include "ceres/partitioned_matrix_view.h" #include <algorithm> #include <cstring> #include <vector> #include <glog/logging.h> #include "ceres/block_sparse_matrix.h" #include "ceres/block_structure.h" #include "ceres/internal/eigen.h" namespace ceres { namespace internal { PartitionedMatrixView::PartitionedMatrixView( const BlockSparseMatrixBase& matrix, int num_col_blocks_a) : matrix_(matrix), num_col_blocks_e_(num_col_blocks_a) { const CompressedRowBlockStructure* bs = matrix_.block_structure(); CHECK_NOTNULL(bs); num_col_blocks_f_ = bs->cols.size() - num_col_blocks_a; // Compute the number of row blocks in E. The number of row blocks // in E maybe less than the number of row blocks in the input matrix // as some of the row blocks at the bottom may not have any // e_blocks. For a definition of what an e_block is, please see // explicit_schur_complement_solver.h num_row_blocks_e_ = 0; for (int r = 0; r < bs->rows.size(); ++r) { const vector<Cell>& cells = bs->rows[r].cells; if (cells[0].block_id < num_col_blocks_a) { ++num_row_blocks_e_; } } // Compute the number of columns in E and F. num_cols_e_ = 0; num_cols_f_ = 0; for (int c = 0; c < bs->cols.size(); ++c) { const Block& block = bs->cols[c]; if (c < num_col_blocks_a) { num_cols_e_ += block.size; } else { num_cols_f_ += block.size; } } CHECK_EQ(num_cols_e_ + num_cols_f_, matrix_.num_cols()); } PartitionedMatrixView::~PartitionedMatrixView() { } // The next four methods don't seem to be particularly cache // friendly. This is an artifact of how the BlockStructure of the // input matrix is constructed. These methods will benefit from // multithreading as well as improved data layout. void PartitionedMatrixView::RightMultiplyE(const double* x, double* y) const { const CompressedRowBlockStructure* bs = matrix_.block_structure(); // Iterate over the first num_row_blocks_e_ row blocks, and multiply // by the first cell in each row block. for (int r = 0; r < num_row_blocks_e_; ++r) { const double* row_values = matrix_.RowBlockValues(r); const Cell& cell = bs->rows[r].cells[0]; const int row_block_pos = bs->rows[r].block.position; const int row_block_size = bs->rows[r].block.size; const int col_block_id = cell.block_id; const int col_block_pos = bs->cols[col_block_id].position; const int col_block_size = bs->cols[col_block_id].size; ConstVectorRef xref(x + col_block_pos, col_block_size); VectorRef yref(y + row_block_pos, row_block_size); ConstMatrixRef m(row_values + cell.position, row_block_size, col_block_size); yref += m.lazyProduct(xref); } } void PartitionedMatrixView::RightMultiplyF(const double* x, double* y) const { const CompressedRowBlockStructure* bs = matrix_.block_structure(); // Iterate over row blocks, and if the row block is in E, then // multiply by all the cells except the first one which is of type // E. If the row block is not in E (i.e its in the bottom // num_row_blocks - num_row_blocks_e row blocks), then all the cells // are of type F and multiply by them all. for (int r = 0; r < bs->rows.size(); ++r) { const int row_block_pos = bs->rows[r].block.position; const int row_block_size = bs->rows[r].block.size; VectorRef yref(y + row_block_pos, row_block_size); const vector<Cell>& cells = bs->rows[r].cells; for (int c = (r < num_row_blocks_e_) ? 1 : 0; c < cells.size(); ++c) { const double* row_values = matrix_.RowBlockValues(r); const int col_block_id = cells[c].block_id; const int col_block_pos = bs->cols[col_block_id].position; const int col_block_size = bs->cols[col_block_id].size; ConstVectorRef xref(x + col_block_pos - num_cols_e(), col_block_size); ConstMatrixRef m(row_values + cells[c].position, row_block_size, col_block_size); yref += m.lazyProduct(xref); } } } void PartitionedMatrixView::LeftMultiplyE(const double* x, double* y) const { const CompressedRowBlockStructure* bs = matrix_.block_structure(); // Iterate over the first num_row_blocks_e_ row blocks, and multiply // by the first cell in each row block. for (int r = 0; r < num_row_blocks_e_; ++r) { const Cell& cell = bs->rows[r].cells[0]; const double* row_values = matrix_.RowBlockValues(r); const int row_block_pos = bs->rows[r].block.position; const int row_block_size = bs->rows[r].block.size; const int col_block_id = cell.block_id; const int col_block_pos = bs->cols[col_block_id].position; const int col_block_size = bs->cols[col_block_id].size; ConstVectorRef xref(x + row_block_pos, row_block_size); VectorRef yref(y + col_block_pos, col_block_size); ConstMatrixRef m(row_values + cell.position, row_block_size, col_block_size); yref += m.transpose().lazyProduct(xref); } } void PartitionedMatrixView::LeftMultiplyF(const double* x, double* y) const { const CompressedRowBlockStructure* bs = matrix_.block_structure(); // Iterate over row blocks, and if the row block is in E, then // multiply by all the cells except the first one which is of type // E. If the row block is not in E (i.e its in the bottom // num_row_blocks - num_row_blocks_e row blocks), then all the cells // are of type F and multiply by them all. for (int r = 0; r < bs->rows.size(); ++r) { const int row_block_pos = bs->rows[r].block.position; const int row_block_size = bs->rows[r].block.size; ConstVectorRef xref(x + row_block_pos, row_block_size); const vector<Cell>& cells = bs->rows[r].cells; for (int c = (r < num_row_blocks_e_) ? 1 : 0; c < cells.size(); ++c) { const double* row_values = matrix_.RowBlockValues(r); const int col_block_id = cells[c].block_id; const int col_block_pos = bs->cols[col_block_id].position; const int col_block_size = bs->cols[col_block_id].size; VectorRef yref(y + col_block_pos - num_cols_e(), col_block_size); ConstMatrixRef m(row_values + cells[c].position, row_block_size, col_block_size); yref += m.transpose().lazyProduct(xref); } } } // Given a range of columns blocks of a matrix m, compute the block // structure of the block diagonal of the matrix m(:, // start_col_block:end_col_block)'m(:, start_col_block:end_col_block) // and return a BlockSparseMatrix with the this block structure. The // caller owns the result. BlockSparseMatrix* PartitionedMatrixView::CreateBlockDiagonalMatrixLayout( int start_col_block, int end_col_block) const { const CompressedRowBlockStructure* bs = matrix_.block_structure(); CompressedRowBlockStructure* block_diagonal_structure = new CompressedRowBlockStructure; int block_position = 0; int diagonal_cell_position = 0; // Iterate over the column blocks, creating a new diagonal block for // each column block. for (int c = start_col_block; c < end_col_block; ++c) { const Block& block = bs->cols[c]; block_diagonal_structure->cols.push_back(Block()); Block& diagonal_block = block_diagonal_structure->cols.back(); diagonal_block.size = block.size; diagonal_block.position = block_position; block_diagonal_structure->rows.push_back(CompressedRow()); CompressedRow& row = block_diagonal_structure->rows.back(); row.block = diagonal_block; row.cells.push_back(Cell()); Cell& cell = row.cells.back(); cell.block_id = c - start_col_block; cell.position = diagonal_cell_position; block_position += block.size; diagonal_cell_position += block.size * block.size; } // Build a BlockSparseMatrix with the just computed block // structure. return new BlockSparseMatrix(block_diagonal_structure); } BlockSparseMatrix* PartitionedMatrixView::CreateBlockDiagonalEtE() const { BlockSparseMatrix* block_diagonal = CreateBlockDiagonalMatrixLayout(0, num_col_blocks_e_); UpdateBlockDiagonalEtE(block_diagonal); return block_diagonal; } BlockSparseMatrix* PartitionedMatrixView::CreateBlockDiagonalFtF() const { BlockSparseMatrix* block_diagonal = CreateBlockDiagonalMatrixLayout( num_col_blocks_e_, num_col_blocks_e_ + num_col_blocks_f_); UpdateBlockDiagonalFtF(block_diagonal); return block_diagonal; } // Similar to the code in RightMultiplyE, except instead of the matrix // vector multiply its an outer product. // // block_diagonal = block_diagonal(E'E) void PartitionedMatrixView::UpdateBlockDiagonalEtE( BlockSparseMatrix* block_diagonal) const { const CompressedRowBlockStructure* bs = matrix_.block_structure(); const CompressedRowBlockStructure* block_diagonal_structure = block_diagonal->block_structure(); block_diagonal->SetZero(); for (int r = 0; r < num_row_blocks_e_ ; ++r) { const double* row_values = matrix_.RowBlockValues(r); const Cell& cell = bs->rows[r].cells[0]; const int row_block_size = bs->rows[r].block.size; const int block_id = cell.block_id; const int col_block_size = bs->cols[block_id].size; ConstMatrixRef m(row_values + cell.position, row_block_size, col_block_size); const int cell_position = block_diagonal_structure->rows[block_id].cells[0].position; MatrixRef(block_diagonal->mutable_values() + cell_position, col_block_size, col_block_size).noalias() += m.transpose() * m; } } // Similar to the code in RightMultiplyF, except instead of the matrix // vector multiply its an outer product. // // block_diagonal = block_diagonal(F'F) // void PartitionedMatrixView::UpdateBlockDiagonalFtF( BlockSparseMatrix* block_diagonal) const { const CompressedRowBlockStructure* bs = matrix_.block_structure(); const CompressedRowBlockStructure* block_diagonal_structure = block_diagonal->block_structure(); block_diagonal->SetZero(); for (int r = 0; r < bs->rows.size(); ++r) { const int row_block_size = bs->rows[r].block.size; const vector<Cell>& cells = bs->rows[r].cells; const double* row_values = matrix_.RowBlockValues(r); for (int c = (r < num_row_blocks_e_) ? 1 : 0; c < cells.size(); ++c) { const int col_block_id = cells[c].block_id; const int col_block_size = bs->cols[col_block_id].size; ConstMatrixRef m(row_values + cells[c].position, row_block_size, col_block_size); const int diagonal_block_id = col_block_id - num_col_blocks_e_; const int cell_position = block_diagonal_structure->rows[diagonal_block_id].cells[0].position; MatrixRef(block_diagonal->mutable_values() + cell_position, col_block_size, col_block_size).noalias() += m.transpose() * m; } } } } // namespace internal } // namespace ceres <|endoftext|>
<commit_before>#include "post_process/adminizer.hpp" #include <mapnik/params.hpp> #include <mapnik/datasource.hpp> #include <mapnik/datasource_cache.hpp> #include <mapnik/featureset.hpp> #include <boost/geometry.hpp> #include <boost/geometry/geometries/point.hpp> #include <boost/geometry/geometries/box.hpp> #include <boost/geometry/geometries/polygon.hpp> #include <boost/geometry/geometries/multi_point.hpp> #include <boost/geometry/multi/geometries/multi_linestring.hpp> #include <boost/geometry/index/rtree.hpp> // NOTE: this is included only because it's where mapnik::coord2d is // adapted to work with the boost::geometry stuff. we don't actually // clip any polygons. #include <mapnik/polygon_clipper.hpp> namespace bg = boost::geometry; namespace bgi = boost::geometry::index; using point_2d = bg::model::point<double, 2, bg::cs::cartesian>; using box_2d = bg::model::box<point_2d>; using linestring_2d = bg::model::linestring<point_2d>; using multi_point_2d = bg::model::multi_point<point_2d>; using multi_linestring_2d = bg::model::multi_linestring<linestring_2d>; using polygon_2d = bg::model::polygon<point_2d>; namespace { typedef std::pair<box_2d, unsigned int> value; struct entry { entry(polygon_2d &&p, mapnik::value &&v, unsigned int i) : polygon(p), value(v), index(i) { } polygon_2d polygon; mapnik::value value; unsigned int index; }; struct param_updater { mapnik::feature_ptr &m_feature; const std::string &m_param_name; unsigned int m_index; bool m_finished; param_updater(mapnik::feature_ptr &feat, const std::string &param_name) : m_feature(feat), m_param_name(param_name) , m_index(std::numeric_limits<unsigned int>::max()) , m_finished(false) { } void operator()(const entry &e) { if (e.index < m_index) { m_feature->put_new(m_param_name, e.value); m_finished = e.index == 0; m_index = e.index; } } }; template <typename GeomType> struct intersects_iterator { const GeomType &m_geom; const std::vector<entry> &m_entries; param_updater &m_updater; intersects_iterator(const GeomType &geom, const std::vector<entry> &entries, param_updater &updater) : m_geom(geom), m_entries(entries), m_updater(updater) { } intersects_iterator &operator++() { // prefix return *this; } intersects_iterator &operator*() { return *this; } intersects_iterator &operator=(const value &v) { const entry &e = m_entries[v.second]; // do detailed intersection test, as the index only does bounding // box intersection tests. if (intersects(e.polygon)) { m_updater(e); } return *this; } bool intersects(const polygon_2d &) const; }; template <> bool intersects_iterator<multi_point_2d>::intersects(const polygon_2d &poly) const { // TODO: remove this hack when/if bg::intersects supports // intersection on multi type. for (auto point : m_geom) { if (bg::intersects(point, poly)) { return true; } } return false; } template <> bool intersects_iterator<multi_linestring_2d>::intersects(const polygon_2d &poly) const { // TODO: remove this hack when/if bg::intersects supports // intersection on multi type. for (auto line : m_geom) { if (bg::intersects(line, poly)) { return true; } } return false; } template <> bool intersects_iterator<polygon_2d>::intersects(const polygon_2d &poly) const { return bg::intersects(m_geom, poly); } template <typename RTreeType, typename GeomType> void try_update(RTreeType &index, const GeomType &geom, const std::vector<entry> &entries, param_updater &updater) { intersects_iterator<GeomType> itr(geom, entries, updater); index.query(bgi::intersects(bg::return_envelope<box_2d>(geom)), itr); } } // anonymous namespace namespace avecado { namespace post_process { /** * Post-process that applies administrative region attribution * to features, based on geographic location of the geometry. */ class adminizer : public izer { public: adminizer(pt::ptree const& config); virtual ~adminizer(); virtual void process(std::vector<mapnik::feature_ptr> &layer) const; private: mapnik::box2d<double> envelope(const std::vector<mapnik::feature_ptr> &layer) const; multi_point_2d make_boost_point(const mapnik::geometry_type &geom) const; multi_linestring_2d make_boost_linestring(const mapnik::geometry_type &geom) const; polygon_2d make_boost_polygon(const mapnik::geometry_type &geom) const; std::string m_param_name; std::shared_ptr<mapnik::datasource> m_datasource; }; adminizer::adminizer(pt::ptree const& config) : m_param_name(config.get<std::string>("param_name")) { mapnik::parameters params; boost::optional<pt::ptree const &> datasource_config = config.get_child_optional("datasource"); if (datasource_config) { for (auto &kv : *datasource_config) { params[kv.first] = kv.second.data(); } } m_datasource = mapnik::datasource_cache::instance().create(params); } adminizer::~adminizer() { } void adminizer::process(std::vector<mapnik::feature_ptr> &layer) const { typedef bgi::rtree<value, bgi::quadratic<16> > rtree; // build extent of all features in layer mapnik::box2d<double> env = envelope(layer); // query the datasource // TODO: do we want to pass more things like scale denominator // and resolution type? mapnik::featureset_ptr fset = m_datasource->features(mapnik::query(env)); // construct an index over the bounding boxes of the geometry, // first extracting the geometries from mapnik's representation // and transforming them too boost::geometry's representation. std::vector<entry> entries; { unsigned int index = 0; mapnik::feature_ptr f; while (f = fset->next()) { mapnik::value param = f->get(m_param_name); for (auto const &geom : f->paths()) { // ignore all non-polygon types if (geom.type() == mapnik::geometry_type::types::Polygon) { entries.emplace_back(make_boost_polygon(geom), std::move(param), index++); } } } } // create envelope boxes for entries, as these are needed // up-front for the packing algorithm. std::vector<value> values; values.reserve(entries.size()); const size_t num_entries = entries.size(); for (size_t i = 0; i < num_entries; ++i) { values.emplace_back(bg::return_envelope<box_2d>(entries[i].polygon), i); } // construct index using packing algorithm, which leads to // better distribution for querying. rtree index(values.begin(), values.end()); values.clear(); // don't need these any more. // loop over features, finding which items from the datasource // they intersect with. for (mapnik::feature_ptr f : layer) { param_updater updater(f, m_param_name); for (auto const &geom : f->paths()) { if (geom.type() == mapnik::geometry_type::types::Point) { multi_point_2d multi_point = make_boost_point(geom); try_update(index, multi_point, entries, updater); } else if (geom.type() == mapnik::geometry_type::types::LineString) { multi_linestring_2d multi_line = make_boost_linestring(geom); try_update(index, multi_line, entries, updater); } else if (geom.type() == mapnik::geometry_type::types::Polygon) { polygon_2d poly = make_boost_polygon(geom); try_update(index, poly, entries, updater); } // quick exit the loop if there's nothing more to do. if (updater.m_finished) { break; } } } } mapnik::box2d<double> adminizer::envelope(const std::vector<mapnik::feature_ptr> &layer) const { mapnik::box2d<double> result; bool first = true; for (auto const &feature : layer) { if (first) { result = feature->envelope(); } else { result.expand_to_include(feature->envelope()); } } return result; } multi_point_2d adminizer::make_boost_point(const mapnik::geometry_type &geom) const { /* Takes a mapnik geometry and makes a multi_point_2d from it. It has to be a * multipoint, since we don't know from geom.type() if it's a point or multipoint? */ multi_point_2d points; double x = 0, y = 0; geom.rewind(0); unsigned int cmd = mapnik::SEG_END; while ((cmd = geom.vertex(&x, &y)) != mapnik::SEG_END) { points.push_back(bg::make<point_2d>(x, y)); } return points; } multi_linestring_2d adminizer::make_boost_linestring(const mapnik::geometry_type &geom) const { multi_linestring_2d line; double x = 0, y = 0, prev_x = 0, prev_y = 0; geom.rewind(0); unsigned int cmd = mapnik::SEG_END; while ((cmd = geom.vertex(&x, &y)) != mapnik::SEG_END) { if (cmd == mapnik::SEG_MOVETO) { line.push_back(linestring_2d()); line.back().push_back(bg::make<point_2d>(x, y)); } else if (cmd == mapnik::SEG_LINETO) { if (std::abs(x - prev_x) < 1e-12 && std::abs(y - prev_y) < 1e-12) { continue; } line.back().push_back(bg::make<point_2d>(x, y)); } prev_x = x; prev_y = y; } return line; } polygon_2d adminizer::make_boost_polygon(const mapnik::geometry_type &geom) const { polygon_2d poly; double x = 0, y = 0, prev_x = 0, prev_y = 0; unsigned int ring_count = 0; geom.rewind(0); unsigned int cmd = mapnik::SEG_END; while ((cmd = geom.vertex(&x, &y)) != mapnik::SEG_END) { if (cmd == mapnik::SEG_MOVETO) { if (ring_count == 0) { bg::append(poly, bg::make<point_2d>(x, y)); } else { poly.inners().push_back(polygon_2d::inner_container_type::value_type()); bg::append(poly.inners().back(), bg::make<point_2d>(x, y)); } ++ring_count; } else if (cmd == mapnik::SEG_LINETO) { if (std::abs(x - prev_x) < 1e-12 && std::abs(y - prev_y) < 1e-12) { continue; } if (ring_count == 1) { bg::append(poly, bg::make<point_2d>(x, y)); } else { bg::append(poly.inners().back(), bg::make<point_2d>(x, y)); } } prev_x = x; prev_y = y; } return poly; } izer_ptr create_adminizer(pt::ptree const& config) { return std::make_shared<adminizer>(config); } } // namespace post_process } // namespace avecado <commit_msg>Factored out functions in adminizer.<commit_after>#include "post_process/adminizer.hpp" #include <mapnik/params.hpp> #include <mapnik/datasource.hpp> #include <mapnik/datasource_cache.hpp> #include <mapnik/featureset.hpp> #include <boost/geometry.hpp> #include <boost/geometry/geometries/point.hpp> #include <boost/geometry/geometries/box.hpp> #include <boost/geometry/geometries/polygon.hpp> #include <boost/geometry/geometries/multi_point.hpp> #include <boost/geometry/multi/geometries/multi_linestring.hpp> #include <boost/geometry/index/rtree.hpp> // NOTE: this is included only because it's where mapnik::coord2d is // adapted to work with the boost::geometry stuff. we don't actually // clip any polygons. #include <mapnik/polygon_clipper.hpp> namespace bg = boost::geometry; namespace bgi = boost::geometry::index; using point_2d = bg::model::point<double, 2, bg::cs::cartesian>; using box_2d = bg::model::box<point_2d>; using linestring_2d = bg::model::linestring<point_2d>; using multi_point_2d = bg::model::multi_point<point_2d>; using multi_linestring_2d = bg::model::multi_linestring<linestring_2d>; using polygon_2d = bg::model::polygon<point_2d>; namespace { typedef std::pair<box_2d, unsigned int> value; struct entry { entry(polygon_2d &&p, mapnik::value &&v, unsigned int i) : polygon(p), value(v), index(i) { } polygon_2d polygon; mapnik::value value; unsigned int index; }; struct param_updater { mapnik::feature_ptr &m_feature; const std::string &m_param_name; unsigned int m_index; bool m_finished; param_updater(mapnik::feature_ptr &feat, const std::string &param_name) : m_feature(feat), m_param_name(param_name) , m_index(std::numeric_limits<unsigned int>::max()) , m_finished(false) { } void operator()(const entry &e) { if (e.index < m_index) { m_feature->put_new(m_param_name, e.value); m_finished = e.index == 0; m_index = e.index; } } }; template <typename GeomType> struct intersects_iterator { const GeomType &m_geom; const std::vector<entry> &m_entries; param_updater &m_updater; intersects_iterator(const GeomType &geom, const std::vector<entry> &entries, param_updater &updater) : m_geom(geom), m_entries(entries), m_updater(updater) { } intersects_iterator &operator++() { // prefix return *this; } intersects_iterator &operator*() { return *this; } intersects_iterator &operator=(const value &v) { const entry &e = m_entries[v.second]; // do detailed intersection test, as the index only does bounding // box intersection tests. if (intersects(e.polygon)) { m_updater(e); } return *this; } bool intersects(const polygon_2d &) const; }; template <> bool intersects_iterator<multi_point_2d>::intersects(const polygon_2d &poly) const { // TODO: remove this hack when/if bg::intersects supports // intersection on multi type. for (auto point : m_geom) { if (bg::intersects(point, poly)) { return true; } } return false; } template <> bool intersects_iterator<multi_linestring_2d>::intersects(const polygon_2d &poly) const { // TODO: remove this hack when/if bg::intersects supports // intersection on multi type. for (auto line : m_geom) { if (bg::intersects(line, poly)) { return true; } } return false; } template <> bool intersects_iterator<polygon_2d>::intersects(const polygon_2d &poly) const { return bg::intersects(m_geom, poly); } template <typename RTreeType, typename GeomType> void try_update(RTreeType &index, const GeomType &geom, const std::vector<entry> &entries, param_updater &updater) { intersects_iterator<GeomType> itr(geom, entries, updater); index.query(bgi::intersects(bg::return_envelope<box_2d>(geom)), itr); } } // anonymous namespace namespace avecado { namespace post_process { using rtree = bgi::rtree<value, bgi::quadratic<16> >; /** * Post-process that applies administrative region attribution * to features, based on geographic location of the geometry. */ class adminizer : public izer { public: adminizer(pt::ptree const& config); virtual ~adminizer(); virtual void process(std::vector<mapnik::feature_ptr> &layer) const; private: mapnik::box2d<double> envelope(const std::vector<mapnik::feature_ptr> &layer) const; multi_point_2d make_boost_point(const mapnik::geometry_type &geom) const; multi_linestring_2d make_boost_linestring(const mapnik::geometry_type &geom) const; polygon_2d make_boost_polygon(const mapnik::geometry_type &geom) const; std::vector<entry> make_entries(const mapnik::box2d<double> &env) const; rtree make_index(const std::vector<entry> &entries) const; void adminize_feature(mapnik::feature_ptr &f, const rtree &index, const std::vector<entry> &entries) const; // the name of the parameter to take from the admin polygon and set // on the feature being adminized. std::string m_param_name; std::shared_ptr<mapnik::datasource> m_datasource; }; adminizer::adminizer(pt::ptree const& config) : m_param_name(config.get<std::string>("param_name")) { mapnik::parameters params; boost::optional<pt::ptree const &> datasource_config = config.get_child_optional("datasource"); if (datasource_config) { for (auto &kv : *datasource_config) { params[kv.first] = kv.second.data(); } } m_datasource = mapnik::datasource_cache::instance().create(params); } adminizer::~adminizer() { } std::vector<entry> adminizer::make_entries(const mapnik::box2d<double> &env) const { // query the datasource // TODO: do we want to pass more things like scale denominator // and resolution type? mapnik::featureset_ptr fset = m_datasource->features(mapnik::query(env)); std::vector<entry> entries; unsigned int index = 0; mapnik::feature_ptr f; while (f = fset->next()) { mapnik::value param = f->get(m_param_name); for (auto const &geom : f->paths()) { // ignore all non-polygon types if (geom.type() == mapnik::geometry_type::types::Polygon) { entries.emplace_back(make_boost_polygon(geom), std::move(param), index++); } } } return entries; } rtree adminizer::make_index(const std::vector<entry> &entries) const { // create envelope boxes for entries, as these are needed // up-front for the packing algorithm. std::vector<value> values; values.reserve(entries.size()); const size_t num_entries = entries.size(); for (size_t i = 0; i < num_entries; ++i) { values.emplace_back(bg::return_envelope<box_2d>(entries[i].polygon), i); } // construct index using packing algorithm, which leads to // better distribution for querying. return rtree(values.begin(), values.end()); } void adminizer::adminize_feature(mapnik::feature_ptr &f, const rtree &index, const std::vector<entry> &entries) const { param_updater updater(f, m_param_name); for (auto const &geom : f->paths()) { if (geom.type() == mapnik::geometry_type::types::Point) { multi_point_2d multi_point = make_boost_point(geom); try_update(index, multi_point, entries, updater); } else if (geom.type() == mapnik::geometry_type::types::LineString) { multi_linestring_2d multi_line = make_boost_linestring(geom); try_update(index, multi_line, entries, updater); } else if (geom.type() == mapnik::geometry_type::types::Polygon) { polygon_2d poly = make_boost_polygon(geom); try_update(index, poly, entries, updater); } // quick exit the loop if there's nothing more to do. if (updater.m_finished) { break; } } } void adminizer::process(std::vector<mapnik::feature_ptr> &layer) const { // build extent of all features in layer mapnik::box2d<double> env = envelope(layer); // construct an index over the bounding boxes of the geometry, // first extracting the geometries from mapnik's representation // and transforming them too boost::geometry's representation. std::vector<entry> entries = make_entries(env); rtree index = make_index(entries); // loop over features, finding which items from the datasource // they intersect with. for (mapnik::feature_ptr f : layer) { adminize_feature(f, index, entries); } } mapnik::box2d<double> adminizer::envelope(const std::vector<mapnik::feature_ptr> &layer) const { mapnik::box2d<double> result; bool first = true; for (auto const &feature : layer) { if (first) { result = feature->envelope(); } else { result.expand_to_include(feature->envelope()); } } return result; } multi_point_2d adminizer::make_boost_point(const mapnik::geometry_type &geom) const { /* Takes a mapnik geometry and makes a multi_point_2d from it. It has to be a * multipoint, since we don't know from geom.type() if it's a point or multipoint? */ multi_point_2d points; double x = 0, y = 0; geom.rewind(0); unsigned int cmd = mapnik::SEG_END; while ((cmd = geom.vertex(&x, &y)) != mapnik::SEG_END) { points.push_back(bg::make<point_2d>(x, y)); } return points; } multi_linestring_2d adminizer::make_boost_linestring(const mapnik::geometry_type &geom) const { multi_linestring_2d line; double x = 0, y = 0, prev_x = 0, prev_y = 0; geom.rewind(0); unsigned int cmd = mapnik::SEG_END; while ((cmd = geom.vertex(&x, &y)) != mapnik::SEG_END) { if (cmd == mapnik::SEG_MOVETO) { line.push_back(linestring_2d()); line.back().push_back(bg::make<point_2d>(x, y)); } else if (cmd == mapnik::SEG_LINETO) { if (std::abs(x - prev_x) < 1e-12 && std::abs(y - prev_y) < 1e-12) { continue; } line.back().push_back(bg::make<point_2d>(x, y)); } prev_x = x; prev_y = y; } return line; } polygon_2d adminizer::make_boost_polygon(const mapnik::geometry_type &geom) const { polygon_2d poly; double x = 0, y = 0, prev_x = 0, prev_y = 0; unsigned int ring_count = 0; geom.rewind(0); unsigned int cmd = mapnik::SEG_END; while ((cmd = geom.vertex(&x, &y)) != mapnik::SEG_END) { if (cmd == mapnik::SEG_MOVETO) { if (ring_count == 0) { bg::append(poly, bg::make<point_2d>(x, y)); } else { poly.inners().push_back(polygon_2d::inner_container_type::value_type()); bg::append(poly.inners().back(), bg::make<point_2d>(x, y)); } ++ring_count; } else if (cmd == mapnik::SEG_LINETO) { if (std::abs(x - prev_x) < 1e-12 && std::abs(y - prev_y) < 1e-12) { continue; } if (ring_count == 1) { bg::append(poly, bg::make<point_2d>(x, y)); } else { bg::append(poly.inners().back(), bg::make<point_2d>(x, y)); } } prev_x = x; prev_y = y; } return poly; } izer_ptr create_adminizer(pt::ptree const& config) { return std::make_shared<adminizer>(config); } } // namespace post_process } // namespace avecado <|endoftext|>
<commit_before>#pragma once #include "includes.hpp" #define TAGLIB_STATIC #include <taglib/fileref.h> #include <taglib/tag.h> #include <taglib/tpropertymap.h> class playlist : public Component, public FileDragAndDropTarget { struct playlistModel : public TableListBoxModel { base::string paths; std::vector<size_t> paths_i; void init() { paths.clear(); paths_i.clear(); paths_i.push_back(0); } void addItem(const String &path) { //TagLib::FileRef file(f.toRawUTF8()); //f = (file.tag()->album() + L" | " + file.tag()->artist() + L" | " + file.tag()->title()).toCString(); paths.append(path.toStdString()); paths_i.push_back(paths.size()); } base::string getItemPath(size_t index) { return base::string(paths.begin() + paths_i[index], paths.begin() + paths_i[index + 1]); } // GUI int getNumRows() override { return paths_i.size() - 1; } // This is overloaded from TableListBoxModel, and should fill in the background of the whole row void paintRowBackground(Graphics& g, int rowNumber, int /*width*/, int /*height*/, bool rowIsSelected) override { if (rowIsSelected) g.fillAll(Colours::lightblue); else if (rowNumber % 2) g.fillAll(Colour(0xffeeeeee)); } // This is overloaded from TableListBoxModel, and must paint any cells that aren't using custom // components. void paintCell(Graphics& g, int rowNumber, int /*columnId*/, int width, int height, bool /*rowIsSelected*/) override { g.setColour(Colours::black); g.setFont(height * 0.7f); g.drawText(getItemPath(rowNumber), 5, 0, width, height, Justification::centredLeft, true); g.setColour(Colours::black.withAlpha(0.2f)); g.fillRect(width - 1, 0, 1, height); } }; TableListBox box; playlistModel model; JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(playlist); // TODO: system codecs? bool isFileSupported(const String &fname) { return fname.endsWith(".mp3") || fname.endsWith(".wav") || fname.endsWith(".wma") || fname.endsWith(".flac") || fname.endsWith(".ogg") || fname.endsWith(".ape"); } public: playlist() : box("playlist-box", nullptr) { model.init(); setName("playlist"); box.setModel(&model); box.setMultipleSelectionEnabled(true); addAndMakeVisible(box); box.getHeader().addColumn("album", 0, 200, 50, 1000, TableHeaderComponent::defaultFlags); box.getHeader().addColumn("artist", 0, 200, 50, 1000, TableHeaderComponent::defaultFlags); box.getHeader().addColumn("title", 0, 200, 50, 1000, TableHeaderComponent::defaultFlags); box.setMultipleSelectionEnabled(true); } void resized() override { box.setBounds(getLocalBounds().reduced(0)); } bool isInterestedInFileDrag(const StringArray& /*files*/) override { return true; } void fileDragEnter(const StringArray& /*files*/, int /*x*/, int /*y*/) override { repaint(); } void fileDragMove (const StringArray& /*files*/, int /*x*/, int /*y*/) override {} void fileDragExit (const StringArray& /*files*/) override { repaint(); } void filesDropped (const StringArray& files, int /*x*/, int /*y*/) override { for (auto &f : files) { if (isFileSupported(f)) { model.addItem(f); } } box.updateContent(); repaint(); } base::string getSelectedRowString() { return model.getItemPath(box.getSelectedRow()); } }; <commit_msg>+ tags reading<commit_after>#pragma once #include "includes.hpp" #define TAGLIB_STATIC #include <taglib/fileref.h> #include <taglib/tag.h> #include <taglib/tpropertymap.h> class playlist : public Component, public FileDragAndDropTarget { struct playlistModel : public TableListBoxModel { base::string paths, talbum, tartist, ttitle; std::vector<uint> tyear, ttrack; std::vector<size_t> paths_i, talbum_i, tartist_i, ttitle_i; void init() { paths.clear(); talbum.clear(); tartist.clear(); tyear.clear(); ttitle.clear(); ttrack.clear(); paths_i.clear(); paths_i.push_back(0); talbum_i.clear(); talbum_i.push_back(0); tartist_i.clear(); tartist_i.push_back(0); ttitle_i.clear(); ttitle_i.push_back(0); } void addItem(const String &path) { paths.append(path.toStdString()); paths_i.push_back(paths.size()); // read tags from file TagLib::FileRef file(path.toRawUTF8()); if (!file.isNull() && file.tag()) { talbum.append(file.tag()->album().toCString()); tartist.append(file.tag()->artist().toCString()); ttitle.append(file.tag()->title().toCString()); tyear.push_back(file.tag()->year()); ttrack.push_back(file.tag()->track()); } else { tyear.push_back(0); ttrack.push_back(0); } talbum_i.push_back(talbum.size()); tartist_i.push_back(tartist.size()); ttitle_i.push_back(ttitle.size()); } base::string getItemPath(size_t index) { return base::string(paths.begin() + paths_i[index], paths.begin() + paths_i[index + 1]); } uint getItemTrack(size_t index) { return ttrack[index]; } uint getItemYear(size_t index) { return tyear[index]; } base::string getItemAlbum(size_t index) { return base::string(talbum.begin() + talbum_i[index], talbum.begin() + talbum_i[index + 1]); } base::string getItemArtist(size_t index) { return base::string(tartist.begin() + tartist_i[index], tartist.begin() + tartist_i[index + 1]); } base::string getItemTitle(size_t index) { return base::string(ttitle.begin() + ttitle_i[index], ttitle.begin() + ttitle_i[index + 1]); } // GUI int getNumRows() override { return paths_i.size() - 1; } // This is overloaded from TableListBoxModel, and should fill in the background of the whole row void paintRowBackground(Graphics& g, int rowNumber, int /*width*/, int /*height*/, bool rowIsSelected) override { if (rowIsSelected) g.fillAll(Colours::lightblue); else if (rowNumber % 2) g.fillAll(Colour(0xffeeeeee)); } // This is overloaded from TableListBoxModel, and must paint any cells that aren't using custom // components. void paintCell(Graphics& g, int rowNumber, int columnId, int width, int height, bool /*rowIsSelected*/) override { g.setColour(Colours::black); g.setFont(height * 0.7f); if (columnId == 0) g.drawText(base::toStr(getItemTrack(rowNumber)), 5, 0, width, height, Justification::centredLeft, true); else if (columnId == 1) g.drawText(getItemAlbum(rowNumber), 5, 0, width, height, Justification::centredLeft, true); else if (columnId == 2) g.drawText(getItemArtist(rowNumber), 5, 0, width, height, Justification::centredLeft, true); else if (columnId == 3) g.drawText(getItemTitle(rowNumber), 5, 0, width, height, Justification::centredLeft, true); else if (columnId == 4) g.drawText(base::toStr(getItemYear(rowNumber)), 5, 0, width, height, Justification::centredLeft, true); g.setColour(Colours::black.withAlpha(0.2f)); g.fillRect(width - 1, 0, 1, height); } }; TableListBox box; playlistModel model; JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(playlist); // TODO: system codecs? bool isFileSupported(const String &fname) { return fname.endsWith(".mp3") || fname.endsWith(".wav") || fname.endsWith(".wma") || fname.endsWith(".flac") || fname.endsWith(".ogg") || fname.endsWith(".ape"); } public: playlist() : box("playlist-box", nullptr) { model.init(); setName("playlist"); box.setModel(&model); box.setMultipleSelectionEnabled(true); addAndMakeVisible(box); box.getHeader().addColumn("track", 0, 50, 20, 1000, TableHeaderComponent::defaultFlags); box.getHeader().addColumn("album", 1, 200, 150, 1000, TableHeaderComponent::defaultFlags); box.getHeader().addColumn("artist", 2, 200, 150, 1000, TableHeaderComponent::defaultFlags); box.getHeader().addColumn("title", 3, 200, 150, 1000, TableHeaderComponent::defaultFlags); box.getHeader().addColumn("year", 4, 70, 50, 1000, TableHeaderComponent::defaultFlags); box.setMultipleSelectionEnabled(true); } void resized() override { box.setBounds(getLocalBounds().reduced(0)); } bool isInterestedInFileDrag(const StringArray& /*files*/) override { return true; } void fileDragEnter(const StringArray& /*files*/, int /*x*/, int /*y*/) override { repaint(); } void fileDragMove (const StringArray& /*files*/, int /*x*/, int /*y*/) override {} void fileDragExit (const StringArray& /*files*/) override { repaint(); } void filesDropped (const StringArray& files, int /*x*/, int /*y*/) override { for (auto &f : files) { if (isFileSupported(f)) { model.addItem(f); } } box.updateContent(); repaint(); } base::string getSelectedRowString() { return model.getItemPath(box.getSelectedRow()); } }; <|endoftext|>
<commit_before>//! //! @file SignalSecondOrderFilter.hpp //! @author Björn Eriksson <[email protected]> //! @date 2010-01-22 //! //! @brief Contains a Signal Second Order Filter Component using CoreUtilities //! //$Id$ #ifndef SIGNALSECONORDERFILTER_HPP_INCLUDED #define SIGNALSECONORDERFILTER_HPP_INCLUDED #include "../../ComponentEssentials.h" #include "../../ComponentUtilities.h" //! //! @brief //! @ingroup SignalComponents //! class SignalSecondOrderFilter : public ComponentSignal { private: SecondOrderFilter mFilter; double mWnum, mDnum, mWden, mDden, mK; double mStartY; double mMin, mMax; Port *mpIn, *mpOut; public: static Component *Creator() { std::cout << "running Second Order Filter creator" << std::endl; return new SignalSecondOrderFilter("Filter"); } SignalSecondOrderFilter(const string name) : ComponentSignal(name) { mTypeName = "SignalSecondOrderFilter"; mStartY = 0.0; mMin = -1.5E+300; mMax = 1.5E+300; mK = 1.0; mWnum = 1e10; mDnum = 1.0; mWden = 1.0*2.0*3.1415; mDden = 0.7; mpIn = addReadPort("in", "NodeSignal"); mpOut = addWritePort("out", "NodeSignal"); registerParameter("k", "Gain", "-", mK); registerParameter("wnum", "Numerator break frequency", "rad/s", mWnum); registerParameter("dnum", "Numerator damp coefficient", "-", mDnum); registerParameter("wden", "Denumerator break frequency", "rad/s", mWden); registerParameter("dden", "Numerator damp coefficient", "-", mDden); registerParameter("min", "Lower limit for output", "-", mMin); registerParameter("max", "Upper limit for output", "-", mMax); } void initialize() { //double u0 = mpIn->readNode(NodeSignal::VALUE); double num[3]; double den[3]; num[0] = mK/pow(mWnum, 2); num[1] = mK*2.0*mDnum/mWnum; num[2] = mK; den[0] = 1.0/pow(mWden, 2); den[1] = 2.0*mDden/mWden; den[2] = 1.0; mFilter.initialize(mTime, mTimestep, num, den, mStartY, mStartY, mMin, mMax); //Writes out the value for time "zero" mpOut->writeNode(NodeSignal::VALUE, mStartY); } void simulateOneTimestep() { //Get variable values from nodes double u = mpIn->readNode(NodeSignal::VALUE); //Write new values to nodes mpOut->writeNode(NodeSignal::VALUE, mFilter.value(u)); } }; #endif // SIGNALSECONORDERFILTER_HPP_INCLUDED <commit_msg>Changed some parameters (spelled correctly)<commit_after>//! //! @file SignalSecondOrderFilter.hpp //! @author Björn Eriksson <[email protected]> //! @date 2010-01-22 //! //! @brief Contains a Signal Second Order Filter Component using CoreUtilities //! //$Id$ #ifndef SIGNALSECONORDERFILTER_HPP_INCLUDED #define SIGNALSECONORDERFILTER_HPP_INCLUDED #include "../../ComponentEssentials.h" #include "../../ComponentUtilities.h" //! //! @brief //! @ingroup SignalComponents //! class SignalSecondOrderFilter : public ComponentSignal { private: SecondOrderFilter mFilter; double mWnum, mDnum, mWden, mDden, mK; double mStartY; double mMin, mMax; Port *mpIn, *mpOut; public: static Component *Creator() { std::cout << "running Second Order Filter creator" << std::endl; return new SignalSecondOrderFilter("Filter"); } SignalSecondOrderFilter(const string name) : ComponentSignal(name) { mTypeName = "SignalSecondOrderFilter"; mStartY = 0.0; mMin = -1.5E+300; mMax = 1.5E+300; mK = 1.0; mWnum = 1e10; mDnum = 1.0; mWden = 1.0*2.0*3.1415; mDden = 0.7; mpIn = addReadPort("in", "NodeSignal"); mpOut = addWritePort("out", "NodeSignal"); registerParameter("k", "Gain", "-", mK); registerParameter("wnum", "Numerator break frequency", "rad/s", mWnum); registerParameter("dnum", "Numerator damp coefficient", "-", mDnum); registerParameter("wden", "Denominator break frequency", "rad/s", mWden); registerParameter("dden", "Denominator damp coefficient", "-", mDden); registerParameter("min", "Output Lower limit", "-", mMin); registerParameter("max", "Output Upper limit", "-", mMax); } void initialize() { //double u0 = mpIn->readNode(NodeSignal::VALUE); double num[3]; double den[3]; num[0] = mK/pow(mWnum, 2); num[1] = mK*2.0*mDnum/mWnum; num[2] = mK; den[0] = 1.0/pow(mWden, 2); den[1] = 2.0*mDden/mWden; den[2] = 1.0; mFilter.initialize(mTime, mTimestep, num, den, mStartY, mStartY, mMin, mMax); //Writes out the value for time "zero" mpOut->writeNode(NodeSignal::VALUE, mStartY); } void simulateOneTimestep() { //Get variable values from nodes double u = mpIn->readNode(NodeSignal::VALUE); //Write new values to nodes mpOut->writeNode(NodeSignal::VALUE, mFilter.value(u)); } }; #endif // SIGNALSECONORDERFILTER_HPP_INCLUDED <|endoftext|>
<commit_before>/***************************************************************************** idr.cpp (c) 2014 - Nikhil R Podduturi J. Michael Cherry Lab, Department of Genetics, Stanford University School of Medicine Licensed under the GNU General Public License 2.0 license. ******************************************************************************/ #include <stdio.h> #include <string> #include <stdlib.h> #include <cerrno> #include <processPeaks.h> #include <ranker.h> #include <idr.h> using namespace std; #define PROGRAM_NAME "IDR" #define PACKAGE_VERSION "0.1" #define PARAMETER_CHECK(param, paramLen, actualLen) (\ strncmp(argv[i], param, min(actualLen, paramLen))== 0) \ && (actualLen == paramLen) void ShowHelp(void); // Utility struct to keep track of final results struct overlap { string chr; CHRPOS start1; CHRPOS end1; double rankingMeasure1; CHRPOS start2; CHRPOS end2; double rankingMeasure2; double idrLocal; double idr; }; struct sort_pred { bool operator()(const std::pair<int, double> &left, const std::pair<int, double> &right) { return left.second < right.second; } }; #define DEFAULT_IDR_CUTOFF 0.025 #define DEFAULT_OFNAME "idrValues.txt" #define DEFAULT_RANKING_MEASURE "signal.value" #define RANKING_MEASURE_INDEX 6 void ShowHelp(void) { fprintf(stderr, "\n"); fprintf(stderr, "Program: IDR (Irreproducible Discovery Rate)\n"); fprintf(stderr, "Version: %s\n", PACKAGE_VERSION); fprintf(stderr, "Contact: Nikhil R Podduturi <[email protected]>\n\n"); fprintf(stderr, "Usage: idr [options] -a <bed> -b <bed> -g <bed>\n\n"); fprintf(stderr, "Options:\n\n"); fprintf(stderr, " -o Output filename (default: idrValues.txt)\n\n"); fprintf(stderr, " -idr IDR cutoff (default: %e)\n\n", DEFAULT_IDR_CUTOFF); fprintf(stderr, " -rank Type of ranking measure (default: %s)\n\n", DEFAULT_RANKING_MEASURE); exit(1); } class Args { public: string bedAFile; string bedBFile; string genomeFile; string ofname; int rankingMeasure; float idrCutoff; Args( int argc, char* argv[] ) { this->ofname = DEFAULT_OFNAME; this->rankingMeasure = RANKING_MEASURE_INDEX; this->idrCutoff = DEFAULT_IDR_CUTOFF; bool haveBedA = false; bool haveBedB = false; bool haveGenome = false; bool haveOutput = false; if(argc <= 1) ShowHelp(); for(int i = 1; i < argc; i++) { int parameterLength = (int)strlen(argv[i]); if((PARAMETER_CHECK("-h", 2, parameterLength)) || (PARAMETER_CHECK("--help", 6, parameterLength))) { ShowHelp(); } } for(int i = 1; i < argc; i++) { int parameterLength = (int)strlen(argv[i]); if(PARAMETER_CHECK("-a", 2, parameterLength)) { if ((i+1) < argc) { haveBedA = true; this->bedAFile = argv[i + 1]; i++; } } else if(PARAMETER_CHECK("-b", 2, parameterLength)) { if ((i+1) < argc) { haveBedB = true; this->bedBFile = argv[i + 1]; i++; } } else if(PARAMETER_CHECK("-o", 2, parameterLength)) { if((i+1) < argc) { haveOutput = true; this->ofname = argv[i + 1]; i++; } } else if(PARAMETER_CHECK("-g", 2, parameterLength)) { if ((i+1) < argc) { haveGenome = true; this->genomeFile = argv[i + 1]; i++; } } else if(PARAMETER_CHECK("-rank", 5, parameterLength)) { if((i+1) < argc) { if (strcmp( argv[i+1], "p.value" ) == 0) rankingMeasure = 7; else if (strcmp( argv[i+1], "q.value" ) == 0) rankingMeasure = 8; i++; } } else if(PARAMETER_CHECK("-idr", 4, parameterLength)) { if((i+1) < argc) { this->idrCutoff = atof(argv[i + 1]); i++; } } else { fprintf(stderr, "*****ERROR: Unrecognized parameter: %s *****\n\n", argv[i]); ShowHelp(); } } // make sure we have both input files if (!haveBedA || !haveBedB || !haveGenome) { fprintf(stderr, "*****ERROR: Need -a, -b and -g files. *****"); ShowHelp(); } }; }; int build_ranks_vector( ProcessPeaks *bc, int rankingMeasure, vector<overlap> &overlaps, vector<float> &ranks_A, vector<float> &ranks_B) { vector<double> merge_A, merge_B, unmatched_merge_A, unmatched_merge_B; vector<unsigned int> tracker; unsigned int start = 0; for (size_t i = 0; i < bc->_peakA->bedList.size(); ++i) { merge_A.push_back(stod(bc->_peakA->bedList[i].fields[rankingMeasure])); merge_B.push_back(0); while (start < bc->overlap_index_A[i]) { tracker.push_back( bc->overlap_index_B[start] ); double bSigVal = stod(bc->_peakB->bedList[bc->overlap_index_B[start] ].fields[rankingMeasure]); overlap o; string chr(bc->_peakA->bedList[i].chrom); o.chr = chr; o.start1 = bc->_peakA->bedList[i].start; o.end1 = bc->_peakA->bedList[i].end; o.rankingMeasure1 = merge_A[i]; o.start2 = bc->_peakB->bedList[ bc->overlap_index_B[start] ].start; o.end2 = bc->_peakB->bedList[ bc->overlap_index_B[start] ].end; if (merge_B[i] == 0) { merge_B[i] = bSigVal; o.rankingMeasure2 = merge_B[i]; overlaps.push_back(o); } else { merge_B[i] = double (merge_B[i] + bSigVal)/2.0; o.rankingMeasure2 = merge_B[i]; overlaps.pop_back(); overlaps.push_back(o); } ++start; } } sort(tracker.begin(), tracker.end()); for (unsigned int i = 0; i < bc->_peakB->bedList.size(); ++i) { if(find(tracker.begin(), tracker.end(), i) == tracker.end()) { double bSigVal = stod(bc->_peakB->bedList[i].fields[rankingMeasure]); merge_A.push_back( 0 ); merge_B.push_back( bSigVal ); } } for (unsigned int i=0; i < merge_A.size(); ++i) { if ( merge_A[i] != 0 && merge_B[i] != 0 ) { unmatched_merge_A.push_back( -merge_A[i] ); unmatched_merge_B.push_back( -merge_B[i] ); } } fprintf(stderr, "Number of overlaps after removing duplicates - %lu\n", unmatched_merge_A.size()); fprintf(stderr, "Ranking overlaps\n"); rank_vec(unmatched_merge_A, ranks_A, "average"); rank_vec(unmatched_merge_B, ranks_B, "average"); fprintf(stderr, " Done\n"); return 0; } int main(int argc, char* argv[]) { Args args = Args(argc, argv); ProcessPeaks *bc = new ProcessPeaks( args.bedAFile, args.bedBFile, args.genomeFile); vector<overlap> overlaps; /* Find the joint peak list, and rank them */ vector<float> ranks_A, ranks_B; build_ranks_vector( bc, args.rankingMeasure, overlaps, ranks_A, ranks_B ); vector< pair<int, double> > idr(ranks_A.size()); fprintf(stderr, "Fit 2-component model - started\n"); em_gaussian(ranks_A, ranks_B, idr); /* Make a copy of the local IDR vector, and then update the 'second' field to store the global IDR value (XXX use decent variable names...) */ vector<double> idrLocal(ranks_A.size()); for(int i=0; i<idr.size(); ++i) { idrLocal[i] = idr[i].second; } sort(idr.begin(), idr.end(), sort_pred()); for(int i=1; i<idr.size(); ++i) { idr[i].second = idr[i].second + idr[i-1].second; } int num_peaks_passing_threshold = 0; for(int j=0; j<ranks_A.size(); ++j) { idr[j].second = idr[j].second/((double)j); if(idr[j].second <= args.idrCutoff) { num_peaks_passing_threshold += 1; } }; sort(idr.begin(), idr.end()); for (unsigned int i=0; i<idr.size(); ++i) { overlaps[i].idrLocal = idrLocal[i]; overlaps[i].idr = idr[i].second; } std::filebuf fb; fb.open(args.ofname.c_str(), std::ios::out); std::ostream fout(&fb); fout.precision(15); for (unsigned int i=0; i < idr.size(); ++i) { if (overlaps[i].idr <= args.idrCutoff) { fout<<overlaps[i].chr<<"\t"<< overlaps[i].start1<<"\t"<< overlaps[i].end1<<"\t"<< overlaps[i].rankingMeasure1<<"\t"<< overlaps[i].start2<<"\t"<< overlaps[i].end2<<"\t"<< overlaps[i].rankingMeasure2<<"\t"<< std::fixed<<overlaps[i].idrLocal<<"\t"<< std::fixed<<overlaps[i].idr<<endl; } } fb.close(); fprintf(stderr, "Number of peaks passing IDR cutoff of %f - %d\n", args.idrCutoff, num_peaks_passing_threshold); return 0; } <commit_msg>fixed a bug<commit_after>/***************************************************************************** idr.cpp (c) 2014 - Nikhil R Podduturi J. Michael Cherry Lab, Department of Genetics, Stanford University School of Medicine Licensed under the GNU General Public License 2.0 license. ******************************************************************************/ #include <stdio.h> #include <string> #include <stdlib.h> #include <cerrno> #include <processPeaks.h> #include <ranker.h> #include <idr.h> using namespace std; #define PROGRAM_NAME "IDR" #define PACKAGE_VERSION "0.1" #define PARAMETER_CHECK(param, paramLen, actualLen) (\ strncmp(argv[i], param, min(actualLen, paramLen))== 0) \ && (actualLen == paramLen) void ShowHelp(void); // Utility struct to keep track of final results struct overlap { string chr; CHRPOS start1; CHRPOS end1; double rankingMeasure1; CHRPOS start2; CHRPOS end2; double rankingMeasure2; double idrLocal; double idr; }; struct sort_pred { bool operator()(const std::pair<int, double> &left, const std::pair<int, double> &right) { return left.second < right.second; } }; #define DEFAULT_IDR_CUTOFF 0.025 #define DEFAULT_OFNAME "idrValues.txt" #define DEFAULT_RANKING_MEASURE "signal.value" #define RANKING_MEASURE_INDEX 6 void ShowHelp(void) { fprintf(stderr, "\n"); fprintf(stderr, "Program: IDR (Irreproducible Discovery Rate)\n"); fprintf(stderr, "Version: %s\n", PACKAGE_VERSION); fprintf(stderr, "Contact: Nikhil R Podduturi <[email protected]>\n\n"); fprintf(stderr, "Usage: idr [options] -a <bed> -b <bed> -g <bed>\n\n"); fprintf(stderr, "Options:\n\n"); fprintf(stderr, " -o Output filename (default: idrValues.txt)\n\n"); fprintf(stderr, " -idr IDR cutoff (default: %e)\n\n", DEFAULT_IDR_CUTOFF); fprintf(stderr, " -rank Type of ranking measure (default: %s)\n\n", DEFAULT_RANKING_MEASURE); exit(1); } class Args { public: string bedAFile; string bedBFile; string genomeFile; string ofname; int rankingMeasure; float idrCutoff; Args( int argc, char* argv[] ) { this->ofname = DEFAULT_OFNAME; this->rankingMeasure = RANKING_MEASURE_INDEX; this->idrCutoff = DEFAULT_IDR_CUTOFF; bool haveBedA = false; bool haveBedB = false; bool haveGenome = false; bool haveOutput = false; if(argc <= 1) ShowHelp(); for(int i = 1; i < argc; i++) { int parameterLength = (int)strlen(argv[i]); if((PARAMETER_CHECK("-h", 2, parameterLength)) || (PARAMETER_CHECK("--help", 6, parameterLength))) { ShowHelp(); } } for(int i = 1; i < argc; i++) { int parameterLength = (int)strlen(argv[i]); if(PARAMETER_CHECK("-a", 2, parameterLength)) { if ((i+1) < argc) { haveBedA = true; this->bedAFile = argv[i + 1]; i++; } } else if(PARAMETER_CHECK("-b", 2, parameterLength)) { if ((i+1) < argc) { haveBedB = true; this->bedBFile = argv[i + 1]; i++; } } else if(PARAMETER_CHECK("-o", 2, parameterLength)) { if((i+1) < argc) { haveOutput = true; this->ofname = argv[i + 1]; i++; } } else if(PARAMETER_CHECK("-g", 2, parameterLength)) { if ((i+1) < argc) { haveGenome = true; this->genomeFile = argv[i + 1]; i++; } } else if(PARAMETER_CHECK("-rank", 5, parameterLength)) { if((i+1) < argc) { if (strcmp( argv[i+1], "p.value" ) == 0) rankingMeasure = 7; else if (strcmp( argv[i+1], "q.value" ) == 0) rankingMeasure = 8; i++; } } else if(PARAMETER_CHECK("-idr", 4, parameterLength)) { if((i+1) < argc) { this->idrCutoff = atof(argv[i + 1]); i++; } } else { fprintf(stderr, "*****ERROR: Unrecognized parameter: %s *****\n\n", argv[i]); ShowHelp(); } } // make sure we have both input files if (!haveBedA || !haveBedB || !haveGenome) { fprintf(stderr, "*****ERROR: Need -a, -b and -g files. *****"); ShowHelp(); } }; }; int build_ranks_vector( ProcessPeaks *bc, int rankingMeasure, vector<overlap> &overlaps, vector<float> &ranks_A, vector<float> &ranks_B) { vector<double> merge_A, merge_B, unmatched_merge_A, unmatched_merge_B; vector<unsigned int> tracker; unsigned int start = 0; for (size_t i = 0; i < bc->_peakA->bedList.size(); ++i) { merge_A.push_back(atof(bc->_peakA->bedList[i].fields[rankingMeasure].c_str())); merge_B.push_back(0); while (start < bc->overlap_index_A[i]) { tracker.push_back( bc->overlap_index_B[start] ); double bSigVal = atof(bc->_peakB->bedList[bc->overlap_index_B[start] ].fields[rankingMeasure].c_str()); overlap o; string chr(bc->_peakA->bedList[i].chrom); o.chr = chr; o.start1 = bc->_peakA->bedList[i].start; o.end1 = bc->_peakA->bedList[i].end; o.rankingMeasure1 = merge_A[i]; o.start2 = bc->_peakB->bedList[ bc->overlap_index_B[start] ].start; o.end2 = bc->_peakB->bedList[ bc->overlap_index_B[start] ].end; if (merge_B[i] == 0) { merge_B[i] = bSigVal; o.rankingMeasure2 = merge_B[i]; overlaps.push_back(o); } else { merge_B[i] = double (merge_B[i] + bSigVal)/2.0; o.rankingMeasure2 = merge_B[i]; overlaps.pop_back(); overlaps.push_back(o); } ++start; } } sort(tracker.begin(), tracker.end()); for (unsigned int i = 0; i < bc->_peakB->bedList.size(); ++i) { if(find(tracker.begin(), tracker.end(), i) == tracker.end()) { double bSigVal = atof(bc->_peakB->bedList[i].fields[rankingMeasure].c_str()); merge_A.push_back( 0 ); merge_B.push_back( bSigVal ); } } for (unsigned int i=0; i < merge_A.size(); ++i) { if ( merge_A[i] != 0 && merge_B[i] != 0 ) { unmatched_merge_A.push_back( -merge_A[i] ); unmatched_merge_B.push_back( -merge_B[i] ); } } fprintf(stderr, "Number of overlaps after removing duplicates - %lu\n", unmatched_merge_A.size()); fprintf(stderr, "Ranking overlaps\n"); rank_vec(unmatched_merge_A, ranks_A, "average"); rank_vec(unmatched_merge_B, ranks_B, "average"); fprintf(stderr, " Done\n"); return 0; } int main(int argc, char* argv[]) { Args args = Args(argc, argv); ProcessPeaks *bc = new ProcessPeaks( args.bedAFile, args.bedBFile, args.genomeFile); vector<overlap> overlaps; /* Find the joint peak list, and rank them */ vector<float> ranks_A, ranks_B; build_ranks_vector( bc, args.rankingMeasure, overlaps, ranks_A, ranks_B ); vector< pair<int, double> > idr(ranks_A.size()); fprintf(stderr, "Fit 2-component model - started\n"); em_gaussian(ranks_A, ranks_B, idr); /* Make a copy of the local IDR vector, and then update the 'second' field to store the global IDR value (XXX use decent variable names...) */ vector<double> idrLocal(ranks_A.size()); for(int i=0; i<idr.size(); ++i) { idrLocal[i] = idr[i].second; } sort(idr.begin(), idr.end(), sort_pred()); for(int i=1; i<idr.size(); ++i) { idr[i].second = idr[i].second + idr[i-1].second; } int num_peaks_passing_threshold = 0; for(int j=0; j<ranks_A.size(); ++j) { idr[j].second = idr[j].second/((double)j); if(idr[j].second <= args.idrCutoff) { num_peaks_passing_threshold += 1; } }; sort(idr.begin(), idr.end()); for (unsigned int i=0; i<idr.size(); ++i) { overlaps[i].idrLocal = idrLocal[i]; overlaps[i].idr = idr[i].second; } std::filebuf fb; fb.open(args.ofname.c_str(), std::ios::out); std::ostream fout(&fb); fout.precision(15); for (unsigned int i=0; i < idr.size(); ++i) { if (overlaps[i].idr <= args.idrCutoff) { fout<<overlaps[i].chr<<"\t"<< overlaps[i].start1<<"\t"<< overlaps[i].end1<<"\t"<< overlaps[i].rankingMeasure1<<"\t"<< overlaps[i].start2<<"\t"<< overlaps[i].end2<<"\t"<< overlaps[i].rankingMeasure2<<"\t"<< std::fixed<<overlaps[i].idrLocal<<"\t"<< std::fixed<<overlaps[i].idr<<endl; } } fb.close(); fprintf(stderr, "Number of peaks passing IDR cutoff of %f - %d\n", args.idrCutoff, num_peaks_passing_threshold); return 0; } <|endoftext|>
<commit_before>/* * Copyright 2009 The Android Open Source Project * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkBitmapProcState_opts_SSE2.h" #include "SkBitmapProcState_opts_SSSE3.h" #include "SkBlitMask.h" #include "SkBlitRow.h" #include "SkBlitRect_opts_SSE2.h" #include "SkBlitRow_opts_SSE2.h" #include "SkUtils_opts_SSE2.h" #include "SkUtils.h" /* This file must *not* be compiled with -msse or -msse2, otherwise gcc may generate sse2 even for scalar ops (and thus give an invalid instruction on Pentium3 on the code below). Only files named *_SSE2.cpp in this directory should be compiled with -msse2. */ #ifdef _MSC_VER static inline void getcpuid(int info_type, int info[4]) { __asm { mov eax, [info_type] cpuid mov edi, [info] mov [edi], eax mov [edi+4], ebx mov [edi+8], ecx mov [edi+12], edx } } #else #if defined(__x86_64__) static inline void getcpuid(int info_type, int info[4]) { asm volatile ( "cpuid \n\t" : "=a"(info[0]), "=b"(info[1]), "=c"(info[2]), "=d"(info[3]) : "a"(info_type) ); } #else static inline void getcpuid(int info_type, int info[4]) { // We save and restore ebx, so this code can be compatible with -fPIC asm volatile ( "pushl %%ebx \n\t" "cpuid \n\t" "movl %%ebx, %1 \n\t" "popl %%ebx \n\t" : "=a"(info[0]), "=r"(info[1]), "=c"(info[2]), "=d"(info[3]) : "a"(info_type) ); } #endif #endif #if defined(__x86_64__) || defined(_WIN64) /* All x86_64 machines have SSE2, so don't even bother checking. */ static inline bool hasSSE2() { return true; } #else static inline bool hasSSE2() { int cpu_info[4] = { 0 }; getcpuid(1, cpu_info); return (cpu_info[3] & (1<<26)) != 0; } #endif static inline bool hasSSSE3() { int cpu_info[4] = { 0 }; getcpuid(1, cpu_info); return (cpu_info[2] & 0x200) != 0; } static bool cachedHasSSE2() { static bool gHasSSE2 = hasSSE2(); return gHasSSE2; } static bool cachedHasSSSE3() { static bool gHasSSSE3 = hasSSSE3(); return gHasSSSE3; } void SkBitmapProcState::platformProcs() { if (cachedHasSSSE3()) { #if !defined(SK_BUILD_FOR_ANDROID) // Disable SSSE3 optimization for Android x86 if (fSampleProc32 == S32_opaque_D32_filter_DX) { fSampleProc32 = S32_opaque_D32_filter_DX_SSSE3; } else if (fSampleProc32 == S32_alpha_D32_filter_DX) { fSampleProc32 = S32_alpha_D32_filter_DX_SSSE3; } if (fSampleProc32 == S32_opaque_D32_filter_DXDY) { fSampleProc32 = S32_opaque_D32_filter_DXDY_SSSE3; } else if (fSampleProc32 == S32_alpha_D32_filter_DXDY) { fSampleProc32 = S32_alpha_D32_filter_DXDY_SSSE3; } #endif } else if (cachedHasSSE2()) { if (fSampleProc32 == S32_opaque_D32_filter_DX) { fSampleProc32 = S32_opaque_D32_filter_DX_SSE2; } else if (fSampleProc32 == S32_alpha_D32_filter_DX) { fSampleProc32 = S32_alpha_D32_filter_DX_SSE2; } } if (cachedHasSSSE3() || cachedHasSSE2()) { if (fMatrixProc == ClampX_ClampY_filter_scale) { fMatrixProc = ClampX_ClampY_filter_scale_SSE2; } else if (fMatrixProc == ClampX_ClampY_nofilter_scale) { fMatrixProc = ClampX_ClampY_nofilter_scale_SSE2; } if (fMatrixProc == ClampX_ClampY_filter_affine) { fMatrixProc = ClampX_ClampY_filter_affine_SSE2; } else if (fMatrixProc == ClampX_ClampY_nofilter_affine) { fMatrixProc = ClampX_ClampY_nofilter_affine_SSE2; } } } static SkBlitRow::Proc32 platform_32_procs[] = { NULL, // S32_Opaque, S32_Blend_BlitRow32_SSE2, // S32_Blend, S32A_Opaque_BlitRow32_SSE2, // S32A_Opaque S32A_Blend_BlitRow32_SSE2, // S32A_Blend, }; SkBlitRow::Proc SkBlitRow::PlatformProcs4444(unsigned flags) { return NULL; } SkBlitRow::Proc SkBlitRow::PlatformProcs565(unsigned flags) { return NULL; } SkBlitRow::ColorProc SkBlitRow::PlatformColorProc() { if (cachedHasSSE2()) { return Color32_SSE2; } else { return NULL; } } SkBlitRow::Proc32 SkBlitRow::PlatformProcs32(unsigned flags) { if (cachedHasSSE2()) { return platform_32_procs[flags]; } else { return NULL; } } SkBlitMask::ColorProc SkBlitMask::PlatformColorProcs(SkBitmap::Config dstConfig, SkMask::Format maskFormat, SkColor color) { if (SkMask::kA8_Format != maskFormat) { return NULL; } ColorProc proc = NULL; if (cachedHasSSE2()) { switch (dstConfig) { case SkBitmap::kARGB_8888_Config: // The SSE2 version is not (yet) faster for black, so we check // for that. if (SK_ColorBLACK != color) { proc = SkARGB32_A8_BlitMask_SSE2; } break; default: break; } } return proc; } SkBlitMask::BlitLCD16RowProc SkBlitMask::PlatformBlitRowProcs16(bool isOpaque) { if (cachedHasSSE2()) { if (isOpaque) { return SkBlitLCD16OpaqueRow_SSE2; } else { return SkBlitLCD16Row_SSE2; } } else { return NULL; } } SkBlitMask::RowProc SkBlitMask::PlatformRowProcs(SkBitmap::Config dstConfig, SkMask::Format maskFormat, RowFlags flags) { return NULL; } SkMemset16Proc SkMemset16GetPlatformProc() { if (cachedHasSSE2()) { return sk_memset16_SSE2; } else { return NULL; } } SkMemset32Proc SkMemset32GetPlatformProc() { if (cachedHasSSE2()) { return sk_memset32_SSE2; } else { return NULL; } } SkBlitRow::ColorRectProc PlatformColorRectProcFactory() { if (cachedHasSSE2()) { return ColorRect32_SSE2; } else { return NULL; } } <commit_msg>Use intrinsics instead of inline assembly for detecting CPU ID & SSE2/3 support on 64-bit builds in MS Visual Studio 2010. Original code provided by jianliang79.<commit_after>/* * Copyright 2009 The Android Open Source Project * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkBitmapProcState_opts_SSE2.h" #include "SkBitmapProcState_opts_SSSE3.h" #include "SkBlitMask.h" #include "SkBlitRow.h" #include "SkBlitRect_opts_SSE2.h" #include "SkBlitRow_opts_SSE2.h" #include "SkUtils_opts_SSE2.h" #include "SkUtils.h" #if defined(_MSC_VER) && defined(_WIN64) #include <intrin.h> #endif /* This file must *not* be compiled with -msse or -msse2, otherwise gcc may generate sse2 even for scalar ops (and thus give an invalid instruction on Pentium3 on the code below). Only files named *_SSE2.cpp in this directory should be compiled with -msse2. */ #ifdef _MSC_VER static inline void getcpuid(int info_type, int info[4]) { #if defined(_WIN64) __cpuid(info, info_type); #else __asm { mov eax, [info_type] cpuid mov edi, [info] mov [edi], eax mov [edi+4], ebx mov [edi+8], ecx mov [edi+12], edx } #endif } #else #if defined(__x86_64__) static inline void getcpuid(int info_type, int info[4]) { asm volatile ( "cpuid \n\t" : "=a"(info[0]), "=b"(info[1]), "=c"(info[2]), "=d"(info[3]) : "a"(info_type) ); } #else static inline void getcpuid(int info_type, int info[4]) { // We save and restore ebx, so this code can be compatible with -fPIC asm volatile ( "pushl %%ebx \n\t" "cpuid \n\t" "movl %%ebx, %1 \n\t" "popl %%ebx \n\t" : "=a"(info[0]), "=r"(info[1]), "=c"(info[2]), "=d"(info[3]) : "a"(info_type) ); } #endif #endif #if defined(__x86_64__) || defined(_WIN64) /* All x86_64 machines have SSE2, so don't even bother checking. */ static inline bool hasSSE2() { return true; } #else static inline bool hasSSE2() { int cpu_info[4] = { 0 }; getcpuid(1, cpu_info); return (cpu_info[3] & (1<<26)) != 0; } #endif static inline bool hasSSSE3() { int cpu_info[4] = { 0 }; getcpuid(1, cpu_info); return (cpu_info[2] & 0x200) != 0; } static bool cachedHasSSE2() { static bool gHasSSE2 = hasSSE2(); return gHasSSE2; } static bool cachedHasSSSE3() { static bool gHasSSSE3 = hasSSSE3(); return gHasSSSE3; } void SkBitmapProcState::platformProcs() { if (cachedHasSSSE3()) { #if !defined(SK_BUILD_FOR_ANDROID) // Disable SSSE3 optimization for Android x86 if (fSampleProc32 == S32_opaque_D32_filter_DX) { fSampleProc32 = S32_opaque_D32_filter_DX_SSSE3; } else if (fSampleProc32 == S32_alpha_D32_filter_DX) { fSampleProc32 = S32_alpha_D32_filter_DX_SSSE3; } if (fSampleProc32 == S32_opaque_D32_filter_DXDY) { fSampleProc32 = S32_opaque_D32_filter_DXDY_SSSE3; } else if (fSampleProc32 == S32_alpha_D32_filter_DXDY) { fSampleProc32 = S32_alpha_D32_filter_DXDY_SSSE3; } #endif } else if (cachedHasSSE2()) { if (fSampleProc32 == S32_opaque_D32_filter_DX) { fSampleProc32 = S32_opaque_D32_filter_DX_SSE2; } else if (fSampleProc32 == S32_alpha_D32_filter_DX) { fSampleProc32 = S32_alpha_D32_filter_DX_SSE2; } } if (cachedHasSSSE3() || cachedHasSSE2()) { if (fMatrixProc == ClampX_ClampY_filter_scale) { fMatrixProc = ClampX_ClampY_filter_scale_SSE2; } else if (fMatrixProc == ClampX_ClampY_nofilter_scale) { fMatrixProc = ClampX_ClampY_nofilter_scale_SSE2; } if (fMatrixProc == ClampX_ClampY_filter_affine) { fMatrixProc = ClampX_ClampY_filter_affine_SSE2; } else if (fMatrixProc == ClampX_ClampY_nofilter_affine) { fMatrixProc = ClampX_ClampY_nofilter_affine_SSE2; } } } static SkBlitRow::Proc32 platform_32_procs[] = { NULL, // S32_Opaque, S32_Blend_BlitRow32_SSE2, // S32_Blend, S32A_Opaque_BlitRow32_SSE2, // S32A_Opaque S32A_Blend_BlitRow32_SSE2, // S32A_Blend, }; SkBlitRow::Proc SkBlitRow::PlatformProcs4444(unsigned flags) { return NULL; } SkBlitRow::Proc SkBlitRow::PlatformProcs565(unsigned flags) { return NULL; } SkBlitRow::ColorProc SkBlitRow::PlatformColorProc() { if (cachedHasSSE2()) { return Color32_SSE2; } else { return NULL; } } SkBlitRow::Proc32 SkBlitRow::PlatformProcs32(unsigned flags) { if (cachedHasSSE2()) { return platform_32_procs[flags]; } else { return NULL; } } SkBlitMask::ColorProc SkBlitMask::PlatformColorProcs(SkBitmap::Config dstConfig, SkMask::Format maskFormat, SkColor color) { if (SkMask::kA8_Format != maskFormat) { return NULL; } ColorProc proc = NULL; if (cachedHasSSE2()) { switch (dstConfig) { case SkBitmap::kARGB_8888_Config: // The SSE2 version is not (yet) faster for black, so we check // for that. if (SK_ColorBLACK != color) { proc = SkARGB32_A8_BlitMask_SSE2; } break; default: break; } } return proc; } SkBlitMask::BlitLCD16RowProc SkBlitMask::PlatformBlitRowProcs16(bool isOpaque) { if (cachedHasSSE2()) { if (isOpaque) { return SkBlitLCD16OpaqueRow_SSE2; } else { return SkBlitLCD16Row_SSE2; } } else { return NULL; } } SkBlitMask::RowProc SkBlitMask::PlatformRowProcs(SkBitmap::Config dstConfig, SkMask::Format maskFormat, RowFlags flags) { return NULL; } SkMemset16Proc SkMemset16GetPlatformProc() { if (cachedHasSSE2()) { return sk_memset16_SSE2; } else { return NULL; } } SkMemset32Proc SkMemset32GetPlatformProc() { if (cachedHasSSE2()) { return sk_memset32_SSE2; } else { return NULL; } } SkBlitRow::ColorRectProc PlatformColorRectProcFactory() { if (cachedHasSSE2()) { return ColorRect32_SSE2; } else { return NULL; } } <|endoftext|>
<commit_before>/* EEPROM.cpp - esp8266 EEPROM emulation Copyright (c) 2014 Ivan Grokhotkov. All rights reserved. This file is part of the esp8266 core for Arduino environment. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "Arduino.h" #include "EEPROM.h" extern "C" { #include "c_types.h" #include "ets_sys.h" #include "os_type.h" #include "osapi.h" #include "spi_flash.h" } #define CONFIG_START_SECTOR 0x7b #define CONFIG_SECTOR (CONFIG_START_SECTOR + 0) #define CONFIG_ADDR (SPI_FLASH_SEC_SIZE * CONFIG_SECTOR) EEPROMClass::EEPROMClass() : _data(0), _size(0), _dirty(false) { } void EEPROMClass::begin(size_t size) { if (size < 0) return; if (size > SPI_FLASH_SEC_SIZE) size = SPI_FLASH_SEC_SIZE; _data = new uint8_t[size]; _size = size; noInterrupts(); spi_flash_read(CONFIG_ADDR, reinterpret_cast<uint32_t*>(_data), _size); interrupts(); } void EEPROMClass::end() { if (!_size) return; commit(); delete[] _data; _data = 0; _size = 0; } uint8_t EEPROMClass::read(int address) { if (address < 0 || (size_t)address >= _size) return 0; return _data[address]; } void EEPROMClass::write(int address, uint8_t value) { if (address < 0 || (size_t)address >= _size) return; _data[address] = value; _dirty = true; } bool EEPROMClass::commit() { bool ret = false; if (!_size) return false; if(!_dirty) return true; noInterrupts(); if(spi_flash_erase_sector(CONFIG_SECTOR) == SPI_FLASH_RESULT_OK) { if(spi_flash_write(CONFIG_ADDR, reinterpret_cast<uint32_t*>(_data), _size) == SPI_FLASH_RESULT_OK) { _dirty = false; ret = true; } } interrupts(); return ret; } uint8_t * EEPROMClass::getDataPtr() { _dirty = true; return &_data[0]; } EEPROMClass EEPROM; <commit_msg>fix possible null ptr in EEPROM.cpp<commit_after>/* EEPROM.cpp - esp8266 EEPROM emulation Copyright (c) 2014 Ivan Grokhotkov. All rights reserved. This file is part of the esp8266 core for Arduino environment. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "Arduino.h" #include "EEPROM.h" extern "C" { #include "c_types.h" #include "ets_sys.h" #include "os_type.h" #include "osapi.h" #include "spi_flash.h" } #define CONFIG_START_SECTOR 0x7b #define CONFIG_SECTOR (CONFIG_START_SECTOR + 0) #define CONFIG_ADDR (SPI_FLASH_SEC_SIZE * CONFIG_SECTOR) EEPROMClass::EEPROMClass() : _data(0), _size(0), _dirty(false) { } void EEPROMClass::begin(size_t size) { if (size <= 0) return; if (size > SPI_FLASH_SEC_SIZE) size = SPI_FLASH_SEC_SIZE; _data = new uint8_t[size]; _size = size; noInterrupts(); spi_flash_read(CONFIG_ADDR, reinterpret_cast<uint32_t*>(_data), _size); interrupts(); } void EEPROMClass::end() { if (!_size) return; commit(); if(_data) { delete[] _data; } _data = 0; _size = 0; } uint8_t EEPROMClass::read(int address) { if (address < 0 || (size_t)address >= _size) return 0; if(!_data) return 0; return _data[address]; } void EEPROMClass::write(int address, uint8_t value) { if (address < 0 || (size_t)address >= _size) return; if(!_data) return; _data[address] = value; _dirty = true; } bool EEPROMClass::commit() { bool ret = false; if (!_size) return false; if(!_dirty) return true; if(!_data) return false; noInterrupts(); if(spi_flash_erase_sector(CONFIG_SECTOR) == SPI_FLASH_RESULT_OK) { if(spi_flash_write(CONFIG_ADDR, reinterpret_cast<uint32_t*>(_data), _size) == SPI_FLASH_RESULT_OK) { _dirty = false; ret = true; } } interrupts(); return ret; } uint8_t * EEPROMClass::getDataPtr() { _dirty = true; return &_data[0]; } EEPROMClass EEPROM; <|endoftext|>
<commit_before>/* * Copyright (c) 2015 Nathan Osman * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #include <QCoreApplication> #include <QDir> #if defined(Q_OS_UNIX) # include <sys/stat.h> #endif #include "qlocalfile.h" #include "qlocalfile_p.h" QLocalFilePrivate::QLocalFilePrivate(QLocalFile *localFile) : QObject(localFile), q(localFile) { // Store the file in the user's home directory and set the filename to the // name of the application with a "." prepended q->setFileName(QDir::home().absoluteFilePath("." + QCoreApplication::applicationName())); } bool QLocalFilePrivate::setPermission() { #if defined(Q_OS_UNIX) return chmod(q->fileName().toUtf8().constData(), S_IRUSR | S_IWUSR) == 0; #else // Unsupported platform, so setPermission() must fail return false; #endif } bool QLocalFilePrivate::setHidden() { #if defined(Q_OS_UNIX) // On Unix, anything beginning with a "." is hidden return true; #else // Unsupported platform, so setHidden() must fail return false; #endif } QLocalFile::QLocalFile(QObject *parent) : QFile(parent), d(new QLocalFilePrivate(this)) { } bool QLocalFile::open() { return QFile::open(QIODevice::WriteOnly) && d->setPermission() && d->setHidden(); } <commit_msg>Implemented setHidden() on Windows.<commit_after>/* * Copyright (c) 2015 Nathan Osman * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #include <QCoreApplication> #include <QDir> #if defined(Q_OS_UNIX) # include <sys/stat.h> #elif defined(Q_OS_WIN) # include <windows.h> #endif #include "qlocalfile.h" #include "qlocalfile_p.h" QLocalFilePrivate::QLocalFilePrivate(QLocalFile *localFile) : QObject(localFile), q(localFile) { // Store the file in the user's home directory and set the filename to the // name of the application with a "." prepended q->setFileName(QDir::home().absoluteFilePath("." + QCoreApplication::applicationName())); } bool QLocalFilePrivate::setPermission() { #if defined(Q_OS_UNIX) return chmod(q->fileName().toUtf8().constData(), S_IRUSR | S_IWUSR) == 0; #else // Unsupported platform, so setPermission() must fail return false; #endif } bool QLocalFilePrivate::setHidden() { #if defined(Q_OS_UNIX) // On Unix, anything beginning with a "." is hidden return true; #elif defined(Q_OS_WIN) return SetFileAttributesW((LPCWSTR)q->fileName().utf16(), FILE_ATTRIBUTE_HIDDEN) == 0; #else // Unsupported platform, so setHidden() must fail return false; #endif } QLocalFile::QLocalFile(QObject *parent) : QFile(parent), d(new QLocalFilePrivate(this)) { } bool QLocalFile::open() { return QFile::open(QIODevice::WriteOnly) && d->setPermission() && d->setHidden(); } <|endoftext|>
<commit_before>/* * W.J. van der Laan 2011-2012 */ #include "bitcoingui.h" #include "clientmodel.h" #include "walletmodel.h" #include "optionsmodel.h" #include "guiutil.h" #include "guiconstants.h" #include "init.h" #include "ui_interface.h" #include "qtipcserver.h" #include <QApplication> #include <QMessageBox> #include <QTextCodec> #include <QLocale> #include <QTranslator> #include <QSplashScreen> #include <QLibraryInfo> #if defined(BITCOIN_NEED_QT_PLUGINS) && !defined(_BITCOIN_QT_PLUGINS_INCLUDED) #define _BITCOIN_QT_PLUGINS_INCLUDED #define __INSURE__ #include <QtPlugin> Q_IMPORT_PLUGIN(qcncodecs) Q_IMPORT_PLUGIN(qjpcodecs) Q_IMPORT_PLUGIN(qtwcodecs) Q_IMPORT_PLUGIN(qkrcodecs) Q_IMPORT_PLUGIN(qtaccessiblewidgets) #endif // Need a global reference for the notifications to find the GUI static BitcoinGUI *guiref; static QSplashScreen *splashref; static void ThreadSafeMessageBox(const std::string& message, const std::string& caption, int style) { // Message from network thread if(guiref) { bool modal = (style & CClientUIInterface::MODAL); // in case of modal message, use blocking connection to wait for user to click OK QMetaObject::invokeMethod(guiref, "error", modal ? GUIUtil::blockingGUIThreadConnection() : Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(caption)), Q_ARG(QString, QString::fromStdString(message)), Q_ARG(bool, modal)); } else { printf("%s: %s\n", caption.c_str(), message.c_str()); fprintf(stderr, "%s: %s\n", caption.c_str(), message.c_str()); } } static bool ThreadSafeAskFee(int64 nFeeRequired, const std::string& strCaption) { if(!guiref) return false; if(nFeeRequired < MIN_TX_FEE || nFeeRequired <= nTransactionFee || fDaemon) return true; bool payFee = false; QMetaObject::invokeMethod(guiref, "askFee", GUIUtil::blockingGUIThreadConnection(), Q_ARG(qint64, nFeeRequired), Q_ARG(bool*, &payFee)); return payFee; } static void ThreadSafeHandleURI(const std::string& strURI) { if(!guiref) return; QMetaObject::invokeMethod(guiref, "handleURI", GUIUtil::blockingGUIThreadConnection(), Q_ARG(QString, QString::fromStdString(strURI))); } static void InitMessage(const std::string &message) { if(splashref) { splashref->showMessage(QString::fromStdString(message), Qt::AlignBottom|Qt::AlignHCenter, QColor(255,255,200)); QApplication::instance()->processEvents(); } } static void QueueShutdown() { QMetaObject::invokeMethod(QCoreApplication::instance(), "quit", Qt::QueuedConnection); } /* Translate string to current locale using Qt. */ static std::string Translate(const char* psz) { return QCoreApplication::translate("bitcoin-core", psz).toStdString(); } /* Handle runaway exceptions. Shows a message box with the problem and quits the program. */ static void handleRunawayException(std::exception *e) { PrintExceptionContinue(e, "Runaway exception"); QMessageBox::critical(0, "Runaway exception", BitcoinGUI::tr("A fatal error occurred. Sembros can no longer continue safely and will quit.") + QString("\n\n") + QString::fromStdString(strMiscWarning)); exit(1); } #ifndef BITCOIN_QT_TEST int main(int argc, char *argv[]) { // Do this early as we don't want to bother initializing if we are just calling IPC ipcScanRelay(argc, argv); // Internal string conversion is all UTF-8 QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8")); QTextCodec::setCodecForCStrings(QTextCodec::codecForTr()); Q_INIT_RESOURCE(bitcoin); QApplication app(argc, argv); // Install global event filter that makes sure that long tooltips can be word-wrapped app.installEventFilter(new GUIUtil::ToolTipToRichTextFilter(TOOLTIP_WRAP_THRESHOLD, &app)); // Command-line options take precedence: ParseParameters(argc, argv); // ... then bitcoin.conf: if (!boost::filesystem::is_directory(GetDataDir(false))) { // This message can not be translated, as translation is not initialized yet // (which not yet possible because lang=XX can be overridden in bitcoin.conf in the data directory) QMessageBox::critical(0, "Sembros", QString("Error: Specified data directory \"%1\" does not exist.").arg(QString::fromStdString(mapArgs["-datadir"]))); return 1; } ReadConfigFile(mapArgs, mapMultiArgs); // Application identification (must be set before OptionsModel is initialized, // as it is used to locate QSettings) app.setOrganizationName("Sembros"); app.setOrganizationDomain("sembrodevelopment.com"); if(GetBoolArg("-testnet")) // Separate UI settings for testnet app.setApplicationName("Sembros-Qt-testnet"); else app.setApplicationName("Sembros-Qt"); // ... then GUI settings: OptionsModel optionsModel; // Get desired locale (e.g. "de_DE") from command line or use system locale QString lang_territory = QString::fromStdString(GetArg("-lang", QLocale::system().name().toStdString())); QString lang = lang_territory; // Convert to "de" only by truncating "_DE" lang.truncate(lang_territory.lastIndexOf('_')); QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator; // Load language files for configured locale: // - First load the translator for the base language, without territory // - Then load the more specific locale translator // Load e.g. qt_de.qm if (qtTranslatorBase.load("qt_" + lang, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) app.installTranslator(&qtTranslatorBase); // Load e.g. qt_de_DE.qm if (qtTranslator.load("qt_" + lang_territory, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) app.installTranslator(&qtTranslator); // Load e.g. bitcoin_de.qm (shortcut "de" needs to be defined in bitcoin.qrc) if (translatorBase.load(lang, ":/translations/")) app.installTranslator(&translatorBase); // Load e.g. bitcoin_de_DE.qm (shortcut "de_DE" needs to be defined in bitcoin.qrc) if (translator.load(lang_territory, ":/translations/")) app.installTranslator(&translator); // Subscribe to global signals from core uiInterface.ThreadSafeMessageBox.connect(ThreadSafeMessageBox); uiInterface.ThreadSafeAskFee.connect(ThreadSafeAskFee); uiInterface.ThreadSafeHandleURI.connect(ThreadSafeHandleURI); uiInterface.InitMessage.connect(InitMessage); uiInterface.QueueShutdown.connect(QueueShutdown); uiInterface.Translate.connect(Translate); // Show help message immediately after parsing command-line options (for "-lang") and setting locale, // but before showing splash screen. if (mapArgs.count("-?") || mapArgs.count("--help")) { GUIUtil::HelpMessageBox help; help.showOrPrint(); return 1; } QSplashScreen splash(QPixmap(":/images/splash"), 0); if (GetBoolArg("-splash", true) && !GetBoolArg("-min")) { splash.show(); splash.setAutoFillBackground(true); splashref = &splash; } app.processEvents(); app.setQuitOnLastWindowClosed(false); try { // Regenerate startup link, to fix links to old versions if (GUIUtil::GetStartOnSystemStartup()) GUIUtil::SetStartOnSystemStartup(true); BitcoinGUI window; guiref = &window; if(AppInit2()) { { // Put this in a block, so that the Model objects are cleaned up before // calling Shutdown(). optionsModel.Upgrade(); // Must be done after AppInit2 if (splashref) splash.finish(&window); ClientModel clientModel(&optionsModel); WalletModel walletModel(pwalletMain, &optionsModel); window.setClientModel(&clientModel); window.setWalletModel(&walletModel); // If -min option passed, start window minimized. if(GetBoolArg("-min")) { window.showMinimized(); } else { window.show(); } // Place this here as guiref has to be defined if we don't want to lose URIs ipcInit(argc, argv); app.exec(); window.hide(); window.setClientModel(0); window.setWalletModel(0); guiref = 0; } // Shutdown the core and its threads, but don't exit Bitcoin-Qt here Shutdown(NULL); } else { return 1; } } catch (std::exception& e) { handleRunawayException(&e); } catch (...) { handleRunawayException(NULL); } return 0; } #endif // BITCOIN_QT_TEST <commit_msg>update for qt5<commit_after>/* * W.J. van der Laan 2011-2012 */ #include "bitcoingui.h" #include "clientmodel.h" #include "walletmodel.h" #include "optionsmodel.h" #include "guiutil.h" #include "guiconstants.h" #include "init.h" #include "ui_interface.h" #include "qtipcserver.h" #include <QApplication> #include <QMessageBox> #include <QTextCodec> #include <QLocale> #include <QTranslator> #include <QSplashScreen> #include <QLibraryInfo> #if defined(BITCOIN_NEED_QT_PLUGINS) && !defined(_BITCOIN_QT_PLUGINS_INCLUDED) #define _BITCOIN_QT_PLUGINS_INCLUDED #define __INSURE__ #include <QtPlugin> Q_IMPORT_PLUGIN(qcncodecs) Q_IMPORT_PLUGIN(qjpcodecs) Q_IMPORT_PLUGIN(qtwcodecs) Q_IMPORT_PLUGIN(qkrcodecs) Q_IMPORT_PLUGIN(qtaccessiblewidgets) #endif // Need a global reference for the notifications to find the GUI static BitcoinGUI *guiref; static QSplashScreen *splashref; static void ThreadSafeMessageBox(const std::string& message, const std::string& caption, int style) { // Message from network thread if(guiref) { bool modal = (style & CClientUIInterface::MODAL); // in case of modal message, use blocking connection to wait for user to click OK QMetaObject::invokeMethod(guiref, "error", modal ? GUIUtil::blockingGUIThreadConnection() : Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(caption)), Q_ARG(QString, QString::fromStdString(message)), Q_ARG(bool, modal)); } else { printf("%s: %s\n", caption.c_str(), message.c_str()); fprintf(stderr, "%s: %s\n", caption.c_str(), message.c_str()); } } static bool ThreadSafeAskFee(int64 nFeeRequired, const std::string& strCaption) { if(!guiref) return false; if(nFeeRequired < MIN_TX_FEE || nFeeRequired <= nTransactionFee || fDaemon) return true; bool payFee = false; QMetaObject::invokeMethod(guiref, "askFee", GUIUtil::blockingGUIThreadConnection(), Q_ARG(qint64, nFeeRequired), Q_ARG(bool*, &payFee)); return payFee; } static void ThreadSafeHandleURI(const std::string& strURI) { if(!guiref) return; QMetaObject::invokeMethod(guiref, "handleURI", GUIUtil::blockingGUIThreadConnection(), Q_ARG(QString, QString::fromStdString(strURI))); } static void InitMessage(const std::string &message) { if(splashref) { splashref->showMessage(QString::fromStdString(message), Qt::AlignBottom|Qt::AlignHCenter, QColor(255,255,200)); QApplication::instance()->processEvents(); } } static void QueueShutdown() { QMetaObject::invokeMethod(QCoreApplication::instance(), "quit", Qt::QueuedConnection); } /* Translate string to current locale using Qt. */ static std::string Translate(const char* psz) { return QCoreApplication::translate("bitcoin-core", psz).toStdString(); } /* Handle runaway exceptions. Shows a message box with the problem and quits the program. */ static void handleRunawayException(std::exception *e) { PrintExceptionContinue(e, "Runaway exception"); QMessageBox::critical(0, "Runaway exception", BitcoinGUI::tr("A fatal error occurred. Sembros can no longer continue safely and will quit.") + QString("\n\n") + QString::fromStdString(strMiscWarning)); exit(1); } #ifndef BITCOIN_QT_TEST int main(int argc, char *argv[]) { // Do this early as we don't want to bother initializing if we are just calling IPC ipcScanRelay(argc, argv); Q_INIT_RESOURCE(bitcoin); QApplication app(argc, argv); // Install global event filter that makes sure that long tooltips can be word-wrapped app.installEventFilter(new GUIUtil::ToolTipToRichTextFilter(TOOLTIP_WRAP_THRESHOLD, &app)); // Command-line options take precedence: ParseParameters(argc, argv); // ... then bitcoin.conf: if (!boost::filesystem::is_directory(GetDataDir(false))) { // This message can not be translated, as translation is not initialized yet // (which not yet possible because lang=XX can be overridden in bitcoin.conf in the data directory) QMessageBox::critical(0, "Sembros", QString("Error: Specified data directory \"%1\" does not exist.").arg(QString::fromStdString(mapArgs["-datadir"]))); return 1; } ReadConfigFile(mapArgs, mapMultiArgs); // Application identification (must be set before OptionsModel is initialized, // as it is used to locate QSettings) app.setOrganizationName("Sembros"); app.setOrganizationDomain("sembrodevelopment.com"); if(GetBoolArg("-testnet")) // Separate UI settings for testnet app.setApplicationName("Sembros-Qt-testnet"); else app.setApplicationName("Sembros-Qt"); // ... then GUI settings: OptionsModel optionsModel; // Get desired locale (e.g. "de_DE") from command line or use system locale QString lang_territory = QString::fromStdString(GetArg("-lang", QLocale::system().name().toStdString())); QString lang = lang_territory; // Convert to "de" only by truncating "_DE" lang.truncate(lang_territory.lastIndexOf('_')); QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator; // Load language files for configured locale: // - First load the translator for the base language, without territory // - Then load the more specific locale translator // Load e.g. qt_de.qm if (qtTranslatorBase.load("qt_" + lang, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) app.installTranslator(&qtTranslatorBase); // Load e.g. qt_de_DE.qm if (qtTranslator.load("qt_" + lang_territory, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) app.installTranslator(&qtTranslator); // Load e.g. bitcoin_de.qm (shortcut "de" needs to be defined in bitcoin.qrc) if (translatorBase.load(lang, ":/translations/")) app.installTranslator(&translatorBase); // Load e.g. bitcoin_de_DE.qm (shortcut "de_DE" needs to be defined in bitcoin.qrc) if (translator.load(lang_territory, ":/translations/")) app.installTranslator(&translator); // Subscribe to global signals from core uiInterface.ThreadSafeMessageBox.connect(ThreadSafeMessageBox); uiInterface.ThreadSafeAskFee.connect(ThreadSafeAskFee); uiInterface.ThreadSafeHandleURI.connect(ThreadSafeHandleURI); uiInterface.InitMessage.connect(InitMessage); uiInterface.QueueShutdown.connect(QueueShutdown); uiInterface.Translate.connect(Translate); // Show help message immediately after parsing command-line options (for "-lang") and setting locale, // but before showing splash screen. if (mapArgs.count("-?") || mapArgs.count("--help")) { GUIUtil::HelpMessageBox help; help.showOrPrint(); return 1; } QSplashScreen splash(QPixmap(":/images/splash"), 0); if (GetBoolArg("-splash", true) && !GetBoolArg("-min")) { splash.show(); splash.setAutoFillBackground(true); splashref = &splash; } app.processEvents(); app.setQuitOnLastWindowClosed(false); try { // Regenerate startup link, to fix links to old versions if (GUIUtil::GetStartOnSystemStartup()) GUIUtil::SetStartOnSystemStartup(true); BitcoinGUI window; guiref = &window; if(AppInit2()) { { // Put this in a block, so that the Model objects are cleaned up before // calling Shutdown(). optionsModel.Upgrade(); // Must be done after AppInit2 if (splashref) splash.finish(&window); ClientModel clientModel(&optionsModel); WalletModel walletModel(pwalletMain, &optionsModel); window.setClientModel(&clientModel); window.setWalletModel(&walletModel); // If -min option passed, start window minimized. if(GetBoolArg("-min")) { window.showMinimized(); } else { window.show(); } // Place this here as guiref has to be defined if we don't want to lose URIs ipcInit(argc, argv); app.exec(); window.hide(); window.setClientModel(0); window.setWalletModel(0); guiref = 0; } // Shutdown the core and its threads, but don't exit Bitcoin-Qt here Shutdown(NULL); } else { return 1; } } catch (std::exception& e) { handleRunawayException(&e); } catch (...) { handleRunawayException(NULL); } return 0; } #endif // BITCOIN_QT_TEST <|endoftext|>
<commit_before>// @(#)root/io:$Id$ // Author: Elvin Sindrilaru 19/05/2011 /************************************************************************* * Copyright (C) 1995-2011, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #include "TFilePrefetch.h" #include "TTimeStamp.h" #include "TVirtualPerfStats.h" #include "TVirtualMonitoring.h" #include <iostream> #include <string> #include <sstream> #include <cstdio> #include <cstdlib> #include <cctype> static const int kMAX_READ_SIZE = 2; //maximum size of the read list of blocks inline int xtod(char c) { return (c>='0' && c<='9') ? c-'0' : ((c>='A' && c<='F') ? c-'A'+10 : ((c>='a' && c<='f') ? c-'a'+10 : 0)); } using namespace std; ClassImp(TFilePrefetch) //____________________________________________________________________________________________ TFilePrefetch::TFilePrefetch(TFile* file) { // Constructor. fConsumer = 0; fFile = file; fPendingBlocks = new TList(); fReadBlocks = new TList(); fMutexReadList = new TMutex(); fMutexPendingList = new TMutex(); fNewBlockAdded = new TCondition(0); fReadBlockAdded = new TCondition(0); fCondNextFile = new TCondition(0); fSemMasterWorker = new TSemaphore(0); fSemWorkerMaster = new TSemaphore(0); } //____________________________________________________________________________________________ TFilePrefetch::~TFilePrefetch() { // Destructor. //killing consumer thread fSemMasterWorker->Post(); TMutex *mutexCond = fNewBlockAdded->GetMutex(); while (fSemWorkerMaster->Wait(10) != 0) { mutexCond->Lock(); fNewBlockAdded->Signal(); mutexCond->UnLock(); } fConsumer->Join(); SafeDelete(fConsumer); SafeDelete(fPendingBlocks); SafeDelete(fReadBlocks); SafeDelete(fMutexReadList); SafeDelete(fMutexPendingList); SafeDelete(fNewBlockAdded); SafeDelete(fReadBlockAdded); SafeDelete(fCondNextFile); SafeDelete(fSemMasterWorker); SafeDelete(fSemWorkerMaster); } //____________________________________________________________________________________________ void TFilePrefetch::ReadAsync(TFPBlock* block, Bool_t &inCache) { // Read one block and insert it in prefetchBuffers list. char* path = 0; if (CheckBlockInCache(path, block)){ block->SetBuffer(GetBlockFromCache(path, block->GetFullSize())); inCache = kTRUE; } else{ fFile->ReadBuffers(block->GetBuffer(), block->GetPos(), block->GetLen(), block->GetNoElem()); if (fFile->GetArchive()){ for (Int_t i = 0; i < block->GetNoElem(); i++) block->SetPos(i, block->GetPos(i) - fFile->GetArchiveOffset()); } inCache =kFALSE; } delete[] path; } //____________________________________________________________________________________________ void TFilePrefetch::ReadListOfBlocks() { // Get blocks specified in prefetchBlocks. Bool_t inCache = kFALSE; TFPBlock* block = 0; while((block = GetPendingBlock())){ ReadAsync(block, inCache); AddReadBlock(block); if (!inCache) SaveBlockInCache(block); } } //____________________________________________________________________________________________ Bool_t TFilePrefetch::BinarySearchReadList(TFPBlock* blockObj, Long64_t offset, Int_t len, Int_t* index) { // Search for a requested element in a block and return the index. Int_t first = 0, last = -1, mid = -1; last = (Int_t) blockObj->GetNoElem()-1; while (first <= last){ mid = first + (last - first) / 2; if ((offset >= blockObj->GetPos(mid) && offset <= (blockObj->GetPos(mid) + blockObj->GetLen(mid)) && ( (offset + len) <= blockObj->GetPos(mid) + blockObj->GetLen(mid)))){ *index = mid; return true; } else if (blockObj->GetPos(mid) < offset){ first = mid + 1; } else{ last = mid - 1; } } return false; } //____________________________________________________________________________________________ Long64_t TFilePrefetch::GetWaitTime() { // Return the time spent wating for buffer to be read in microseconds. return Long64_t(fWaitTime.RealTime()*1.e+6); } //____________________________________________________________________________________________ Bool_t TFilePrefetch::ReadBuffer(char* buf, Long64_t offset, Int_t len) { // Return a prefetched element. Bool_t found = false; TFPBlock* blockObj = 0; TMutex *mutexBlocks = fMutexReadList; Int_t index = -1; while (1){ mutexBlocks->Lock(); TIter iter(fReadBlocks); while ((blockObj = (TFPBlock*) iter.Next())){ index = -1; if (BinarySearchReadList(blockObj, offset, len, &index)){ found = true; break; } } if (found) break; else{ mutexBlocks->UnLock(); fWaitTime.Start(kFALSE); fReadBlockAdded->Wait(); //wait for a new block to be added fWaitTime.Stop(); } } if (found){ char *pBuff = blockObj->GetPtrToPiece(index); pBuff += (offset - blockObj->GetPos(index)); memcpy(buf, pBuff, len); } mutexBlocks->UnLock(); return found; } //____________________________________________________________________________________________ void TFilePrefetch::ReadBlock(Long64_t* offset, Int_t* len, Int_t nblock) { // Create a TFPBlock object or recycle one and add it to the prefetchBlocks list. TFPBlock* block = CreateBlockObj(offset, len, nblock); AddPendingBlock(block); } //____________________________________________________________________________________________ void TFilePrefetch::AddPendingBlock(TFPBlock* block) { // Safe method to add a block to the pendingList. TMutex *mutexBlocks = fMutexPendingList; TMutex *mutexCond = fNewBlockAdded->GetMutex(); mutexBlocks->Lock(); fPendingBlocks->Add(block); mutexBlocks->UnLock(); mutexCond->Lock(); fNewBlockAdded->Signal(); mutexCond->UnLock(); } //____________________________________________________________________________________________ TFPBlock* TFilePrefetch::GetPendingBlock() { // Safe method to remove a block from the pendingList. TFPBlock* block = 0; TMutex *mutex = fMutexPendingList; mutex->Lock(); if (fPendingBlocks->GetSize()){ block = (TFPBlock*)fPendingBlocks->First(); block = (TFPBlock*)fPendingBlocks->Remove(block); } mutex->UnLock(); return block; } //____________________________________________________________________________________________ void TFilePrefetch::AddReadBlock(TFPBlock* block) { // Safe method to add a block to the readList. TMutex *mutexCond = fReadBlockAdded->GetMutex(); TMutex *mutex = fMutexReadList; mutex->Lock(); if (fReadBlocks->GetSize() >= kMAX_READ_SIZE){ TFPBlock* movedBlock = (TFPBlock*) fReadBlocks->First(); movedBlock = (TFPBlock*)fReadBlocks->Remove(movedBlock); delete movedBlock; movedBlock = 0; } fReadBlocks->Add(block); mutex->UnLock(); //signal the addition of a new block mutexCond->Lock(); fReadBlockAdded->Signal(); mutexCond->UnLock(); } //____________________________________________________________________________________________ TFPBlock* TFilePrefetch::CreateBlockObj(Long64_t* offset, Int_t* len, Int_t noblock) { // Create a new block or recycle an old one. TFPBlock* blockObj = 0; TMutex *mutex = fMutexReadList; mutex->Lock(); if (fReadBlocks->GetSize() >= kMAX_READ_SIZE){ blockObj = static_cast<TFPBlock*>(fReadBlocks->First()); fReadBlocks->Remove(blockObj); mutex->UnLock(); blockObj->ReallocBlock(offset, len, noblock); } else{ mutex->UnLock(); blockObj = new TFPBlock(offset, len, noblock); } return blockObj; } //____________________________________________________________________________________________ TThread* TFilePrefetch::GetThread() const { // Return reference to the consumer thread. return fConsumer; } //____________________________________________________________________________________________ void TFilePrefetch::SetFile(TFile *file) { // Change the file fFile = file; } //____________________________________________________________________________________________ Int_t TFilePrefetch::ThreadStart() { // Used to start the consumer thread. int rc; fConsumer= new TThread((TThread::VoidRtnFunc_t) ThreadProc, (void*) this); rc = fConsumer->Run(); return rc; } //____________________________________________________________________________________________ TThread::VoidRtnFunc_t TFilePrefetch::ThreadProc(void* arg) { // Execution loop of the consumer thread. TFilePrefetch* pClass = (TFilePrefetch*) arg; TMutex *mutex = pClass->fCondNextFile->GetMutex(); pClass->fNewBlockAdded->Wait(); while(pClass->fSemMasterWorker->TryWait() == 1) { pClass->ReadListOfBlocks(); //need to signal TChain that we finished work //in the previous file, before we move on mutex->Lock(); pClass->fCondNextFile->Signal(); mutex->UnLock(); pClass->fNewBlockAdded->Wait(); } pClass->fSemWorkerMaster->Post(); return (TThread::VoidRtnFunc_t) 1; } //########################################### CACHING PART ############################################################### //____________________________________________________________________________________________ Int_t TFilePrefetch::SumHex(const char *hex) { // Sum up individual hex values to obtain a decimal value. Int_t result = 0; const char* ptr = hex; for(Int_t i=0; i < (Int_t)strlen(hex); i++) result += xtod(ptr[i]); return result; } //____________________________________________________________________________________________ Bool_t TFilePrefetch::CheckBlockInCache(char*& path, TFPBlock* block) { // Test if the block is in cache. if (fPathCache == "") return false; Bool_t found = false; TString fullPath(fPathCache); // path of the cached files. Int_t value = 0; if (gSystem->OpenDirectory(fullPath) == 0) gSystem->mkdir(fullPath); //dir is SHA1 value modulo 16; filename is the value of the SHA1(offset+len) TMD5* md = new TMD5(); TString concatStr; for (Int_t i=0; i < block->GetNoElem(); i++){ concatStr.Form("%lld", block->GetPos(i)); md->Update((UChar_t*)concatStr.Data(), concatStr.Length()); } md->Final(); TString fileName( md->AsString() ); value = SumHex(fileName); value = value % 16; TString dirName; dirName.Form("%i", value); fullPath += "/" + dirName + "/" + fileName; FileStat_t stat; if (gSystem->GetPathInfo(fullPath, stat) == 0) { path = new char[fullPath.Length() + 1]; strlcpy(path, fullPath,fullPath.Length() + 1); found = true; } else found = false; delete md; return found; } //____________________________________________________________________________________________ char* TFilePrefetch::GetBlockFromCache(const char* path, Int_t length) { // Return a buffer from cache. char *buffer = 0; TString strPath = path; strPath += "?filetype=raw"; TFile* file = new TFile(strPath); Double_t start = 0; if (gPerfStats != 0) start = TTimeStamp(); buffer = (char*) calloc(length+1, sizeof(char)); file->ReadBuffer(buffer, 0, length); fFile->fBytesRead += length; fFile->fgBytesRead += length; fFile->SetReadCalls(fFile->GetReadCalls() + 1); fFile->fgReadCalls++; if (gMonitoringWriter) gMonitoringWriter->SendFileReadProgress(fFile); if (gPerfStats != 0) { gPerfStats->FileReadEvent(fFile, length, start); } delete file; return buffer; } //____________________________________________________________________________________________ void TFilePrefetch::SaveBlockInCache(TFPBlock* block) { // Save the block content in cache. if (fPathCache == "") return; //dir is SHA1 value modulo 16; filename is the value of the SHA1 TMD5* md = new TMD5(); TString concatStr; for(Int_t i=0; i< block->GetNoElem(); i++){ concatStr.Form("%lld", block->GetPos(i)); md->Update((UChar_t*)concatStr.Data(), concatStr.Length()); } md->Final(); TString fileName( md->AsString() ); Int_t value = SumHex(fileName); value = value % 16; TString fullPath( fPathCache ); TString dirName; dirName.Form("%i", value); fullPath += ("/" + dirName); if (gSystem->OpenDirectory(fullPath) == false) gSystem->mkdir(fullPath); TFile* file = 0; fullPath += ("/" + fileName); FileStat_t stat; if (gSystem->GetPathInfo(fullPath, stat) == 0) { fullPath += "?filetype=raw"; file = TFile::Open(fullPath, "update"); } else{ fullPath += "?filetype=raw"; file = TFile::Open(fullPath, "new"); } if (file) { // coverity[unchecked_value] We do not print error message, have not error return code and close the file anyway, not need to check the return value. file->WriteBuffer(block->GetBuffer(), block->GetFullSize()); file->Close(); delete file; } delete md; } //____________________________________________________________________________________________ Bool_t TFilePrefetch::CheckCachePath(const char* locationCache) { // Validate the input file cache path. Bool_t found = true; TString path = locationCache; Ssiz_t pos = path.Index(":/"); if (pos > 0) { TSubString prot = path(0, pos); TSubString dir = path(pos + 2, path.Length()); TString protocol(prot); TString directory(dir); for(Int_t i=0; i < directory.Sizeof()-1; i++) if (!isdigit(directory[i]) && !isalpha(directory[i]) && directory[i] !='/' && directory[i] != ':'){ found = false; break; } } else found = false; return found; } //____________________________________________________________________________________________ Bool_t TFilePrefetch::SetCache(const char* path) { // Set the path of the cache directory. if (CheckCachePath(path)){ fPathCache = path; if (!gSystem->OpenDirectory(path)){ gSystem->mkdir(path); } } else return false; return true; } <commit_msg>white spaces<commit_after>// @(#)root/io:$Id$ // Author: Elvin Sindrilaru 19/05/2011 /************************************************************************* * Copyright (C) 1995-2011, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #include "TFilePrefetch.h" #include "TTimeStamp.h" #include "TVirtualPerfStats.h" #include "TVirtualMonitoring.h" #include <iostream> #include <string> #include <sstream> #include <cstdio> #include <cstdlib> #include <cctype> static const int kMAX_READ_SIZE = 2; //maximum size of the read list of blocks inline int xtod(char c) { return (c>='0' && c<='9') ? c-'0' : ((c>='A' && c<='F') ? c-'A'+10 : ((c>='a' && c<='f') ? c-'a'+10 : 0)); } using namespace std; ClassImp(TFilePrefetch) //____________________________________________________________________________________________ TFilePrefetch::TFilePrefetch(TFile* file) { // Constructor. fConsumer = 0; fFile = file; fPendingBlocks = new TList(); fReadBlocks = new TList(); fMutexReadList = new TMutex(); fMutexPendingList = new TMutex(); fNewBlockAdded = new TCondition(0); fReadBlockAdded = new TCondition(0); fCondNextFile = new TCondition(0); fSemMasterWorker = new TSemaphore(0); fSemWorkerMaster = new TSemaphore(0); } //____________________________________________________________________________________________ TFilePrefetch::~TFilePrefetch() { // Destructor. //killing consumer thread fSemMasterWorker->Post(); TMutex *mutexCond = fNewBlockAdded->GetMutex(); while (fSemWorkerMaster->Wait(10) != 0) { mutexCond->Lock(); fNewBlockAdded->Signal(); mutexCond->UnLock(); } fConsumer->Join(); SafeDelete(fConsumer); SafeDelete(fPendingBlocks); SafeDelete(fReadBlocks); SafeDelete(fMutexReadList); SafeDelete(fMutexPendingList); SafeDelete(fNewBlockAdded); SafeDelete(fReadBlockAdded); SafeDelete(fCondNextFile); SafeDelete(fSemMasterWorker); SafeDelete(fSemWorkerMaster); } //____________________________________________________________________________________________ void TFilePrefetch::ReadAsync(TFPBlock* block, Bool_t &inCache) { // Read one block and insert it in prefetchBuffers list. char* path = 0; if (CheckBlockInCache(path, block)){ block->SetBuffer(GetBlockFromCache(path, block->GetFullSize())); inCache = kTRUE; } else{ fFile->ReadBuffers(block->GetBuffer(), block->GetPos(), block->GetLen(), block->GetNoElem()); if (fFile->GetArchive()){ for (Int_t i = 0; i < block->GetNoElem(); i++) block->SetPos(i, block->GetPos(i) - fFile->GetArchiveOffset()); } inCache =kFALSE; } delete[] path; } //____________________________________________________________________________________________ void TFilePrefetch::ReadListOfBlocks() { // Get blocks specified in prefetchBlocks. Bool_t inCache = kFALSE; TFPBlock* block = 0; while((block = GetPendingBlock())){ ReadAsync(block, inCache); AddReadBlock(block); if (!inCache) SaveBlockInCache(block); } } //____________________________________________________________________________________________ Bool_t TFilePrefetch::BinarySearchReadList(TFPBlock* blockObj, Long64_t offset, Int_t len, Int_t* index) { // Search for a requested element in a block and return the index. Int_t first = 0, last = -1, mid = -1; last = (Int_t) blockObj->GetNoElem()-1; while (first <= last){ mid = first + (last - first) / 2; if ((offset >= blockObj->GetPos(mid) && offset <= (blockObj->GetPos(mid) + blockObj->GetLen(mid)) && ( (offset + len) <= blockObj->GetPos(mid) + blockObj->GetLen(mid)))){ *index = mid; return true; } else if (blockObj->GetPos(mid) < offset){ first = mid + 1; } else{ last = mid - 1; } } return false; } //____________________________________________________________________________________________ Long64_t TFilePrefetch::GetWaitTime() { // Return the time spent wating for buffer to be read in microseconds. return Long64_t(fWaitTime.RealTime()*1.e+6); } //____________________________________________________________________________________________ Bool_t TFilePrefetch::ReadBuffer(char* buf, Long64_t offset, Int_t len) { // Return a prefetched element. Bool_t found = false; TFPBlock* blockObj = 0; TMutex *mutexBlocks = fMutexReadList; Int_t index = -1; while (1){ mutexBlocks->Lock(); TIter iter(fReadBlocks); while ((blockObj = (TFPBlock*) iter.Next())){ index = -1; if (BinarySearchReadList(blockObj, offset, len, &index)){ found = true; break; } } if (found) break; else{ mutexBlocks->UnLock(); fWaitTime.Start(kFALSE); fReadBlockAdded->Wait(); //wait for a new block to be added fWaitTime.Stop(); } } if (found){ char *pBuff = blockObj->GetPtrToPiece(index); pBuff += (offset - blockObj->GetPos(index)); memcpy(buf, pBuff, len); } mutexBlocks->UnLock(); return found; } //____________________________________________________________________________________________ void TFilePrefetch::ReadBlock(Long64_t* offset, Int_t* len, Int_t nblock) { // Create a TFPBlock object or recycle one and add it to the prefetchBlocks list. TFPBlock* block = CreateBlockObj(offset, len, nblock); AddPendingBlock(block); } //____________________________________________________________________________________________ void TFilePrefetch::AddPendingBlock(TFPBlock* block) { // Safe method to add a block to the pendingList. TMutex *mutexBlocks = fMutexPendingList; TMutex *mutexCond = fNewBlockAdded->GetMutex(); mutexBlocks->Lock(); fPendingBlocks->Add(block); mutexBlocks->UnLock(); mutexCond->Lock(); fNewBlockAdded->Signal(); mutexCond->UnLock(); } //____________________________________________________________________________________________ TFPBlock* TFilePrefetch::GetPendingBlock() { // Safe method to remove a block from the pendingList. TFPBlock* block = 0; TMutex *mutex = fMutexPendingList; mutex->Lock(); if (fPendingBlocks->GetSize()){ block = (TFPBlock*)fPendingBlocks->First(); block = (TFPBlock*)fPendingBlocks->Remove(block); } mutex->UnLock(); return block; } //____________________________________________________________________________________________ void TFilePrefetch::AddReadBlock(TFPBlock* block) { // Safe method to add a block to the readList. TMutex *mutexCond = fReadBlockAdded->GetMutex(); TMutex *mutex = fMutexReadList; mutex->Lock(); if (fReadBlocks->GetSize() >= kMAX_READ_SIZE){ TFPBlock* movedBlock = (TFPBlock*) fReadBlocks->First(); movedBlock = (TFPBlock*)fReadBlocks->Remove(movedBlock); delete movedBlock; movedBlock = 0; } fReadBlocks->Add(block); mutex->UnLock(); //signal the addition of a new block mutexCond->Lock(); fReadBlockAdded->Signal(); mutexCond->UnLock(); } //____________________________________________________________________________________________ TFPBlock* TFilePrefetch::CreateBlockObj(Long64_t* offset, Int_t* len, Int_t noblock) { // Create a new block or recycle an old one. TFPBlock* blockObj = 0; TMutex *mutex = fMutexReadList; mutex->Lock(); if (fReadBlocks->GetSize() >= kMAX_READ_SIZE){ blockObj = static_cast<TFPBlock*>(fReadBlocks->First()); fReadBlocks->Remove(blockObj); mutex->UnLock(); blockObj->ReallocBlock(offset, len, noblock); } else{ mutex->UnLock(); blockObj = new TFPBlock(offset, len, noblock); } return blockObj; } //____________________________________________________________________________________________ TThread* TFilePrefetch::GetThread() const { // Return reference to the consumer thread. return fConsumer; } //____________________________________________________________________________________________ void TFilePrefetch::SetFile(TFile *file) { // Change the file fFile = file; } //____________________________________________________________________________________________ Int_t TFilePrefetch::ThreadStart() { // Used to start the consumer thread. int rc; fConsumer= new TThread((TThread::VoidRtnFunc_t) ThreadProc, (void*) this); rc = fConsumer->Run(); return rc; } //____________________________________________________________________________________________ TThread::VoidRtnFunc_t TFilePrefetch::ThreadProc(void* arg) { // Execution loop of the consumer thread. TFilePrefetch* pClass = (TFilePrefetch*) arg; TMutex *mutex = pClass->fCondNextFile->GetMutex(); pClass->fNewBlockAdded->Wait(); while(pClass->fSemMasterWorker->TryWait() == 1) { pClass->ReadListOfBlocks(); //need to signal TChain that we finished work //in the previous file, before we move on mutex->Lock(); pClass->fCondNextFile->Signal(); mutex->UnLock(); pClass->fNewBlockAdded->Wait(); } pClass->fSemWorkerMaster->Post(); return (TThread::VoidRtnFunc_t) 1; } //########################################### CACHING PART ############################################################### //____________________________________________________________________________________________ Int_t TFilePrefetch::SumHex(const char *hex) { // Sum up individual hex values to obtain a decimal value. Int_t result = 0; const char* ptr = hex; for(Int_t i=0; i < (Int_t)strlen(hex); i++) result += xtod(ptr[i]); return result; } //____________________________________________________________________________________________ Bool_t TFilePrefetch::CheckBlockInCache(char*& path, TFPBlock* block) { // Test if the block is in cache. if (fPathCache == "") return false; Bool_t found = false; TString fullPath(fPathCache); // path of the cached files. Int_t value = 0; if (gSystem->OpenDirectory(fullPath) == 0) gSystem->mkdir(fullPath); //dir is SHA1 value modulo 16; filename is the value of the SHA1(offset+len) TMD5* md = new TMD5(); TString concatStr; for (Int_t i=0; i < block->GetNoElem(); i++){ concatStr.Form("%lld", block->GetPos(i)); md->Update((UChar_t*)concatStr.Data(), concatStr.Length()); } md->Final(); TString fileName( md->AsString() ); value = SumHex(fileName); value = value % 16; TString dirName; dirName.Form("%i", value); fullPath += "/" + dirName + "/" + fileName; FileStat_t stat; if (gSystem->GetPathInfo(fullPath, stat) == 0) { path = new char[fullPath.Length() + 1]; strlcpy(path, fullPath,fullPath.Length() + 1); found = true; } else found = false; delete md; return found; } //____________________________________________________________________________________________ char* TFilePrefetch::GetBlockFromCache(const char* path, Int_t length) { // Return a buffer from cache. char *buffer = 0; TString strPath = path; strPath += "?filetype=raw"; TFile* file = new TFile(strPath); Double_t start = 0; if (gPerfStats != 0) start = TTimeStamp(); buffer = (char*) calloc(length+1, sizeof(char)); file->ReadBuffer(buffer, 0, length); fFile->fBytesRead += length; fFile->fgBytesRead += length; fFile->SetReadCalls(fFile->GetReadCalls() + 1); fFile->fgReadCalls++; if (gMonitoringWriter) gMonitoringWriter->SendFileReadProgress(fFile); if (gPerfStats != 0) { gPerfStats->FileReadEvent(fFile, length, start); } delete file; return buffer; } //____________________________________________________________________________________________ void TFilePrefetch::SaveBlockInCache(TFPBlock* block) { // Save the block content in cache. if (fPathCache == "") return; //dir is SHA1 value modulo 16; filename is the value of the SHA1 TMD5* md = new TMD5(); TString concatStr; for(Int_t i=0; i< block->GetNoElem(); i++){ concatStr.Form("%lld", block->GetPos(i)); md->Update((UChar_t*)concatStr.Data(), concatStr.Length()); } md->Final(); TString fileName( md->AsString() ); Int_t value = SumHex(fileName); value = value % 16; TString fullPath( fPathCache ); TString dirName; dirName.Form("%i", value); fullPath += ("/" + dirName); if (gSystem->OpenDirectory(fullPath) == false) gSystem->mkdir(fullPath); TFile* file = 0; fullPath += ("/" + fileName); FileStat_t stat; if (gSystem->GetPathInfo(fullPath, stat) == 0) { fullPath += "?filetype=raw"; file = TFile::Open(fullPath, "update"); } else{ fullPath += "?filetype=raw"; file = TFile::Open(fullPath, "new"); } if (file) { // coverity[unchecked_value] We do not print error message, have not error return code and close the file anyway, not need to check the return value. file->WriteBuffer(block->GetBuffer(), block->GetFullSize()); file->Close(); delete file; } delete md; } //____________________________________________________________________________________________ Bool_t TFilePrefetch::CheckCachePath(const char* locationCache) { // Validate the input file cache path. Bool_t found = true; TString path = locationCache; Ssiz_t pos = path.Index(":/"); if (pos > 0) { TSubString prot = path(0, pos); TSubString dir = path(pos + 2, path.Length()); TString protocol(prot); TString directory(dir); for(Int_t i=0; i < directory.Sizeof()-1; i++) if (!isdigit(directory[i]) && !isalpha(directory[i]) && directory[i] !='/' && directory[i] != ':'){ found = false; break; } } else found = false; return found; } //____________________________________________________________________________________________ Bool_t TFilePrefetch::SetCache(const char* path) { // Set the path of the cache directory. if (CheckCachePath(path)){ fPathCache = path; if (!gSystem->OpenDirectory(path)){ gSystem->mkdir(path); } } else return false; return true; } <|endoftext|>
<commit_before>/* * AudioGraph Audio Graph Layer for Jamoma DSP * Creates a wrapper for TTAudioObjects that can be used to build an audio processing graph. * Copyright © 2008, Timothy Place * * License: This code is licensed under the terms of the "New BSD License" * http://creativecommons.org/licenses/BSD/ */ #include "TTAudioGraphObject.h" #include "TTAudioGraphInlet.h" #include "TTAudioGraphOutlet.h" #define thisTTClass TTAudioGraphObject TTMutexPtr TTAudioGraphObject::sSharedMutex = NULL; // Arguments // 1. (required) The name of the Jamoma DSP object you want to wrap // 2. (optional) Number of inlets, default = 1 // 3. (optional) Number of outlets, default = 1 TTObjectPtr TTAudioGraphObject::instantiate (TTSymbolPtr name, TTValue& arguments) { return new TTAudioGraphObject(arguments); } extern "C" void TTAudioGraphObject::registerClass() { TTClassRegister(TT("audio.object"), "audio, graph, wrapper", TTAudioGraphObject::instantiate ); } TTAudioGraphObject :: TTAudioGraphObject (TTValue& arguments) : TTGraphObject(arguments), mDescription(NULL), mAudioFlags(kTTAudioGraphProcessor), mInputSignals(NULL), mOutputSignals(NULL), mVectorSize(0) { TTErr err = kTTErrNone; TTSymbolPtr wrappedObjectName = NULL; //TTUInt16 initialNumChannels = 1; TTUInt16 numInlets = 1; TTUInt16 numOutlets = 1; TT_ASSERT(audiograph_correct_instantiation_arg_count, arguments.getSize() > 0); arguments.get(0, &wrappedObjectName); if (arguments.getSize() > 1) arguments.get(1, numInlets); if (arguments.getSize() > 2) arguments.get(2, numOutlets); // instantiated by the TTGraph super-class //err = TTObjectInstantiate(wrappedObjectName, &mUnitGenerator, initialNumChannels); err = TTObjectInstantiate(kTTSym_audiosignalarray, (TTObjectPtr*)&mInputSignals, numInlets); err = TTObjectInstantiate(kTTSym_audiosignalarray, (TTObjectPtr*)&mOutputSignals, numOutlets); mAudioInlets.resize(numInlets); mInputSignals->setMaxNumAudioSignals(numInlets); mInputSignals->numAudioSignals = numInlets; // TODO: this array num signals access is kind of clumsy and inconsistent [tap] mAudioOutlets.resize(numOutlets); mOutputSignals->setMaxNumAudioSignals(numOutlets); mOutputSignals->numAudioSignals = numOutlets; // if an object supports the 'setOwner' message, then we tell it that we want to become the owner // this is particularly important for the dac object TTValue v = TTPtr(this); mKernel->sendMessage(TT("setOwner"), v); if (!sSharedMutex) sSharedMutex = new TTMutex(false); } TTAudioGraphObject::~TTAudioGraphObject() { TTObjectRelease((TTObjectPtr*)&mInputSignals); TTObjectRelease((TTObjectPtr*)&mOutputSignals); } void TTAudioGraphObject::prepareAudioDescription() { if (valid && mDescription) { mDescription->sIndex = 0; mDescription = NULL; for (TTAudioGraphInletIter inlet = mAudioInlets.begin(); inlet != mAudioInlets.end(); inlet++) inlet->prepareDescriptions(); } } void TTAudioGraphObject::getAudioDescription(TTAudioGraphDescription& desc) { if (mDescription) { // a description for this object has already been created -- use it. desc = *mDescription; } else { // create a new description for this object. desc.mClassName = mKernel->getName(); desc.mObjectInstance = mKernel; // desc.mAudioDescriptions.clear(); desc.mAudioDescriptionsForInlets.clear(); desc.mID = desc.sIndex++; mDescription = &desc; // for (TTAudioGraphInletIter inlet = mAudioInlets.begin(); inlet != mAudioInlets.end(); inlet++) // inlet->getDescriptions(desc.mAudioDescriptions); for (TTAudioGraphInletIter inlet = mAudioInlets.begin(); inlet != mAudioInlets.end(); inlet++) { TTAudioGraphDescriptionVector vector; inlet->getDescriptions(vector); desc.mAudioDescriptionsForInlets.push_back(vector); } getDescription(desc.mControlDescription); } } TTErr TTAudioGraphObject::resetAudio() { sSharedMutex->lock(); for_each(mAudioInlets.begin(), mAudioInlets.end(), mem_fun_ref(&TTAudioGraphInlet::reset)); sSharedMutex->unlock(); return kTTErrNone; } TTErr TTAudioGraphObject::connectAudio(TTAudioGraphObjectPtr anObject, TTUInt16 fromOutletNumber, TTUInt16 toInletNumber) { TTErr err; // it might seem like connections should not need the critical region: // the vector gets a little longer and the new items might be ignored the first time // it doesn't change the order or delete things or copy them around in the vector like a drop() does // but: // if the resize of the vector can't happen in-place, then the whole thing gets copied and the old one destroyed sSharedMutex->lock(); err = mAudioInlets[toInletNumber].connect(anObject, fromOutletNumber); sSharedMutex->unlock(); return err; } TTErr TTAudioGraphObject::dropAudio(TTAudioGraphObjectPtr anObject, TTUInt16 fromOutletNumber, TTUInt16 toInletNumber) { TTErr err = kTTErrInvalidValue; sSharedMutex->lock(); if (toInletNumber < mAudioInlets.size()) err = mAudioInlets[toInletNumber].drop(anObject, fromOutletNumber); sSharedMutex->unlock(); return err; } TTErr TTAudioGraphObject::preprocess(const TTAudioGraphPreprocessData& initData) { lock(); if (valid && mStatus != kTTAudioGraphProcessNotStarted) { TTAudioSignalPtr audioSignal; TTUInt16 index = 0; mStatus = kTTAudioGraphProcessNotStarted; for (TTAudioGraphInletIter inlet = mAudioInlets.begin(); inlet != mAudioInlets.end(); inlet++) { inlet->preprocess(initData); audioSignal = inlet->getBuffer(); // TODO: It seems like we can just cache this once when we init the graph, because the number of inlets cannot change on-the-fly mInputSignals->setSignal(index, audioSignal); index++; } index = 0; for (TTAudioGraphOutletIter outlet = mAudioOutlets.begin(); outlet != mAudioOutlets.end(); outlet++) { audioSignal = outlet->getBuffer(); mOutputSignals->setSignal(index, audioSignal); index++; } if (mAudioFlags & kTTAudioGraphGenerator) { if (mVectorSize != initData.vectorSize) { mVectorSize = initData.vectorSize; mOutputSignals->allocAllWithVectorSize(initData.vectorSize); } } } unlock(); return kTTErrNone; } TTErr TTAudioGraphObject::process(TTAudioSignalPtr& returnedSignal, TTUInt16 forOutletNumber) { lock(); switch (mStatus) { // we have not processed anything yet, so let's get started case kTTAudioGraphProcessNotStarted: mStatus = kTTAudioGraphProcessingCurrently; if (mAudioFlags & kTTAudioGraphGenerator) { // a generator (or no input) getUnitGenerator()->process(mInputSignals, mOutputSignals); } else { // a processor // zero our collected input samples mInputSignals->clearAll(); // pull (process, sum, and collect) all of our source audio for_each(mAudioInlets.begin(), mAudioInlets.end(), mem_fun_ref(&TTAudioGraphInlet::process)); if (!(mAudioFlags & kTTAudioGraphNonAdapting)) { // examples of non-adapting objects are join≈ and matrix≈ // non-adapting in this case means channel numbers -- vector sizes still adapt mOutputSignals->matchNumChannels(mInputSignals); } mOutputSignals->allocAllWithVectorSize(mInputSignals->getVectorSize()); // adapt ugen based on the input we are going to process getUnitGenerator()->adaptMaxNumChannels(mInputSignals->getMaxNumChannels()); getUnitGenerator()->setSampleRate(mInputSignals->getSignal(0).getSampleRate()); // finally, process the audio getUnitGenerator()->process(mInputSignals, mOutputSignals); } // TODO: we're doing a copy below -- is that what we really want? Or can we just return the pointer? returnedSignal = mAudioOutlets[forOutletNumber].mBufferedOutput; mStatus = kTTAudioGraphProcessComplete; break; // we already processed everything that needs to be processed, so just set the pointer case kTTAudioGraphProcessComplete: returnedSignal = mAudioOutlets[forOutletNumber].mBufferedOutput; break; // to prevent feedback / infinite loops, we just hand back the last calculated output here case kTTAudioGraphProcessingCurrently: returnedSignal = mAudioOutlets[forOutletNumber].mBufferedOutput; break; // we should never get here default: unlock(); return kTTErrGeneric; } unlock(); return kTTErrNone; } <commit_msg>minor cleanup<commit_after>/* * AudioGraph Audio Graph Layer for Jamoma DSP * Creates a wrapper for TTAudioObjects that can be used to build an audio processing graph. * Copyright © 2008, Timothy Place * * License: This code is licensed under the terms of the "New BSD License" * http://creativecommons.org/licenses/BSD/ */ #include "TTAudioGraphObject.h" #include "TTAudioGraphInlet.h" #include "TTAudioGraphOutlet.h" #define thisTTClass TTAudioGraphObject TTMutexPtr TTAudioGraphObject::sSharedMutex = NULL; // Arguments // 1. (required) The name of the Jamoma DSP object you want to wrap // 2. (optional) Number of inlets, default = 1 // 3. (optional) Number of outlets, default = 1 TTObjectPtr TTAudioGraphObject::instantiate (TTSymbolPtr name, TTValue& arguments) { return new TTAudioGraphObject(arguments); } extern "C" void TTAudioGraphObject::registerClass() { TTClassRegister(TT("audio.object"), "audio, graph, wrapper", TTAudioGraphObject::instantiate ); } TTAudioGraphObject :: TTAudioGraphObject (TTValue& arguments) : TTGraphObject(arguments), mDescription(NULL), mAudioFlags(kTTAudioGraphProcessor), mInputSignals(NULL), mOutputSignals(NULL), mVectorSize(0) { TTErr err = kTTErrNone; TTSymbolPtr wrappedObjectName = NULL; //TTUInt16 initialNumChannels = 1; TTUInt16 numInlets = 1; TTUInt16 numOutlets = 1; TT_ASSERT(audiograph_correct_instantiation_arg_count, arguments.getSize() > 0); arguments.get(0, &wrappedObjectName); if (arguments.getSize() > 1) arguments.get(1, numInlets); if (arguments.getSize() > 2) arguments.get(2, numOutlets); // instantiated by the TTGraph super-class //err = TTObjectInstantiate(wrappedObjectName, &mUnitGenerator, initialNumChannels); err = TTObjectInstantiate(kTTSym_audiosignalarray, (TTObjectPtr*)&mInputSignals, numInlets); err = TTObjectInstantiate(kTTSym_audiosignalarray, (TTObjectPtr*)&mOutputSignals, numOutlets); mAudioInlets.resize(numInlets); mInputSignals->setMaxNumAudioSignals(numInlets); mInputSignals->numAudioSignals = numInlets; // TODO: this array num signals access is kind of clumsy and inconsistent [tap] mAudioOutlets.resize(numOutlets); mOutputSignals->setMaxNumAudioSignals(numOutlets); mOutputSignals->numAudioSignals = numOutlets; // if an object supports the 'setOwner' message, then we tell it that we want to become the owner // this is particularly important for the dac object TTValue v = TTPtr(this); mKernel->sendMessage(TT("setOwner"), v); if (!sSharedMutex) sSharedMutex = new TTMutex(false); } TTAudioGraphObject::~TTAudioGraphObject() { TTObjectRelease((TTObjectPtr*)&mInputSignals); TTObjectRelease((TTObjectPtr*)&mOutputSignals); } void TTAudioGraphObject::prepareAudioDescription() { if (valid && mDescription) { mDescription->sIndex = 0; mDescription = NULL; for (TTAudioGraphInletIter inlet = mAudioInlets.begin(); inlet != mAudioInlets.end(); inlet++) inlet->prepareDescriptions(); } } void TTAudioGraphObject::getAudioDescription(TTAudioGraphDescription& desc) { if (mDescription) { // a description for this object has already been created -- use it. desc = *mDescription; } else { // create a new description for this object. desc.mClassName = mKernel->getName(); desc.mObjectInstance = mKernel; desc.mAudioDescriptionsForInlets.clear(); desc.mID = desc.sIndex++; mDescription = &desc; for (TTAudioGraphInletIter inlet = mAudioInlets.begin(); inlet != mAudioInlets.end(); inlet++) { TTAudioGraphDescriptionVector vector; inlet->getDescriptions(vector); desc.mAudioDescriptionsForInlets.push_back(vector); } getDescription(desc.mControlDescription); } } TTErr TTAudioGraphObject::resetAudio() { sSharedMutex->lock(); for_each(mAudioInlets.begin(), mAudioInlets.end(), mem_fun_ref(&TTAudioGraphInlet::reset)); sSharedMutex->unlock(); return kTTErrNone; } TTErr TTAudioGraphObject::connectAudio(TTAudioGraphObjectPtr anObject, TTUInt16 fromOutletNumber, TTUInt16 toInletNumber) { TTErr err; // it might seem like connections should not need the critical region: // the vector gets a little longer and the new items might be ignored the first time // it doesn't change the order or delete things or copy them around in the vector like a drop() does // but: // if the resize of the vector can't happen in-place, then the whole thing gets copied and the old one destroyed sSharedMutex->lock(); err = mAudioInlets[toInletNumber].connect(anObject, fromOutletNumber); sSharedMutex->unlock(); return err; } TTErr TTAudioGraphObject::dropAudio(TTAudioGraphObjectPtr anObject, TTUInt16 fromOutletNumber, TTUInt16 toInletNumber) { TTErr err = kTTErrInvalidValue; sSharedMutex->lock(); if (toInletNumber < mAudioInlets.size()) err = mAudioInlets[toInletNumber].drop(anObject, fromOutletNumber); sSharedMutex->unlock(); return err; } TTErr TTAudioGraphObject::preprocess(const TTAudioGraphPreprocessData& initData) { lock(); if (valid && mStatus != kTTAudioGraphProcessNotStarted) { TTAudioSignalPtr audioSignal; TTUInt16 index = 0; mStatus = kTTAudioGraphProcessNotStarted; for (TTAudioGraphInletIter inlet = mAudioInlets.begin(); inlet != mAudioInlets.end(); inlet++) { inlet->preprocess(initData); audioSignal = inlet->getBuffer(); // TODO: It seems like we can just cache this once when we init the graph, because the number of inlets cannot change on-the-fly mInputSignals->setSignal(index, audioSignal); index++; } index = 0; for (TTAudioGraphOutletIter outlet = mAudioOutlets.begin(); outlet != mAudioOutlets.end(); outlet++) { audioSignal = outlet->getBuffer(); mOutputSignals->setSignal(index, audioSignal); index++; } if (mAudioFlags & kTTAudioGraphGenerator) { if (mVectorSize != initData.vectorSize) { mVectorSize = initData.vectorSize; mOutputSignals->allocAllWithVectorSize(initData.vectorSize); } } } unlock(); return kTTErrNone; } TTErr TTAudioGraphObject::process(TTAudioSignalPtr& returnedSignal, TTUInt16 forOutletNumber) { lock(); switch (mStatus) { // we have not processed anything yet, so let's get started case kTTAudioGraphProcessNotStarted: mStatus = kTTAudioGraphProcessingCurrently; if (mAudioFlags & kTTAudioGraphGenerator) { // a generator (or no input) getUnitGenerator()->process(mInputSignals, mOutputSignals); } else { // a processor // zero our collected input samples mInputSignals->clearAll(); // pull (process, sum, and collect) all of our source audio for_each(mAudioInlets.begin(), mAudioInlets.end(), mem_fun_ref(&TTAudioGraphInlet::process)); if (!(mAudioFlags & kTTAudioGraphNonAdapting)) { // examples of non-adapting objects are join≈ and matrix≈ // non-adapting in this case means channel numbers -- vector sizes still adapt mOutputSignals->matchNumChannels(mInputSignals); } mOutputSignals->allocAllWithVectorSize(mInputSignals->getVectorSize()); // adapt ugen based on the input we are going to process getUnitGenerator()->adaptMaxNumChannels(mInputSignals->getMaxNumChannels()); getUnitGenerator()->setSampleRate(mInputSignals->getSignal(0).getSampleRate()); // finally, process the audio getUnitGenerator()->process(mInputSignals, mOutputSignals); } // TODO: we're doing a copy below -- is that what we really want? Or can we just return the pointer? returnedSignal = mAudioOutlets[forOutletNumber].mBufferedOutput; mStatus = kTTAudioGraphProcessComplete; break; // we already processed everything that needs to be processed, so just set the pointer case kTTAudioGraphProcessComplete: returnedSignal = mAudioOutlets[forOutletNumber].mBufferedOutput; break; // to prevent feedback / infinite loops, we just hand back the last calculated output here case kTTAudioGraphProcessingCurrently: returnedSignal = mAudioOutlets[forOutletNumber].mBufferedOutput; break; // we should never get here default: unlock(); return kTTErrGeneric; } unlock(); return kTTErrNone; } <|endoftext|>
<commit_before>/* * Jamoma Asynchronous Object Graph Layer * Creates a wrapper for TTObjects that can be used to build a control graph for asynchronous message passing. * Copyright © 2010, Timothy Place * * License: This code is licensed under the terms of the GNU LGPL * http://www.gnu.org/licenses/lgpl.html */ #include "TTGraphDescription.h" #include <fstream> #include <iostream> using namespace std; void TTGraphDescription::exportRuby(const TTString& fullpathToFile) { TTString rubyContent; int index = -1; TTStringVector nodeNames; ofstream rubyFile(fullpathToFile.c_str()); rubyContent += "require \"TTRuby\"\n\n"; exportRubyNode(rubyContent, index, nodeNames); rubyFile.write(rubyContent.c_str(), rubyContent.size()); rubyFile.close(); } int TTGraphDescription::exportRubyNode(TTString& content, int& index, TTStringVector& nodeNames) { char objName[16]; int localIndex; index++; localIndex = index; snprintf(objName, 16, "obj%i", index); nodeNames.push_back(TTString(objName)); content += objName; content += " = TTControl.new \""; content += mClassName->getString(); content += "\"\n"; for (TTGraphDescriptionIter input = mInputDescriptions.begin(); input != mInputDescriptions.end(); input++) { int inputIndex = input->exportRubyNode(content, index, nodeNames); content += objName; content += ".connect "; content += nodeNames[inputIndex]; content += "\n"; } return localIndex; } void TTGraphDescription::exportCpp(const TTString& fullpathToFile) { TTString content; int index = -1; TTStringVector nodeNames; ofstream aFile(fullpathToFile.c_str()); content += "#include \"TTGraphAPI.h\"\n\n"; content += "int main()\n{\n"; content += " TTGraphInit();\n\n"; exportCppNode(content, index, nodeNames); content += " return 0;\n"; content += "}\n"; aFile.write(content.c_str(), content.size()); aFile.close(); } int TTGraphDescription::exportCppNode(TTString& content, int& index, TTStringVector& nodeNames) { char objName[16]; int localIndex; index++; localIndex = index; snprintf(objName, 16, "obj%i", index); nodeNames.push_back(TTString(objName)); content += " TTMulticoreObjectPtr "; content += objName; content += ";\n"; content += " TTObjectInstantiate(TT(\"multicore.object\"), (TTObjectPtr*)&"; content += objName; content += ", TTValue(TT(\""; content += mClassName->getString(); content += "\")))\n\n"; for (TTGraphDescriptionIter input = mInputDescriptions.begin(); input != mInputDescriptions.end(); input++) { int inputIndex = input->exportCppNode(content, index, nodeNames); // note: calls into TTGraph's exportRubyNode content += " "; content += objName; content += "->connect("; content += nodeNames[inputIndex]; content += ");\n"; } return localIndex; } void TTGraphDescription::exportMax(const TTString& fullpathToFile) { TTString content; int index = -1; TTStringVector nodeNames; ofstream aFile(fullpathToFile.c_str()); content += "{\n"; content += " \"patcher\" : {\n"; content += " \"boxes\" : [\n"; exportMaxNode(content, index, nodeNames); content += " ]\n"; content += " }\n"; content += "}\n"; aFile.write(content.c_str(), content.size()); aFile.close(); } int TTGraphDescription::exportMaxNode(TTString& content, int& index, TTStringVector& nodeNames) { char objName[16]; char location[16]; int localIndex; index++; localIndex = index; snprintf(objName, 16, "obj%i", index); nodeNames.push_back(TTString(objName)); if (index > 0) content += ",\n"; content += " {\n"; content += " \"box\" : {\n"; content += " \"id\" : \""; content += objName; content += "\",\n"; content += " \"maxclass\" : \"newobj\",\n"; content += " \"text\" : \"jcom."; // TODO: is there a better way to know about object name mappings? if (mClassName == TT("multicore.output")) content += "dac"; else content += mClassName->getString(); content += "≈\",\n"; content += " \"patching_rect\" : [ 50.0, "; snprintf(location, 16, "%f", 400.0 - (index * 40.0)); content += location; content += ", 100.0, 20.0]\n"; content += " }\n"; content += " }\n"; for (TTGraphDescriptionIter input = mInputDescriptions.begin(); input != mInputDescriptions.end(); input++) { int inputIndex; inputIndex = input->exportMaxNode(content, index, nodeNames); if (index == inputIndex) { // I think this means that we are processing the top of the chain?) content += " ],"; content += " \"lines\" : ["; } else content += ",\n"; content += " {\n"; content += " \"patchline\" : {\n"; content += " \"destination\" : [ \""; content += objName; content += "\", 0],\n"; content += " \"source\" : [ \""; content += nodeNames[inputIndex]; content += "\", 0]\n"; content += " }\n"; content += " }\n"; } return localIndex; } <commit_msg>fix for C++ export to actually create Graph objects instead of Multicore objects<commit_after>/* * Jamoma Asynchronous Object Graph Layer * Creates a wrapper for TTObjects that can be used to build a control graph for asynchronous message passing. * Copyright © 2010, Timothy Place * * License: This code is licensed under the terms of the GNU LGPL * http://www.gnu.org/licenses/lgpl.html */ #include "TTGraphDescription.h" #include <fstream> #include <iostream> using namespace std; void TTGraphDescription::exportRuby(const TTString& fullpathToFile) { TTString rubyContent; int index = -1; TTStringVector nodeNames; ofstream rubyFile(fullpathToFile.c_str()); rubyContent += "require \"TTRuby\"\n\n"; exportRubyNode(rubyContent, index, nodeNames); rubyFile.write(rubyContent.c_str(), rubyContent.size()); rubyFile.close(); } int TTGraphDescription::exportRubyNode(TTString& content, int& index, TTStringVector& nodeNames) { char objName[16]; int localIndex; index++; localIndex = index; snprintf(objName, 16, "obj%i", index); nodeNames.push_back(TTString(objName)); content += objName; content += " = TTControl.new \""; content += mClassName->getString(); content += "\"\n"; for (TTGraphDescriptionIter input = mInputDescriptions.begin(); input != mInputDescriptions.end(); input++) { int inputIndex = input->exportRubyNode(content, index, nodeNames); content += objName; content += ".connect "; content += nodeNames[inputIndex]; content += "\n"; } return localIndex; } void TTGraphDescription::exportCpp(const TTString& fullpathToFile) { TTString content; int index = -1; TTStringVector nodeNames; ofstream aFile(fullpathToFile.c_str()); content += "#include \"TTGraphAPI.h\"\n\n"; content += "int main()\n{\n"; content += " TTGraphInit();\n\n"; exportCppNode(content, index, nodeNames); content += " return 0;\n"; content += "}\n"; aFile.write(content.c_str(), content.size()); aFile.close(); } int TTGraphDescription::exportCppNode(TTString& content, int& index, TTStringVector& nodeNames) { char objName[16]; int localIndex; index++; localIndex = index; snprintf(objName, 16, "obj%i", index); nodeNames.push_back(TTString(objName)); content += " TTGraphObjectPtr "; content += objName; content += ";\n"; content += " TTObjectInstantiate(TT(\"graph.object\"), (TTObjectPtr*)&"; content += objName; content += ", TTValue(TT(\""; content += mClassName->getString(); content += "\")))\n\n"; for (TTGraphDescriptionIter input = mInputDescriptions.begin(); input != mInputDescriptions.end(); input++) { int inputIndex = input->exportCppNode(content, index, nodeNames); // note: calls into TTGraph's exportRubyNode content += " "; content += objName; content += "->connect("; content += nodeNames[inputIndex]; content += ");\n"; } return localIndex; } void TTGraphDescription::exportMax(const TTString& fullpathToFile) { TTString content; int index = -1; TTStringVector nodeNames; ofstream aFile(fullpathToFile.c_str()); content += "{\n"; content += " \"patcher\" : {\n"; content += " \"boxes\" : [\n"; exportMaxNode(content, index, nodeNames); content += " ]\n"; content += " }\n"; content += "}\n"; aFile.write(content.c_str(), content.size()); aFile.close(); } int TTGraphDescription::exportMaxNode(TTString& content, int& index, TTStringVector& nodeNames) { char objName[16]; char location[16]; int localIndex; index++; localIndex = index; snprintf(objName, 16, "obj%i", index); nodeNames.push_back(TTString(objName)); if (index > 0) content += ",\n"; content += " {\n"; content += " \"box\" : {\n"; content += " \"id\" : \""; content += objName; content += "\",\n"; content += " \"maxclass\" : \"newobj\",\n"; content += " \"text\" : \"jcom."; // TODO: is there a better way to know about object name mappings? if (mClassName == TT("multicore.output")) content += "dac"; else content += mClassName->getString(); content += "≈\",\n"; content += " \"patching_rect\" : [ 50.0, "; snprintf(location, 16, "%f", 400.0 - (index * 40.0)); content += location; content += ", 100.0, 20.0]\n"; content += " }\n"; content += " }\n"; for (TTGraphDescriptionIter input = mInputDescriptions.begin(); input != mInputDescriptions.end(); input++) { int inputIndex; inputIndex = input->exportMaxNode(content, index, nodeNames); if (index == inputIndex) { // I think this means that we are processing the top of the chain?) content += " ],"; content += " \"lines\" : ["; } else content += ",\n"; content += " {\n"; content += " \"patchline\" : {\n"; content += " \"destination\" : [ \""; content += objName; content += "\", 0],\n"; content += " \"source\" : [ \""; content += nodeNames[inputIndex]; content += "\", 0]\n"; content += " }\n"; content += " }\n"; } return localIndex; } <|endoftext|>
<commit_before>// Copyright (c) 2006, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google 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. // minidump_dump.cc: Print the contents of a minidump file in somewhat // readable text. // // Author: Mark Mentovai #include <stdio.h> #include "google_breakpad/processor/minidump.h" #include "processor/logging.h" namespace { using google_breakpad::Minidump; using google_breakpad::MinidumpThreadList; using google_breakpad::MinidumpModuleList; using google_breakpad::MinidumpMemoryList; using google_breakpad::MinidumpException; using google_breakpad::MinidumpAssertion; using google_breakpad::MinidumpSystemInfo; using google_breakpad::MinidumpMiscInfo; using google_breakpad::MinidumpBreakpadInfo; static bool PrintMinidumpDump(const char *minidump_file) { Minidump minidump(minidump_file); if (!minidump.Read()) { BPLOG(ERROR) << "minidump.Read() failed"; return false; } minidump.Print(); int errors = 0; MinidumpThreadList *thread_list = minidump.GetThreadList(); if (!thread_list) { ++errors; BPLOG(ERROR) << "minidump.GetThreadList() failed"; } else { thread_list->Print(); } MinidumpModuleList *module_list = minidump.GetModuleList(); if (!module_list) { ++errors; BPLOG(ERROR) << "minidump.GetModuleList() failed"; } else { module_list->Print(); } MinidumpMemoryList *memory_list = minidump.GetMemoryList(); if (!memory_list) { ++errors; BPLOG(ERROR) << "minidump.GetMemoryList() failed"; } else { memory_list->Print(); } MinidumpException *exception = minidump.GetException(); if (!exception) { BPLOG(INFO) << "minidump.GetException() failed"; } else { exception->Print(); } MinidumpAssertion *assertion = minidump.GetAssertion(); if (!assertion) { BPLOG(INFO) << "minidump.GetAssertion() failed"; } else { assertion->Print(); } MinidumpSystemInfo *system_info = minidump.GetSystemInfo(); if (!system_info) { ++errors; BPLOG(ERROR) << "minidump.GetSystemInfo() failed"; } else { system_info->Print(); } MinidumpMiscInfo *misc_info = minidump.GetMiscInfo(); if (!misc_info) { ++errors; BPLOG(ERROR) << "minidump.GetMiscInfo() failed"; } else { misc_info->Print(); } MinidumpBreakpadInfo *breakpad_info = minidump.GetBreakpadInfo(); if (!breakpad_info) { // Breakpad info is optional, so don't treat this as an error. BPLOG(INFO) << "minidump.GetBreakpadInfo() failed"; } else { breakpad_info->Print(); } return errors == 0; } } // namespace int main(int argc, char **argv) { BPLOG_INIT(&argc, &argv); if (argc != 2) { fprintf(stderr, "usage: %s <file>\n", argv[0]); return 1; } return PrintMinidumpDump(argv[1]) ? 0 : 1; } <commit_msg>Enable dumping of the Linux extension streams.<commit_after>// Copyright (c) 2006, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google 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. // minidump_dump.cc: Print the contents of a minidump file in somewhat // readable text. // // Author: Mark Mentovai #include <stdio.h> #include <string.h> #include "client/linux/minidump_writer/minidump_extension_linux.h" #include "google_breakpad/processor/minidump.h" #include "processor/logging.h" #include "processor/scoped_ptr.h" namespace { using google_breakpad::Minidump; using google_breakpad::MinidumpThreadList; using google_breakpad::MinidumpModuleList; using google_breakpad::MinidumpMemoryList; using google_breakpad::MinidumpException; using google_breakpad::MinidumpAssertion; using google_breakpad::MinidumpSystemInfo; using google_breakpad::MinidumpMiscInfo; using google_breakpad::MinidumpBreakpadInfo; static void DumpRawStream(Minidump *minidump, u_int32_t stream_type, const char *stream_name, int *errors) { u_int32_t length = 0; if (!minidump->SeekToStreamType(stream_type, &length)) { return; } printf("Stream %s:\n", stream_name); if (length == 0) { printf("\n"); return; } std::vector<char> contents(length); if (!minidump->ReadBytes(&contents[0], length)) { ++*errors; BPLOG(ERROR) << "minidump.ReadBytes failed"; return; } size_t current_offset = 0; while (current_offset < length) { size_t remaining = length - current_offset; printf("%.*s", remaining, &contents[current_offset]); char *next_null = reinterpret_cast<char *>( memchr(&contents[current_offset], 0, remaining)); if (next_null == NULL) break; printf("\\0\n"); size_t null_offset = next_null - &contents[0]; current_offset = null_offset + 1; } printf("\n\n"); } static bool PrintMinidumpDump(const char *minidump_file) { Minidump minidump(minidump_file); if (!minidump.Read()) { BPLOG(ERROR) << "minidump.Read() failed"; return false; } minidump.Print(); int errors = 0; MinidumpThreadList *thread_list = minidump.GetThreadList(); if (!thread_list) { ++errors; BPLOG(ERROR) << "minidump.GetThreadList() failed"; } else { thread_list->Print(); } MinidumpModuleList *module_list = minidump.GetModuleList(); if (!module_list) { ++errors; BPLOG(ERROR) << "minidump.GetModuleList() failed"; } else { module_list->Print(); } MinidumpMemoryList *memory_list = minidump.GetMemoryList(); if (!memory_list) { ++errors; BPLOG(ERROR) << "minidump.GetMemoryList() failed"; } else { memory_list->Print(); } MinidumpException *exception = minidump.GetException(); if (!exception) { BPLOG(INFO) << "minidump.GetException() failed"; } else { exception->Print(); } MinidumpAssertion *assertion = minidump.GetAssertion(); if (!assertion) { BPLOG(INFO) << "minidump.GetAssertion() failed"; } else { assertion->Print(); } MinidumpSystemInfo *system_info = minidump.GetSystemInfo(); if (!system_info) { ++errors; BPLOG(ERROR) << "minidump.GetSystemInfo() failed"; } else { system_info->Print(); } MinidumpMiscInfo *misc_info = minidump.GetMiscInfo(); if (!misc_info) { ++errors; BPLOG(ERROR) << "minidump.GetMiscInfo() failed"; } else { misc_info->Print(); } MinidumpBreakpadInfo *breakpad_info = minidump.GetBreakpadInfo(); if (!breakpad_info) { // Breakpad info is optional, so don't treat this as an error. BPLOG(INFO) << "minidump.GetBreakpadInfo() failed"; } else { breakpad_info->Print(); } DumpRawStream(&minidump, MD_LINUX_CMD_LINE, "MD_LINUX_CMD_LINE", &errors); DumpRawStream(&minidump, MD_LINUX_ENVIRON, "MD_LINUX_ENVIRON", &errors); DumpRawStream(&minidump, MD_LINUX_LSB_RELEASE, "MD_LINUX_LSB_RELEASE", &errors); DumpRawStream(&minidump, MD_LINUX_PROC_STATUS, "MD_LINUX_PROC_STATUS", &errors); DumpRawStream(&minidump, MD_LINUX_CPU_INFO, "MD_LINUX_CPU_INFO", &errors); return errors == 0; } } // namespace int main(int argc, char **argv) { BPLOG_INIT(&argc, &argv); if (argc != 2) { fprintf(stderr, "usage: %s <file>\n", argv[0]); return 1; } return PrintMinidumpDump(argv[1]) ? 0 : 1; } <|endoftext|>
<commit_before>/* * PKCS #8 * (C) 1999-2008 Jack Lloyd * * Distributed under the terms of the Botan license */ #include <botan/pkcs8.h> #include <botan/get_pbe.h> #include <botan/der_enc.h> #include <botan/ber_dec.h> #include <botan/asn1_obj.h> #include <botan/oids.h> #include <botan/pem.h> #include <botan/internal/pk_algs.h> #include <memory> namespace Botan { namespace PKCS8 { namespace { /* * Get info from an EncryptedPrivateKeyInfo */ SecureVector<byte> PKCS8_extract(DataSource& source, AlgorithmIdentifier& pbe_alg_id) { SecureVector<byte> key_data; BER_Decoder(source) .start_cons(SEQUENCE) .decode(pbe_alg_id) .decode(key_data, OCTET_STRING) .verify_end(); return key_data; } /* * PEM decode and/or decrypt a private key */ SecureVector<byte> PKCS8_decode(DataSource& source, const User_Interface& ui, AlgorithmIdentifier& pk_alg_id) { AlgorithmIdentifier pbe_alg_id; SecureVector<byte> key_data, key; bool is_encrypted = true; try { if(ASN1::maybe_BER(source) && !PEM_Code::matches(source)) key_data = PKCS8_extract(source, pbe_alg_id); else { std::string label; key_data = PEM_Code::decode(source, label); if(label == "PRIVATE KEY") is_encrypted = false; else if(label == "ENCRYPTED PRIVATE KEY") { DataSource_Memory key_source(key_data); key_data = PKCS8_extract(key_source, pbe_alg_id); } else throw PKCS8_Exception("Unknown PEM label " + label); } if(key_data.empty()) throw PKCS8_Exception("No key data found"); } catch(Decoding_Error) { throw Decoding_Error("PKCS #8 private key decoding failed"); } if(!is_encrypted) key = key_data; const u32bit MAX_TRIES = 3; u32bit tries = 0; while(true) { try { if(MAX_TRIES && tries >= MAX_TRIES) break; if(is_encrypted) { DataSource_Memory params(pbe_alg_id.parameters); std::auto_ptr<PBE> pbe(get_pbe(pbe_alg_id.oid, params)); User_Interface::UI_Result result = User_Interface::OK; const std::string passphrase = ui.get_passphrase("PKCS #8 private key", source.id(), result); if(result == User_Interface::CANCEL_ACTION) break; pbe->set_key(passphrase); Pipe decryptor(pbe.release()); decryptor.process_msg(key_data, key_data.size()); key = decryptor.read_all(); } u32bit version; BER_Decoder(key) .start_cons(SEQUENCE) .decode(version) .decode(pk_alg_id) .decode(key, OCTET_STRING) .discard_remaining() .end_cons(); if(version != 0) throw Decoding_Error("PKCS #8: Unknown version number"); break; } catch(Decoding_Error) { ++tries; } } if(key.empty()) throw Decoding_Error("PKCS #8 private key decoding failed"); return key; } } /* * DER or PEM encode a PKCS #8 private key */ void encode(const Private_Key& key, Pipe& pipe, X509_Encoding encoding) { std::auto_ptr<PKCS8_Encoder> encoder(key.pkcs8_encoder()); if(!encoder.get()) throw Encoding_Error("PKCS8::encode: Key does not support encoding"); const u32bit PKCS8_VERSION = 0; SecureVector<byte> contents = DER_Encoder() .start_cons(SEQUENCE) .encode(PKCS8_VERSION) .encode(encoder->alg_id()) .encode(encoder->key_bits(), OCTET_STRING) .end_cons() .get_contents(); if(encoding == PEM) pipe.write(PEM_Code::encode(contents, "PRIVATE KEY")); else pipe.write(contents); } /* * Encode and encrypt a PKCS #8 private key */ void encrypt_key(const Private_Key& key, Pipe& pipe, RandomNumberGenerator& rng, const std::string& pass, const std::string& pbe_algo, X509_Encoding encoding) { const std::string DEFAULT_PBE = "PBE-PKCS5v20(SHA-1,TripleDES/CBC)"; Pipe raw_key; raw_key.start_msg(); encode(key, raw_key, RAW_BER); raw_key.end_msg(); std::auto_ptr<PBE> pbe(get_pbe(((pbe_algo != "") ? pbe_algo : DEFAULT_PBE))); pbe->new_params(rng); pbe->set_key(pass); AlgorithmIdentifier pbe_algid(pbe->get_oid(), pbe->encode_params()); Pipe key_encrytor(pbe.release()); key_encrytor.process_msg(raw_key); SecureVector<byte> enc_key = DER_Encoder() .start_cons(SEQUENCE) .encode(pbe_algid) .encode(key_encrytor.read_all(), OCTET_STRING) .end_cons() .get_contents(); if(encoding == PEM) pipe.write(PEM_Code::encode(enc_key, "ENCRYPTED PRIVATE KEY")); else pipe.write(enc_key); } /* * PEM encode a PKCS #8 private key */ std::string PEM_encode(const Private_Key& key) { Pipe pem; pem.start_msg(); encode(key, pem, PEM); pem.end_msg(); return pem.read_all_as_string(); } /* * Encrypt and PEM encode a PKCS #8 private key */ std::string PEM_encode(const Private_Key& key, RandomNumberGenerator& rng, const std::string& pass, const std::string& pbe_algo) { if(pass == "") return PEM_encode(key); Pipe pem; pem.start_msg(); encrypt_key(key, pem, rng, pass, pbe_algo, PEM); pem.end_msg(); return pem.read_all_as_string(); } /* * Extract a private key and return it */ Private_Key* load_key(DataSource& source, RandomNumberGenerator& rng, const User_Interface& ui) { AlgorithmIdentifier alg_id; SecureVector<byte> pkcs8_key = PKCS8_decode(source, ui, alg_id); const std::string alg_name = OIDS::lookup(alg_id.oid); if(alg_name == "" || alg_name == alg_id.oid.as_string()) throw PKCS8_Exception("Unknown algorithm OID: " + alg_id.oid.as_string()); std::auto_ptr<Private_Key> key(get_private_key(alg_name)); if(!key.get()) throw PKCS8_Exception("Unknown PK algorithm/OID: " + alg_name + ", " + alg_id.oid.as_string()); std::auto_ptr<PKCS8_Decoder> decoder(key->pkcs8_decoder(rng)); if(!decoder.get()) throw Decoding_Error("Key does not support PKCS #8 decoding"); decoder->alg_id(alg_id); decoder->key_bits(pkcs8_key); return key.release(); } /* * Extract a private key and return it */ Private_Key* load_key(const std::string& fsname, RandomNumberGenerator& rng, const User_Interface& ui) { DataSource_Stream source(fsname, true); return PKCS8::load_key(source, rng, ui); } /* * Extract a private key and return it */ Private_Key* load_key(DataSource& source, RandomNumberGenerator& rng, const std::string& pass) { return PKCS8::load_key(source, rng, User_Interface(pass)); } /* * Extract a private key and return it */ Private_Key* load_key(const std::string& fsname, RandomNumberGenerator& rng, const std::string& pass) { return PKCS8::load_key(fsname, rng, User_Interface(pass)); } /* * Make a copy of this private key */ Private_Key* copy_key(const Private_Key& key, RandomNumberGenerator& rng) { Pipe bits; bits.start_msg(); PKCS8::encode(key, bits); bits.end_msg(); DataSource_Memory source(bits.read_all()); return PKCS8::load_key(source, rng); } } } <commit_msg>Switch from TripleDES to AES-256 for private key encryption by default. OpenSSL 0.9.8 understands keys encrypted like this fine, which was the big reason for holding back on this before IIRC. AES-256 was chosen over AES-128 not for the longer key length (it's a password hash so unlikely to have more than 96 bits of entropy) but for the extra 4 rounds of AES-256 vs AES-128.<commit_after>/* * PKCS #8 * (C) 1999-2008 Jack Lloyd * * Distributed under the terms of the Botan license */ #include <botan/pkcs8.h> #include <botan/get_pbe.h> #include <botan/der_enc.h> #include <botan/ber_dec.h> #include <botan/asn1_obj.h> #include <botan/oids.h> #include <botan/pem.h> #include <botan/internal/pk_algs.h> #include <memory> namespace Botan { namespace PKCS8 { namespace { /* * Get info from an EncryptedPrivateKeyInfo */ SecureVector<byte> PKCS8_extract(DataSource& source, AlgorithmIdentifier& pbe_alg_id) { SecureVector<byte> key_data; BER_Decoder(source) .start_cons(SEQUENCE) .decode(pbe_alg_id) .decode(key_data, OCTET_STRING) .verify_end(); return key_data; } /* * PEM decode and/or decrypt a private key */ SecureVector<byte> PKCS8_decode(DataSource& source, const User_Interface& ui, AlgorithmIdentifier& pk_alg_id) { AlgorithmIdentifier pbe_alg_id; SecureVector<byte> key_data, key; bool is_encrypted = true; try { if(ASN1::maybe_BER(source) && !PEM_Code::matches(source)) key_data = PKCS8_extract(source, pbe_alg_id); else { std::string label; key_data = PEM_Code::decode(source, label); if(label == "PRIVATE KEY") is_encrypted = false; else if(label == "ENCRYPTED PRIVATE KEY") { DataSource_Memory key_source(key_data); key_data = PKCS8_extract(key_source, pbe_alg_id); } else throw PKCS8_Exception("Unknown PEM label " + label); } if(key_data.empty()) throw PKCS8_Exception("No key data found"); } catch(Decoding_Error) { throw Decoding_Error("PKCS #8 private key decoding failed"); } if(!is_encrypted) key = key_data; const u32bit MAX_TRIES = 3; u32bit tries = 0; while(true) { try { if(MAX_TRIES && tries >= MAX_TRIES) break; if(is_encrypted) { DataSource_Memory params(pbe_alg_id.parameters); std::auto_ptr<PBE> pbe(get_pbe(pbe_alg_id.oid, params)); User_Interface::UI_Result result = User_Interface::OK; const std::string passphrase = ui.get_passphrase("PKCS #8 private key", source.id(), result); if(result == User_Interface::CANCEL_ACTION) break; pbe->set_key(passphrase); Pipe decryptor(pbe.release()); decryptor.process_msg(key_data, key_data.size()); key = decryptor.read_all(); } u32bit version; BER_Decoder(key) .start_cons(SEQUENCE) .decode(version) .decode(pk_alg_id) .decode(key, OCTET_STRING) .discard_remaining() .end_cons(); if(version != 0) throw Decoding_Error("PKCS #8: Unknown version number"); break; } catch(Decoding_Error) { ++tries; } } if(key.empty()) throw Decoding_Error("PKCS #8 private key decoding failed"); return key; } } /* * DER or PEM encode a PKCS #8 private key */ void encode(const Private_Key& key, Pipe& pipe, X509_Encoding encoding) { std::auto_ptr<PKCS8_Encoder> encoder(key.pkcs8_encoder()); if(!encoder.get()) throw Encoding_Error("PKCS8::encode: Key does not support encoding"); const u32bit PKCS8_VERSION = 0; SecureVector<byte> contents = DER_Encoder() .start_cons(SEQUENCE) .encode(PKCS8_VERSION) .encode(encoder->alg_id()) .encode(encoder->key_bits(), OCTET_STRING) .end_cons() .get_contents(); if(encoding == PEM) pipe.write(PEM_Code::encode(contents, "PRIVATE KEY")); else pipe.write(contents); } /* * Encode and encrypt a PKCS #8 private key */ void encrypt_key(const Private_Key& key, Pipe& pipe, RandomNumberGenerator& rng, const std::string& pass, const std::string& pbe_algo, X509_Encoding encoding) { const std::string DEFAULT_PBE = "PBE-PKCS5v20(SHA-1,AES-128/CBC)"; Pipe raw_key; raw_key.start_msg(); encode(key, raw_key, RAW_BER); raw_key.end_msg(); std::auto_ptr<PBE> pbe(get_pbe(((pbe_algo != "") ? pbe_algo : DEFAULT_PBE))); pbe->new_params(rng); pbe->set_key(pass); AlgorithmIdentifier pbe_algid(pbe->get_oid(), pbe->encode_params()); Pipe key_encrytor(pbe.release()); key_encrytor.process_msg(raw_key); SecureVector<byte> enc_key = DER_Encoder() .start_cons(SEQUENCE) .encode(pbe_algid) .encode(key_encrytor.read_all(), OCTET_STRING) .end_cons() .get_contents(); if(encoding == PEM) pipe.write(PEM_Code::encode(enc_key, "ENCRYPTED PRIVATE KEY")); else pipe.write(enc_key); } /* * PEM encode a PKCS #8 private key */ std::string PEM_encode(const Private_Key& key) { Pipe pem; pem.start_msg(); encode(key, pem, PEM); pem.end_msg(); return pem.read_all_as_string(); } /* * Encrypt and PEM encode a PKCS #8 private key */ std::string PEM_encode(const Private_Key& key, RandomNumberGenerator& rng, const std::string& pass, const std::string& pbe_algo) { if(pass == "") return PEM_encode(key); Pipe pem; pem.start_msg(); encrypt_key(key, pem, rng, pass, pbe_algo, PEM); pem.end_msg(); return pem.read_all_as_string(); } /* * Extract a private key and return it */ Private_Key* load_key(DataSource& source, RandomNumberGenerator& rng, const User_Interface& ui) { AlgorithmIdentifier alg_id; SecureVector<byte> pkcs8_key = PKCS8_decode(source, ui, alg_id); const std::string alg_name = OIDS::lookup(alg_id.oid); if(alg_name == "" || alg_name == alg_id.oid.as_string()) throw PKCS8_Exception("Unknown algorithm OID: " + alg_id.oid.as_string()); std::auto_ptr<Private_Key> key(get_private_key(alg_name)); if(!key.get()) throw PKCS8_Exception("Unknown PK algorithm/OID: " + alg_name + ", " + alg_id.oid.as_string()); std::auto_ptr<PKCS8_Decoder> decoder(key->pkcs8_decoder(rng)); if(!decoder.get()) throw Decoding_Error("Key does not support PKCS #8 decoding"); decoder->alg_id(alg_id); decoder->key_bits(pkcs8_key); return key.release(); } /* * Extract a private key and return it */ Private_Key* load_key(const std::string& fsname, RandomNumberGenerator& rng, const User_Interface& ui) { DataSource_Stream source(fsname, true); return PKCS8::load_key(source, rng, ui); } /* * Extract a private key and return it */ Private_Key* load_key(DataSource& source, RandomNumberGenerator& rng, const std::string& pass) { return PKCS8::load_key(source, rng, User_Interface(pass)); } /* * Extract a private key and return it */ Private_Key* load_key(const std::string& fsname, RandomNumberGenerator& rng, const std::string& pass) { return PKCS8::load_key(fsname, rng, User_Interface(pass)); } /* * Make a copy of this private key */ Private_Key* copy_key(const Private_Key& key, RandomNumberGenerator& rng) { Pipe bits; bits.start_msg(); PKCS8::encode(key, bits); bits.end_msg(); DataSource_Memory source(bits.read_all()); return PKCS8::load_key(source, rng); } } } <|endoftext|>
<commit_before>/*************************************************************************** main.cpp - description ------------------- begin : Wed Aug 2 11:23:04 CEST 2000 copyright : (C) 2000 by Hans Dijkema email : [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 <kcmdlineargs.h> #include <kaboutdata.h> #include <dcopclient.h> #include "kmailcvt.h" static const KCmdLineOptions options[] = { KCmdLineLastOption }; int main(int argc, char *argv[]) { KLocale::setMainCatalogue("kmailcvt"); KAboutData aboutData( "kmailcvt", I18N_NOOP("KMailCVT"), "3", I18N_NOOP("KMail Import Filters"), KAboutData::License_GPL_V2, I18N_NOOP("(c) 2000-2005, The KMailCVT developers")); aboutData.addAuthor("Hans Dijkema",I18N_NOOP("Original author"), "[email protected]"); aboutData.addAuthor("Danny Kukawka", I18N_NOOP("Maintainer & New filters"), "[email protected]"); aboutData.addAuthor("Laurence Anderson", I18N_NOOP("New GUI & cleanups"), "[email protected]"); aboutData.addCredit("Daniel Molkentin", I18N_NOOP("New GUI & cleanups"), "[email protected]"); KCmdLineArgs::init( argc, argv, &aboutData ); KCmdLineArgs::addCmdLineOptions( options ); // Add our own options. KApplication a; KMailCVT *kmailcvt = new KMailCVT(); a.setMainWidget(kmailcvt); kmailcvt->show(); DCOPClient *client=a.dcopClient(); if (!client->attach()) { return 1; } return a.exec(); } <commit_msg>Adapt api<commit_after>/*************************************************************************** main.cpp - description ------------------- begin : Wed Aug 2 11:23:04 CEST 2000 copyright : (C) 2000 by Hans Dijkema email : [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 <kcmdlineargs.h> #include <kaboutdata.h> #include <dcopclient.h> #include "kmailcvt.h" static const KCmdLineOptions options[] = { KCmdLineLastOption }; int main(int argc, char *argv[]) { KLocale::setMainCatalog("kmailcvt"); KAboutData aboutData( "kmailcvt", I18N_NOOP("KMailCVT"), "3", I18N_NOOP("KMail Import Filters"), KAboutData::License_GPL_V2, I18N_NOOP("(c) 2000-2005, The KMailCVT developers")); aboutData.addAuthor("Hans Dijkema",I18N_NOOP("Original author"), "[email protected]"); aboutData.addAuthor("Danny Kukawka", I18N_NOOP("Maintainer & New filters"), "[email protected]"); aboutData.addAuthor("Laurence Anderson", I18N_NOOP("New GUI & cleanups"), "[email protected]"); aboutData.addCredit("Daniel Molkentin", I18N_NOOP("New GUI & cleanups"), "[email protected]"); KCmdLineArgs::init( argc, argv, &aboutData ); KCmdLineArgs::addCmdLineOptions( options ); // Add our own options. KApplication a; KMailCVT *kmailcvt = new KMailCVT(); a.setMainWidget(kmailcvt); kmailcvt->show(); DCOPClient *client=a.dcopClient(); if (!client->attach()) { return 1; } return a.exec(); } <|endoftext|>
<commit_before>/* Kernel modules can handle sub-microsecond interrupts: http://raspberrypi.stackexchange.com/questions/8586/arm-timer-in-kernel-module-with-precision-less-than-microsecond cat /proc/timer_list indicates that high-res timer (hrtimer) resolution is actually 1 ns hrtimer is available to userspace programs. http://elinux.org/High_Resolution_Timers Or is it kernel modules? http://raspberrypi.stackexchange.com/questions/8586/arm-timer-in-kernel-module-with-precision-less-than-microsecond hrtimers are now used in Posix timers and nanosleep and itimers: http://lwn.net/Articles/168399/ https://www.kernel.org/doc/Documentation/timers/hrtimers.txt */ int main() { return 0; } <commit_msg>Working hrtimer test<commit_after>/* Kernel modules can handle sub-microsecond interrupts: http://raspberrypi.stackexchange.com/questions/8586/arm-timer-in-kernel-module-with-precision-less-than-microsecond cat /proc/timer_list indicates that high-res timer (hrtimer) resolution is actually 1 ns hrtimer is available to userspace programs. http://elinux.org/High_Resolution_Timers Or is it kernel modules? http://raspberrypi.stackexchange.com/questions/8586/arm-timer-in-kernel-module-with-precision-less-than-microsecond hrtimers are now used in Posix timers and nanosleep and itimers: http://lwn.net/Articles/168399/ https://www.kernel.org/doc/Documentation/timers/hrtimers.txt Distributions for testNanoSleep @ 1/2 second: Ubunutu Laptop (40 samples): mean: 206546.75 ns, sd: 40484.71056 ns, about 40 uSec */ #include <time.h> #include <stdio.h> void getClockInfo() { clockid_t types[] = {CLOCK_REALTIME, CLOCK_MONOTONIC, CLOCK_PROCESS_CPUTIME_ID, CLOCK_THREAD_CPUTIME_ID, (clockid_t)-1}; struct timespec spec; for (int i=0; types[i] != (clockid_t)-1; i++) { if (clock_getres( types[i], &spec ) != 0) { printf("Timer %d not supported.\n", types[i]); } else { printf("Timer: %d, Seconds: %ld Nanos: %ld\n", i, spec.tv_sec, spec.tv_nsec); } } } void logTime(int clockId) { struct timespec time; clock_gettime(clockId, &time); printf("Time: %lu.%lu\n", time.tv_sec, time.tv_nsec); } void testNanoSleep() { struct timespec tim, tim2; tim.tv_sec = 0; tim.tv_nsec = 500000000; logTime(0); nanosleep(&tim, &tim2); logTime(0); } long testSleepPrecision() { struct timespec sleepDur, remaining, startTime, endTime; sleepDur.tv_sec = 0; sleepDur.tv_nsec = 500000000; clock_gettime(0, &startTime); nanosleep(&sleepDur, &remaining); clock_gettime(0, &endTime); endTime.tv_sec -= startTime.tv_sec; return (endTime.tv_sec - sleepDur.tv_sec)*1000000000 + (endTime.tv_nsec - startTime.tv_nsec - sleepDur.tv_nsec); } int main(int argc, char** argv) { getClockInfo(); testNanoSleep(); for (int i=0; i<40; ++i) { printf("%lu, ", testSleepPrecision()); } } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: TestQuadRotationalExtrusionMultiBlock.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ // .SECTION Thanks // This test was written by Philippe Pebay, Kitware SAS 2011 #include "vtkCamera.h" #include "vtkCompositeDataGeometryFilter.h" #include "vtkInformation.h" #include "vtkMultiBlockDataSet.h" #include "vtkNew.h" #include "vtkPolyDataMapper.h" #include "vtkPolyDataNormals.h" #include "vtkProperty.h" #include "vtkRegressionTestImage.h" #include "vtkRenderer.h" #include "vtkRenderWindow.h" #include "vtkRenderWindowInteractor.h" #include "vtkQuadRotationalExtrusionFilter.h" #include "vtkTestUtilities.h" #include "vtkXMLPolyDataReader.h" //---------------------------------------------------------------------------- int TestQuadRotationalExtrusionMultiBlock( int argc, char * argv [] ) { // Read block 0 of 2D polygonal input mesh char* fName0 = vtkTestUtilities::ExpandDataFileName( argc, argv, "Data/SemiDisk/SemiDisk-0.vtp"); vtkNew<vtkXMLPolyDataReader> reader0; reader0->SetFileName( fName0 ); reader0->Update(); delete [] fName0; // Read block 1 of 2D polygonal input mesh char* fName1 = vtkTestUtilities::ExpandDataFileName( argc, argv, "Data/SemiDisk/SemiDisk-1.vtp"); vtkNew<vtkXMLPolyDataReader> reader1; reader1->SetFileName( fName1 ); reader1->Update(); delete [] fName1; // Create multi-block data set for quad-based sweep vtkNew<vtkMultiBlockDataSet> inMesh; inMesh->SetNumberOfBlocks( 2 ); inMesh->GetMetaData( static_cast<unsigned>( 0 ) )->Set( vtkCompositeDataSet::NAME(), "Block 0" ); inMesh->SetBlock( 0, reader0->GetOutput() ); inMesh->GetMetaData( static_cast<unsigned>( 1 ) )->Set( vtkCompositeDataSet::NAME(), "Block 1" ); inMesh->SetBlock( 1, reader1->GetOutput() ); // Create 3/4 of a cylinder by rotational extrusion vtkNew<vtkQuadRotationalExtrusionFilter> sweeper; sweeper->SetResolution( 18 ); sweeper->SetInputData( inMesh.GetPointer() ); sweeper->SetAxisToX(); sweeper->SetDefaultAngle( 270 ); sweeper->AddPerBlockAngle( 1, 90. ); sweeper->AddPerBlockAngle( 2, 45.) ; // Turn composite output into single polydata vtkNew<vtkCompositeDataGeometryFilter> outMesh; outMesh->SetInputConnection( sweeper->GetOutputPort() ); // Create normals for smooth rendering vtkNew<vtkPolyDataNormals> normals; normals->SetInputConnection( outMesh->GetOutputPort() ); // Create mapper for surface representation of whole mesh vtkNew<vtkPolyDataMapper> outMeshMapper; outMeshMapper->SetInputConnection( normals->GetOutputPort() ); outMeshMapper->SetResolveCoincidentTopologyToPolygonOffset(); // Create actor for surface representation of whole mesh vtkNew<vtkActor> outMeshActor; outMeshActor->SetMapper( outMeshMapper.GetPointer() ); outMeshActor->GetProperty()->SetRepresentationToSurface(); outMeshActor->GetProperty()->SetInterpolationToGouraud(); outMeshActor->GetProperty()->SetColor( .9, .9, .9 ); // Retrieve polydata blocks output by sweeper sweeper->Update(); vtkMultiBlockDataSet* outMeshMB = sweeper->GetOutput(); vtkPolyData* outMesh0 = vtkPolyData::SafeDownCast( outMeshMB->GetBlock( 0 ) ); vtkPolyData* outMesh1 = vtkPolyData::SafeDownCast( outMeshMB->GetBlock( 1 ) ); // Create mapper for wireframe representation of block 0 vtkNew<vtkPolyDataMapper> outBlockMapper0; outBlockMapper0->SetInputData( outMesh0 ); outBlockMapper0->SetResolveCoincidentTopologyToPolygonOffset(); // Create actor for wireframe representation of block 0 vtkNew<vtkActor> outBlockActor0; outBlockActor0->SetMapper( outBlockMapper0.GetPointer() ); outBlockActor0->GetProperty()->SetRepresentationToWireframe(); outBlockActor0->GetProperty()->SetColor( .9, 0., 0.); outBlockActor0->GetProperty()->SetAmbient( 1. ); outBlockActor0->GetProperty()->SetDiffuse( 0. ); outBlockActor0->GetProperty()->SetSpecular( 0. ); // Create mapper for wireframe representation of block 1 vtkNew<vtkPolyDataMapper> outBlockMapper1; outBlockMapper1->SetInputData( outMesh1 ); outBlockMapper1->SetResolveCoincidentTopologyToPolygonOffset(); // Create actor for wireframe representation of block 1 vtkNew<vtkActor> outBlockActor1; outBlockActor1->SetMapper( outBlockMapper1.GetPointer() ); outBlockActor1->GetProperty()->SetRepresentationToWireframe(); outBlockActor1->GetProperty()->SetColor( 0., .9, 0.); outBlockActor1->GetProperty()->SetAmbient( 1. ); outBlockActor1->GetProperty()->SetDiffuse( 0. ); outBlockActor1->GetProperty()->SetSpecular( 0. ); // Create a renderer, add actors to it vtkNew<vtkRenderer> ren1; ren1->AddActor( outMeshActor.GetPointer() ); ren1->AddActor( outBlockActor0.GetPointer() ); ren1->AddActor( outBlockActor1.GetPointer() ); ren1->SetBackground( 1., 1., 1. ); // Create a renderWindow vtkNew<vtkRenderWindow> renWin; renWin->AddRenderer( ren1.GetPointer() ); renWin->SetSize( 400, 400 ); renWin->SetMultiSamples( 0 ); // Create a good view angle vtkNew<vtkCamera> camera; //camera->SetClippingRange( 0.576398, 28.8199 ); camera->SetFocalPoint( 36.640094041788934, 0.3387609170199118, 1.2087523663629445 ); camera->SetPosition( 37.77735939083618, 0.42739828159854326, 2.988046512725565 ); camera->SetViewUp( -0.40432906992858864, 0.8891923825021084, 0.21413759621072337 ); camera->SetViewAngle( 30. ); ren1->SetActiveCamera( camera.GetPointer() ); // Create interactor vtkNew<vtkRenderWindowInteractor> iren; iren->SetRenderWindow( renWin.GetPointer() ); // Render and test renWin->Render(); int retVal = vtkRegressionTestImage( renWin.GetPointer() ); if ( retVal == vtkRegressionTester::DO_INTERACTOR ) { iren->Start(); } return !retVal; } <commit_msg>Add a valid image that was sqeeking by earlier<commit_after>/*========================================================================= Program: Visualization Toolkit Module: TestQuadRotationalExtrusionMultiBlock.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ // .SECTION Thanks // This test was written by Philippe Pebay, Kitware SAS 2011 #include "vtkCamera.h" #include "vtkCompositeDataGeometryFilter.h" #include "vtkInformation.h" #include "vtkMultiBlockDataSet.h" #include "vtkNew.h" #include "vtkPolyDataMapper.h" #include "vtkPolyDataNormals.h" #include "vtkProperty.h" #include "vtkRegressionTestImage.h" #include "vtkRenderer.h" #include "vtkRenderWindow.h" #include "vtkRenderWindowInteractor.h" #include "vtkQuadRotationalExtrusionFilter.h" #include "vtkTestUtilities.h" #include "vtkXMLPolyDataReader.h" //---------------------------------------------------------------------------- int TestQuadRotationalExtrusionMultiBlock( int argc, char * argv [] ) { // Read block 0 of 2D polygonal input mesh char* fName0 = vtkTestUtilities::ExpandDataFileName( argc, argv, "Data/SemiDisk/SemiDisk-0.vtp"); vtkNew<vtkXMLPolyDataReader> reader0; reader0->SetFileName( fName0 ); reader0->Update(); delete [] fName0; // Read block 1 of 2D polygonal input mesh char* fName1 = vtkTestUtilities::ExpandDataFileName( argc, argv, "Data/SemiDisk/SemiDisk-1.vtp"); vtkNew<vtkXMLPolyDataReader> reader1; reader1->SetFileName( fName1 ); reader1->Update(); delete [] fName1; // Create multi-block data set for quad-based sweep vtkNew<vtkMultiBlockDataSet> inMesh; inMesh->SetNumberOfBlocks( 2 ); inMesh->GetMetaData( static_cast<unsigned>( 0 ) )->Set( vtkCompositeDataSet::NAME(), "Block 0" ); inMesh->SetBlock( 0, reader0->GetOutput() ); inMesh->GetMetaData( static_cast<unsigned>( 1 ) )->Set( vtkCompositeDataSet::NAME(), "Block 1" ); inMesh->SetBlock( 1, reader1->GetOutput() ); // Create 3/4 of a cylinder by rotational extrusion vtkNew<vtkQuadRotationalExtrusionFilter> sweeper; sweeper->SetResolution( 18 ); sweeper->SetInputData( inMesh.GetPointer() ); sweeper->SetAxisToX(); sweeper->SetDefaultAngle( 270 ); sweeper->AddPerBlockAngle( 1, 90. ); sweeper->AddPerBlockAngle( 2, 45.) ; // Turn composite output into single polydata vtkNew<vtkCompositeDataGeometryFilter> outMesh; outMesh->SetInputConnection( sweeper->GetOutputPort() ); // Create normals for smooth rendering vtkNew<vtkPolyDataNormals> normals; normals->SetInputConnection( outMesh->GetOutputPort() ); // Create mapper for surface representation of whole mesh vtkNew<vtkPolyDataMapper> outMeshMapper; outMeshMapper->SetInputConnection( normals->GetOutputPort() ); outMeshMapper->SetResolveCoincidentTopologyToPolygonOffset(); // Create actor for surface representation of whole mesh vtkNew<vtkActor> outMeshActor; outMeshActor->SetMapper( outMeshMapper.GetPointer() ); outMeshActor->GetProperty()->SetRepresentationToSurface(); outMeshActor->GetProperty()->SetInterpolationToGouraud(); outMeshActor->GetProperty()->SetColor( .9, .9, .9 ); // Retrieve polydata blocks output by sweeper sweeper->Update(); vtkMultiBlockDataSet* outMeshMB = sweeper->GetOutput(); vtkPolyData* outMesh0 = vtkPolyData::SafeDownCast( outMeshMB->GetBlock( 0 ) ); vtkPolyData* outMesh1 = vtkPolyData::SafeDownCast( outMeshMB->GetBlock( 1 ) ); // Create mapper for wireframe representation of block 0 vtkNew<vtkPolyDataMapper> outBlockMapper0; outBlockMapper0->SetInputData( outMesh0 ); outBlockMapper0->SetResolveCoincidentTopologyToPolygonOffset(); // Create actor for wireframe representation of block 0 vtkNew<vtkActor> outBlockActor0; outBlockActor0->SetMapper( outBlockMapper0.GetPointer() ); outBlockActor0->GetProperty()->SetRepresentationToWireframe(); outBlockActor0->GetProperty()->SetColor( .9, 0., 0.); outBlockActor0->GetProperty()->SetAmbient( 1. ); outBlockActor0->GetProperty()->SetDiffuse( 0. ); outBlockActor0->GetProperty()->SetSpecular( 0. ); // Create mapper for wireframe representation of block 1 vtkNew<vtkPolyDataMapper> outBlockMapper1; outBlockMapper1->SetInputData( outMesh1 ); outBlockMapper1->SetResolveCoincidentTopologyToPolygonOffset(); // Create actor for wireframe representation of block 1 vtkNew<vtkActor> outBlockActor1; outBlockActor1->SetMapper( outBlockMapper1.GetPointer() ); outBlockActor1->GetProperty()->SetRepresentationToWireframe(); outBlockActor1->GetProperty()->SetColor( 0., .9, 0.); outBlockActor1->GetProperty()->SetAmbient( 1. ); outBlockActor1->GetProperty()->SetDiffuse( 0. ); outBlockActor1->GetProperty()->SetSpecular( 0. ); // Create a renderer, add actors to it vtkNew<vtkRenderer> ren1; ren1->AddActor( outMeshActor.GetPointer() ); ren1->AddActor( outBlockActor0.GetPointer() ); ren1->AddActor( outBlockActor1.GetPointer() ); ren1->SetBackground( 1., 1., 1. ); // Create a renderWindow vtkNew<vtkRenderWindow> renWin; renWin->AddRenderer( ren1.GetPointer() ); renWin->SetSize( 400, 400 ); renWin->SetMultiSamples( 0 ); // Create a good view angle vtkNew<vtkCamera> camera; //camera->SetClippingRange( 0.576398, 28.8199 ); camera->SetFocalPoint( 36.640094041788934, 0.3387609170199118, 1.2087523663629445 ); camera->SetPosition( 37.77735939083618, 0.42739828159854326, 2.988046512725565 ); camera->SetViewUp( -0.40432906992858864, 0.8891923825021084, 0.21413759621072337 ); camera->SetViewAngle( 30. ); ren1->SetActiveCamera( camera.GetPointer() ); ren1->ResetCameraClippingRange(); // Create interactor vtkNew<vtkRenderWindowInteractor> iren; iren->SetRenderWindow( renWin.GetPointer() ); // Render and test renWin->Render(); int retVal = vtkRegressionTestImage( renWin.GetPointer() ); if ( retVal == vtkRegressionTester::DO_INTERACTOR ) { iren->Start(); } return !retVal; } <|endoftext|>
<commit_before>/******************************************************************************* * ALMA - Atacama Large Millimiter Array * (c) Associated Universities Inc., 2002 * * (c) European Southern Observatory, 2002 * Copyright by ESO (in the framework of the ALMA collaboration) * and Cosylab 2002, All rights reserved * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * * * "@(#) $Id: contLogTestImpl.cpp,v 1.5 2007/12/11 09:34:17 cparedes Exp $" * * who when what * -------- ---------- ---------------------------------------------- * eallaert 2007-11-05 initial version * */ #include <contLogTestImpl.h> #include <ACSErrTypeCommon.h> #include <loggingLogLevelDefinition.h> #include <iostream> ACE_RCSID(contLogTest, contLogTestImpl, "$Id: contLogTestImpl.cpp,v 1.5 2007/12/11 09:34:17 cparedes Exp $") /* ----------------------------------------------------------------*/ TestLogLevelsComp::TestLogLevelsComp( const ACE_CString &name, maci::ContainerServices * containerServices) : ACSComponentImpl(name, containerServices) { // ACS_TRACE is used for debugging purposes ACS_TRACE("::TestLogLevelsComp::TestLogLevelsComp"); } /* ----------------------------------------------------------------*/ TestLogLevelsComp::~TestLogLevelsComp() { // ACS_TRACE is used for debugging purposes ACS_TRACE("::TestLogLevelsComp::~TestLogLevelsComp"); ACS_DEBUG_PARAM("::TestLogLevelsComp::~TestLogLevelsComp", "Destroying %s...", name()); } /* --------------------- [ CORBA interface ] ----------------------*/ ::contLogTest::LongSeq* TestLogLevelsComp::getLevels () throw (CORBA::SystemException, ACSErrTypeCommon::CouldntPerformActionEx) { std::cout << "Hi there!" << std::endl; ::contLogTest::LongSeq_var level = new ::contLogTest::LongSeq(5); level->length(5); // need the equivalent of Java's logConfig.getMinLogLevel() etc. in C++ for (int i = 0; i <5 ; i++) level[i] = static_cast< CORBA::Long >(i); std::cout << "Done filling levels." << std::endl; return level._retn(); } void TestLogLevelsComp::logDummyMessages (const ::contLogTest::LongSeq & levels) { for (CORBA::ULong t=0; t<levels.length(); t++){ ACE_Log_Priority p = LogLevelDefinition::getACELogPriority(levels[t]); ACS_SHORT_LOG((p, "dummy log message for core level %d", levels[t])); } } /* --------------- [ MACI DLL support functions ] -----------------*/ #include <maciACSComponentDefines.h> MACI_DLL_SUPPORT_FUNCTIONS(TestLogLevelsComp) /* ----------------------------------------------------------------*/ /*___oOo___*/ <commit_msg>Added "last log" message in logDummyMessages() method, as identifier when picking up logs (instead of relying on timeout).<commit_after>/******************************************************************************* * ALMA - Atacama Large Millimiter Array * (c) Associated Universities Inc., 2002 * * (c) European Southern Observatory, 2002 * Copyright by ESO (in the framework of the ALMA collaboration) * and Cosylab 2002, All rights reserved * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * * * "@(#) $Id: contLogTestImpl.cpp,v 1.6 2007/12/14 16:48:44 eallaert Exp $" * * who when what * -------- ---------- ---------------------------------------------- * eallaert 2007-11-05 initial version * */ #include <contLogTestImpl.h> #include <ACSErrTypeCommon.h> #include <loggingLogLevelDefinition.h> #include <iostream> ACE_RCSID(contLogTest, contLogTestImpl, "$Id: contLogTestImpl.cpp,v 1.6 2007/12/14 16:48:44 eallaert Exp $") /* ----------------------------------------------------------------*/ TestLogLevelsComp::TestLogLevelsComp( const ACE_CString &name, maci::ContainerServices * containerServices) : ACSComponentImpl(name, containerServices) { // ACS_TRACE is used for debugging purposes ACS_TRACE("::TestLogLevelsComp::TestLogLevelsComp"); } /* ----------------------------------------------------------------*/ TestLogLevelsComp::~TestLogLevelsComp() { // ACS_TRACE is used for debugging purposes ACS_TRACE("::TestLogLevelsComp::~TestLogLevelsComp"); ACS_DEBUG_PARAM("::TestLogLevelsComp::~TestLogLevelsComp", "Destroying %s...", name()); } /* --------------------- [ CORBA interface ] ----------------------*/ ::contLogTest::LongSeq* TestLogLevelsComp::getLevels () throw (CORBA::SystemException, ACSErrTypeCommon::CouldntPerformActionEx) { ::contLogTest::LongSeq_var level = new ::contLogTest::LongSeq(5); level->length(5); // need the equivalent of Java's logConfig.getMinLogLevel() etc. in C++ for (int i = 0; i <5 ; i++) level[i] = static_cast< CORBA::Long >(i); return level._retn(); } void TestLogLevelsComp::logDummyMessages (const ::contLogTest::LongSeq & levels) { ACE_Log_Priority p; CORBA::ULong t=0; for (t=0; t<levels.length(); t++){ p = LogLevelDefinition::getACELogPriority(levels[t]); LogLevelDefinition lld = LogLevelDefinition::fromInteger(levels[t]); ACS_SHORT_LOG((p, "dummy log message for core level %d/%s", lld.getValue(), lld.getName().c_str())); } ACS_SHORT_LOG((p, "===last log messsage===", levels[t])); } /* --------------- [ MACI DLL support functions ] -----------------*/ #include <maciACSComponentDefines.h> MACI_DLL_SUPPORT_FUNCTIONS(TestLogLevelsComp) /* ----------------------------------------------------------------*/ /*___oOo___*/ <|endoftext|>
<commit_before>// Copyright (c) 2016-2018 The Syscoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <test/test_syscoin_services.h> #include <util/time.h> #include <rpc/server.h> #include <services/asset.h> #include <base58.h> #include <chainparams.h> #include <boost/test/unit_test.hpp> #include <iterator> #include <key.h> using namespace std; BOOST_GLOBAL_FIXTURE( SyscoinTestingSetup ); BOOST_FIXTURE_TEST_SUITE(syscoin_asset_allocation_tests, BasicSyscoinTestingSetup) BOOST_AUTO_TEST_CASE(generate_asset_allocation_address_sync) { UniValue r; printf("Running generate_asset_allocation_address_sync...\n"); GenerateBlocks(5); string newaddress = GetNewFundedAddress("node1"); BOOST_CHECK_NO_THROW(r = CallExtRPC("node1", "getnewaddress")); string newaddressreceiver = r.get_str(); string guid = AssetNew("node1", newaddress, "data", "''", "8", "10000", "1000000"); AssetSend("node1", guid, "\"[{\\\"address\\\":\\\"" + newaddressreceiver + "\\\",\\\"amount\\\":5000}]\""); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationinfo " + guid + " " + newaddressreceiver )); UniValue balance = find_value(r.get_obj(), "balance"); BOOST_CHECK_NO_THROW(r = CallRPC("node2", "assetallocationinfo " + guid + " " + newaddressreceiver )); balance = find_value(r.get_obj(), "balance"); StopNode("node2"); StartNode("node2"); GenerateBlocks(5, "node2"); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationinfo " + guid + " " + newaddressreceiver )); balance = find_value(r.get_obj(), "balance"); BOOST_CHECK_NO_THROW(r = CallRPC("node2", "assetallocationinfo " + guid + " " + newaddressreceiver )); balance = find_value(r.get_obj(), "balance"); } BOOST_AUTO_TEST_CASE(generate_asset_allocation_lock) { UniValue r; printf("Running generate_asset_allocation_lock...\n"); GenerateBlocks(5); string txid; string newaddress1 = GetNewFundedAddress("node2"); string newaddress = GetNewFundedAddress("node1", txid); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "getrawtransaction " + txid + " true" )); UniValue voutArray = find_value(r.get_obj(), "vout"); int vout = 0; for(unsigned int i = 0;i<voutArray.size();i++){ UniValue scriptObj = find_value(voutArray[i].get_obj(), "scriptPubKey").get_obj(); UniValue addressesArray = find_value(scriptObj, "addresses"); for(unsigned int j = 0;j<addressesArray.size();j++){ if(addressesArray[j].get_str() == newaddress) vout = i; } } string voutstr = itostr(vout); // lock outpoint so other txs can't spend through wallet auto-selection BOOST_CHECK_NO_THROW(CallRPC("node1", "lockunspent false \"[{\\\"txid\\\":\\\"" + txid + "\\\",\\\"vout\\\":" + voutstr + "}]\"" )); string guid = AssetNew("node1", newaddress, "data","''", "8", "1", "100000"); AssetSend("node1", guid, "\"[{\\\"address\\\":\\\"" + newaddress + "\\\",\\\"amount\\\":1}]\""); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationinfo " + guid + " " + newaddress )); UniValue balance = find_value(r.get_obj(), "balance"); BOOST_CHECK_EQUAL(AssetAmountFromValue(balance, 8), 1 * COIN); LockAssetAllocation("node1", guid, newaddress, txid, voutstr); // unlock now to test spending BOOST_CHECK_NO_THROW(CallRPC("node1", "lockunspent true \"[{\\\"txid\\\":\\\"" + txid + "\\\",\\\"vout\\\":" + voutstr + "}]\"" )); string txid0 = AssetAllocationTransfer(false, "node1", guid, newaddress, "\"[{\\\"address\\\":\\\"" + newaddress1 + "\\\",\\\"amount\\\":0.11}]\""); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationinfo " + guid + " " + newaddress1 )); balance = find_value(r.get_obj(), "balance"); BOOST_CHECK_EQUAL(AssetAmountFromValue(balance, 8), 0.11 * COIN); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "getrawtransaction " + txid0 + " true" )); UniValue vinArray = find_value(r.get_obj(), "vin"); bool found = false; for(unsigned int i = 0;i<vinArray.size();i++){ if(find_value(vinArray[i].get_obj(), "txid").get_str() == txid && find_value(vinArray[i].get_obj(), "vout").get_int() == vout){ found = true; break; } } BOOST_CHECK(found); } BOOST_AUTO_TEST_CASE(generate_asset_allocation_send_address) { UniValue r; printf("Running generate_asset_allocation_send_address...\n"); GenerateBlocks(5); GenerateBlocks(101, "node2"); string newaddress1 = GetNewFundedAddress("node1"); CallRPC("node2", "sendtoaddress " + newaddress1 + " 1", true, false); CallRPC("node2", "sendtoaddress " + newaddress1 + " 1", true, false); GenerateBlocks(5); GenerateBlocks(5, "node2"); BOOST_CHECK_NO_THROW(r = CallExtRPC("node1", "getnewaddress")); string newaddress2 = r.get_str(); string guid = AssetNew("node1", newaddress1, "data","''", "8", "1", "100000"); AssetSend("node1", guid, "\"[{\\\"address\\\":\\\"" + newaddress1 + "\\\",\\\"amount\\\":1}]\""); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationinfo " + guid + " " + newaddress1 )); UniValue balance = find_value(r.get_obj(), "balance"); BOOST_CHECK_EQUAL(AssetAmountFromValue(balance, 8), 1 * COIN); string txid0 = AssetAllocationTransfer(false, "node1", guid, newaddress1, "\"[{\\\"address\\\":\\\"" + newaddress2 + "\\\",\\\"amount\\\":0.11}]\""); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationinfo " + guid + " " + newaddress2 )); balance = find_value(r.get_obj(), "balance"); BOOST_CHECK_EQUAL(AssetAmountFromValue(balance, 8), 0.11 * COIN); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " " + newaddress1 + " " + txid0)); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_NOT_FOUND); // send using zdag string txid1 = AssetAllocationTransfer(true, "node1", guid, newaddress1, "\"[{\\\"address\\\":\\\"" + newaddress2 + "\\\",\\\"amount\\\":0.12}]\""); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationinfo " + guid + " " + newaddress2)); balance = find_value(r.get_obj(), "balance_zdag"); BOOST_CHECK_EQUAL(AssetAmountFromValue(balance, 8), 0.23 * COIN); // non zdag cannot be found since it was already mined, but ends up briefly in conflict state because sender is conflicted BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " " + newaddress1 + " " + txid0)); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_MINOR_CONFLICT); // first tx should have to wait 1 sec for good status BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " " + newaddress1 + " " + txid1)); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_MINOR_CONFLICT); // check just sender BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " " + newaddress1 + " ''")); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_MINOR_CONFLICT); // wait for 1 second as required by unit test MilliSleep(1000); // second send string txid2 = AssetAllocationTransfer(true, "node1", guid, newaddress1, "\"[{\\\"address\\\":\\\"" + newaddress2 + "\\\",\\\"amount\\\":0.13}]\""); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationinfo " + guid + " " + newaddress2 )); balance = find_value(r.get_obj(), "balance_zdag"); BOOST_CHECK_EQUAL(AssetAmountFromValue(balance, 8), 0.36 * COIN); // sender is conflicted so txid0 is conflicted by extension even if its not found BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " " + newaddress1 + " " + txid0)); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_MINOR_CONFLICT); // first ones now OK because it was found explicitly BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " " + newaddress1 + " " + txid1)); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_STATUS_OK); // second one hasn't waited enough time yet BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " " + newaddress1 + " " + txid2)); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_MINOR_CONFLICT); // check just sender BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " " + newaddress1 + " ''")); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_MINOR_CONFLICT); // wait for 1.5 second to clear minor warning status MilliSleep(1500); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " " + newaddress1 + " " + txid0)); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_NOT_FOUND); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " " + newaddress1 + " " + txid1)); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_STATUS_OK); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " " + newaddress1 + " " + txid2)); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_STATUS_OK); // check just sender as well BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " " + newaddress1 + " ''")); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_STATUS_OK); // after pow, should get not found on all of them GenerateBlocks(1); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " " + newaddress1 + " " + txid0)); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_NOT_FOUND); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " " + newaddress1 + " " + txid1)); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_NOT_FOUND); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " " + newaddress1 + " " + txid2)); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_NOT_FOUND); // check just sender as well BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " " + newaddress1 + " ''")); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_NOT_FOUND); ECC_Stop(); } BOOST_AUTO_TEST_SUITE_END () <commit_msg>wip lock test<commit_after>// Copyright (c) 2016-2018 The Syscoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <test/test_syscoin_services.h> #include <util/time.h> #include <rpc/server.h> #include <services/asset.h> #include <base58.h> #include <chainparams.h> #include <boost/test/unit_test.hpp> #include <iterator> #include <key.h> using namespace std; BOOST_GLOBAL_FIXTURE( SyscoinTestingSetup ); BOOST_FIXTURE_TEST_SUITE(syscoin_asset_allocation_tests, BasicSyscoinTestingSetup) BOOST_AUTO_TEST_CASE(generate_asset_allocation_address_sync) { UniValue r; printf("Running generate_asset_allocation_address_sync...\n"); GenerateBlocks(5); string newaddress = GetNewFundedAddress("node1"); BOOST_CHECK_NO_THROW(r = CallExtRPC("node1", "getnewaddress")); string newaddressreceiver = r.get_str(); string guid = AssetNew("node1", newaddress, "data", "''", "8", "10000", "1000000"); AssetSend("node1", guid, "\"[{\\\"address\\\":\\\"" + newaddressreceiver + "\\\",\\\"amount\\\":5000}]\""); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationinfo " + guid + " " + newaddressreceiver )); UniValue balance = find_value(r.get_obj(), "balance"); BOOST_CHECK_NO_THROW(r = CallRPC("node2", "assetallocationinfo " + guid + " " + newaddressreceiver )); balance = find_value(r.get_obj(), "balance"); StopNode("node2"); StartNode("node2"); GenerateBlocks(5, "node2"); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationinfo " + guid + " " + newaddressreceiver )); balance = find_value(r.get_obj(), "balance"); BOOST_CHECK_NO_THROW(r = CallRPC("node2", "assetallocationinfo " + guid + " " + newaddressreceiver )); balance = find_value(r.get_obj(), "balance"); } BOOST_AUTO_TEST_CASE(generate_asset_allocation_lock) { UniValue r; printf("Running generate_asset_allocation_lock...\n"); GenerateBlocks(5); string txid; string newaddress1 = GetNewFundedAddress("node2"); string newaddress = GetNewFundedAddress("node1", txid); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "getrawtransaction " + txid + " true" )); UniValue voutArray = find_value(r.get_obj(), "vout"); int vout = 0; for(unsigned int i = 0;i<voutArray.size();i++){ UniValue scriptObj = find_value(voutArray[i].get_obj(), "scriptPubKey").get_obj(); UniValue addressesArray = find_value(scriptObj, "addresses"); for(unsigned int j = 0;j<addressesArray.size();j++){ if(addressesArray[j].get_str() == newaddress) vout = i; } } string voutstr = itostr(vout); // lock outpoint so other txs can't spend through wallet auto-selection BOOST_CHECK_NO_THROW(CallRPC("node1", "lockunspent false \"[{\\\"txid\\\":\\\"" + txid + "\\\",\\\"vout\\\":" + voutstr + "}]\"" )); string guid = AssetNew("node1", newaddress, "data","''", "8", "1", "100000"); AssetSend("node1", guid, "\"[{\\\"address\\\":\\\"" + newaddress + "\\\",\\\"amount\\\":1}]\""); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationinfo " + guid + " " + newaddress )); UniValue balance = find_value(r.get_obj(), "balance"); BOOST_CHECK_EQUAL(AssetAmountFromValue(balance, 8), 1 * COIN); LockAssetAllocation("node1", guid, newaddress, txid, voutstr); // unlock now to test spending BOOST_CHECK_NO_THROW(CallRPC("node1", "lockunspent true \"[{\\\"txid\\\":\\\"" + txid + "\\\",\\\"vout\\\":" + voutstr + "}]\"" )); // cannot spend as normal through sendrawtransaction BOOST_CHECK_NO_THROW(r = CallRPC("node1", "createrawtransaction \"[{\\\"txid\\\":\\\"" + txid + "\\\",\\\"vout\\\":" + voutstr + "}]\", \"[{\\\"" + newaddress1 + "\\\":0.01}]\"")); BOOST_CHECK_NO_THROW(r = CallRPC(node, "signrawtransactionwithwallet " + r.get_str())); string hex_str = find_value(r.get_obj(), "hex").get_str(); BOOST_CHECK_NO_THROW(r = CallRPC(node, "testmempoolaccept \"[\\\"" + hex_str + "\\\"]\"")); BOOST_CHECK(find_value(r.get_array()[0].get_obj(), "allowed").get_bool()); BOOST_CHECK_THROW(r = CallRPC(node, "sendrawtransaction " + hex_str, true, false), runtime_error); string txid0 = AssetAllocationTransfer(false, "node1", guid, newaddress, "\"[{\\\"address\\\":\\\"" + newaddress1 + "\\\",\\\"amount\\\":0.11}]\""); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationinfo " + guid + " " + newaddress1 )); balance = find_value(r.get_obj(), "balance"); BOOST_CHECK_EQUAL(AssetAmountFromValue(balance, 8), 0.11 * COIN); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "getrawtransaction " + txid0 + " true" )); UniValue vinArray = find_value(r.get_obj(), "vin"); bool found = false; for(unsigned int i = 0;i<vinArray.size();i++){ if(find_value(vinArray[i].get_obj(), "txid").get_str() == txid && find_value(vinArray[i].get_obj(), "vout").get_int() == vout){ found = true; break; } } BOOST_CHECK(found); } BOOST_AUTO_TEST_CASE(generate_asset_allocation_send_address) { UniValue r; printf("Running generate_asset_allocation_send_address...\n"); GenerateBlocks(5); GenerateBlocks(101, "node2"); string newaddress1 = GetNewFundedAddress("node1"); CallRPC("node2", "sendtoaddress " + newaddress1 + " 1", true, false); CallRPC("node2", "sendtoaddress " + newaddress1 + " 1", true, false); GenerateBlocks(5); GenerateBlocks(5, "node2"); BOOST_CHECK_NO_THROW(r = CallExtRPC("node1", "getnewaddress")); string newaddress2 = r.get_str(); string guid = AssetNew("node1", newaddress1, "data","''", "8", "1", "100000"); AssetSend("node1", guid, "\"[{\\\"address\\\":\\\"" + newaddress1 + "\\\",\\\"amount\\\":1}]\""); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationinfo " + guid + " " + newaddress1 )); UniValue balance = find_value(r.get_obj(), "balance"); BOOST_CHECK_EQUAL(AssetAmountFromValue(balance, 8), 1 * COIN); string txid0 = AssetAllocationTransfer(false, "node1", guid, newaddress1, "\"[{\\\"address\\\":\\\"" + newaddress2 + "\\\",\\\"amount\\\":0.11}]\""); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationinfo " + guid + " " + newaddress2 )); balance = find_value(r.get_obj(), "balance"); BOOST_CHECK_EQUAL(AssetAmountFromValue(balance, 8), 0.11 * COIN); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " " + newaddress1 + " " + txid0)); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_NOT_FOUND); // send using zdag string txid1 = AssetAllocationTransfer(true, "node1", guid, newaddress1, "\"[{\\\"address\\\":\\\"" + newaddress2 + "\\\",\\\"amount\\\":0.12}]\""); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationinfo " + guid + " " + newaddress2)); balance = find_value(r.get_obj(), "balance_zdag"); BOOST_CHECK_EQUAL(AssetAmountFromValue(balance, 8), 0.23 * COIN); // non zdag cannot be found since it was already mined, but ends up briefly in conflict state because sender is conflicted BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " " + newaddress1 + " " + txid0)); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_MINOR_CONFLICT); // first tx should have to wait 1 sec for good status BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " " + newaddress1 + " " + txid1)); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_MINOR_CONFLICT); // check just sender BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " " + newaddress1 + " ''")); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_MINOR_CONFLICT); // wait for 1 second as required by unit test MilliSleep(1000); // second send string txid2 = AssetAllocationTransfer(true, "node1", guid, newaddress1, "\"[{\\\"address\\\":\\\"" + newaddress2 + "\\\",\\\"amount\\\":0.13}]\""); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationinfo " + guid + " " + newaddress2 )); balance = find_value(r.get_obj(), "balance_zdag"); BOOST_CHECK_EQUAL(AssetAmountFromValue(balance, 8), 0.36 * COIN); // sender is conflicted so txid0 is conflicted by extension even if its not found BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " " + newaddress1 + " " + txid0)); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_MINOR_CONFLICT); // first ones now OK because it was found explicitly BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " " + newaddress1 + " " + txid1)); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_STATUS_OK); // second one hasn't waited enough time yet BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " " + newaddress1 + " " + txid2)); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_MINOR_CONFLICT); // check just sender BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " " + newaddress1 + " ''")); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_MINOR_CONFLICT); // wait for 1.5 second to clear minor warning status MilliSleep(1500); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " " + newaddress1 + " " + txid0)); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_NOT_FOUND); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " " + newaddress1 + " " + txid1)); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_STATUS_OK); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " " + newaddress1 + " " + txid2)); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_STATUS_OK); // check just sender as well BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " " + newaddress1 + " ''")); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_STATUS_OK); // after pow, should get not found on all of them GenerateBlocks(1); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " " + newaddress1 + " " + txid0)); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_NOT_FOUND); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " " + newaddress1 + " " + txid1)); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_NOT_FOUND); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " " + newaddress1 + " " + txid2)); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_NOT_FOUND); // check just sender as well BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " " + newaddress1 + " ''")); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_NOT_FOUND); ECC_Stop(); } BOOST_AUTO_TEST_SUITE_END () <|endoftext|>
<commit_before>/* * 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 3 of the License, or * (at your option) any later version. * * Written (W) 2011 Heiko Strathmann * Copyright (C) 2011 Berlin Institute of Technology and Max-Planck-Society */ #include "modelselection/ModelSelectionParameters.h" #include "lib/DataType.h" #include "base/DynArray.h" #include "base/Parameter.h" using namespace shogun; CModelSelectionParameters::CModelSelectionParameters() { m_name=NULL; m_values=new SGVector<float64_t> (NULL, 0); m_sgobject=NULL; } CModelSelectionParameters::CModelSelectionParameters(char* name) : m_name(name) { m_values=new SGVector<float64_t> (NULL, 0); m_sgobject=NULL; } CModelSelectionParameters::CModelSelectionParameters(CSGObject* sgobject) : m_sgobject(sgobject) { SG_REF(sgobject); m_name=NULL; m_values=new SGVector<float64_t> (NULL, 0); } CModelSelectionParameters::~CModelSelectionParameters() { if (m_values) { delete[] m_values->vector; delete m_values; } SG_UNREF(m_sgobject); } void CModelSelectionParameters::destroy() { for (index_t i=0; i<m_child_nodes.get_num_elements(); ++i) m_child_nodes[i]->destroy(); delete this; } void CModelSelectionParameters::append_child(CModelSelectionParameters* child) { /* only possible if there are no values set */ if (m_values->vector) SG_ERROR("not possible to append child: there already is a range\n"); m_child_nodes.append_element(child); } void CModelSelectionParameters::set_range(float64_t min, float64_t max, ERangeType type, float64_t step, float64_t type_base) { if (m_sgobject || has_childs()) { SG_ERROR("unable to set range for an CSGObject model selection " "parameter\n"); } /* possibly delete old range values */ delete[] m_values->vector; if (max<min) SG_ERROR("unable to set range: maximum=%f < minimum=%f\n", max, min); /* create value vector */ index_t num_values=CMath::round(max-min)/step+1; m_values->length=num_values; m_values->vector=new float64_t[num_values]; /* fill array */ for (index_t i=0; i<num_values; ++i) { float64_t current=min+i*step; switch (type) { case R_LINEAR: m_values->vector[i]=current; break; case R_EXP: m_values->vector[i]=CMath::pow(type_base, current); break; case R_LOG: if (current<=0) SG_ERROR("log(x) with x=%f\n", current); /* custom base b: log_b(i*step)=log_2(i*step)/log_2(b) */ m_values->vector[i]=CMath::log2(current)/CMath::log2(type_base); break; } } } void CModelSelectionParameters::get_combinations( DynArray<CParameterCombination*>& result) { /* leaf case: node with values and no childs. * build trees of Parameter instances which each contain one value */ if (m_values->vector) { for (index_t i=0; i<m_values->length; ++i) { /* create tree with only one parameter element */ Parameter* p=new Parameter(); p->add(&m_values->vector[i], m_name); result.append_element(new CParameterCombination(p)); } } /* two cases here, similar * -case CSGObject: * -case root node (no name, no values, but childs * build all permutations of the result trees of children with values and * combine them iteratively children which are something different */ else if (m_sgobject||(!m_name&&!m_sgobject&&!m_values->vector)) { /* only consider combinations if this CSGObject has children */ if (m_child_nodes.get_num_elements()) { /* split leaf and no-leaf child combinations */ DynArray<CModelSelectionParameters*> leaf_childs; DynArray<CModelSelectionParameters*> non_leaf_childs; for (index_t i=0; i<m_child_nodes.get_num_elements(); ++i) { CModelSelectionParameters* current=m_child_nodes[i]; /* split childs with values (leafs) and childs with other */ if (current->m_values->vector) leaf_childs.append_element(current); else non_leaf_childs.append_element(current); } /* extract all tree sets of all leaf childs */ DynArray<DynArray<CParameterCombination*>*> leaf_sets; for (index_t i=0; i<leaf_childs.get_num_elements(); ++i) { /* temporary DynArray instance */ leaf_sets.append_element( new DynArray<CParameterCombination*> ()); /* recursively get all combinations and put into above array */ leaf_childs[i]->get_combinations(*leaf_sets[i]); } /* build product of all these tree sets */ DynArray<CParameterCombination*> leaf_combinations; /* new root node is needed for new trees, depends on current case */ CParameterCombination* new_root=NULL; if (m_sgobject) { Parameter* p=new Parameter(); p->add(&m_sgobject, m_sgobject->get_name()); new_root=new CParameterCombination(p); } else new_root=new CParameterCombination(); /* above created DynArray instances are deleted by this call */ CParameterCombination::leaf_sets_multiplication(leaf_sets, new_root, leaf_combinations); /* if there are no non-leaf sets, just use the above result */ if (!non_leaf_childs.get_num_elements()) result=leaf_combinations; /* in the other case, the non-leafs have also to be treated, but * combined iteratively */ else { /* extract all tree sets of non-leaf nodes */ DynArray<DynArray<CParameterCombination*>*> non_leaf_combinations; for (index_t i=0; i<non_leaf_childs.get_num_elements(); ++i) { /* temporary DynArray instance */ non_leaf_combinations.append_element( new DynArray<CParameterCombination*> ()); /* recursively get all combinations and put into above * array */ non_leaf_childs[i]->get_combinations( *non_leaf_combinations[i]); } /* combine combinations of leafs and non-leafs */ /* if there are only non-leaf children, nothing is combined */ if (!leaf_combinations.get_num_elements()) { /* non-leaf children are only pasted together. However, the * new root node is to put as root in front of all trees. * If there were leaf children before, this is done by * leaf_sets_multiplication. In this case it has to be done * by hand. */ for (index_t j=0; j <non_leaf_combinations.get_num_elements(); ++j) { DynArray<CParameterCombination*>* current_non_leaf_set= non_leaf_combinations[j]; for (index_t k=0; k <current_non_leaf_set->get_num_elements(); ++k) { CParameterCombination* current_non_leaf_tree= current_non_leaf_set->get_element(k); /* append new root with rest of tree to current * tree. re-use of new_root variable, safe here */ new_root=new CParameterCombination(); new_root->append_child(current_non_leaf_tree); result.append_element(new_root); } } /* since there were no non-leaf sets, they do not have to be * deleted here */ } else { for (index_t i=0; i<leaf_combinations.get_num_elements(); ++i) { CParameterCombination* current_leaf_tree= leaf_combinations[i]; for (index_t j=0; j <non_leaf_combinations.get_num_elements(); ++j) { DynArray<CParameterCombination*> * current_non_leaf_set= non_leaf_combinations[j]; for (index_t k=0; k <current_non_leaf_set->get_num_elements(); ++k) { CParameterCombination* current_non_leaf_tree= current_non_leaf_set->get_element(k); /* copy the current trees and append non-leaf * tree to leaf tree. Note that the root in the * non-leaf tree is already the current * CSGObject and therefore the non-leaf tree * copy may just be appended as child */ CParameterCombination* leaf_copy= current_leaf_tree->copy_tree(); CParameterCombination* non_leaf_copy= current_non_leaf_tree->copy_tree(); leaf_copy->append_child(non_leaf_copy); result.append_element(leaf_copy); } } } /* delete non-leaf combination trees */ for (index_t i=0; i <leaf_combinations.get_num_elements(); ++i) leaf_combinations[i]->destroy(true, true); for (index_t i=0; i <non_leaf_combinations.get_num_elements(); ++i) { DynArray<CParameterCombination*>* current_non_leaf_set= non_leaf_combinations[i]; for (index_t j=0; j <current_non_leaf_set->get_num_elements(); ++j) current_non_leaf_set->get_element(j)->destroy(true, true); } /* the arrays of the non-leaf sets have to be deleted in * both cases: if there were leaf childs or not */ for (index_t i=0; i <non_leaf_combinations.get_num_elements(); ++i) delete non_leaf_combinations[i]; } } } } /* case name placeholder node: a node which contains a (parameter) name and * one (or more) CSGObject nodes which are to be substituted into the * parameter with the above name. The parameter name is one of the learning * machine, like "kernel". basically all combinations of all childs have to * be appended to the result and a new root is to be added to all trees */ else if (m_name&&!m_values->vector) { if (!m_child_nodes.get_num_elements()) { SG_ERROR("ModelSelectionParameter node with name but no childs or " "values.\n"); } for (index_t i=0; i<m_child_nodes.get_num_elements(); ++i) { /* recursively get all combinations of the current child */ DynArray<CParameterCombination*> child_combinations; m_child_nodes[i]->get_combinations(child_combinations); /* and process them each */ for (index_t j=0; j<child_combinations.get_num_elements(); ++j) { /* append new root node with the name */ CParameterCombination* new_root=new CParameterCombination( m_name); new_root->append_child(child_combinations[j]); child_combinations.set_element(new_root, j); /* append them to the result */ result.append_element(child_combinations[j]); } } } } void CModelSelectionParameters::print(int prefix_num) { /* prefix is enlarged */ char* prefix=new char[prefix_num+1]; for (index_t i=0; i<prefix_num; ++i) prefix[i]='\t'; prefix[prefix_num]='\0'; if (has_childs()) { /* this node might also be a parameter */ SG_PRINT("%s%s with\n", prefix, m_sgobject ? m_sgobject->get_name() : m_name); /* now recursively print successors */ /* cast safe because only CModelSelectionParameters are added to list */ for (index_t i=0; i<m_child_nodes.get_num_elements(); ++i) m_child_nodes[i]->print(prefix_num+1); } else { /* has to be a node with name and a numeric range or a single sg_object * without children*/ if (m_sgobject) { SG_PRINT("%s%s\n", prefix, m_sgobject->get_name()); } else { SG_PRINT("%s%s with values: ", prefix, m_name); CMath::display_vector(m_values->vector, m_values->length); } } delete[] prefix; } <commit_msg>Revert "initial (working) version of the tree structure to specify parameters and their ranges for model selection."<commit_after><|endoftext|>
<commit_before>//============================================================================ // Name : ImageProcessingController.cpp // Author : ITM13 // Version : 1.0 // Copyright : Copyright (c) 2014 Swank Rat, MIT License (MIT) // Description : //============================================================================ #include "ImageProcessingController.h" #include "..\shared\Logger.h" ImageProcessingController::ImageProcessingController() { webcamService = new WebcamService(); } ImageProcessingController::~ImageProcessingController() { StopImageProcessing(); webcamService = nullptr; } void ImageProcessingController::StartImageProcessing() { webcamService->AddObserver(this); webcamService->StartRecording(); } bool ImageProcessingController::StopImageProcessing() { webcamService->StopRecording(); webcamService->RemoveObserver(this); return true; } void ImageProcessingController::Update(WebcamService* observable) { Logger::addMessage("New image available"); observable->GetLastImage(); } <commit_msg>removed logging<commit_after>//============================================================================ // Name : ImageProcessingController.cpp // Author : ITM13 // Version : 1.0 // Copyright : Copyright (c) 2014 Swank Rat, MIT License (MIT) // Description : //============================================================================ #include "ImageProcessingController.h" #include "..\shared\Logger.h" ImageProcessingController::ImageProcessingController() { webcamService = new WebcamService(); } ImageProcessingController::~ImageProcessingController() { StopImageProcessing(); webcamService = nullptr; } void ImageProcessingController::StartImageProcessing() { webcamService->AddObserver(this); webcamService->StartRecording(); } bool ImageProcessingController::StopImageProcessing() { webcamService->StopRecording(); webcamService->RemoveObserver(this); return true; } void ImageProcessingController::Update(WebcamService* observable) { observable->GetLastImage(); } <|endoftext|>
<commit_before>/* * Copyright(c) Sophist Solutions, Inc. 1990-2021. All rights reserved */ #include "../../StroikaPreComp.h" #if qHasFeature_OpenSSL #include <openssl/evp.h> #include <openssl/md5.h> #endif #include "../../Characters/StringBuilder.h" #include "../../Characters/ToString.h" #include "../../Containers/Common.h" #include "../../Debug/Assertions.h" #include "../../Execution/Common.h" #include "../../Execution/Synchronized.h" #include "../../Memory/SmallStackBuffer.h" #include "Exception.h" #include "DerivedKey.h" using std::byte; using namespace Stroika::Foundation; using namespace Stroika::Foundation::Containers; using namespace Stroika::Foundation::Cryptography; using namespace Stroika::Foundation::Cryptography::OpenSSL; using namespace Stroika::Foundation::Memory; using Memory::BLOB; using Memory::SmallStackBuffer; #if qHasFeature_OpenSSL && defined(_MSC_VER) // Use #pragma comment lib instead of explicit entry in the lib entry of the project file #if OPENSSL_VERSION_NUMBER < 0x1010000fL #pragma comment(lib, "libeay32.lib") #pragma comment(lib, "ssleay32.lib") #else #pragma comment(lib, "libcrypto.lib") #pragma comment(lib, "libssl.lib") #pragma comment(lib, "ws2_32.lib") #pragma comment(lib, "crypt32.lib") #endif #endif #if qHasFeature_OpenSSL namespace { // This trick counts on the fact that EVP_BytesToKey() only ever looks at key_len and iv_len struct FakeCryptoAlgo_ #if OPENSSL_VERSION_NUMBER < 0x1010000fL : ::EVP_CIPHER #endif { #if OPENSSL_VERSION_NUMBER >= 0x1010000fL ::EVP_CIPHER* tmpCipher{}; #endif FakeCryptoAlgo_ () = delete; FakeCryptoAlgo_ (const FakeCryptoAlgo_&) = delete; FakeCryptoAlgo_ (size_t keyLength, size_t ivLength) { #if OPENSSL_VERSION_NUMBER >= 0x1010000fL Assert (keyLength < size_t (numeric_limits<int>::max ())); // for static cast below Assert (ivLength < size_t (numeric_limits<int>::max ())); // for static cast below tmpCipher = ::EVP_CIPHER_meth_new (0, 0, static_cast<int> (keyLength)); ::EVP_CIPHER_meth_set_iv_length (tmpCipher, static_cast<int> (ivLength)); #else (void)::memset (this, 0, sizeof (*this)); DISABLE_COMPILER_MSC_WARNING_START (4267) this->key_len = keyLength; this->iv_len = ivLength; DISABLE_COMPILER_MSC_WARNING_END (4267) #endif } #if OPENSSL_VERSION_NUMBER >= 0x1010000fL ~FakeCryptoAlgo_ () { ::EVP_CIPHER_meth_free (tmpCipher); } #endif operator const ::EVP_CIPHER* () const { #if OPENSSL_VERSION_NUMBER >= 0x1010000fL return tmpCipher; #else return this; #endif } }; } #endif #if qHasFeature_OpenSSL /* ******************************************************************************** ********************** Cryptography::OpenSSL::DerivedKey *********************** ******************************************************************************** */ size_t DerivedKey::KeyLength (CipherAlgorithm cipherAlgorithm) { return ::EVP_CIPHER_key_length (cipherAlgorithm); } size_t DerivedKey::IVLength (CipherAlgorithm cipherAlgorithm) { return ::EVP_CIPHER_iv_length (cipherAlgorithm); } String DerivedKey::ToString () const { Characters::StringBuilder result; result += L"{"; result += L"key: " + Characters::ToString (fKey); result += L", "; result += L"IV: " + Characters::ToString (fIV); result += L"}"; return result.str (); } #endif /* ******************************************************************************** **************** Cryptography::OpenSSL::WinCryptDeriveKey ********************** ******************************************************************************** */ #if qHasFeature_OpenSSL namespace { pair<BLOB, BLOB> mkWinCryptDeriveKey_ (size_t keyLen, [[maybe_unused]] DigestAlgorithm digestAlgorithm, const BLOB& passwd) { // @todo https://stroika.atlassian.net/browse/STK-192 /* * From http://msdn2.microsoft.com/en-us/library/aa379916.aspx * * o Form a 64-byte buffer by repeating the constant 0x36 64 times. * Let k be the length of the hash value that is represented by the * input parameter hBaseData. Set the first k bytes of the buffer to the result * of an XOR operation of the first k bytes of the buffer with the hash value that * is represented by the input parameter hBaseData. * o Form a 64-byte buffer by repeating the constant 0x5C 64 times. * Set the first k bytes of the buffer to the result of an XOR operation of the * first k bytes of the buffer with the hash value that is represented by the input parameter hBaseData. * o Hash the result of step 1 by using the same hash algorithm as that used to compute the * hash value that is represented by the hBaseData parameter. * o Hash the result of step 2 by using the same hash algorithm as that used * to compute the hash value that is represented by the hBaseData parameter. * o Concatenate the result of step 3 with the result of step 4. * o Use the first n bytes of the result of step 5 as the derived key. */ size_t usePWDLen = min (passwd.length (), static_cast<size_t> (64)); const byte* passwordBytes = passwd.begin (); byte buf1[64]; { std::fill_n (buf1, NEltsOf (buf1), static_cast<byte> (0x36)); for (unsigned long i = 0; i < usePWDLen; ++i) { buf1[i] ^= passwordBytes[i]; } } byte buf2[64]; { std::fill_n (buf2, NEltsOf (buf2), static_cast<byte> (0x5C)); for (unsigned long i = 0; i < usePWDLen; ++i) { buf2[i] ^= passwordBytes[i]; } } Require (digestAlgorithm == DigestAlgorithms::kMD5); // else NYI uint8_t md5OutputBuf[2 * MD5_DIGEST_LENGTH]; (void)::MD5 (reinterpret_cast<unsigned char*> (buf1), NEltsOf (buf1), md5OutputBuf); (void)::MD5 (reinterpret_cast<unsigned char*> (buf2), NEltsOf (buf2), md5OutputBuf + MD5_DIGEST_LENGTH); Assert (keyLen <= NEltsOf (md5OutputBuf)); // NYI otherwise - but we could zero fill BLOB resultKey{begin (md5OutputBuf), begin (md5OutputBuf) + std::min (NEltsOf (md5OutputBuf), keyLen)}; BLOB iv; return pair<BLOB, BLOB>{resultKey, iv}; } size_t mkDefKeyLen_ (WinCryptDeriveKey::Provider provider, CipherAlgorithm cipherAlgorithm) { // @todo see table https://msdn.microsoft.com/en-us/library/aa379916.aspx switch (provider) { case WinCryptDeriveKey::Provider::Base: { if ( cipherAlgorithm == CipherAlgorithms::kRC2_CBC () or cipherAlgorithm == CipherAlgorithms::kRC2_CFB () or cipherAlgorithm == CipherAlgorithms::kRC2_ECB () or cipherAlgorithm == CipherAlgorithms::kRC2_OFB () or cipherAlgorithm == CipherAlgorithms::kRC4 ()) { return 40 / 8; } #if 0 case CipherAlgorithm::eDES { return 56 / 8; } #endif } break; case WinCryptDeriveKey::Provider::Enhanced: { if ( cipherAlgorithm == CipherAlgorithms::kRC2_CBC () or cipherAlgorithm == CipherAlgorithms::kRC2_CFB () or cipherAlgorithm == CipherAlgorithms::kRC2_ECB () or cipherAlgorithm == CipherAlgorithms::kRC2_OFB () or cipherAlgorithm == CipherAlgorithms::kRC4 ()) { return 128 / 8; } } break; } AssertNotImplemented (); // incomplete set of defautl see above table return 128 / 8; } } WinCryptDeriveKey::WinCryptDeriveKey (size_t keyLen, DigestAlgorithm digestAlgorithm, const BLOB& passwd) : DerivedKey{mkWinCryptDeriveKey_ (keyLen, digestAlgorithm, passwd)} { } WinCryptDeriveKey::WinCryptDeriveKey (Provider provider, CipherAlgorithm cipherAlgorithm, DigestAlgorithm digestAlgorithm, const BLOB& passwd) : DerivedKey{WinCryptDeriveKey{mkDefKeyLen_ (provider, cipherAlgorithm), digestAlgorithm, passwd}} { } #endif #if qHasFeature_OpenSSL /* ******************************************************************************** ******************* Cryptography::OpenSSL::EVP_BytesToKey ********************** ******************************************************************************** */ namespace { pair<BLOB, BLOB> mkEVP_BytesToKey_ (size_t keyLen, size_t ivLen, DigestAlgorithm digestAlgorithm, const BLOB& passwd, unsigned int nRounds, const optional<BLOB>& salt) { Require (nRounds >= 1); SmallStackBuffer<byte> useKey{SmallStackBufferCommon::eUninitialized, keyLen}; SmallStackBuffer<byte> useIV{SmallStackBufferCommon::eUninitialized, ivLen}; if (salt and salt->GetSize () != 8) [[UNLIKELY_ATTR]] { // Could truncate and fill to adapt to different sized salt... Execution::Throw (Execution::Exception{L"only 8-byte salt with EVP_BytesToKey"sv}); } int i = ::EVP_BytesToKey ( FakeCryptoAlgo_ (keyLen, ivLen), digestAlgorithm, reinterpret_cast<const unsigned char*> (salt ? NullCoalesce (salt).begin () : nullptr), reinterpret_cast<const unsigned char*> (passwd.begin ()), static_cast<int> (passwd.size ()), nRounds, reinterpret_cast<unsigned char*> (useKey.begin ()), reinterpret_cast<unsigned char*> (useIV.begin ())); if (i == 0) { Cryptography::OpenSSL::Exception::ThrowLastError (); } Assert (i == static_cast<int> (keyLen)); return pair<BLOB, BLOB>{BLOB{useKey.begin (), useKey.end ()}, BLOB{useIV.begin (), useIV.end ()}}; } } template <> EVP_BytesToKey::EVP_BytesToKey (size_t keyLen, size_t ivLen, DigestAlgorithm digestAlgorithm, const BLOB& passwd, unsigned int nRounds, const optional<BLOB>& salt) : DerivedKey{mkEVP_BytesToKey_ (keyLen, ivLen, digestAlgorithm, passwd, nRounds, salt)} { } /* ******************************************************************************** ****************** Cryptography::OpenSSL::PKCS5_PBKDF2_HMAC ******************** ******************************************************************************** */ namespace { pair<BLOB, BLOB> mkPKCS5_PBKDF2_HMAC_ (size_t keyLen, size_t ivLen, DigestAlgorithm digestAlgorithm, const BLOB& passwd, unsigned int nRounds, const optional<BLOB>& salt) { SmallStackBuffer<byte> outBuf{SmallStackBufferCommon::eUninitialized, keyLen + ivLen}; Assert (keyLen + ivLen < size_t (numeric_limits<int>::max ())); // for static cast below int a = ::PKCS5_PBKDF2_HMAC ( reinterpret_cast<const char*> (passwd.begin ()), static_cast<int> (passwd.length ()), reinterpret_cast<const unsigned char*> (salt ? salt->begin () : nullptr), static_cast<int> (salt ? salt->size () : 0), nRounds, digestAlgorithm, static_cast<int> (keyLen + ivLen), reinterpret_cast<unsigned char*> (outBuf.begin ())); if (a == 0) [[UNLIKELY_ATTR]] { Execution::Throw (Execution::Exception{L"PKCS5_PBKDF2_HMAC error"sv}); } const byte* p = outBuf.begin (); return pair<BLOB, BLOB> (BLOB (p, p + keyLen), BLOB (p + keyLen, p + keyLen + ivLen)); } } template <> PKCS5_PBKDF2_HMAC::PKCS5_PBKDF2_HMAC (size_t keyLen, size_t ivLen, DigestAlgorithm digestAlgorithm, const BLOB& passwd, unsigned int nRounds, const optional<BLOB>& salt) : DerivedKey{mkPKCS5_PBKDF2_HMAC_ (keyLen, ivLen, digestAlgorithm, passwd, nRounds, salt)} { } #endif <commit_msg>rewrite use of openssl md5 (now deprecated) with Stroika local copy of algorithm<commit_after>/* * Copyright(c) Sophist Solutions, Inc. 1990-2021. All rights reserved */ #include "../../StroikaPreComp.h" #if qHasFeature_OpenSSL #include <openssl/evp.h> #endif #include "../../Characters/StringBuilder.h" #include "../../Characters/ToString.h" #include "../../Containers/Common.h" #include "../../Cryptography/Digest/Algorithm/MD5.h" #include "../../Cryptography/Digest/Digester.h" #include "../../Cryptography/Digest/Hash.h" #include "../../Debug/Assertions.h" #include "../../Execution/Common.h" #include "../../Execution/Synchronized.h" #include "../../Memory/SmallStackBuffer.h" #include "Exception.h" #include "DerivedKey.h" using std::byte; using namespace Stroika::Foundation; using namespace Stroika::Foundation::Containers; using namespace Stroika::Foundation::Cryptography; using namespace Stroika::Foundation::Cryptography::OpenSSL; using namespace Stroika::Foundation::Memory; using Memory::BLOB; using Memory::SmallStackBuffer; #if qHasFeature_OpenSSL && defined(_MSC_VER) // Use #pragma comment lib instead of explicit entry in the lib entry of the project file #if OPENSSL_VERSION_NUMBER < 0x1010000fL #pragma comment(lib, "libeay32.lib") #pragma comment(lib, "ssleay32.lib") #else #pragma comment(lib, "libcrypto.lib") #pragma comment(lib, "libssl.lib") #pragma comment(lib, "ws2_32.lib") #pragma comment(lib, "crypt32.lib") #endif #endif #if qHasFeature_OpenSSL namespace { // This trick counts on the fact that EVP_BytesToKey() only ever looks at key_len and iv_len struct FakeCryptoAlgo_ #if OPENSSL_VERSION_NUMBER < 0x1010000fL : ::EVP_CIPHER #endif { #if OPENSSL_VERSION_NUMBER >= 0x1010000fL ::EVP_CIPHER* tmpCipher{}; #endif FakeCryptoAlgo_ () = delete; FakeCryptoAlgo_ (const FakeCryptoAlgo_&) = delete; FakeCryptoAlgo_ (size_t keyLength, size_t ivLength) { #if OPENSSL_VERSION_NUMBER >= 0x1010000fL Assert (keyLength < size_t (numeric_limits<int>::max ())); // for static cast below Assert (ivLength < size_t (numeric_limits<int>::max ())); // for static cast below tmpCipher = ::EVP_CIPHER_meth_new (0, 0, static_cast<int> (keyLength)); ::EVP_CIPHER_meth_set_iv_length (tmpCipher, static_cast<int> (ivLength)); #else (void)::memset (this, 0, sizeof (*this)); DISABLE_COMPILER_MSC_WARNING_START (4267) this->key_len = keyLength; this->iv_len = ivLength; DISABLE_COMPILER_MSC_WARNING_END (4267) #endif } #if OPENSSL_VERSION_NUMBER >= 0x1010000fL ~FakeCryptoAlgo_ () { ::EVP_CIPHER_meth_free (tmpCipher); } #endif operator const ::EVP_CIPHER* () const { #if OPENSSL_VERSION_NUMBER >= 0x1010000fL return tmpCipher; #else return this; #endif } }; } #endif #if qHasFeature_OpenSSL /* ******************************************************************************** ********************** Cryptography::OpenSSL::DerivedKey *********************** ******************************************************************************** */ size_t DerivedKey::KeyLength (CipherAlgorithm cipherAlgorithm) { return ::EVP_CIPHER_key_length (cipherAlgorithm); } size_t DerivedKey::IVLength (CipherAlgorithm cipherAlgorithm) { return ::EVP_CIPHER_iv_length (cipherAlgorithm); } String DerivedKey::ToString () const { Characters::StringBuilder result; result += L"{"; result += L"key: " + Characters::ToString (fKey); result += L", "; result += L"IV: " + Characters::ToString (fIV); result += L"}"; return result.str (); } #endif /* ******************************************************************************** **************** Cryptography::OpenSSL::WinCryptDeriveKey ********************** ******************************************************************************** */ #if qHasFeature_OpenSSL namespace { pair<BLOB, BLOB> mkWinCryptDeriveKey_ (size_t keyLen, [[maybe_unused]] DigestAlgorithm digestAlgorithm, const BLOB& passwd) { // @todo https://stroika.atlassian.net/browse/STK-192 /* * From http://msdn2.microsoft.com/en-us/library/aa379916.aspx * * o Form a 64-byte buffer by repeating the constant 0x36 64 times. * Let k be the length of the hash value that is represented by the * input parameter hBaseData. Set the first k bytes of the buffer to the result * of an XOR operation of the first k bytes of the buffer with the hash value that * is represented by the input parameter hBaseData. * o Form a 64-byte buffer by repeating the constant 0x5C 64 times. * Set the first k bytes of the buffer to the result of an XOR operation of the * first k bytes of the buffer with the hash value that is represented by the input parameter hBaseData. * o Hash the result of step 1 by using the same hash algorithm as that used to compute the * hash value that is represented by the hBaseData parameter. * o Hash the result of step 2 by using the same hash algorithm as that used * to compute the hash value that is represented by the hBaseData parameter. * o Concatenate the result of step 3 with the result of step 4. * o Use the first n bytes of the result of step 5 as the derived key. */ size_t usePWDLen = min (passwd.length (), static_cast<size_t> (64)); const byte* passwordBytes = passwd.begin (); byte buf1[64]; { std::fill_n (buf1, NEltsOf (buf1), static_cast<byte> (0x36)); for (unsigned long i = 0; i < usePWDLen; ++i) { buf1[i] ^= passwordBytes[i]; } } byte buf2[64]; { std::fill_n (buf2, NEltsOf (buf2), static_cast<byte> (0x5C)); for (unsigned long i = 0; i < usePWDLen; ++i) { buf2[i] ^= passwordBytes[i]; } } Require (digestAlgorithm == DigestAlgorithms::kMD5); // else NYI Digest::Algorithm::DigesterAlgorithm<Digest::Algorithm::MD5>::ReturnType encodedResults[] = { Digest::ComputeDigest<Digest::Algorithm::MD5> (begin (buf1), end (buf1)), Digest::ComputeDigest<Digest::Algorithm::MD5> (begin (buf2), end (buf2))}; Assert (keyLen <= sizeof (encodedResults)); // NYI otherwise - but we could zero fill const byte* encodedResultBytes = reinterpret_cast<const byte*> (begin (encodedResults)); BLOB resultKey{encodedResultBytes, encodedResultBytes + std::min (sizeof (encodedResults), keyLen)}; BLOB iv; return pair<BLOB, BLOB>{resultKey, iv}; } size_t mkDefKeyLen_ (WinCryptDeriveKey::Provider provider, CipherAlgorithm cipherAlgorithm) { // @todo see table https://msdn.microsoft.com/en-us/library/aa379916.aspx switch (provider) { case WinCryptDeriveKey::Provider::Base: { if ( cipherAlgorithm == CipherAlgorithms::kRC2_CBC () or cipherAlgorithm == CipherAlgorithms::kRC2_CFB () or cipherAlgorithm == CipherAlgorithms::kRC2_ECB () or cipherAlgorithm == CipherAlgorithms::kRC2_OFB () or cipherAlgorithm == CipherAlgorithms::kRC4 ()) { return 40 / 8; } #if 0 case CipherAlgorithm::eDES { return 56 / 8; } #endif } break; case WinCryptDeriveKey::Provider::Enhanced: { if ( cipherAlgorithm == CipherAlgorithms::kRC2_CBC () or cipherAlgorithm == CipherAlgorithms::kRC2_CFB () or cipherAlgorithm == CipherAlgorithms::kRC2_ECB () or cipherAlgorithm == CipherAlgorithms::kRC2_OFB () or cipherAlgorithm == CipherAlgorithms::kRC4 ()) { return 128 / 8; } } break; } AssertNotImplemented (); // incomplete set of defautl see above table return 128 / 8; } } WinCryptDeriveKey::WinCryptDeriveKey (size_t keyLen, DigestAlgorithm digestAlgorithm, const BLOB& passwd) : DerivedKey{mkWinCryptDeriveKey_ (keyLen, digestAlgorithm, passwd)} { } WinCryptDeriveKey::WinCryptDeriveKey (Provider provider, CipherAlgorithm cipherAlgorithm, DigestAlgorithm digestAlgorithm, const BLOB& passwd) : DerivedKey{WinCryptDeriveKey{mkDefKeyLen_ (provider, cipherAlgorithm), digestAlgorithm, passwd}} { } #endif #if qHasFeature_OpenSSL /* ******************************************************************************** ******************* Cryptography::OpenSSL::EVP_BytesToKey ********************** ******************************************************************************** */ namespace { pair<BLOB, BLOB> mkEVP_BytesToKey_ (size_t keyLen, size_t ivLen, DigestAlgorithm digestAlgorithm, const BLOB& passwd, unsigned int nRounds, const optional<BLOB>& salt) { Require (nRounds >= 1); SmallStackBuffer<byte> useKey{SmallStackBufferCommon::eUninitialized, keyLen}; SmallStackBuffer<byte> useIV{SmallStackBufferCommon::eUninitialized, ivLen}; if (salt and salt->GetSize () != 8) [[UNLIKELY_ATTR]] { // Could truncate and fill to adapt to different sized salt... Execution::Throw (Execution::Exception{L"only 8-byte salt with EVP_BytesToKey"sv}); } int i = ::EVP_BytesToKey ( FakeCryptoAlgo_ (keyLen, ivLen), digestAlgorithm, reinterpret_cast<const unsigned char*> (salt ? NullCoalesce (salt).begin () : nullptr), reinterpret_cast<const unsigned char*> (passwd.begin ()), static_cast<int> (passwd.size ()), nRounds, reinterpret_cast<unsigned char*> (useKey.begin ()), reinterpret_cast<unsigned char*> (useIV.begin ())); if (i == 0) { Cryptography::OpenSSL::Exception::ThrowLastError (); } Assert (i == static_cast<int> (keyLen)); return pair<BLOB, BLOB>{BLOB{useKey.begin (), useKey.end ()}, BLOB{useIV.begin (), useIV.end ()}}; } } template <> EVP_BytesToKey::EVP_BytesToKey (size_t keyLen, size_t ivLen, DigestAlgorithm digestAlgorithm, const BLOB& passwd, unsigned int nRounds, const optional<BLOB>& salt) : DerivedKey{mkEVP_BytesToKey_ (keyLen, ivLen, digestAlgorithm, passwd, nRounds, salt)} { } /* ******************************************************************************** ****************** Cryptography::OpenSSL::PKCS5_PBKDF2_HMAC ******************** ******************************************************************************** */ namespace { pair<BLOB, BLOB> mkPKCS5_PBKDF2_HMAC_ (size_t keyLen, size_t ivLen, DigestAlgorithm digestAlgorithm, const BLOB& passwd, unsigned int nRounds, const optional<BLOB>& salt) { SmallStackBuffer<byte> outBuf{SmallStackBufferCommon::eUninitialized, keyLen + ivLen}; Assert (keyLen + ivLen < size_t (numeric_limits<int>::max ())); // for static cast below int a = ::PKCS5_PBKDF2_HMAC ( reinterpret_cast<const char*> (passwd.begin ()), static_cast<int> (passwd.length ()), reinterpret_cast<const unsigned char*> (salt ? salt->begin () : nullptr), static_cast<int> (salt ? salt->size () : 0), nRounds, digestAlgorithm, static_cast<int> (keyLen + ivLen), reinterpret_cast<unsigned char*> (outBuf.begin ())); if (a == 0) [[UNLIKELY_ATTR]] { Execution::Throw (Execution::Exception{L"PKCS5_PBKDF2_HMAC error"sv}); } const byte* p = outBuf.begin (); return pair<BLOB, BLOB> (BLOB (p, p + keyLen), BLOB (p + keyLen, p + keyLen + ivLen)); } } template <> PKCS5_PBKDF2_HMAC::PKCS5_PBKDF2_HMAC (size_t keyLen, size_t ivLen, DigestAlgorithm digestAlgorithm, const BLOB& passwd, unsigned int nRounds, const optional<BLOB>& salt) : DerivedKey{mkPKCS5_PBKDF2_HMAC_ (keyLen, ivLen, digestAlgorithm, passwd, nRounds, salt)} { } #endif <|endoftext|>
<commit_before>// Copyright Tenzir GmbH. All rights reserved. #define SUITE type_registry #include "vast/system/type_registry.hpp" #include "vast/test/fixtures/actor_system_and_events.hpp" #include "vast/test/test.hpp" #include "vast/default_table_slice_builder.hpp" #include "vast/detail/notifying_stream_manager.hpp" #include "vast/detail/spawn_container_source.hpp" #include "vast/system/data_store.hpp" #include "vast/system/exporter.hpp" #include "vast/system/importer.hpp" #include "vast/type.hpp" #include <caf/stateful_actor.hpp> #include <caf/test/dsl.hpp> #include <stddef.h> using namespace vast; namespace { const vast::record_type mock_layout = vast::record_type{ {"string", vast::string_type{}}, {"count", vast::count_type{}}, {"real", vast::real_type{}}, }.name("mock"); vast::table_slice_ptr make_data(std::string a, vast::count b, vast::real c) { vast::default_table_slice_builder builder(mock_layout); builder.append(a); builder.append(b); builder.append(c); return builder.finish(); } } // namespace struct fixture : fixtures::deterministic_actor_system_and_events { fixture() { MESSAGE("spawning AUT"); aut = spawn_aut(); REQUIRE(aut); CHECK_EQUAL(state().data.size(), 0); } ~fixture() { MESSAGE("shutting down AUT"); self->send_exit(aut, caf::exit_reason::user_shutdown); } using type_registry_actor = system::type_registry_type::stateful_pointer<system::type_registry_state>; caf::actor spawn_aut() { auto handle = sys.spawn(system::type_registry, directory); sched.run(); return caf::actor_cast<caf::actor>(handle); } system::type_registry_state& state() { return caf::actor_cast<type_registry_actor>(aut)->state; } caf::actor aut; }; FIXTURE_SCOPE(type_registry_tests, fixture) TEST(type_registry) { MESSAGE("importing mock data"); { auto slices = std::vector{1000, make_data("1", 2u, 3.0)}; vast::detail::spawn_container_source(sys, std::move(slices), aut); run(); CHECK_EQUAL(state().data.size(), 1); } MESSAGE("retrieving layouts"); { size_t size = -1; std::string name = "mock"; self->send(aut, name); run(); bool done = false; self ->do_receive([&](std::unordered_set<vast::type> result) { size = result.size(); done = true; }) .until(done); CHECK_EQUAL(size, 1); } self->send_exit(aut, caf::exit_reason::user_shutdown); } FIXTURE_SCOPE_END() <commit_msg>Test multiple layouts with same name in unit tests<commit_after>// Copyright Tenzir GmbH. All rights reserved. #define SUITE type_registry #include "vast/system/type_registry.hpp" #include "vast/test/fixtures/actor_system_and_events.hpp" #include "vast/test/test.hpp" #include "vast/default_table_slice_builder.hpp" #include "vast/detail/notifying_stream_manager.hpp" #include "vast/detail/spawn_container_source.hpp" #include "vast/system/data_store.hpp" #include "vast/system/exporter.hpp" #include "vast/system/importer.hpp" #include "vast/type.hpp" #include <caf/stateful_actor.hpp> #include <caf/test/dsl.hpp> #include <stddef.h> using namespace vast; namespace { const vast::record_type mock_layout_a = vast::record_type{ {"a", vast::string_type{}}, {"b", vast::count_type{}}, {"c", vast::real_type{}}, }.name("mock"); vast::table_slice_ptr make_data_a(std::string a, vast::count b, vast::real c) { vast::default_table_slice_builder builder(mock_layout_a); builder.append(a); builder.append(b); builder.append(c); return builder.finish(); } const vast::record_type mock_layout_b = vast::record_type{ {"a", vast::string_type{}}, {"b", vast::count_type{}}, {"c", vast::real_type{}}, {"d", vast::string_type{}}, }.name("mock"); vast::table_slice_ptr make_data_b(std::string a, vast::count b, vast::real c, std::string d) { vast::default_table_slice_builder builder(mock_layout_b); builder.append(a); builder.append(b); builder.append(c); builder.append(d); return builder.finish(); } } // namespace struct fixture : fixtures::deterministic_actor_system_and_events { fixture() { MESSAGE("spawning AUT"); aut = spawn_aut(); REQUIRE(aut); CHECK_EQUAL(state().data.size(), 0); } ~fixture() { MESSAGE("shutting down AUT"); self->send_exit(aut, caf::exit_reason::user_shutdown); } using type_registry_actor = system::type_registry_type::stateful_pointer<system::type_registry_state>; caf::actor spawn_aut() { auto handle = sys.spawn(system::type_registry, directory); sched.run(); return caf::actor_cast<caf::actor>(handle); } system::type_registry_state& state() { return caf::actor_cast<type_registry_actor>(aut)->state; } caf::actor aut; }; FIXTURE_SCOPE(type_registry_tests, fixture) TEST(type_registry) { MESSAGE("importing mock data"); { auto slices_a = std::vector{1000, make_data_a("1", 2u, 3.0)}; auto slices_b = std::vector{1000, make_data_b("1", 2u, 3.0, "4")}; vast::detail::spawn_container_source(sys, std::move(slices_a), aut); vast::detail::spawn_container_source(sys, std::move(slices_b), aut); run(); CHECK_EQUAL(state().data.size(), 1); } MESSAGE("retrieving layouts"); { size_t size = -1; std::string name = "mock"; self->send(aut, name); run(); bool done = false; self ->do_receive([&](std::unordered_set<vast::type> result) { size = result.size(); done = true; }) .until(done); CHECK_EQUAL(size, 2); } self->send_exit(aut, caf::exit_reason::user_shutdown); } FIXTURE_SCOPE_END() <|endoftext|>
<commit_before>#include "queue_model_windowed_mg1.h" #include "simulator.h" #include "config.hpp" #include "log.h" QueueModelWindowedMG1::QueueModelWindowedMG1(String name, UInt32 id) : m_window_size(SubsecondTime::NS(Sim()->getCfg()->getInt("queue_model/windowed_mg1/window_size"))) {} QueueModelWindowedMG1::~QueueModelWindowedMG1() {} SubsecondTime QueueModelWindowedMG1::computeQueueDelay(SubsecondTime pkt_time, SubsecondTime processing_time, core_id_t requester) { SubsecondTime t_queue = SubsecondTime::Zero(); removeItems(pkt_time - m_window_size); if (m_num_arrivals > 1) { double utilization = (double)m_service_time_sum / m_window_size.getPS(); double arrival_rate = (double)m_num_arrivals / m_window_size.getPS(); double service_time_Es2 = m_service_time_sum2 / m_num_arrivals; // If requesters do not throttle based on returned latency, it's their problem, not ours if (utilization > .99) utilization = .99; t_queue = SubsecondTime::PS(arrival_rate * service_time_Es2 / (2 * (1. - utilization))); // Our memory is limited in time to m_window_size. It would be strange to return more latency than that. if (t_queue > m_window_size) t_queue = m_window_size; } addItem(pkt_time, processing_time); return t_queue; } void QueueModelWindowedMG1::addItem(SubsecondTime pkt_time, SubsecondTime service_time) { m_window.insert(std::pair<SubsecondTime, SubsecondTime>(pkt_time, service_time)); m_num_arrivals ++; m_service_time_sum += service_time.getPS(); m_service_time_sum2 += service_time.getPS() * service_time.getPS(); } void QueueModelWindowedMG1::removeItems(SubsecondTime earliest_time) { while(!m_window.empty() && m_window.begin()->first < earliest_time) { std::multimap<SubsecondTime, SubsecondTime>::iterator entry = m_window.begin(); m_num_arrivals --; m_service_time_sum -= entry->second.getPS(); m_service_time_sum2 -= entry->second.getPS() * entry->second.getPS(); m_window.erase(entry); } } <commit_msg>[windowed_mg1] Initialize all member variables<commit_after>#include "queue_model_windowed_mg1.h" #include "simulator.h" #include "config.hpp" #include "log.h" QueueModelWindowedMG1::QueueModelWindowedMG1(String name, UInt32 id) : m_window_size(SubsecondTime::NS(Sim()->getCfg()->getInt("queue_model/windowed_mg1/window_size"))) , m_num_arrivals(0) , m_service_time_sum(0) , m_service_time_sum2(0) {} QueueModelWindowedMG1::~QueueModelWindowedMG1() {} SubsecondTime QueueModelWindowedMG1::computeQueueDelay(SubsecondTime pkt_time, SubsecondTime processing_time, core_id_t requester) { SubsecondTime t_queue = SubsecondTime::Zero(); removeItems(pkt_time - m_window_size); if (m_num_arrivals > 1) { double utilization = (double)m_service_time_sum / m_window_size.getPS(); double arrival_rate = (double)m_num_arrivals / m_window_size.getPS(); double service_time_Es2 = m_service_time_sum2 / m_num_arrivals; // If requesters do not throttle based on returned latency, it's their problem, not ours if (utilization > .99) utilization = .99; t_queue = SubsecondTime::PS(arrival_rate * service_time_Es2 / (2 * (1. - utilization))); // Our memory is limited in time to m_window_size. It would be strange to return more latency than that. if (t_queue > m_window_size) t_queue = m_window_size; } addItem(pkt_time, processing_time); return t_queue; } void QueueModelWindowedMG1::addItem(SubsecondTime pkt_time, SubsecondTime service_time) { m_window.insert(std::pair<SubsecondTime, SubsecondTime>(pkt_time, service_time)); m_num_arrivals ++; m_service_time_sum += service_time.getPS(); m_service_time_sum2 += service_time.getPS() * service_time.getPS(); } void QueueModelWindowedMG1::removeItems(SubsecondTime earliest_time) { while(!m_window.empty() && m_window.begin()->first < earliest_time) { std::multimap<SubsecondTime, SubsecondTime>::iterator entry = m_window.begin(); m_num_arrivals --; m_service_time_sum -= entry->second.getPS(); m_service_time_sum2 -= entry->second.getPS() * entry->second.getPS(); m_window.erase(entry); } } <|endoftext|>
<commit_before>#include "ist/InnerSphereTree.h" #include <iostream> #include <math.h> #include <limits> using namespace std; namespace chai3d { /* Constructor of an inner sphere tree. */ InnerSphereTree::InnerSphereTree() { } /* Destructor of the inner sphere tree. */ InnerSphereTree::~InnerSphereTree() { delete rootSphere; } void InnerSphereTree::printAABBCollisionTree(int diepte) { cout << "INNER SPHERE TREE" << endl; for (int i = 0; i < spheres.size(); i++) { cout << "Sphere: " << spheres[i]->getPosition() << endl; } } /* This function computes if a collision has occured between two inner sphere trees. \param ist2 he other inner sphere tree to compute the possible collision. \param setting The traversalsettings. \param collisionfeedback How close the collision is. \param maxdiepte The maximumdepth the function is allowed to check for collision. \return If to inner sphere trees have collided. */ bool InnerSphereTree::computeCollision(cGenericCollision* ist2, traversalSetting setting, double &collisionfeedback, int maxdiepte, cVector3d myLocal, cVector3d BLocal, cVector3d& positie) { // Sanity check if (ist2 == NULL) return false; if (this->getCollisionTreeType() != ist2->getCollisionTreeType()) return false; switch (setting) { case traversalSetting::DISTANCE: { InnerSphereTree* IST_B = dynamic_cast<InnerSphereTree*>(ist2); InnerSphereTree* IST_A = this; Sphere* parent_A = IST_B->getRootSphere(); Sphere* parent_B = IST_A->getRootSphere(); double mindist = std::numeric_limits<double>::max(); int huidige = 0; } case traversalSetting::COMBINED: return false; case traversalSetting::VOLUME_PEN: return false; default: return false; } return true; } /* Get the root sphere of this inner sphere tree. \return The rootsphere. */ Sphere* InnerSphereTree::getRootSphere() { return rootSphere; } int InnerSphereTree::buildTree(std::vector<Sphere*> leafs, const int a_depth) { for (int i = 0; i < leafs.size(); i++) { spheres.push_back(leafs[i]); } return 0; } //implementation of the BNG algorthm //n-->the number of prototypes //size is the max axis of the boundary box of the object void InnerSphereTree::BNG(double size, Sphere* node, std::vector<Sphere*> leafs, const int a_depth) { #define TMAX 500 //als we de diepte hebben bereikt dan moeten we de kinderen nog toevoegen if (node->getDepth() == a_depth) { addLeafs(leafs, node); return; } struct prototype { cVector3d pos; std::vector<Sphere*> lfs; }; prototype w[4]; double x = node->getPosition().x(); double y = node->getPosition().y(); double z = node->getPosition().z(); double r = node->getRadius(); //chose start pos prototypes w[0].pos.set(x + r, y + r, z); w[1].pos.set(x + r, y - r, z + r); w[2].pos.set(x - r, y + r, z - r); w[3].pos.set(x - r, y - r, z - r); //define epsilon double eps = 0.00001 * size; std::vector<std::vector<int>> weights; int t = 0; bool stop = false; while (!stop && (t <= TMAX)) { int teller = 0; //for every sphere we calculate the distance to each prototype and decide the weights for (int j = 0; j < leafs.size(); j++) { double d[4]; int n[4] = { 0,0,0,0 }; d[0] = (leafs[j]->getPosition() - w[0].pos).length(); d[1] = (leafs[j]->getPosition() - w[1].pos).length(); d[2] = (leafs[j]->getPosition() - w[2].pos).length(); d[3] = (leafs[j]->getPosition() - w[3].pos).length(); for (int i = 0; i < 4; i++) { for (int k = i + 1; k < 4; k++) { if (d[i] < d[k]) n[i]++; else n[k]++; } } for (int i = 0; i < 4; i++) weights[i][j] = n[i]; } //calculate new prototype positions float L = 2 * pow((0.01 / 2.0), t / TMAX); for (int k = 0; k < 4; k++) { double sumf = 0; cVector3d sumv = cVector3d(0, 0, 0); for (int i = 0; i < leafs.size(); i++) { float volume = pow(leafs[i]->getRadius(), 3)*(4.0 / 3.0)* M_PI; float hL = exp(-weights[0][i] / L); float f = hL*volume; cVector3d vec = cVector3d(0, 0, 0); vec = f*(leafs[i]->getPosition()); sumf += f; sumv += vec; } sumv = sumv / sumf; if((w[k].pos - sumv).length() < eps) teller++; if (teller == 4) stop = true; w[k].pos = sumv; } t++; } float max[4] = { 0,0,0,0 }; for (int j = 0; j < leafs.size(); j++) { float mindist = numeric_limits<float>::infinity(); float rad; int num; for (int i = 0; i < 4; i++) { float d = (leafs[j]->getPosition() - w[i].pos).length(); if (d < mindist) { mindist = d; num = i; rad = leafs[j]->getRadius(); } } if (max[num] < (mindist + rad)) max[num] = (mindist + rad); w[num].lfs.push_back(leafs[j]); } //we got all wheights with a vector to their leaves //with all including radius of their leaves for (int i = 0; i < 4; i++) { Sphere* s = new Sphere(); s->setPosition(w[i].pos); s->setRadius(max[i]); s->setState(sphereState::SPHERE_INTERNAL); s->setDepth(node->getDepth()+1); s->setParent(node); //set as child of node node->addChild(s); //recursive call BNG(size, s, w[i].lfs, a_depth); } } void InnerSphereTree::addLeafs(std::vector<Sphere*> leafs, Sphere * node) { for (int i = 0; i < leafs.size(); i++) { leafs[i]->setParent(node); node->addChild(leafs[i]); } } void InnerSphereTree::render(cRenderOptions& a_options) { #ifdef C_USE_OPENGL glDisable(GL_LIGHTING); glLineWidth(1.0); glColor4fv(cColorf(1.0, 0, 0).getData()); for (int i = 0; i < spheres.size(); i++) { spheres[i]->render(); } glEnable(GL_LIGHTING); #endif } }<commit_msg>BNG weight 2-dim vector mod<commit_after>#include "ist/InnerSphereTree.h" #include <iostream> #include <math.h> #include <limits> using namespace std; namespace chai3d { /* Constructor of an inner sphere tree. */ InnerSphereTree::InnerSphereTree() { } /* Destructor of the inner sphere tree. */ InnerSphereTree::~InnerSphereTree() { delete rootSphere; } void InnerSphereTree::printAABBCollisionTree(int diepte) { cout << "INNER SPHERE TREE" << endl; for (int i = 0; i < spheres.size(); i++) { cout << "Sphere: " << spheres[i]->getPosition() << endl; } } /* This function computes if a collision has occured between two inner sphere trees. \param ist2 he other inner sphere tree to compute the possible collision. \param setting The traversalsettings. \param collisionfeedback How close the collision is. \param maxdiepte The maximumdepth the function is allowed to check for collision. \return If to inner sphere trees have collided. */ bool InnerSphereTree::computeCollision(cGenericCollision* ist2, traversalSetting setting, double &collisionfeedback, int maxdiepte, cVector3d myLocal, cVector3d BLocal, cVector3d& positie) { // Sanity check if (ist2 == NULL) return false; if (this->getCollisionTreeType() != ist2->getCollisionTreeType()) return false; switch (setting) { case traversalSetting::DISTANCE: { InnerSphereTree* IST_B = dynamic_cast<InnerSphereTree*>(ist2); InnerSphereTree* IST_A = this; Sphere* parent_A = IST_B->getRootSphere(); Sphere* parent_B = IST_A->getRootSphere(); double mindist = std::numeric_limits<double>::max(); int huidige = 0; } case traversalSetting::COMBINED: return false; case traversalSetting::VOLUME_PEN: return false; default: return false; } return true; } /* Get the root sphere of this inner sphere tree. \return The rootsphere. */ Sphere* InnerSphereTree::getRootSphere() { return rootSphere; } int InnerSphereTree::buildTree(std::vector<Sphere*> leafs, const int a_depth) { for (int i = 0; i < leafs.size(); i++) { spheres.push_back(leafs[i]); } return 0; } //implementation of the BNG algorthm //n-->the number of prototypes //size is the max axis of the boundary box of the object void InnerSphereTree::BNG(double size, Sphere* node, std::vector<Sphere*> leafs, const int a_depth) { #define TMAX 500 //als we de diepte hebben bereikt dan moeten we de kinderen nog toevoegen if (node->getDepth() == a_depth) { addLeafs(leafs, node); return; } struct prototype { cVector3d pos; std::vector<Sphere*> lfs; }; prototype w[4]; double x = node->getPosition().x(); double y = node->getPosition().y(); double z = node->getPosition().z(); double r = node->getRadius(); //chose start pos prototypes w[0].pos.set(x + r, y + r, z); w[1].pos.set(x + r, y - r, z + r); w[2].pos.set(x - r, y + r, z - r); w[3].pos.set(x - r, y - r, z - r); //define epsilon double eps = 0.00001 * size; //first index of weights is the number of the leaf std::vector<std::vector<int>> weights; //row with prototypes per leaf std::vector<int> row; int t = 0; bool stop = false; while (!stop && (t <= TMAX)) { int teller = 0; //for every sphere we calculate the distance to each prototype and decide the weights for (int j = 0; j < leafs.size(); j++) { double d[4]; int n[4] = { 0,0,0,0 }; d[0] = (leafs[j]->getPosition() - w[0].pos).length(); d[1] = (leafs[j]->getPosition() - w[1].pos).length(); d[2] = (leafs[j]->getPosition() - w[2].pos).length(); d[3] = (leafs[j]->getPosition() - w[3].pos).length(); for (int i = 0; i < 4; i++) { for (int k = i + 1; k < 4; k++) { if (d[i] < d[k]) n[i]++; else n[k]++; } } row.clear(); for (int i = 0; i < 4; i++) row.push_back(n[i]); //first index of weights is the number of the leaf weights.push_back(row); } //calculate new prototype positions float L = 2 * pow((0.01 / 2.0), t / TMAX); for (int k = 0; k < 4; k++) { double sumf = 0; cVector3d sumv = cVector3d(0, 0, 0); for (int i = 0; i < leafs.size(); i++) { float volume = pow(leafs[i]->getRadius(), 3)*(4.0 / 3.0)* M_PI; float hL = exp(-weights[i][k] / L); float f = hL*volume; cVector3d vec = cVector3d(0, 0, 0); vec = f*(leafs[i]->getPosition()); sumf += f; sumv += vec; } sumv = sumv / sumf; if((w[k].pos - sumv).length() < eps) teller++; if (teller == 4) stop = true; w[k].pos = sumv; } t++; } float max[4] = { 0,0,0,0 }; for (int j = 0; j < leafs.size(); j++) { float mindist = numeric_limits<float>::infinity(); float rad; int num; for (int i = 0; i < 4; i++) { float d = (leafs[j]->getPosition() - w[i].pos).length(); if (d < mindist) { mindist = d; num = i; rad = leafs[j]->getRadius(); } } if (max[num] < (mindist + rad)) max[num] = (mindist + rad); w[num].lfs.push_back(leafs[j]); } //we got all wheights with a vector to their leaves //with all including radius of their leaves for (int i = 0; i < 4; i++) { Sphere* s = new Sphere(); s->setPosition(w[i].pos); s->setRadius(max[i]); s->setState(sphereState::SPHERE_INTERNAL); s->setDepth(node->getDepth()+1); s->setParent(node); //set as child of node node->addChild(s); //recursive call BNG(size, s, w[i].lfs, a_depth); } } void InnerSphereTree::addLeafs(std::vector<Sphere*> leafs, Sphere * node) { for (int i = 0; i < leafs.size(); i++) { leafs[i]->setParent(node); node->addChild(leafs[i]); } } void InnerSphereTree::render(cRenderOptions& a_options) { #ifdef C_USE_OPENGL glDisable(GL_LIGHTING); glLineWidth(1.0); glColor4fv(cColorf(1.0, 0, 0).getData()); for (int i = 0; i < spheres.size(); i++) { spheres[i]->render(); } glEnable(GL_LIGHTING); #endif } }<|endoftext|>
<commit_before>// -*- C++ -*- // // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // Charles A. Williams // Rensselaer Polytechnic Institute // (C) 2004 All Rights Reserved // // Copyright 2004 Rensselaer Polytechnic Institute. // All worldwide rights reserved. A license to use, copy, modify and // distribute this software for non-commercial research purposes only // is hereby granted, provided that this copyright notice and // accompanying disclaimer is not modified or removed from the software. // // DISCLAIMER: The software is distributed "AS IS" without any express // or implied warranty, including but not limited to, any implied // warranties of merchantability or fitness for a particular purpose // or any warranty of non-infringement of any current or pending patent // rights. The authors of the software make no representations about // the suitability of this software for any particular purpose. The // entire risk as to the quality and performance of the software is with // the user. Should the software prove defective, the user assumes the // cost of all necessary servicing, repair or correction. In // particular, neither Rensselaer Polytechnic Institute, nor the authors // of the software are liable for any indirect, special, consequential, // or incidental damages related to the software, to the maximum extent // the law permits. // // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // #include <portinfo> #include <Python.h> #include <stdio.h> #include <string.h> // USES strncpy() #include "exceptionhandler.h" char* safestrcat(char* dest, const char* src, const int destsize) { // Perform a safe string concatenation. If the destination string is // too small to append all of the src string, only the portion of // the src string that will fit is appended. // maximum number of chars we can add to dest string from src string // 1 accounts for terminating '\0' not included in strlen const int maxadd = destsize - (1+strlen(dest)); if (strlen(src) < maxadd) // we can safely add all chars from src to dest strcat(dest, src); else // we can only add maxadd chars from src to dest, mesg will be truncated strncat(dest, src, maxadd); return dest; } int exceptionhandler(const int errorcode, const char* errorstring) { // Generate python exceptions from error codes const int maxsize = 1024; char errormsg[maxsize]; // copy at most 1023 chars (account for terminating '\0') strncpy(errormsg, errorstring, maxsize-1); switch(errorcode) { case 0: break; case 1: PyErr_SetString(PyExc_IOError, safestrcat(errormsg, ": Error opening file for reading.", maxsize)); break; case 2: PyErr_SetString(PyExc_IOError, safestrcat(errormsg, ": Error opening file for writing.", maxsize)); break; case 3: PyErr_SetString(PyExc_IOError, safestrcat(errormsg, ": Error reading from file.", maxsize)); break; case 4: PyErr_SetString(PyExc_IOError, safestrcat(errormsg, ": Error writing to file.", maxsize)); break; case 5: PyErr_SetString(PyExc_IOError, safestrcat(errormsg, ": Invalid or missing units specification.", maxsize)); break; case 100: PyErr_SetString(PyExc_ValueError, safestrcat(errormsg, ": Attempt to use undefined history.", maxsize)); break; case 101: PyErr_SetString(PyExc_ValueError, safestrcat(errormsg, ": Attempt to use undefined material model.", maxsize)); break; case 102: PyErr_SetString(PyExc_ValueError, safestrcat(errormsg, ": Invalid number of state variables.", maxsize)); break; case 103: PyErr_SetString(PyExc_ValueError, safestrcat(errormsg, ": Zero or negative diagonal in stiffness matrix.", maxsize)); break; case 104: PyErr_SetString(PyExc_ValueError, safestrcat(errormsg, ": BC assigned for nonexistent node.", maxsize)); break; case 105: PyErr_SetString(PyExc_ValueError, safestrcat(errormsg, ": Wrong number of nodes read.", maxsize)); break; case 106: PyErr_SetString(PyExc_ValueError, safestrcat(errormsg, ": Invalid element type specified.", maxsize)); break; case 107: PyErr_SetString(PyExc_ValueError, safestrcat(errormsg, ": Invalid material type specified.", maxsize)); break; case 108: PyErr_SetString(PyExc_ValueError, safestrcat(errormsg, ": Undefined node used in connectivity.", maxsize)); break; case 109: PyErr_SetString(PyExc_ValueError, safestrcat(errormsg, ": Differential force applied to non-slippery node.", maxsize)); break; case 110: PyErr_SetString(PyExc_ValueError, safestrcat(errormsg, ": Matrix not positive-definite.", maxsize)); break; case 111: PyErr_SetString(PyExc_ValueError, safestrcat(errormsg, ": Load history times are out of order.", maxsize)); break; case 112: PyErr_SetString(PyExc_ValueError, safestrcat(errormsg, ": Not enough points to define a plane for slippery nodes.", maxsize)); break; case 113: PyErr_SetString(PyExc_ValueError, safestrcat(errormsg, ": Zero or negative jacobian for element.", maxsize)); break; case 300: PyErr_SetString(PyExc_MemoryError, safestrcat(errormsg, ": Insufficient memory assigned.", maxsize)); break; default: PyErr_SetString(PyExc_ValueError, safestrcat(errormsg, ": Unknown error.", maxsize)); break; } return errorcode; } // version // $Id: exceptionhandler.cc,v 1.1 2004/07/16 21:11:32 willic3 Exp $ // End of file <commit_msg>Increased maximum size of error string.<commit_after>// -*- C++ -*- // // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // Charles A. Williams // Rensselaer Polytechnic Institute // (C) 2004 All Rights Reserved // // Copyright 2004 Rensselaer Polytechnic Institute. // All worldwide rights reserved. A license to use, copy, modify and // distribute this software for non-commercial research purposes only // is hereby granted, provided that this copyright notice and // accompanying disclaimer is not modified or removed from the software. // // DISCLAIMER: The software is distributed "AS IS" without any express // or implied warranty, including but not limited to, any implied // warranties of merchantability or fitness for a particular purpose // or any warranty of non-infringement of any current or pending patent // rights. The authors of the software make no representations about // the suitability of this software for any particular purpose. The // entire risk as to the quality and performance of the software is with // the user. Should the software prove defective, the user assumes the // cost of all necessary servicing, repair or correction. In // particular, neither Rensselaer Polytechnic Institute, nor the authors // of the software are liable for any indirect, special, consequential, // or incidental damages related to the software, to the maximum extent // the law permits. // // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // #include <portinfo> #include <Python.h> #include <stdio.h> #include <string.h> // USES strncpy() #include "exceptionhandler.h" char* safestrcat(char* dest, const char* src, const int destsize) { // Perform a safe string concatenation. If the destination string is // too small to append all of the src string, only the portion of // the src string that will fit is appended. // maximum number of chars we can add to dest string from src string // 1 accounts for terminating '\0' not included in strlen const int maxadd = destsize - (1+strlen(dest)); if (strlen(src) < maxadd) // we can safely add all chars from src to dest strcat(dest, src); else // we can only add maxadd chars from src to dest, mesg will be truncated strncat(dest, src, maxadd); return dest; } int exceptionhandler(const int errorcode, const char* errorstring) { // Generate python exceptions from error codes const int maxsize = 2048; char errormsg[maxsize]; // copy at most 1023 chars (account for terminating '\0') strncpy(errormsg, errorstring, maxsize-1); switch(errorcode) { case 0: break; case 1: PyErr_SetString(PyExc_IOError, safestrcat(errormsg, ": Error opening file for reading.", maxsize)); break; case 2: PyErr_SetString(PyExc_IOError, safestrcat(errormsg, ": Error opening file for writing.", maxsize)); break; case 3: PyErr_SetString(PyExc_IOError, safestrcat(errormsg, ": Error reading from file.", maxsize)); break; case 4: PyErr_SetString(PyExc_IOError, safestrcat(errormsg, ": Error writing to file.", maxsize)); break; case 5: PyErr_SetString(PyExc_IOError, safestrcat(errormsg, ": Invalid or missing units specification.", maxsize)); break; case 100: PyErr_SetString(PyExc_ValueError, safestrcat(errormsg, ": Attempt to use undefined history.", maxsize)); break; case 101: PyErr_SetString(PyExc_ValueError, safestrcat(errormsg, ": Attempt to use undefined material model.", maxsize)); break; case 102: PyErr_SetString(PyExc_ValueError, safestrcat(errormsg, ": Invalid number of state variables.", maxsize)); break; case 103: PyErr_SetString(PyExc_ValueError, safestrcat(errormsg, ": Zero or negative diagonal in stiffness matrix.", maxsize)); break; case 104: PyErr_SetString(PyExc_ValueError, safestrcat(errormsg, ": BC assigned for nonexistent node.", maxsize)); break; case 105: PyErr_SetString(PyExc_ValueError, safestrcat(errormsg, ": Wrong number of nodes read.", maxsize)); break; case 106: PyErr_SetString(PyExc_ValueError, safestrcat(errormsg, ": Invalid element type specified.", maxsize)); break; case 107: PyErr_SetString(PyExc_ValueError, safestrcat(errormsg, ": Invalid material type specified.", maxsize)); break; case 108: PyErr_SetString(PyExc_ValueError, safestrcat(errormsg, ": Undefined node used in connectivity.", maxsize)); break; case 109: PyErr_SetString(PyExc_ValueError, safestrcat(errormsg, ": Differential force applied to non-slippery node.", maxsize)); break; case 110: PyErr_SetString(PyExc_ValueError, safestrcat(errormsg, ": Matrix not positive-definite.", maxsize)); break; case 111: PyErr_SetString(PyExc_ValueError, safestrcat(errormsg, ": Load history times are out of order.", maxsize)); break; case 112: PyErr_SetString(PyExc_ValueError, safestrcat(errormsg, ": Not enough points to define a plane for slippery nodes.", maxsize)); break; case 113: PyErr_SetString(PyExc_ValueError, safestrcat(errormsg, ": Zero or negative jacobian for element.", maxsize)); break; case 300: PyErr_SetString(PyExc_MemoryError, safestrcat(errormsg, ": Insufficient memory assigned.", maxsize)); break; default: PyErr_SetString(PyExc_ValueError, safestrcat(errormsg, ": Unknown error.", maxsize)); break; } return errorcode; } // version // $Id: exceptionhandler.cc,v 1.2 2004/08/12 23:38:42 willic3 Exp $ // End of file <|endoftext|>
<commit_before>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbNeuralNetworkMachineLearningModel.h" #include "otbSVMMachineLearningModel.h" typedef float PrecisionType; typedef otb::MachineLearningModel<PrecisionType,PrecisionType> MachineLearningModelRegressionType; typedef MachineLearningModelRegressionType::InputValueType InputValueRegressionType; typedef MachineLearningModelRegressionType::InputSampleType InputSampleRegressionType; typedef MachineLearningModelRegressionType::InputListSampleType InputListSampleRegressionType; typedef MachineLearningModelRegressionType::TargetValueType TargetValueRegressionType; typedef MachineLearningModelRegressionType::TargetSampleType TargetSampleRegressionType; typedef MachineLearningModelRegressionType::TargetListSampleType TargetListSampleRegressionType; const double epsilon = 0.1; template <typename TPrecision> struct LinearFunctionSampleGenerator { typedef TPrecision PrecisionType; LinearFunctionSampleGenerator(TPrecision a, TPrecision b) : m_a(a), m_b(b), m_NbInputVars(1), m_NbOutputVars(1) { m_isl = InputListSampleRegressionType::New(); m_tsl = TargetListSampleRegressionType::New(); std::srand(0); }; void GenerateSamples(TPrecision sMin, TPrecision sMax, size_t nbSamples) { m_isl->SetMeasurementVectorSize(m_NbInputVars); m_tsl->SetMeasurementVectorSize(m_NbOutputVars); TPrecision sampleStep = (sMax-sMin)/nbSamples; for(size_t i=0; i<nbSamples; ++i) { InputSampleRegressionType inputSample; inputSample.Reserve(m_NbInputVars); TPrecision x = std::rand()/static_cast<TPrecision>(RAND_MAX)*nbSamples; TPrecision inputValue = sMin+ x*sampleStep; inputSample[0] = inputValue; TPrecision outputValue = m_a*inputValue+m_b; m_isl->PushBack(inputSample); m_tsl->PushBack(outputValue); } } TPrecision m_a; TPrecision m_b; const size_t m_NbInputVars; const size_t m_NbOutputVars; InputListSampleRegressionType::Pointer m_isl; TargetListSampleRegressionType::Pointer m_tsl; }; template <typename SampleGeneratorType, typename RegressionType> int validate(SampleGeneratorType& sg, RegressionType& rgrsn) { std::cout << "Validation\n"; //Check the prediction accuracy typename InputListSampleRegressionType::Iterator sampleIt = sg.m_isl->Begin(); typename TargetListSampleRegressionType::Iterator resultIt = sg.m_tsl->Begin(); typename InputListSampleRegressionType::Iterator sampleLast = sg.m_isl->End(); typename TargetListSampleRegressionType::Iterator resultLast = sg.m_tsl->End(); typename SampleGeneratorType::PrecisionType rmse = 0.0; size_t nbSamples = 0; while(sampleIt != sampleLast && resultIt != resultLast) { typename SampleGeneratorType::PrecisionType invalue = sampleIt.GetMeasurementVector()[0]; typename SampleGeneratorType::PrecisionType prediction = rgrsn->Predict(sampleIt.GetMeasurementVector())[0]; typename SampleGeneratorType::PrecisionType expected = resultIt.GetMeasurementVector()[0]; rmse += pow(prediction - expected, 2.0); ++sampleIt; ++resultIt; ++nbSamples; } rmse /= nbSamples; if(rmse > epsilon) return EXIT_FAILURE; return EXIT_SUCCESS; } int otbNeuralNetworkRegressionLinearMonovariate(int itkNotUsed(argc), char * itkNotUsed(argv) []) { LinearFunctionSampleGenerator<PrecisionType> lfsg(1.0, 0.0); std::cout << "Generating samples\n"; lfsg.GenerateSamples(-0.5, 0.5, 20000); typedef otb::NeuralNetworkMachineLearningModel<InputValueRegressionType, TargetValueRegressionType> NeuralNetworkType; NeuralNetworkType::Pointer regression = NeuralNetworkType::New(); regression->SetRegressionMode(1); regression->SetTrainMethod(CvANN_MLP_TrainParams::BACKPROP); std::vector<unsigned int> layerSizes; layerSizes.push_back(1); layerSizes.push_back(5); layerSizes.push_back(1); regression->SetLayerSizes(layerSizes); regression->SetActivateFunction(CvANN_MLP::SIGMOID_SYM); regression->SetAlpha(1.0); regression->SetBeta(1.0); regression->SetBackPropDWScale(0.1); regression->SetBackPropMomentScale(0.1); regression->SetRegPropDW0(0.1); regression->SetRegPropDWMin(1e-7); regression->SetTermCriteriaType(CV_TERMCRIT_EPS); regression->SetEpsilon(1e-5); regression->SetMaxIter(1e20); regression->SetInputListSample(lfsg.m_isl); regression->SetTargetListSample(lfsg.m_tsl); std::cout << "Training\n"; regression->Train(); return validate(lfsg, regression); } int otbSVMRegressionLinearMonovariate(int itkNotUsed(argc), char * itkNotUsed(argv) []) { LinearFunctionSampleGenerator<PrecisionType> lfsg(1.0, 0.0); std::cout << "Generating samples\n"; lfsg.GenerateSamples(-0.5, 0.5, 20000); typedef otb::SVMMachineLearningModel<InputValueRegressionType, TargetValueRegressionType> SVMType; SVMType::Pointer regression = SVMType::New(); regression->SetRegressionMode(1); regression->SetNu(0.5); regression->SetKernelType(CvSVM::RBF); regression->SetTermCriteriaType(CV_TERMCRIT_ITER+CV_TERMCRIT_EPS); regression->SetMaxIter(100000); regression->SetEpsilon(FLT_EPSILON); regression->SetParameterOptimization(true); regression->SetInputListSample(lfsg.m_isl); regression->SetTargetListSample(lfsg.m_tsl); std::cout << "Training\n"; regression->Train(); return validate(lfsg, regression); } <commit_msg>TEST: change parameters for faster test<commit_after>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbNeuralNetworkMachineLearningModel.h" #include "otbSVMMachineLearningModel.h" typedef float PrecisionType; typedef otb::MachineLearningModel<PrecisionType,PrecisionType> MachineLearningModelRegressionType; typedef MachineLearningModelRegressionType::InputValueType InputValueRegressionType; typedef MachineLearningModelRegressionType::InputSampleType InputSampleRegressionType; typedef MachineLearningModelRegressionType::InputListSampleType InputListSampleRegressionType; typedef MachineLearningModelRegressionType::TargetValueType TargetValueRegressionType; typedef MachineLearningModelRegressionType::TargetSampleType TargetSampleRegressionType; typedef MachineLearningModelRegressionType::TargetListSampleType TargetListSampleRegressionType; const double epsilon = 0.1; template <typename TPrecision> struct LinearFunctionSampleGenerator { typedef TPrecision PrecisionType; LinearFunctionSampleGenerator(TPrecision a, TPrecision b) : m_a(a), m_b(b), m_NbInputVars(1), m_NbOutputVars(1) { m_isl = InputListSampleRegressionType::New(); m_tsl = TargetListSampleRegressionType::New(); std::srand(0); }; void GenerateSamples(TPrecision sMin, TPrecision sMax, size_t nbSamples) { m_isl->SetMeasurementVectorSize(m_NbInputVars); m_tsl->SetMeasurementVectorSize(m_NbOutputVars); TPrecision sampleStep = (sMax-sMin)/nbSamples; for(size_t i=0; i<nbSamples; ++i) { InputSampleRegressionType inputSample; inputSample.Reserve(m_NbInputVars); TPrecision x = std::rand()/static_cast<TPrecision>(RAND_MAX)*nbSamples; TPrecision inputValue = sMin+ x*sampleStep; inputSample[0] = inputValue; TPrecision outputValue = m_a*inputValue+m_b; m_isl->PushBack(inputSample); m_tsl->PushBack(outputValue); } } TPrecision m_a; TPrecision m_b; const size_t m_NbInputVars; const size_t m_NbOutputVars; InputListSampleRegressionType::Pointer m_isl; TargetListSampleRegressionType::Pointer m_tsl; }; template <typename SampleGeneratorType, typename RegressionType> int validate(SampleGeneratorType& sg, RegressionType& rgrsn) { std::cout << "Validation\n"; //Check the prediction accuracy typename InputListSampleRegressionType::Iterator sampleIt = sg.m_isl->Begin(); typename TargetListSampleRegressionType::Iterator resultIt = sg.m_tsl->Begin(); typename InputListSampleRegressionType::Iterator sampleLast = sg.m_isl->End(); typename TargetListSampleRegressionType::Iterator resultLast = sg.m_tsl->End(); typename SampleGeneratorType::PrecisionType rmse = 0.0; size_t nbSamples = 0; while(sampleIt != sampleLast && resultIt != resultLast) { typename SampleGeneratorType::PrecisionType invalue = sampleIt.GetMeasurementVector()[0]; typename SampleGeneratorType::PrecisionType prediction = rgrsn->Predict(sampleIt.GetMeasurementVector())[0]; typename SampleGeneratorType::PrecisionType expected = resultIt.GetMeasurementVector()[0]; rmse += pow(prediction - expected, 2.0); ++sampleIt; ++resultIt; ++nbSamples; } rmse /= nbSamples; if(rmse > epsilon) return EXIT_FAILURE; return EXIT_SUCCESS; } int otbNeuralNetworkRegressionLinearMonovariate(int itkNotUsed(argc), char * itkNotUsed(argv) []) { LinearFunctionSampleGenerator<PrecisionType> lfsg(1.0, 0.0); std::cout << "Generating samples\n"; lfsg.GenerateSamples(-0.5, 0.5, 20000); typedef otb::NeuralNetworkMachineLearningModel<InputValueRegressionType, TargetValueRegressionType> NeuralNetworkType; NeuralNetworkType::Pointer regression = NeuralNetworkType::New(); regression->SetRegressionMode(1); regression->SetTrainMethod(CvANN_MLP_TrainParams::BACKPROP); std::vector<unsigned int> layerSizes; layerSizes.push_back(1); layerSizes.push_back(5); layerSizes.push_back(1); regression->SetLayerSizes(layerSizes); regression->SetActivateFunction(CvANN_MLP::SIGMOID_SYM); regression->SetAlpha(1.0); regression->SetBeta(1.0); regression->SetBackPropDWScale(0.1); regression->SetBackPropMomentScale(0.1); regression->SetRegPropDW0(0.1); regression->SetRegPropDWMin(1e-7); regression->SetTermCriteriaType(CV_TERMCRIT_EPS); regression->SetEpsilon(1e-5); regression->SetMaxIter(1e20); regression->SetInputListSample(lfsg.m_isl); regression->SetTargetListSample(lfsg.m_tsl); std::cout << "Training\n"; regression->Train(); return validate(lfsg, regression); } int otbSVMRegressionLinearMonovariate(int itkNotUsed(argc), char * itkNotUsed(argv) []) { LinearFunctionSampleGenerator<PrecisionType> lfsg(1.0, 0.0); std::cout << "Generating samples\n"; lfsg.GenerateSamples(-0.5, 0.5, 200); typedef otb::SVMMachineLearningModel<InputValueRegressionType, TargetValueRegressionType> SVMType; SVMType::Pointer regression = SVMType::New(); regression->SetRegressionMode(1); regression->SetNu(0.5); regression->SetKernelType(CvSVM::RBF); regression->SetTermCriteriaType(CV_TERMCRIT_ITER+CV_TERMCRIT_EPS); regression->SetMaxIter(100000); regression->SetEpsilon(1e-5); regression->SetParameterOptimization(true); regression->SetInputListSample(lfsg.m_isl); regression->SetTargetListSample(lfsg.m_tsl); std::cout << "Training\n"; regression->Train(); return validate(lfsg, regression); } <|endoftext|>
<commit_before>#include "addressbookpage.h" #include "ui_addressbookpage.h" #include "addresstablemodel.h" #include "optionsmodel.h" #include "bitcoingui.h" #include "editaddressdialog.h" #include "csvmodelwriter.h" #include "guiutil.h" #include <QSortFilterProxyModel> #include <QClipboard> #include <QMessageBox> #include <QMenu> #ifdef USE_QRCODE #include "qrcodedialog.h" #endif AddressBookPage::AddressBookPage(Mode mode, Tabs tab, QWidget *parent) : QDialog(parent), ui(new Ui::AddressBookPage), model(0), optionsModel(0), mode(mode), tab(tab) { ui->setupUi(this); #ifdef Q_OS_MAC // Icons on push buttons are very uncommon on Mac ui->newAddressButton->setIcon(QIcon()); ui->copyToClipboardButton->setIcon(QIcon()); ui->deleteButton->setIcon(QIcon()); #endif #ifndef USE_QRCODE ui->showQRCodeButton->setVisible(false); #endif switch(mode) { case ForSending: connect(ui->tableView, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(accept())); ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers); ui->tableView->setFocus(); break; case ForEditing: ui->okayButtonBox->setVisible(false); break; } switch(tab) { case SendingTab: ui->explanationLabel->setVisible(false); ui->deleteButton->setVisible(true); ui->signMessageButton->setVisible(false); break; case ReceivingTab: ui->deleteButton->setVisible(false); ui->signMessageButton->setVisible(true); break; } // Context menu actions QAction *copyLabelAction = new QAction(tr("Copy &Label"), this); QAction *copyAddressAction = new QAction(ui->copyToClipboardButton->text(), this); QAction *editAction = new QAction(tr("&Edit"), this); QAction *showQRCodeAction = new QAction(ui->showQRCodeButton->text(), this); QAction *signMessageAction = new QAction(ui->signMessageButton->text(), this); QAction *verifyMessageAction = new QAction(ui->verifyMessageButton->text(), this); deleteAction = new QAction(ui->deleteButton->text(), this); // Build context menu contextMenu = new QMenu(this); contextMenu->addAction(copyAddressAction); contextMenu->addAction(copyLabelAction); contextMenu->addAction(editAction); if(tab == SendingTab) contextMenu->addAction(deleteAction); contextMenu->addSeparator(); contextMenu->addAction(showQRCodeAction); if(tab == ReceivingTab) contextMenu->addAction(signMessageAction); else if(tab == SendingTab) contextMenu->addAction(verifyMessageAction); // Connect signals for context menu actions connect(copyAddressAction, SIGNAL(triggered()), this, SLOT(on_copyToClipboardButton_clicked())); connect(copyLabelAction, SIGNAL(triggered()), this, SLOT(onCopyLabelAction())); connect(editAction, SIGNAL(triggered()), this, SLOT(onEditAction())); connect(deleteAction, SIGNAL(triggered()), this, SLOT(on_deleteButton_clicked())); connect(showQRCodeAction, SIGNAL(triggered()), this, SLOT(on_showQRCodeButton_clicked())); connect(signMessageAction, SIGNAL(triggered()), this, SLOT(on_signMessageButton_clicked())); connect(verifyMessageAction, SIGNAL(triggered()), this, SLOT(on_verifyMessageButton_clicked())); connect(ui->tableView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextualMenu(QPoint))); // Pass through accept action from button box connect(ui->okayButtonBox, SIGNAL(accepted()), this, SLOT(accept())); } AddressBookPage::~AddressBookPage() { delete ui; } void AddressBookPage::setModel(AddressTableModel *model) { this->model = model; if(!model) return; proxyModel = new QSortFilterProxyModel(this); proxyModel->setSourceModel(model); proxyModel->setDynamicSortFilter(true); proxyModel->setSortCaseSensitivity(Qt::CaseInsensitive); proxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive); switch(tab) { case ReceivingTab: // Receive filter proxyModel->setFilterRole(AddressTableModel::TypeRole); proxyModel->setFilterFixedString(AddressTableModel::Receive); break; case SendingTab: // Send filter proxyModel->setFilterRole(AddressTableModel::TypeRole); proxyModel->setFilterFixedString(AddressTableModel::Send); break; } ui->tableView->setModel(proxyModel); ui->tableView->sortByColumn(0, Qt::AscendingOrder); // Set column widths ui->tableView->horizontalHeader()->setSectionResizeMode(AddressTableModel::Label, QHeaderView::Stretch); ui->tableView->horizontalHeader()->setSectionResizeMode(AddressTableModel::Address, QHeaderView::ResizeToContents); ui->tableView->horizontalHeader()->resizeSection(AddressTableModel::Address, 320); connect(ui->tableView->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), this, SLOT(selectionChanged())); // Select row for newly created address connect(model, SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(selectNewAddress(QModelIndex,int,int))); selectionChanged(); } void AddressBookPage::setOptionsModel(OptionsModel *optionsModel) { this->optionsModel = optionsModel; } void AddressBookPage::on_copyToClipboardButton_clicked() { GUIUtil::copyEntryData(ui->tableView, AddressTableModel::Address); } void AddressBookPage::onCopyLabelAction() { GUIUtil::copyEntryData(ui->tableView, AddressTableModel::Label); } void AddressBookPage::onEditAction() { if(!ui->tableView->selectionModel()) return; QModelIndexList indexes = ui->tableView->selectionModel()->selectedRows(); if(indexes.isEmpty()) return; EditAddressDialog dlg( tab == SendingTab ? EditAddressDialog::EditSendingAddress : EditAddressDialog::EditReceivingAddress); dlg.setModel(model); QModelIndex origIndex = proxyModel->mapToSource(indexes.at(0)); dlg.loadRow(origIndex.row()); dlg.exec(); } void AddressBookPage::on_signMessageButton_clicked() { QTableView *table = ui->tableView; QModelIndexList indexes = table->selectionModel()->selectedRows(AddressTableModel::Address); QString addr; foreach (QModelIndex index, indexes) { QVariant address = index.data(); addr = address.toString(); } emit signMessage(addr); } void AddressBookPage::on_verifyMessageButton_clicked() { QTableView *table = ui->tableView; QModelIndexList indexes = table->selectionModel()->selectedRows(AddressTableModel::Address); QString addr; foreach (QModelIndex index, indexes) { QVariant address = index.data(); addr = address.toString(); } emit verifyMessage(addr); } void AddressBookPage::on_newAddressButton_clicked() { if(!model) return; EditAddressDialog dlg( tab == SendingTab ? EditAddressDialog::NewSendingAddress : EditAddressDialog::NewReceivingAddress, this); dlg.setModel(model); if(dlg.exec()) { newAddressToSelect = dlg.getAddress(); } } void AddressBookPage::on_deleteButton_clicked() { QTableView *table = ui->tableView; if(!table->selectionModel()) return; QModelIndexList indexes = table->selectionModel()->selectedRows(); if(!indexes.isEmpty()) { table->model()->removeRow(indexes.at(0).row()); } } void AddressBookPage::selectionChanged() { // Set button states based on selected tab and selection QTableView *table = ui->tableView; if(!table->selectionModel()) return; if(table->selectionModel()->hasSelection()) { switch(tab) { case SendingTab: // In sending tab, allow deletion of selection ui->deleteButton->setEnabled(true); ui->deleteButton->setVisible(true); deleteAction->setEnabled(true); ui->signMessageButton->setEnabled(false); ui->signMessageButton->setVisible(false); ui->verifyMessageButton->setEnabled(true); ui->verifyMessageButton->setVisible(true); break; case ReceivingTab: // Deleting receiving addresses, however, is not allowed ui->deleteButton->setEnabled(false); ui->deleteButton->setVisible(false); deleteAction->setEnabled(false); ui->signMessageButton->setEnabled(true); ui->signMessageButton->setVisible(true); ui->verifyMessageButton->setEnabled(false); ui->verifyMessageButton->setVisible(false); break; } ui->copyToClipboardButton->setEnabled(true); ui->showQRCodeButton->setEnabled(true); } else { ui->deleteButton->setEnabled(false); ui->showQRCodeButton->setEnabled(false); ui->copyToClipboardButton->setEnabled(false); ui->signMessageButton->setEnabled(false); ui->verifyMessageButton->setEnabled(false); } } void AddressBookPage::done(int retval) { QTableView *table = ui->tableView; if(!table->selectionModel() || !table->model()) return; // When this is a tab/widget and not a model dialog, ignore "done" if(mode == ForEditing) return; // Figure out which address was selected, and return it QModelIndexList indexes = table->selectionModel()->selectedRows(AddressTableModel::Address); foreach (QModelIndex index, indexes) { QVariant address = table->model()->data(index); returnValue = address.toString(); } if(returnValue.isEmpty()) { // If no address entry selected, return rejected retval = Rejected; } QDialog::done(retval); } void AddressBookPage::exportClicked() { // CSV is currently the only supported format QString filename = GUIUtil::getSaveFileName( this, tr("Export Address Book Data"), QString(), tr("Comma separated file (*.csv)")); if (filename.isNull()) return; CSVModelWriter writer(filename); // name, column, role writer.setModel(proxyModel); writer.addColumn("Label", AddressTableModel::Label, Qt::EditRole); writer.addColumn("Address", AddressTableModel::Address, Qt::EditRole); if(!writer.write()) { QMessageBox::critical(this, tr("Error exporting"), tr("Could not write to file %1.").arg(filename), QMessageBox::Abort, QMessageBox::Abort); } } void AddressBookPage::on_showQRCodeButton_clicked() { #ifdef USE_QRCODE QTableView *table = ui->tableView; QModelIndexList indexes = table->selectionModel()->selectedRows(AddressTableModel::Address); foreach (QModelIndex index, indexes) { QString address = index.data().toString(), label = index.sibling(index.row(), 0).data(Qt::EditRole).toString(); QRCodeDialog *dialog = new QRCodeDialog(address, label, tab == ReceivingTab, this); if(optionsModel) dialog->setModel(optionsModel); dialog->setAttribute(Qt::WA_DeleteOnClose); dialog->show(); } #endif } void AddressBookPage::contextualMenu(const QPoint &point) { QModelIndex index = ui->tableView->indexAt(point); if(index.isValid()) { contextMenu->exec(QCursor::pos()); } } void AddressBookPage::selectNewAddress(const QModelIndex &parent, int begin, int end) { QModelIndex idx = proxyModel->mapFromSource(model->index(begin, AddressTableModel::Address, parent)); if(idx.isValid() && (idx.data(Qt::EditRole).toString() == newAddressToSelect)) { // Select row of newly created address, once ui->tableView->setFocus(); ui->tableView->selectRow(idx.row()); newAddressToSelect.clear(); } } <commit_msg>Fix "verify message" button visible on receive page<commit_after>#include "addressbookpage.h" #include "ui_addressbookpage.h" #include "addresstablemodel.h" #include "optionsmodel.h" #include "bitcoingui.h" #include "editaddressdialog.h" #include "csvmodelwriter.h" #include "guiutil.h" #include <QSortFilterProxyModel> #include <QClipboard> #include <QMessageBox> #include <QMenu> #ifdef USE_QRCODE #include "qrcodedialog.h" #endif AddressBookPage::AddressBookPage(Mode mode, Tabs tab, QWidget *parent) : QDialog(parent), ui(new Ui::AddressBookPage), model(0), optionsModel(0), mode(mode), tab(tab) { ui->setupUi(this); #ifdef Q_OS_MAC // Icons on push buttons are very uncommon on Mac ui->newAddressButton->setIcon(QIcon()); ui->copyToClipboardButton->setIcon(QIcon()); ui->deleteButton->setIcon(QIcon()); #endif #ifndef USE_QRCODE ui->showQRCodeButton->setVisible(false); #endif switch(mode) { case ForSending: connect(ui->tableView, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(accept())); ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers); ui->tableView->setFocus(); break; case ForEditing: ui->okayButtonBox->setVisible(false); break; } switch(tab) { case SendingTab: ui->explanationLabel->setVisible(false); ui->deleteButton->setVisible(true); ui->signMessageButton->setVisible(false); break; case ReceivingTab: ui->deleteButton->setVisible(false); ui->verifyMessageButton->setVisible(false); ui->signMessageButton->setVisible(true); break; } // Context menu actions QAction *copyLabelAction = new QAction(tr("Copy &Label"), this); QAction *copyAddressAction = new QAction(ui->copyToClipboardButton->text(), this); QAction *editAction = new QAction(tr("&Edit"), this); QAction *showQRCodeAction = new QAction(ui->showQRCodeButton->text(), this); QAction *signMessageAction = new QAction(ui->signMessageButton->text(), this); QAction *verifyMessageAction = new QAction(ui->verifyMessageButton->text(), this); deleteAction = new QAction(ui->deleteButton->text(), this); // Build context menu contextMenu = new QMenu(this); contextMenu->addAction(copyAddressAction); contextMenu->addAction(copyLabelAction); contextMenu->addAction(editAction); if(tab == SendingTab) contextMenu->addAction(deleteAction); contextMenu->addSeparator(); contextMenu->addAction(showQRCodeAction); if(tab == ReceivingTab) contextMenu->addAction(signMessageAction); else if(tab == SendingTab) contextMenu->addAction(verifyMessageAction); // Connect signals for context menu actions connect(copyAddressAction, SIGNAL(triggered()), this, SLOT(on_copyToClipboardButton_clicked())); connect(copyLabelAction, SIGNAL(triggered()), this, SLOT(onCopyLabelAction())); connect(editAction, SIGNAL(triggered()), this, SLOT(onEditAction())); connect(deleteAction, SIGNAL(triggered()), this, SLOT(on_deleteButton_clicked())); connect(showQRCodeAction, SIGNAL(triggered()), this, SLOT(on_showQRCodeButton_clicked())); connect(signMessageAction, SIGNAL(triggered()), this, SLOT(on_signMessageButton_clicked())); connect(verifyMessageAction, SIGNAL(triggered()), this, SLOT(on_verifyMessageButton_clicked())); connect(ui->tableView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextualMenu(QPoint))); // Pass through accept action from button box connect(ui->okayButtonBox, SIGNAL(accepted()), this, SLOT(accept())); } AddressBookPage::~AddressBookPage() { delete ui; } void AddressBookPage::setModel(AddressTableModel *model) { this->model = model; if(!model) return; proxyModel = new QSortFilterProxyModel(this); proxyModel->setSourceModel(model); proxyModel->setDynamicSortFilter(true); proxyModel->setSortCaseSensitivity(Qt::CaseInsensitive); proxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive); switch(tab) { case ReceivingTab: // Receive filter proxyModel->setFilterRole(AddressTableModel::TypeRole); proxyModel->setFilterFixedString(AddressTableModel::Receive); break; case SendingTab: // Send filter proxyModel->setFilterRole(AddressTableModel::TypeRole); proxyModel->setFilterFixedString(AddressTableModel::Send); break; } ui->tableView->setModel(proxyModel); ui->tableView->sortByColumn(0, Qt::AscendingOrder); // Set column widths ui->tableView->horizontalHeader()->setSectionResizeMode(AddressTableModel::Label, QHeaderView::Stretch); ui->tableView->horizontalHeader()->setSectionResizeMode(AddressTableModel::Address, QHeaderView::ResizeToContents); ui->tableView->horizontalHeader()->resizeSection(AddressTableModel::Address, 320); connect(ui->tableView->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), this, SLOT(selectionChanged())); // Select row for newly created address connect(model, SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(selectNewAddress(QModelIndex,int,int))); selectionChanged(); } void AddressBookPage::setOptionsModel(OptionsModel *optionsModel) { this->optionsModel = optionsModel; } void AddressBookPage::on_copyToClipboardButton_clicked() { GUIUtil::copyEntryData(ui->tableView, AddressTableModel::Address); } void AddressBookPage::onCopyLabelAction() { GUIUtil::copyEntryData(ui->tableView, AddressTableModel::Label); } void AddressBookPage::onEditAction() { if(!ui->tableView->selectionModel()) return; QModelIndexList indexes = ui->tableView->selectionModel()->selectedRows(); if(indexes.isEmpty()) return; EditAddressDialog dlg( tab == SendingTab ? EditAddressDialog::EditSendingAddress : EditAddressDialog::EditReceivingAddress); dlg.setModel(model); QModelIndex origIndex = proxyModel->mapToSource(indexes.at(0)); dlg.loadRow(origIndex.row()); dlg.exec(); } void AddressBookPage::on_signMessageButton_clicked() { QTableView *table = ui->tableView; QModelIndexList indexes = table->selectionModel()->selectedRows(AddressTableModel::Address); QString addr; foreach (QModelIndex index, indexes) { QVariant address = index.data(); addr = address.toString(); } emit signMessage(addr); } void AddressBookPage::on_verifyMessageButton_clicked() { QTableView *table = ui->tableView; QModelIndexList indexes = table->selectionModel()->selectedRows(AddressTableModel::Address); QString addr; foreach (QModelIndex index, indexes) { QVariant address = index.data(); addr = address.toString(); } emit verifyMessage(addr); } void AddressBookPage::on_newAddressButton_clicked() { if(!model) return; EditAddressDialog dlg( tab == SendingTab ? EditAddressDialog::NewSendingAddress : EditAddressDialog::NewReceivingAddress, this); dlg.setModel(model); if(dlg.exec()) { newAddressToSelect = dlg.getAddress(); } } void AddressBookPage::on_deleteButton_clicked() { QTableView *table = ui->tableView; if(!table->selectionModel()) return; QModelIndexList indexes = table->selectionModel()->selectedRows(); if(!indexes.isEmpty()) { table->model()->removeRow(indexes.at(0).row()); } } void AddressBookPage::selectionChanged() { // Set button states based on selected tab and selection QTableView *table = ui->tableView; if(!table->selectionModel()) return; if(table->selectionModel()->hasSelection()) { switch(tab) { case SendingTab: // In sending tab, allow deletion of selection ui->deleteButton->setEnabled(true); ui->deleteButton->setVisible(true); deleteAction->setEnabled(true); ui->signMessageButton->setEnabled(false); ui->signMessageButton->setVisible(false); ui->verifyMessageButton->setEnabled(true); ui->verifyMessageButton->setVisible(true); break; case ReceivingTab: // Deleting receiving addresses, however, is not allowed ui->deleteButton->setEnabled(false); ui->deleteButton->setVisible(false); deleteAction->setEnabled(false); ui->signMessageButton->setEnabled(true); ui->signMessageButton->setVisible(true); ui->verifyMessageButton->setEnabled(false); ui->verifyMessageButton->setVisible(false); break; } ui->copyToClipboardButton->setEnabled(true); ui->showQRCodeButton->setEnabled(true); } else { ui->deleteButton->setEnabled(false); ui->showQRCodeButton->setEnabled(false); ui->copyToClipboardButton->setEnabled(false); ui->signMessageButton->setEnabled(false); ui->verifyMessageButton->setEnabled(false); } } void AddressBookPage::done(int retval) { QTableView *table = ui->tableView; if(!table->selectionModel() || !table->model()) return; // When this is a tab/widget and not a model dialog, ignore "done" if(mode == ForEditing) return; // Figure out which address was selected, and return it QModelIndexList indexes = table->selectionModel()->selectedRows(AddressTableModel::Address); foreach (QModelIndex index, indexes) { QVariant address = table->model()->data(index); returnValue = address.toString(); } if(returnValue.isEmpty()) { // If no address entry selected, return rejected retval = Rejected; } QDialog::done(retval); } void AddressBookPage::exportClicked() { // CSV is currently the only supported format QString filename = GUIUtil::getSaveFileName( this, tr("Export Address Book Data"), QString(), tr("Comma separated file (*.csv)")); if (filename.isNull()) return; CSVModelWriter writer(filename); // name, column, role writer.setModel(proxyModel); writer.addColumn("Label", AddressTableModel::Label, Qt::EditRole); writer.addColumn("Address", AddressTableModel::Address, Qt::EditRole); if(!writer.write()) { QMessageBox::critical(this, tr("Error exporting"), tr("Could not write to file %1.").arg(filename), QMessageBox::Abort, QMessageBox::Abort); } } void AddressBookPage::on_showQRCodeButton_clicked() { #ifdef USE_QRCODE QTableView *table = ui->tableView; QModelIndexList indexes = table->selectionModel()->selectedRows(AddressTableModel::Address); foreach (QModelIndex index, indexes) { QString address = index.data().toString(), label = index.sibling(index.row(), 0).data(Qt::EditRole).toString(); QRCodeDialog *dialog = new QRCodeDialog(address, label, tab == ReceivingTab, this); if(optionsModel) dialog->setModel(optionsModel); dialog->setAttribute(Qt::WA_DeleteOnClose); dialog->show(); } #endif } void AddressBookPage::contextualMenu(const QPoint &point) { QModelIndex index = ui->tableView->indexAt(point); if(index.isValid()) { contextMenu->exec(QCursor::pos()); } } void AddressBookPage::selectNewAddress(const QModelIndex &parent, int begin, int end) { QModelIndex idx = proxyModel->mapFromSource(model->index(begin, AddressTableModel::Address, parent)); if(idx.isValid() && (idx.data(Qt::EditRole).toString() == newAddressToSelect)) { // Select row of newly created address, once ui->tableView->setFocus(); ui->tableView->selectRow(idx.row()); newAddressToSelect.clear(); } } <|endoftext|>
<commit_before>#include "aliastablemodel.h" #include "guiutil.h" #include "walletmodel.h" #include "wallet.h" #include "base58.h" #include <QFont> using namespace std; const QString AliasTableModel::Alias = "A"; const QString AliasTableModel::DataAlias = "D"; class CAliasDB; extern CAliasDB *paliasdb; int GetAliasExpirationDepth(int nHeight); struct AliasTableEntry { enum Type { Alias, DataAlias }; Type type; QString value; QString alias; QString expirationdepth; AliasTableEntry() {} AliasTableEntry(Type type, const QString &value, const QString &alias, const QString &expirationdepth): type(type), value(value), alias(alias), expirationdepth(expirationdepth) {} }; struct AliasTableEntryLessThan { bool operator()(const AliasTableEntry &a, const AliasTableEntry &b) const { return a.alias < b.alias; } bool operator()(const AliasTableEntry &a, const QString &b) const { return a.alias < b; } bool operator()(const QString &a, const AliasTableEntry &b) const { return a < b.alias; } }; #define NAMEMAPTYPE map<vector<unsigned char>, uint256> // Private implementation class AliasTablePriv { public: CWallet *wallet; QList<AliasTableEntry> cachedAliasTable; AliasTableModel *parent; AliasTablePriv(CWallet *wallet, AliasTableModel *parent): wallet(wallet), parent(parent) {} void refreshAliasTable() { cachedAliasTable.clear(); { CBlockIndex* pindex = pindexGenesisBlock; LOCK(wallet->cs_wallet); while (pindex) { int nHeight = pindex->nHeight; CBlock block; block.ReadFromDisk(pindex); uint256 txblkhash; BOOST_FOREACH(CTransaction& tx, block.vtx) { if (tx.nVersion != SYSCOIN_TX_VERSION) continue; int op, nOut; vector<vector<unsigned char> > vvchArgs; bool o = DecodeAliasTx(tx, op, nOut, vvchArgs, nHeight); if (!o || !IsAliasOp(op) || !IsAliasMine(tx)) continue; // get the transaction if(!GetTransaction(tx.GetHash(), tx, txblkhash, true)) continue; if (op == OP_ALIAS_NEW) continue; const vector<unsigned char> &vchName = vvchArgs[0]; const vector<unsigned char> &vchValue = vvchArgs[op == OP_ALIAS_ACTIVATE ? 2 : 1]; if(!GetTransaction(tx.GetHash(), tx, txblkhash, true)) continue; vector<CAliasIndex> vtxPos; if (!paliasdb->ReadAlias(vchName, vtxPos)) continue; CAliasIndex txName = vtxPos.back(); unsigned long nExpDepth = txName.nHeight + GetAliasExpirationDepth(txName.nHeight); cachedAliasTable.append(AliasTableEntry(tx.data.size() ? AliasTableEntry::DataAlias : AliasTableEntry::Alias, QString::fromStdString(stringFromVch(vchValue)), QString::fromStdString(stringFromVch(vchName)), QString::fromStdString(strprintf("%lu", nExpDepth)))); } pindex = pindex->pnext; } } // qLowerBound() and qUpperBound() require our cachedAliasTable list to be sorted in asc order qSort(cachedAliasTable.begin(), cachedAliasTable.end(), AliasTableEntryLessThan()); } void updateEntry(const QString &alias, const QString &value, const QString &exp, bool isData, int status) { // Find alias / value in model QList<AliasTableEntry>::iterator lower = qLowerBound( cachedAliasTable.begin(), cachedAliasTable.end(), alias, AliasTableEntryLessThan()); QList<AliasTableEntry>::iterator upper = qUpperBound( cachedAliasTable.begin(), cachedAliasTable.end(), alias, AliasTableEntryLessThan()); int lowerIndex = (lower - cachedAliasTable.begin()); int upperIndex = (upper - cachedAliasTable.begin()); bool inModel = (lower != upper); AliasTableEntry::Type newEntryType = isData ? AliasTableEntry::DataAlias : AliasTableEntry::Alias; switch(status) { case CT_NEW: if(inModel) { OutputDebugStringF("Warning: AliasTablePriv::updateEntry: Got CT_NOW, but entry is already in model\n"); break; } parent->beginInsertRows(QModelIndex(), lowerIndex, lowerIndex); cachedAliasTable.insert(lowerIndex, AliasTableEntry(newEntryType, value, alias, exp)); parent->endInsertRows(); break; case CT_UPDATED: if(!inModel) { OutputDebugStringF("Warning: AliasTablePriv::updateEntry: Got CT_UPDATED, but entry is not in model\n"); break; } lower->type = newEntryType; lower->value = value; lower->expirationdepth = exp; parent->emitDataChanged(lowerIndex); break; case CT_DELETED: if(!inModel) { OutputDebugStringF("Warning: AliasTablePriv::updateEntry: Got CT_DELETED, but entry is not in model\n"); break; } parent->beginRemoveRows(QModelIndex(), lowerIndex, upperIndex-1); cachedAliasTable.erase(lower, upper); parent->endRemoveRows(); break; } } int size() { return cachedAliasTable.size(); } AliasTableEntry *index(int idx) { if(idx >= 0 && idx < cachedAliasTable.size()) { return &cachedAliasTable[idx]; } else { return 0; } } }; AliasTableModel::AliasTableModel(CWallet *wallet, WalletModel *parent) : QAbstractTableModel(parent),walletModel(parent),wallet(wallet),priv(0) { columns << tr("Alias") << tr("Value") << tr("Expiration Height"); priv = new AliasTablePriv(wallet, this); priv->refreshAliasTable(); } AliasTableModel::~AliasTableModel() { delete priv; } int AliasTableModel::rowCount(const QModelIndex &parent) const { Q_UNUSED(parent); return priv->size(); } int AliasTableModel::columnCount(const QModelIndex &parent) const { Q_UNUSED(parent); return columns.length(); } QVariant AliasTableModel::data(const QModelIndex &index, int role) const { if(!index.isValid()) return QVariant(); AliasTableEntry *rec = static_cast<AliasTableEntry*>(index.internalPointer()); if(role == Qt::DisplayRole || role == Qt::EditRole) { switch(index.column()) { case Value: return rec->value; case Name: return rec->alias; case ExpirationDepth: return rec->expirationdepth; } } else if (role == Qt::FontRole) { QFont font; // if(index.column() == Name) // { // font = GUIUtil::bitcoinAddressFont(); // } return font; } else if (role == TypeRole) { switch(rec->type) { case AliasTableEntry::Alias: return Alias; case AliasTableEntry::DataAlias: return DataAlias; default: break; } } return QVariant(); } bool AliasTableModel::setData(const QModelIndex &index, const QVariant &value, int role) { if(!index.isValid()) return false; AliasTableEntry *rec = static_cast<AliasTableEntry*>(index.internalPointer()); editStatus = OK; if(role == Qt::EditRole) { switch(index.column()) { case ExpirationDepth: // Do nothing, if old value == new value if(rec->expirationdepth == value.toString()) { editStatus = NO_CHANGES; return false; } //wallet->SetAddressBookName(CBitcoinAlias(rec->alias.toStdString()).Get(), value.toString().toStdString()); break; case Value: // Do nothing, if old value == new value if(rec->value == value.toString()) { editStatus = NO_CHANGES; return false; } //wallet->SetAddressBookName(CBitcoinAlias(rec->alias.toStdString()).Get(), value.toString().toStdString()); break; case Name: // Do nothing, if old alias == new alias if(rec->alias == value.toString()) { editStatus = NO_CHANGES; return false; } // Refuse to set invalid alias, set error status and return false else if(false /* validate alias */) { editStatus = INVALID_ALIAS; return false; } // Check for duplicate aliases to prevent accidental deletion of aliases, if you try // to paste an existing alias over another alias (with a different label) else if(false /* check duplicates */) { editStatus = DUPLICATE_ALIAS; return false; } // Double-check that we're not overwriting a receiving alias else if(rec->type == AliasTableEntry::Alias) { { // update alias } } break; } return true; } return false; } QVariant AliasTableModel::headerData(int section, Qt::Orientation orientation, int role) const { if(orientation == Qt::Horizontal) { if(role == Qt::DisplayRole) { return columns[section]; } } return QVariant(); } Qt::ItemFlags AliasTableModel::flags(const QModelIndex &index) const { if(!index.isValid()) return 0; //AliasTableEntry *rec = static_cast<AliasTableEntry*>(index.internalPointer()); Qt::ItemFlags retval = Qt::ItemIsSelectable | Qt::ItemIsEnabled; // only value is editable. if(index.column()==Value) { retval |= Qt::ItemIsEditable; } // return retval; return 0; } QModelIndex AliasTableModel::index(int row, int column, const QModelIndex &parent) const { Q_UNUSED(parent); AliasTableEntry *data = priv->index(row); if(data) { return createIndex(row, column, priv->index(row)); } else { return QModelIndex(); } } void AliasTableModel::updateEntry(const QString &alias, const QString &value, const QString &exp, bool isMine, int status) { // Update alias book model from Bitcoin core priv->updateEntry(alias, value, exp, isMine, status); } QString AliasTableModel::addRow(const QString &type, const QString &value, const QString &alias, const QString &exp) { std::string strValue = value.toStdString(); std::string strAlias = alias.toStdString(); std::string strExp = exp.toStdString(); editStatus = OK; if(false /*validate alias*/) { editStatus = INVALID_ALIAS; return QString(); } // Check for duplicate aliases { LOCK(wallet->cs_wallet); if(false/* check duplicate aliases */) { editStatus = DUPLICATE_ALIAS; return QString(); } } // Add entry return QString::fromStdString(strAlias); } bool AliasTableModel::removeRows(int row, int count, const QModelIndex &parent) { // refuse to remove aliases. return false; } /* Look up value for alias, if not found return empty string. */ QString AliasTableModel::valueForAlias(const QString &alias) const { return QString::fromStdString("{}"); } int AliasTableModel::lookupAlias(const QString &alias) const { QModelIndexList lst = match(index(0, Name, QModelIndex()), Qt::EditRole, alias, 1, Qt::MatchExactly); if(lst.isEmpty()) { return -1; } else { return lst.at(0).row(); } } void AliasTableModel::emitDataChanged(int idx) { emit dataChanged(index(idx, 0, QModelIndex()), index(idx, columns.length()-1, QModelIndex())); } <commit_msg>New Alias Model<commit_after>#include "aliastablemodel.h" #include "guiutil.h" #include "walletmodel.h" #include "wallet.h" #include "base58.h" #include <QFont> using namespace std; const QString AliasTableModel::Alias = "A"; const QString AliasTableModel::DataAlias = "D"; class CAliasDB; extern CAliasDB *paliasdb; int GetAliasExpirationDepth(int nHeight); struct AliasTableEntry { enum Type { Alias, DataAlias }; Type type; QString value; QString alias; QString expirationdepth; AliasTableEntry() {} AliasTableEntry(Type type, const QString &value, const QString &alias, const QString &expirationdepth): type(type), value(value), alias(alias), expirationdepth(expirationdepth) {} }; struct AliasTableEntryLessThan { bool operator()(const AliasTableEntry &a, const AliasTableEntry &b) const { return a.alias < b.alias; } bool operator()(const AliasTableEntry &a, const QString &b) const { return a.alias < b; } bool operator()(const QString &a, const AliasTableEntry &b) const { return a < b.alias; } }; #define NAMEMAPTYPE map<vector<unsigned char>, uint256> // Private implementation class AliasTablePriv { public: CWallet *wallet; QList<AliasTableEntry> cachedAliasTable; AliasTableModel *parent; AliasTablePriv(CWallet *wallet, AliasTableModel *parent): wallet(wallet), parent(parent) {} void refreshAliasTable() { cachedAliasTable.clear(); { CBlockIndex* pindex = pindexGenesisBlock; LOCK(wallet->cs_wallet); while (pindex) { int nHeight = pindex->nHeight; CBlock block; block.ReadFromDisk(pindex); uint256 txblkhash; BOOST_FOREACH(CTransaction& tx, block.vtx) { if (tx.nVersion != SYSCOIN_TX_VERSION) continue; int op, nOut; vector<vector<unsigned char> > vvchArgs; bool o = DecodeAliasTx(tx, op, nOut, vvchArgs, nHeight); if (!o || !IsAliasOp(op) || !IsAliasMine(tx)) continue; // get the transaction if(!GetTransaction(tx.GetHash(), tx, txblkhash, true)) continue; if (op == OP_ALIAS_NEW) continue; const vector<unsigned char> &vchName = vvchArgs[0]; const vector<unsigned char> &vchValue = vvchArgs[op == OP_ALIAS_ACTIVATE ? 2 : 1]; if(!GetTransaction(tx.GetHash(), tx, txblkhash, true)) continue; vector<CAliasIndex> vtxPos; if (!paliasdb->ReadAlias(vchName, vtxPos)) continue; CAliasIndex txName = vtxPos.back(); unsigned long nExpDepth = txName.nHeight + GetAliasExpirationDepth(txName.nHeight); cachedAliasTable.append(AliasTableEntry(tx.data.size() ? AliasTableEntry::DataAlias : AliasTableEntry::Alias, QString::fromStdString(stringFromVch(vchValue)), QString::fromStdString(stringFromVch(vchName)), QString::fromStdString(strprintf("%lu", nExpDepth)))); } pindex = pindex->pnext; } } // qLowerBound() and qUpperBound() require our cachedAliasTable list to be sorted in asc order qSort(cachedAliasTable.begin(), cachedAliasTable.end(), AliasTableEntryLessThan()); } void updateEntry(const QString &alias, const QString &value, const QString &exp, bool isData, int status) { // Find alias / value in model QList<AliasTableEntry>::iterator lower = qLowerBound( cachedAliasTable.begin(), cachedAliasTable.end(), alias, AliasTableEntryLessThan()); QList<AliasTableEntry>::iterator upper = qUpperBound( cachedAliasTable.begin(), cachedAliasTable.end(), alias, AliasTableEntryLessThan()); int lowerIndex = (lower - cachedAliasTable.begin()); int upperIndex = (upper - cachedAliasTable.begin()); bool inModel = (lower != upper); AliasTableEntry::Type newEntryType = isData ? AliasTableEntry::DataAlias : AliasTableEntry::Alias; switch(status) { case CT_NEW: if(inModel) { OutputDebugStringF("Warning: AliasTablePriv::updateEntry: Got CT_NOW, but entry is already in model\n"); break; } parent->beginInsertRows(QModelIndex(), lowerIndex, lowerIndex); cachedAliasTable.insert(lowerIndex, AliasTableEntry(newEntryType, value, alias, exp)); parent->endInsertRows(); break; case CT_UPDATED: if(!inModel) { OutputDebugStringF("Warning: AliasTablePriv::updateEntry: Got CT_UPDATED, but entry is not in model\n"); break; } lower->type = newEntryType; lower->value = value; lower->expirationdepth = exp; parent->emitDataChanged(lowerIndex); break; case CT_DELETED: if(!inModel) { OutputDebugStringF("Warning: AliasTablePriv::updateEntry: Got CT_DELETED, but entry is not in model\n"); break; } parent->beginRemoveRows(QModelIndex(), lowerIndex, upperIndex-1); cachedAliasTable.erase(lower, upper); parent->endRemoveRows(); break; } } int size() { return cachedAliasTable.size(); } AliasTableEntry *index(int idx) { if(idx >= 0 && idx < cachedAliasTable.size()) { return &cachedAliasTable[idx]; } else { return 0; } } }; AliasTableModel::AliasTableModel(CWallet *wallet, WalletModel *parent, bool allAliases) : QAbstractTableModel(parent),walletModel(parent),wallet(wallet),priv(0) { columns << tr("Alias") << tr("Expiration Height") << tr("GUID"); priv = new AliasTablePriv(wallet, this); priv->refreshAliasTable(); } AliasTableModel::~AliasTableModel() { delete priv; } int AliasTableModel::rowCount(const QModelIndex &parent) const { Q_UNUSED(parent); return priv->size(); } int AliasTableModel::columnCount(const QModelIndex &parent) const { Q_UNUSED(parent); return columns.length(); } QVariant AliasTableModel::data(const QModelIndex &index, int role) const { if(!index.isValid()) return QVariant(); AliasTableEntry *rec = static_cast<AliasTableEntry*>(index.internalPointer()); if(role == Qt::DisplayRole || role == Qt::EditRole) { switch(index.column()) { case Value: return rec->value; case Name: return rec->alias; case ExpirationDepth: return rec->expirationdepth; } } else if (role == Qt::FontRole) { QFont font; // if(index.column() == Name) // { // font = GUIUtil::bitcoinAddressFont(); // } return font; } else if (role == TypeRole) { switch(rec->type) { case AliasTableEntry::Alias: return Alias; case AliasTableEntry::DataAlias: return DataAlias; default: break; } } return QVariant(); } bool AliasTableModel::setData(const QModelIndex &index, const QVariant &value, int role) { if(!index.isValid()) return false; AliasTableEntry *rec = static_cast<AliasTableEntry*>(index.internalPointer()); editStatus = OK; if(role == Qt::EditRole) { switch(index.column()) { case ExpirationDepth: // Do nothing, if old value == new value if(rec->expirationdepth == value.toString()) { editStatus = NO_CHANGES; return false; } //wallet->SetAddressBookName(CBitcoinAlias(rec->alias.toStdString()).Get(), value.toString().toStdString()); break; case Value: // Do nothing, if old value == new value if(rec->value == value.toString()) { editStatus = NO_CHANGES; return false; } //wallet->SetAddressBookName(CBitcoinAlias(rec->alias.toStdString()).Get(), value.toString().toStdString()); break; case Name: // Do nothing, if old alias == new alias if(rec->alias == value.toString()) { editStatus = NO_CHANGES; return false; } // Refuse to set invalid alias, set error status and return false else if(false /* validate alias */) { editStatus = INVALID_ALIAS; return false; } // Check for duplicate aliases to prevent accidental deletion of aliases, if you try // to paste an existing alias over another alias (with a different label) else if(false /* check duplicates */) { editStatus = DUPLICATE_ALIAS; return false; } // Double-check that we're not overwriting a receiving alias else if(rec->type == AliasTableEntry::Alias) { { // update alias } } break; } return true; } return false; } QVariant AliasTableModel::headerData(int section, Qt::Orientation orientation, int role) const { if(orientation == Qt::Horizontal) { if(role == Qt::DisplayRole) { return columns[section]; } } return QVariant(); } Qt::ItemFlags AliasTableModel::flags(const QModelIndex &index) const { if(!index.isValid()) return 0; //AliasTableEntry *rec = static_cast<AliasTableEntry*>(index.internalPointer()); Qt::ItemFlags retval = Qt::ItemIsSelectable | Qt::ItemIsEnabled; // only value is editable. if(index.column()==Value) { retval |= Qt::ItemIsEditable; } // return retval; return 0; } QModelIndex AliasTableModel::index(int row, int column, const QModelIndex &parent) const { Q_UNUSED(parent); AliasTableEntry *data = priv->index(row); if(data) { return createIndex(row, column, priv->index(row)); } else { return QModelIndex(); } } void AliasTableModel::updateEntry(const QString &alias, const QString &value, const QString &exp, bool isMine, int status) { // Update alias book model from Bitcoin core priv->updateEntry(alias, value, exp, isMine, status); } QString AliasTableModel::addRow(const QString &type, const QString &value, const QString &alias, const QString &exp) { std::string strValue = value.toStdString(); std::string strAlias = alias.toStdString(); std::string strExp = exp.toStdString(); editStatus = OK; if(false /*validate alias*/) { editStatus = INVALID_ALIAS; return QString(); } // Check for duplicate aliases { LOCK(wallet->cs_wallet); if(false/* check duplicate aliases */) { editStatus = DUPLICATE_ALIAS; return QString(); } } // Add entry return QString::fromStdString(strAlias); } bool AliasTableModel::removeRows(int row, int count, const QModelIndex &parent) { // refuse to remove aliases. return false; } /* Look up value for alias, if not found return empty string. */ QString AliasTableModel::valueForAlias(const QString &alias) const { return QString::fromStdString("{}"); } int AliasTableModel::lookupAlias(const QString &alias) const { QModelIndexList lst = match(index(0, Name, QModelIndex()), Qt::EditRole, alias, 1, Qt::MatchExactly); if(lst.isEmpty()) { return -1; } else { return lst.at(0).row(); } } void AliasTableModel::emitDataChanged(int idx) { emit dataChanged(index(idx, 0, QModelIndex()), index(idx, columns.length()-1, QModelIndex())); } <|endoftext|>
<commit_before>#include "stdafx.h" #include "common/RhoPort.h" #include "common/StringConverter.h" #include "ruby/ext/rho/rhoruby.h" #include "MainWindow.h" #ifdef OS_WINCE__ #include <tapi.h> #include <tsp.h> //#include <sms.h> #endif using namespace rho; using namespace rho::common; extern "C" HWND getMainWnd(); extern "C" { #ifdef OS_WINCE__ static const int PHONE_NUMBER_BUFFER_SIZE = 512; bool getPhoneNumFromSIMCard (String &number) { #define EXIT_ON_NULL(_p) if (_p == NULL){ hr = E_OUTOFMEMORY; goto FuncExit; } #define EXIT_ON_FALSE(_f) if (!(_f)) { hr = E_FAIL; goto FuncExit; } #define MAX(i, j) ((i) > (j) ? (i) : (j)) const int TAPI_API_LOW_VERSION = 0x00020000; const int TAPI_API_HIGH_VERSION = 0x00020000; const int LINE_NUMBER = 1; HRESULT hr = E_FAIL; LRESULT lResult = 0; HLINEAPP hLineApp; DWORD dwNumDevs; DWORD dwAPIVersion = TAPI_API_HIGH_VERSION; LINEINITIALIZEEXPARAMS liep; DWORD dwTAPILineDeviceID; const DWORD dwAddressID = LINE_NUMBER - 1; liep.dwTotalSize = sizeof(liep); liep.dwOptions = LINEINITIALIZEEXOPTION_USEEVENT; if (SUCCEEDED(lineInitializeEx(&hLineApp, 0, 0, TEXT("ExTapi_Lib"), &dwNumDevs, &dwAPIVersion, &liep))) { BYTE* pCapBuf = NULL; DWORD dwCapBufSize = PHONE_NUMBER_BUFFER_SIZE; LINEEXTENSIONID LineExtensionID; LINEDEVCAPS* pLineDevCaps = NULL; LINEADDRESSCAPS* placAddressCaps = NULL; pCapBuf = new BYTE[dwCapBufSize]; EXIT_ON_NULL(pCapBuf); pLineDevCaps = (LINEDEVCAPS*)pCapBuf; pLineDevCaps->dwTotalSize = dwCapBufSize; // Get TSP Line Device ID dwTAPILineDeviceID = 0xffffffff; for (DWORD dwCurrentDevID = 0 ; dwCurrentDevID < dwNumDevs ; dwCurrentDevID++) { if (0 == lineNegotiateAPIVersion(hLineApp, dwCurrentDevID, TAPI_API_LOW_VERSION, TAPI_API_HIGH_VERSION, &dwAPIVersion, &LineExtensionID)) { lResult = lineGetDevCaps(hLineApp, dwCurrentDevID, dwAPIVersion, 0, pLineDevCaps); if (dwCapBufSize < pLineDevCaps->dwNeededSize) { delete[] pCapBuf; dwCapBufSize = pLineDevCaps->dwNeededSize; pCapBuf = new BYTE[dwCapBufSize]; EXIT_ON_NULL(pCapBuf); pLineDevCaps = (LINEDEVCAPS*)pCapBuf; pLineDevCaps->dwTotalSize = dwCapBufSize; lResult = lineGetDevCaps(hLineApp, dwCurrentDevID, dwAPIVersion, 0, pLineDevCaps); } if ((0 == lResult) && (0 == _tcscmp((TCHAR*)((BYTE*)pLineDevCaps+pLineDevCaps->dwLineNameOffset), CELLTSP_LINENAME_STRING))) { dwTAPILineDeviceID = dwCurrentDevID; break; } } } placAddressCaps = (LINEADDRESSCAPS*)pCapBuf; placAddressCaps->dwTotalSize = dwCapBufSize; lResult = lineGetAddressCaps(hLineApp, dwTAPILineDeviceID, dwAddressID, dwAPIVersion, 0, placAddressCaps); if (dwCapBufSize < placAddressCaps->dwNeededSize) { delete[] pCapBuf; dwCapBufSize = placAddressCaps->dwNeededSize; pCapBuf = new BYTE[dwCapBufSize]; EXIT_ON_NULL(pCapBuf); placAddressCaps = (LINEADDRESSCAPS*)pCapBuf; placAddressCaps->dwTotalSize = dwCapBufSize; lResult = lineGetAddressCaps(hLineApp, dwTAPILineDeviceID, dwAddressID, dwAPIVersion, 0, placAddressCaps); } if (0 == lResult) { EXIT_ON_FALSE(0 != placAddressCaps->dwAddressSize); // A non-zero dwAddressSize means a phone number was found ASSERT(0 != placAddressCaps->dwAddressOffset); PWCHAR tsAddress = (WCHAR*)(((BYTE*)placAddressCaps)+placAddressCaps->dwAddressOffset); number = convertToStringA (tsAddress); hr = S_OK; } delete[] pCapBuf; } // End if () FuncExit: lineShutdown(hLineApp); if (hr != S_OK) { LOG(ERROR) + "failed to get phone number from SIM"; return false; } return true; #undef EXIT_ON_NULL #undef EXIT_ON_FALSE #undef MAX } /* bool getPhoneNumFromSMSBearer (String &number) { SMS_ADDRESS psmsaAddress; if (SmsGetPhoneNumber (&psmsaAddress) != S_OK) { LOG(ERROR) + "failed to get phone number using SMS bearer"; return false; } number = convertToStringA(psmsaAddress.ptsAddress); return true; } */ bool getPhoneNumFromOwnerInfo (String &number) { HKEY hKey; DWORD dwType, dwCount = PHONE_NUMBER_BUFFER_SIZE; TCHAR strValue [PHONE_NUMBER_BUFFER_SIZE]; LONG res; TCHAR errMsg[1024]; if ((res = RegOpenKeyEx(HKEY_CURRENT_USER, TEXT("ControlPanel\\Owner"), NULL, KEY_EXECUTE , &hKey)) == 0) { if ((res = RegQueryValueEx (hKey, TEXT("Telephone"), NULL, &dwType, (LPBYTE )strValue, &dwCount)) == 0) { if (dwType != REG_SZ) { LOG(ERROR) + "Settings/Owner Information/Telephone has invalid type"; RegCloseKey(hKey); return false; } if (dwCount > 0) { strValue[dwCount + 1] = '\0'; if (_tcslen((strValue)) == 0) { LOG(INFO) + "Settings/Owner Information/Telephone is empty"; RegCloseKey(hKey); return false; } number = convertToStringA(strValue); RegCloseKey(hKey); return true; } } } RegCloseKey(hKey); FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM, 0, GetLastError(), 0, errMsg, sizeof(errMsg), NULL); LOG(ERROR) + errMsg; return false; } VALUE phone_number() { String number; if (getPhoneNumFromSIMCard(number)) return rho_ruby_create_string(number.c_str()); // if (getPhoneNumFromSMSBearer(number)) // return rho_ruby_create_string(number.c_str()); if (getPhoneNumFromOwnerInfo(number)) return rho_ruby_create_string(number.c_str()); return rho_ruby_get_NIL(); } #else VALUE phone_number() { return rho_ruby_get_NIL(); } #endif static int has_camera() { #ifdef OS_WINCE /* DEVMGR_DEVICE_INFORMATION devInfo = {0}; GUID guidCamera = { 0xCB998A05, 0x122C, 0x4166, 0x84, 0x6A, 0x93, 0x3E, 0x4D, 0x7E, 0x3C, 0x86 }; devInfo.dwSize = sizeof(devInfo); HANDLE hDevice = FindFirstDevice( DeviceSearchByGuid, &guidCamera, &devInfo); if ( hDevice != INVALID_HANDLE_VALUE ) { FindClose(hDevice); return 1; } return 0;*/ return 1; #else return 0; #endif } static double get_screen_ppi_x() { HWND hWndDesktop = GetDesktopWindow(); HDC hdcDesktop = GetDC(hWndDesktop); int mms = GetDeviceCaps(hdcDesktop, HORZSIZE); int pixels = GetDeviceCaps(hdcDesktop, HORZRES); double ret = (pixels*25.4)/mms; return ret; } static double get_screen_ppi_y() { HWND hWndDesktop = GetDesktopWindow(); HDC hdcDesktop = GetDC(hWndDesktop); int mms = GetDeviceCaps(hdcDesktop, VERTSIZE); int pixels = GetDeviceCaps(hdcDesktop, VERTRES); double ret = (pixels*25.4)/mms; return ret; } int rho_sysimpl_get_property(char* szPropName, VALUE* resValue) { if (strcasecmp("has_camera",szPropName) == 0) {*resValue = rho_ruby_create_boolean(has_camera()); return 1;} if (strcasecmp("phone_number",szPropName) == 0) {*resValue = phone_number();return 1;} if (strcasecmp("ppi_x",szPropName) == 0) {*resValue = rho_ruby_create_double(get_screen_ppi_x()); return 1;} if (strcasecmp("ppi_y",szPropName) == 0) {*resValue = rho_ruby_create_double(get_screen_ppi_y()); return 1; } return 0; } VALUE rho_sys_get_locale() { wchar_t szLang[20]; int nRes = GetLocaleInfo(LOCALE_USER_DEFAULT,LOCALE_SABBREVLANGNAME , szLang, 20); szLang[2] = 0; wcslwr(szLang); return rho_ruby_create_string(convertToStringA(szLang).c_str()); } int rho_sys_get_screen_width() { #ifdef OS_WINCE return GetSystemMetrics(SM_CXSCREEN); #else return CMainWindow::getScreenWidth(); #endif } int rho_sys_get_screen_height() { #ifdef OS_WINCE return GetSystemMetrics(SM_CYSCREEN); #else return CMainWindow::getScreenHeight(); #endif } VALUE rho_sys_makephonecall(const char* callname, int nparams, char** param_names, char** param_values) { return rho_ruby_get_NIL(); } static int g_rho_has_network = 1; void rho_sysimpl_sethas_network(int nValue) { g_rho_has_network = nValue; } VALUE rho_sys_has_network() { return rho_ruby_create_boolean(g_rho_has_network!=0); } void rho_sys_app_exit() { ::PostMessage(getMainWnd(), WM_COMMAND, MAKEWPARAM(IDM_EXIT,0), (LPARAM )0); } } //extern "C" <commit_msg>Implemented task #2948192 - system property to check for version (WM)<commit_after>#include "stdafx.h" #include "common/RhoPort.h" #include "common/StringConverter.h" #include "ruby/ext/rho/rhoruby.h" #include "MainWindow.h" #ifdef OS_WINCE__ #include <tapi.h> #include <tsp.h> //#include <sms.h> #endif using namespace rho; using namespace rho::common; extern "C" HWND getMainWnd(); extern "C" char* wce_wctomb(const wchar_t* w); extern "C" { #ifdef OS_WINCE__ static const int PHONE_NUMBER_BUFFER_SIZE = 512; bool getPhoneNumFromSIMCard (String &number) { #define EXIT_ON_NULL(_p) if (_p == NULL){ hr = E_OUTOFMEMORY; goto FuncExit; } #define EXIT_ON_FALSE(_f) if (!(_f)) { hr = E_FAIL; goto FuncExit; } #define MAX(i, j) ((i) > (j) ? (i) : (j)) const int TAPI_API_LOW_VERSION = 0x00020000; const int TAPI_API_HIGH_VERSION = 0x00020000; const int LINE_NUMBER = 1; HRESULT hr = E_FAIL; LRESULT lResult = 0; HLINEAPP hLineApp; DWORD dwNumDevs; DWORD dwAPIVersion = TAPI_API_HIGH_VERSION; LINEINITIALIZEEXPARAMS liep; DWORD dwTAPILineDeviceID; const DWORD dwAddressID = LINE_NUMBER - 1; liep.dwTotalSize = sizeof(liep); liep.dwOptions = LINEINITIALIZEEXOPTION_USEEVENT; if (SUCCEEDED(lineInitializeEx(&hLineApp, 0, 0, TEXT("ExTapi_Lib"), &dwNumDevs, &dwAPIVersion, &liep))) { BYTE* pCapBuf = NULL; DWORD dwCapBufSize = PHONE_NUMBER_BUFFER_SIZE; LINEEXTENSIONID LineExtensionID; LINEDEVCAPS* pLineDevCaps = NULL; LINEADDRESSCAPS* placAddressCaps = NULL; pCapBuf = new BYTE[dwCapBufSize]; EXIT_ON_NULL(pCapBuf); pLineDevCaps = (LINEDEVCAPS*)pCapBuf; pLineDevCaps->dwTotalSize = dwCapBufSize; // Get TSP Line Device ID dwTAPILineDeviceID = 0xffffffff; for (DWORD dwCurrentDevID = 0 ; dwCurrentDevID < dwNumDevs ; dwCurrentDevID++) { if (0 == lineNegotiateAPIVersion(hLineApp, dwCurrentDevID, TAPI_API_LOW_VERSION, TAPI_API_HIGH_VERSION, &dwAPIVersion, &LineExtensionID)) { lResult = lineGetDevCaps(hLineApp, dwCurrentDevID, dwAPIVersion, 0, pLineDevCaps); if (dwCapBufSize < pLineDevCaps->dwNeededSize) { delete[] pCapBuf; dwCapBufSize = pLineDevCaps->dwNeededSize; pCapBuf = new BYTE[dwCapBufSize]; EXIT_ON_NULL(pCapBuf); pLineDevCaps = (LINEDEVCAPS*)pCapBuf; pLineDevCaps->dwTotalSize = dwCapBufSize; lResult = lineGetDevCaps(hLineApp, dwCurrentDevID, dwAPIVersion, 0, pLineDevCaps); } if ((0 == lResult) && (0 == _tcscmp((TCHAR*)((BYTE*)pLineDevCaps+pLineDevCaps->dwLineNameOffset), CELLTSP_LINENAME_STRING))) { dwTAPILineDeviceID = dwCurrentDevID; break; } } } placAddressCaps = (LINEADDRESSCAPS*)pCapBuf; placAddressCaps->dwTotalSize = dwCapBufSize; lResult = lineGetAddressCaps(hLineApp, dwTAPILineDeviceID, dwAddressID, dwAPIVersion, 0, placAddressCaps); if (dwCapBufSize < placAddressCaps->dwNeededSize) { delete[] pCapBuf; dwCapBufSize = placAddressCaps->dwNeededSize; pCapBuf = new BYTE[dwCapBufSize]; EXIT_ON_NULL(pCapBuf); placAddressCaps = (LINEADDRESSCAPS*)pCapBuf; placAddressCaps->dwTotalSize = dwCapBufSize; lResult = lineGetAddressCaps(hLineApp, dwTAPILineDeviceID, dwAddressID, dwAPIVersion, 0, placAddressCaps); } if (0 == lResult) { EXIT_ON_FALSE(0 != placAddressCaps->dwAddressSize); // A non-zero dwAddressSize means a phone number was found ASSERT(0 != placAddressCaps->dwAddressOffset); PWCHAR tsAddress = (WCHAR*)(((BYTE*)placAddressCaps)+placAddressCaps->dwAddressOffset); number = convertToStringA (tsAddress); hr = S_OK; } delete[] pCapBuf; } // End if () FuncExit: lineShutdown(hLineApp); if (hr != S_OK) { LOG(ERROR) + "failed to get phone number from SIM"; return false; } return true; #undef EXIT_ON_NULL #undef EXIT_ON_FALSE #undef MAX } /* bool getPhoneNumFromSMSBearer (String &number) { SMS_ADDRESS psmsaAddress; if (SmsGetPhoneNumber (&psmsaAddress) != S_OK) { LOG(ERROR) + "failed to get phone number using SMS bearer"; return false; } number = convertToStringA(psmsaAddress.ptsAddress); return true; } */ bool getPhoneNumFromOwnerInfo (String &number) { HKEY hKey; DWORD dwType, dwCount = PHONE_NUMBER_BUFFER_SIZE; TCHAR strValue [PHONE_NUMBER_BUFFER_SIZE]; LONG res; TCHAR errMsg[1024]; if ((res = RegOpenKeyEx(HKEY_CURRENT_USER, TEXT("ControlPanel\\Owner"), NULL, KEY_EXECUTE , &hKey)) == 0) { if ((res = RegQueryValueEx (hKey, TEXT("Telephone"), NULL, &dwType, (LPBYTE )strValue, &dwCount)) == 0) { if (dwType != REG_SZ) { LOG(ERROR) + "Settings/Owner Information/Telephone has invalid type"; RegCloseKey(hKey); return false; } if (dwCount > 0) { strValue[dwCount + 1] = '\0'; if (_tcslen((strValue)) == 0) { LOG(INFO) + "Settings/Owner Information/Telephone is empty"; RegCloseKey(hKey); return false; } number = convertToStringA(strValue); RegCloseKey(hKey); return true; } } } RegCloseKey(hKey); FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM, 0, GetLastError(), 0, errMsg, sizeof(errMsg), NULL); LOG(ERROR) + errMsg; return false; } VALUE phone_number() { String number; if (getPhoneNumFromSIMCard(number)) return rho_ruby_create_string(number.c_str()); // if (getPhoneNumFromSMSBearer(number)) // return rho_ruby_create_string(number.c_str()); if (getPhoneNumFromOwnerInfo(number)) return rho_ruby_create_string(number.c_str()); return rho_ruby_get_NIL(); } #else VALUE phone_number() { return rho_ruby_get_NIL(); } #endif static int has_camera() { #ifdef OS_WINCE /* DEVMGR_DEVICE_INFORMATION devInfo = {0}; GUID guidCamera = { 0xCB998A05, 0x122C, 0x4166, 0x84, 0x6A, 0x93, 0x3E, 0x4D, 0x7E, 0x3C, 0x86 }; devInfo.dwSize = sizeof(devInfo); HANDLE hDevice = FindFirstDevice( DeviceSearchByGuid, &guidCamera, &devInfo); if ( hDevice != INVALID_HANDLE_VALUE ) { FindClose(hDevice); return 1; } return 0;*/ return 1; #else return 0; #endif } static double get_screen_ppi_x() { HWND hWndDesktop = GetDesktopWindow(); HDC hdcDesktop = GetDC(hWndDesktop); int mms = GetDeviceCaps(hdcDesktop, HORZSIZE); int pixels = GetDeviceCaps(hdcDesktop, HORZRES); double ret = (pixels*25.4)/mms; return ret; } static double get_screen_ppi_y() { HWND hWndDesktop = GetDesktopWindow(); HDC hdcDesktop = GetDC(hWndDesktop); int mms = GetDeviceCaps(hdcDesktop, VERTSIZE); int pixels = GetDeviceCaps(hdcDesktop, VERTRES); double ret = (pixels*25.4)/mms; return ret; } int rho_sysimpl_get_property(char* szPropName, VALUE* resValue) { if (strcasecmp("has_camera",szPropName) == 0) {*resValue = rho_ruby_create_boolean(has_camera()); return 1;} if (strcasecmp("phone_number",szPropName) == 0) {*resValue = phone_number();return 1;} if (strcasecmp("ppi_x",szPropName) == 0) {*resValue = rho_ruby_create_double(get_screen_ppi_x()); return 1;} if (strcasecmp("ppi_y",szPropName) == 0) {*resValue = rho_ruby_create_double(get_screen_ppi_y()); return 1; } if (strcasecmp("device_name",szPropName) == 0) { #ifdef OS_WINDOWS *resValue = rho_ruby_create_string("Win32"); #else HKEY hKey; if (RegOpenKeyEx( HKEY_LOCAL_MACHINE, _T("Ident"), 0, KEY_READ, &hKey ) != ERROR_SUCCESS) return 0; DWORD dwType = REG_SZ; DWORD dwDataSize = 0; if ( RegQueryValueEx( hKey, _T("name"), 0, &dwType, (PBYTE)NULL, &dwDataSize ) != ERROR_SUCCESS) return 0; std::vector<wchar_t> deviceName(dwDataSize + 1); RegQueryValueEx( hKey, _T("name"), 0, &dwType, (PBYTE)&deviceName[0], &dwDataSize ); char *s = wce_wctomb(&deviceName[0]); *resValue = rho_ruby_create_string(s); ::free(s); RegCloseKey(hKey); return 1; #endif } if (strcasecmp("os_version",szPropName) == 0) { OSVERSIONINFO osv; osv.dwOSVersionInfoSize = sizeof(osv); if (!GetVersionEx(&osv)) return 0; char buf[50]; snprintf(buf, sizeof(buf), "%u.%u.%u", (unsigned)osv.dwMajorVersion, (unsigned)osv.dwMinorVersion, (unsigned)osv.dwBuildNumber); *resValue = rho_ruby_create_string(&buf[0]); return 1; } return 0; } VALUE rho_sys_get_locale() { wchar_t szLang[20]; int nRes = GetLocaleInfo(LOCALE_USER_DEFAULT,LOCALE_SABBREVLANGNAME , szLang, 20); szLang[2] = 0; wcslwr(szLang); return rho_ruby_create_string(convertToStringA(szLang).c_str()); } int rho_sys_get_screen_width() { #ifdef OS_WINCE return GetSystemMetrics(SM_CXSCREEN); #else return CMainWindow::getScreenWidth(); #endif } int rho_sys_get_screen_height() { #ifdef OS_WINCE return GetSystemMetrics(SM_CYSCREEN); #else return CMainWindow::getScreenHeight(); #endif } VALUE rho_sys_makephonecall(const char* callname, int nparams, char** param_names, char** param_values) { return rho_ruby_get_NIL(); } static int g_rho_has_network = 1; void rho_sysimpl_sethas_network(int nValue) { g_rho_has_network = nValue; } VALUE rho_sys_has_network() { return rho_ruby_create_boolean(g_rho_has_network!=0); } void rho_sys_app_exit() { ::PostMessage(getMainWnd(), WM_COMMAND, MAKEWPARAM(IDM_EXIT,0), (LPARAM )0); } } //extern "C" <|endoftext|>
<commit_before><commit_msg>[test.elliptic-cg-discretization] updated test<commit_after><|endoftext|>
<commit_before>/* * MapKey.h * * This file is part of the "LLGL" project (Copyright (c) 2015 by Lukas Hermanns) * See "LICENSE.txt" for license information. */ #include "MapKey.h" #include <map> #include <X11/Xutil.h> namespace LLGL { #define KEYPAIR(KEYSYM, KEY) { KEYSYM, Key::KEY } static std::map<KeySym, Key> GenerateLinuxKeyCodeMap() { return { KEYPAIR( XK_BackSpace , Back ), KEYPAIR( XK_Tab , Tab ), KEYPAIR( XK_Clear , Clear ), KEYPAIR( XK_Return , Return ), KEYPAIR( XK_Menu , Menu ), KEYPAIR( XK_Pause , Pause ), KEYPAIR( XK_Caps_Lock , Capital ), KEYPAIR( XK_Escape , Escape ), KEYPAIR( XK_space , Space ), KEYPAIR( XK_Page_Up , PageUp ), KEYPAIR( XK_Page_Down , PageDown ), KEYPAIR( XK_End , End ), KEYPAIR( XK_Home , Home ), KEYPAIR( XK_Left , Left ), KEYPAIR( XK_Up , Up ), KEYPAIR( XK_Right , Right ), KEYPAIR( XK_Down , Down ), KEYPAIR( XK_Select , Select ), KEYPAIR( XK_Execute , Exe ), KEYPAIR( XK_Print , Snapshot ), KEYPAIR( XK_Insert , Insert ), KEYPAIR( XK_Delete , Delete ), KEYPAIR( XK_Help , Help ), KEYPAIR( XK_0 , D0 ), KEYPAIR( XK_1 , D1 ), KEYPAIR( XK_2 , D2 ), KEYPAIR( XK_3 , D3 ), KEYPAIR( XK_4 , D4 ), KEYPAIR( XK_5 , D5 ), KEYPAIR( XK_6 , D6 ), KEYPAIR( XK_7 , D7 ), KEYPAIR( XK_8 , D8 ), KEYPAIR( XK_9 , D9 ), KEYPAIR( XK_a , A ), KEYPAIR( XK_b , B ), KEYPAIR( XK_c , C ), KEYPAIR( XK_d , D ), KEYPAIR( XK_e , E ), KEYPAIR( XK_f , F ), KEYPAIR( XK_g , G ), KEYPAIR( XK_h , H ), KEYPAIR( XK_i , I ), KEYPAIR( XK_j , J ), KEYPAIR( XK_k , K ), KEYPAIR( XK_l , L ), KEYPAIR( XK_m , M ), KEYPAIR( XK_n , N ), KEYPAIR( XK_o , O ), KEYPAIR( XK_p , P ), KEYPAIR( XK_q , Q ), KEYPAIR( XK_r , R ), KEYPAIR( XK_s , S ), KEYPAIR( XK_t , T ), KEYPAIR( XK_u , U ), KEYPAIR( XK_v , V ), KEYPAIR( XK_w , W ), KEYPAIR( XK_x , X ), KEYPAIR( XK_y , Y ), KEYPAIR( XK_z , Z ), KEYPAIR( XK_Meta_L , WinLeft ), KEYPAIR( XK_Meta_R , WinRight ), KEYPAIR( 65438 , Keypad0 ), KEYPAIR( 65436 , Keypad1 ), KEYPAIR( 65433 , Keypad2 ), KEYPAIR( 65435 , Keypad3 ), KEYPAIR( 65430 , Keypad4 ), KEYPAIR( 65437 , Keypad5 ), KEYPAIR( 65432 , Keypad6 ), KEYPAIR( 65429 , Keypad7 ), KEYPAIR( 65431 , Keypad8 ), KEYPAIR( 65434 , Keypad9 ), KEYPAIR( XK_KP_Multiply , KeypadMultiply ), KEYPAIR( XK_KP_Add , KeypadPlus ), KEYPAIR( XK_KP_Separator, KeypadSeparator ), KEYPAIR( XK_KP_Subtract , KeypadSubtract ), KEYPAIR( XK_KP_Decimal , KeypadDecimal ), KEYPAIR( XK_KP_Divide , KeypadDivide ), KEYPAIR( XK_F1 , F1 ), KEYPAIR( XK_F2 , F2 ), KEYPAIR( XK_F3 , F3 ), KEYPAIR( XK_F4 , F4 ), KEYPAIR( XK_F5 , F5 ), KEYPAIR( XK_F6 , F6 ), KEYPAIR( XK_F7 , F7 ), KEYPAIR( XK_F8 , F8 ), KEYPAIR( XK_F9 , F9 ), KEYPAIR( XK_F10 , F10 ), KEYPAIR( XK_F11 , F11 ), KEYPAIR( XK_F12 , F12 ), KEYPAIR( XK_F13 , F13 ), KEYPAIR( XK_F14 , F14 ), KEYPAIR( XK_F15 , F15 ), KEYPAIR( XK_F16 , F16 ), KEYPAIR( XK_F17 , F17 ), KEYPAIR( XK_F18 , F18 ), KEYPAIR( XK_F19 , F19 ), KEYPAIR( XK_F20 , F20 ), KEYPAIR( XK_F21 , F21 ), KEYPAIR( XK_F22 , F22 ), KEYPAIR( XK_F23 , F23 ), KEYPAIR( XK_F24 , F24 ), KEYPAIR( XK_Scroll_Lock , Scroll ), KEYPAIR( XK_Shift_L , LShift ), KEYPAIR( XK_Shift_R , RShift ), KEYPAIR( XK_Control_L , LControl ), KEYPAIR( XK_Control_R , RControl ), KEYPAIR( XK_plus , Plus ), KEYPAIR( XK_comma , Comma ), KEYPAIR( XK_minus , Minus ), KEYPAIR( XK_period , Period ), KEYPAIR( 94 , Exponent ), }; }; static std::map<KeySym, Key> linuxKeyCodeMap = GenerateLinuxKeyCodeMap(); #undef KEYPAIR Key MapKey(XKeyEvent& keyEvent) { auto keyCode = XLookupKeysym(&keyEvent, 0); auto it = linuxKeyCodeMap.find(keyCode); return (it != linuxKeyCodeMap.end() ? it->second : Key::Pause); } } // /namespace LLGL // ================================================================================ <commit_msg>Updated MapKey.cpp for Linux port.<commit_after>/* * MapKey.h * * This file is part of the "LLGL" project (Copyright (c) 2015 by Lukas Hermanns) * See "LICENSE.txt" for license information. */ #include "MapKey.h" #include <map> #include <X11/Xutil.h> namespace LLGL { #define KEYPAIR(KEYSYM, KEY) { KEYSYM, Key::KEY } static std::map<KeySym, Key> GenerateLinuxKeyCodeMap() { return { KEYPAIR( XK_BackSpace , Back ), KEYPAIR( XK_Tab , Tab ), KEYPAIR( XK_Clear , Clear ), KEYPAIR( XK_Return , Return ), KEYPAIR( XK_Menu , Menu ), KEYPAIR( XK_Pause , Pause ), KEYPAIR( XK_Caps_Lock , Capital ), KEYPAIR( XK_Escape , Escape ), KEYPAIR( XK_space , Space ), KEYPAIR( XK_Page_Up , PageUp ), KEYPAIR( XK_Page_Down , PageDown ), KEYPAIR( XK_End , End ), KEYPAIR( XK_Home , Home ), KEYPAIR( XK_Left , Left ), KEYPAIR( XK_Up , Up ), KEYPAIR( XK_Right , Right ), KEYPAIR( XK_Down , Down ), KEYPAIR( XK_Select , Select ), KEYPAIR( XK_Execute , Exe ), KEYPAIR( XK_Print , Snapshot ), KEYPAIR( XK_Insert , Insert ), KEYPAIR( XK_Delete , Delete ), KEYPAIR( XK_Help , Help ), KEYPAIR( XK_0 , D0 ), KEYPAIR( XK_1 , D1 ), KEYPAIR( XK_2 , D2 ), KEYPAIR( XK_3 , D3 ), KEYPAIR( XK_4 , D4 ), KEYPAIR( XK_5 , D5 ), KEYPAIR( XK_6 , D6 ), KEYPAIR( XK_7 , D7 ), KEYPAIR( XK_8 , D8 ), KEYPAIR( XK_9 , D9 ), KEYPAIR( XK_a , A ), KEYPAIR( XK_b , B ), KEYPAIR( XK_c , C ), KEYPAIR( XK_d , D ), KEYPAIR( XK_e , E ), KEYPAIR( XK_f , F ), KEYPAIR( XK_g , G ), KEYPAIR( XK_h , H ), KEYPAIR( XK_i , I ), KEYPAIR( XK_j , J ), KEYPAIR( XK_k , K ), KEYPAIR( XK_l , L ), KEYPAIR( XK_m , M ), KEYPAIR( XK_n , N ), KEYPAIR( XK_o , O ), KEYPAIR( XK_p , P ), KEYPAIR( XK_q , Q ), KEYPAIR( XK_r , R ), KEYPAIR( XK_s , S ), KEYPAIR( XK_t , T ), KEYPAIR( XK_u , U ), KEYPAIR( XK_v , V ), KEYPAIR( XK_w , W ), KEYPAIR( XK_x , X ), KEYPAIR( XK_y , Y ), KEYPAIR( XK_z , Z ), KEYPAIR( XK_Meta_L , LWin ), KEYPAIR( XK_Meta_R , RWin ), KEYPAIR( 65438 , Keypad0 ), KEYPAIR( 65436 , Keypad1 ), KEYPAIR( 65433 , Keypad2 ), KEYPAIR( 65435 , Keypad3 ), KEYPAIR( 65430 , Keypad4 ), KEYPAIR( 65437 , Keypad5 ), KEYPAIR( 65432 , Keypad6 ), KEYPAIR( 65429 , Keypad7 ), KEYPAIR( 65431 , Keypad8 ), KEYPAIR( 65434 , Keypad9 ), KEYPAIR( XK_KP_Multiply , KeypadMultiply ), KEYPAIR( XK_KP_Add , KeypadPlus ), KEYPAIR( XK_KP_Separator, KeypadSeparator ), KEYPAIR( XK_KP_Subtract , KeypadMinus ), KEYPAIR( XK_KP_Decimal , KeypadDecimal ), KEYPAIR( XK_KP_Divide , KeypadDivide ), KEYPAIR( XK_F1 , F1 ), KEYPAIR( XK_F2 , F2 ), KEYPAIR( XK_F3 , F3 ), KEYPAIR( XK_F4 , F4 ), KEYPAIR( XK_F5 , F5 ), KEYPAIR( XK_F6 , F6 ), KEYPAIR( XK_F7 , F7 ), KEYPAIR( XK_F8 , F8 ), KEYPAIR( XK_F9 , F9 ), KEYPAIR( XK_F10 , F10 ), KEYPAIR( XK_F11 , F11 ), KEYPAIR( XK_F12 , F12 ), KEYPAIR( XK_F13 , F13 ), KEYPAIR( XK_F14 , F14 ), KEYPAIR( XK_F15 , F15 ), KEYPAIR( XK_F16 , F16 ), KEYPAIR( XK_F17 , F17 ), KEYPAIR( XK_F18 , F18 ), KEYPAIR( XK_F19 , F19 ), KEYPAIR( XK_F20 , F20 ), KEYPAIR( XK_F21 , F21 ), KEYPAIR( XK_F22 , F22 ), KEYPAIR( XK_F23 , F23 ), KEYPAIR( XK_F24 , F24 ), KEYPAIR( XK_Scroll_Lock , ScrollLock ), KEYPAIR( XK_Shift_L , LShift ), KEYPAIR( XK_Shift_R , RShift ), KEYPAIR( XK_Control_L , LControl ), KEYPAIR( XK_Control_R , RControl ), KEYPAIR( XK_plus , Plus ), KEYPAIR( XK_comma , Comma ), KEYPAIR( XK_minus , Minus ), KEYPAIR( XK_period , Period ), KEYPAIR( 94 , Exponent ), }; }; static std::map<KeySym, Key> linuxKeyCodeMap = GenerateLinuxKeyCodeMap(); #undef KEYPAIR Key MapKey(XKeyEvent& keyEvent) { auto keyCode = XLookupKeysym(&keyEvent, 0); auto it = linuxKeyCodeMap.find(keyCode); return (it != linuxKeyCodeMap.end() ? it->second : Key::Pause); } } // /namespace LLGL // ================================================================================ <|endoftext|>
<commit_before>/* * MapKey.cpp (Win32) * * This file is part of the "LLGL" project (Copyright (c) 2015 by Lukas Hermanns) * See "LICENSE.txt" for license information. */ #include "MapKey.h" namespace LLGL { #define KEY(c) Key::c #define DUMMY KEY(Pause) // <-- any key, a dummy will never be used static Key win32KeyCodeMap[256] = { DUMMY, // 0x00 KEY(LButton ), // 0x01 KEY(RButton ), // 0x02 KEY(Cancel ), // 0x03 KEY(MButton ), // 0x04 KEY(XButton1 ), // 0x05 KEY(XButton2 ), // 0x06 DUMMY, // 0x07 KEY(Back ), // 0x08 KEY(Tab ), // 0x09 DUMMY, // 0x0a DUMMY, // 0x0b KEY(Clear ), // 0x0c KEY(Return ), // 0x0d DUMMY, // 0x0e DUMMY, // 0x0f KEY(Shift ), // 0x10 KEY(Control ), // 0x11 KEY(Menu ), // 0x12 KEY(Pause ), // 0x13 KEY(Capital ), // 0x14 DUMMY, // 0x15 DUMMY, // 0x16 DUMMY, // 0x17 DUMMY, // 0x18 DUMMY, // 0x19 DUMMY, // 0x1a KEY(Escape ), // 0x1b DUMMY, // 0x1c DUMMY, // 0x1d DUMMY, // 0x1e DUMMY, // 0x1f KEY(Space ), // 0x20 KEY(PageUp ), // 0x21 KEY(PageDown ), // 0x22 KEY(End ), // 0x23 KEY(Home ), // 0x24 KEY(Left ), // 0x25 KEY(Up ), // 0x26 KEY(Right ), // 0x27 KEY(Down ), // 0x28 KEY(Select ), // 0x29 KEY(Print ), // 0x2a KEY(Exe ), // 0x2b KEY(Snapshot ), // 0x2c KEY(Insert ), // 0x2d KEY(Delete ), // 0x2e KEY(Help ), // 0x2f KEY(D0 ), // 0x30 KEY(D1 ), // 0x31 KEY(D2 ), // 0x32 KEY(D3 ), // 0x33 KEY(D4 ), // 0x34 KEY(D5 ), // 0x35 KEY(D6 ), // 0x36 KEY(D7 ), // 0x37 KEY(D8 ), // 0x38 KEY(D9 ), // 0x39 DUMMY, // 0x3a DUMMY, // 0x3b DUMMY, // 0x3c DUMMY, // 0x3d DUMMY, // 0x3e DUMMY, // 0x3f DUMMY, // 0x40 KEY(A ), // 0x41 KEY(B ), // 0x42 KEY(C ), // 0x43 KEY(D ), // 0x44 KEY(E ), // 0x45 KEY(F ), // 0x46 KEY(G ), // 0x47 KEY(H ), // 0x48 KEY(I ), // 0x49 KEY(J ), // 0x4a KEY(K ), // 0x4b KEY(L ), // 0x4c KEY(M ), // 0x4d KEY(N ), // 0x4e KEY(O ), // 0x4f KEY(P ), // 0x50 KEY(Q ), // 0x51 KEY(R ), // 0x52 KEY(S ), // 0x53 KEY(T ), // 0x54 KEY(U ), // 0x55 KEY(V ), // 0x56 KEY(W ), // 0x57 KEY(X ), // 0x58 KEY(Y ), // 0x59 KEY(Z ), // 0x5a KEY(LWin ), // 0x5b KEY(RWin ), // 0x5c KEY(Apps ), // 0x5d DUMMY, // 0x5e KEY(Sleep ), // 0x5f KEY(Keypad0 ), // 0x60 KEY(Keypad1 ), // 0x61 KEY(Keypad2 ), // 0x62 KEY(Keypad3 ), // 0x63 KEY(Keypad4 ), // 0x64 KEY(Keypad5 ), // 0x65 KEY(Keypad6 ), // 0x66 KEY(Keypad7 ), // 0x67 KEY(Keypad8 ), // 0x68 KEY(Keypad9 ), // 0x69 KEY(KeypadMultiply ), // 0x6a KEY(KeypadPlus ), // 0x6b KEY(KeypadSeparator ), // 0x6c KEY(KeypadMinus ), // 0x6d KEY(KeypadDecimal ), // 0x6e KEY(KeypadDivide ), // 0x6f KEY(F1 ), // 0x70 KEY(F2 ), // 0x71 KEY(F3 ), // 0x72 KEY(F4 ), // 0x73 KEY(F5 ), // 0x74 KEY(F6 ), // 0x75 KEY(F7 ), // 0x76 KEY(F8 ), // 0x77 KEY(F9 ), // 0x78 KEY(F10 ), // 0x79 KEY(F11 ), // 0x7a KEY(F12 ), // 0x7b KEY(F13 ), // 0x7c KEY(F14 ), // 0x7d KEY(F15 ), // 0x7e KEY(F16 ), // 0x7f KEY(F17 ), // 0x80 KEY(F18 ), // 0x81 KEY(F19 ), // 0x82 KEY(F20 ), // 0x83 KEY(F21 ), // 0x84 KEY(F22 ), // 0x85 KEY(F23 ), // 0x86 KEY(F24 ), // 0x87 DUMMY, // 0x88 DUMMY, // 0x89 DUMMY, // 0x8a DUMMY, // 0x8b DUMMY, // 0x8c DUMMY, // 0x8d DUMMY, // 0x8e DUMMY, // 0x8f KEY(NumLock ), // 0x90 KEY(ScrollLock ), // 0x91 DUMMY, // 0x92 DUMMY, // 0x93 DUMMY, // 0x94 DUMMY, // 0x95 DUMMY, // 0x96 DUMMY, // 0x97 DUMMY, // 0x98 DUMMY, // 0x99 DUMMY, // 0x9a DUMMY, // 0x9b DUMMY, // 0x9c DUMMY, // 0x9d DUMMY, // 0x9e DUMMY, // 0x9f KEY(LShift ), // 0xa0 KEY(RShift ), // 0xa1 KEY(LControl ), // 0xa2 KEY(RControl ), // 0xa3 KEY(LMenu ), // 0xa4 KEY(RMenu ), // 0xa5 KEY(BrowserBack ), // 0xa6 KEY(BrowserForward ), // 0xa7 KEY(BrowserRefresh ), // 0xa8 KEY(BrowserStop ), // 0xa9 KEY(BrowserSearch ), // 0xaa KEY(BrowserFavorits ), // 0xab KEY(BrowserHome ), // 0xac KEY(VolumeMute ), // 0xad KEY(VolumeDown ), // 0xae KEY(VolumeUp ), // 0xaf KEY(MediaNextTrack ), // 0xb0 KEY(MediaPrevTrack ), // 0xb1 KEY(MediaStop ), // 0xb2 KEY(MediaPlayPause ), // 0xb3 KEY(LaunchMail ), // 0xb4 KEY(LaunchMediaSelect ), // 0xb5 KEY(LaunchApp1 ), // 0xb6 KEY(LaunchApp2 ), // 0xb7 DUMMY, // 0xb8 DUMMY, // 0xb9 DUMMY, // 0xba KEY(Plus ), // 0xbb KEY(Comma ), // 0xbc KEY(Minus ), // 0xbd KEY(Period ), // 0xbe DUMMY, // 0xbf DUMMY, // 0xc0 DUMMY, // 0xc1 DUMMY, // 0xc2 DUMMY, // 0xc3 DUMMY, // 0xc4 DUMMY, // 0xc5 DUMMY, // 0xc6 DUMMY, // 0xc7 DUMMY, // 0xc8 DUMMY, // 0xc9 DUMMY, // 0xca DUMMY, // 0xcb DUMMY, // 0xcc DUMMY, // 0xcd DUMMY, // 0xce DUMMY, // 0xcf DUMMY, // 0xd0 DUMMY, // 0xd1 DUMMY, // 0xd2 DUMMY, // 0xd3 DUMMY, // 0xd4 DUMMY, // 0xd5 DUMMY, // 0xd6 DUMMY, // 0xd7 DUMMY, // 0xd8 DUMMY, // 0xd9 DUMMY, // 0xda DUMMY, // 0xdb KEY(Exponent ), // 0xdc DUMMY, // 0xdd DUMMY, // 0xde DUMMY, // 0xdf DUMMY, // 0xe0 DUMMY, // 0xe1 DUMMY, // 0xe2 DUMMY, // 0xe3 DUMMY, // 0xe4 DUMMY, // 0xe5 DUMMY, // 0xe6 DUMMY, // 0xe7 DUMMY, // 0xe8 DUMMY, // 0xe9 DUMMY, // 0xea DUMMY, // 0xeb DUMMY, // 0xec DUMMY, // 0xed DUMMY, // 0xee DUMMY, // 0xef DUMMY, // 0xf0 DUMMY, // 0xf1 DUMMY, // 0xf2 DUMMY, // 0xf3 DUMMY, // 0xf4 DUMMY, // 0xf5 KEY(Attn ), // 0xf6 KEY(CrSel ), // 0xf7 KEY(ExSel ), // 0xf8 KEY(ErEOF ), // 0xf9 KEY(Play ), // 0xfa KEY(Zoom ), // 0xfb KEY(NoName ), // 0xfc KEY(PA1 ), // 0xfd KEY(OEMClear ), // 0xfe DUMMY, // 0xff }; #undef KEY #undef DUMMY Key MapKey(unsigned char sysKeyCode) { return win32KeyCodeMap[sysKeyCode]; } } // /namespace LLGL // ================================================================================ <commit_msg>Minor change.<commit_after>/* * MapKey.cpp (Win32) * * This file is part of the "LLGL" project (Copyright (c) 2015 by Lukas Hermanns) * See "LICENSE.txt" for license information. */ #include "MapKey.h" namespace LLGL { #define KEY(c) Key::c #define DUMMY KEY(Pause) // <-- any key, a dummy will never be used static const Key win32KeyCodeMap[256] = { DUMMY, // 0x00 KEY(LButton ), // 0x01 KEY(RButton ), // 0x02 KEY(Cancel ), // 0x03 KEY(MButton ), // 0x04 KEY(XButton1 ), // 0x05 KEY(XButton2 ), // 0x06 DUMMY, // 0x07 KEY(Back ), // 0x08 KEY(Tab ), // 0x09 DUMMY, // 0x0a DUMMY, // 0x0b KEY(Clear ), // 0x0c KEY(Return ), // 0x0d DUMMY, // 0x0e DUMMY, // 0x0f KEY(Shift ), // 0x10 KEY(Control ), // 0x11 KEY(Menu ), // 0x12 KEY(Pause ), // 0x13 KEY(Capital ), // 0x14 DUMMY, // 0x15 DUMMY, // 0x16 DUMMY, // 0x17 DUMMY, // 0x18 DUMMY, // 0x19 DUMMY, // 0x1a KEY(Escape ), // 0x1b DUMMY, // 0x1c DUMMY, // 0x1d DUMMY, // 0x1e DUMMY, // 0x1f KEY(Space ), // 0x20 KEY(PageUp ), // 0x21 KEY(PageDown ), // 0x22 KEY(End ), // 0x23 KEY(Home ), // 0x24 KEY(Left ), // 0x25 KEY(Up ), // 0x26 KEY(Right ), // 0x27 KEY(Down ), // 0x28 KEY(Select ), // 0x29 KEY(Print ), // 0x2a KEY(Exe ), // 0x2b KEY(Snapshot ), // 0x2c KEY(Insert ), // 0x2d KEY(Delete ), // 0x2e KEY(Help ), // 0x2f KEY(D0 ), // 0x30 KEY(D1 ), // 0x31 KEY(D2 ), // 0x32 KEY(D3 ), // 0x33 KEY(D4 ), // 0x34 KEY(D5 ), // 0x35 KEY(D6 ), // 0x36 KEY(D7 ), // 0x37 KEY(D8 ), // 0x38 KEY(D9 ), // 0x39 DUMMY, // 0x3a DUMMY, // 0x3b DUMMY, // 0x3c DUMMY, // 0x3d DUMMY, // 0x3e DUMMY, // 0x3f DUMMY, // 0x40 KEY(A ), // 0x41 KEY(B ), // 0x42 KEY(C ), // 0x43 KEY(D ), // 0x44 KEY(E ), // 0x45 KEY(F ), // 0x46 KEY(G ), // 0x47 KEY(H ), // 0x48 KEY(I ), // 0x49 KEY(J ), // 0x4a KEY(K ), // 0x4b KEY(L ), // 0x4c KEY(M ), // 0x4d KEY(N ), // 0x4e KEY(O ), // 0x4f KEY(P ), // 0x50 KEY(Q ), // 0x51 KEY(R ), // 0x52 KEY(S ), // 0x53 KEY(T ), // 0x54 KEY(U ), // 0x55 KEY(V ), // 0x56 KEY(W ), // 0x57 KEY(X ), // 0x58 KEY(Y ), // 0x59 KEY(Z ), // 0x5a KEY(LWin ), // 0x5b KEY(RWin ), // 0x5c KEY(Apps ), // 0x5d DUMMY, // 0x5e KEY(Sleep ), // 0x5f KEY(Keypad0 ), // 0x60 KEY(Keypad1 ), // 0x61 KEY(Keypad2 ), // 0x62 KEY(Keypad3 ), // 0x63 KEY(Keypad4 ), // 0x64 KEY(Keypad5 ), // 0x65 KEY(Keypad6 ), // 0x66 KEY(Keypad7 ), // 0x67 KEY(Keypad8 ), // 0x68 KEY(Keypad9 ), // 0x69 KEY(KeypadMultiply ), // 0x6a KEY(KeypadPlus ), // 0x6b KEY(KeypadSeparator ), // 0x6c KEY(KeypadMinus ), // 0x6d KEY(KeypadDecimal ), // 0x6e KEY(KeypadDivide ), // 0x6f KEY(F1 ), // 0x70 KEY(F2 ), // 0x71 KEY(F3 ), // 0x72 KEY(F4 ), // 0x73 KEY(F5 ), // 0x74 KEY(F6 ), // 0x75 KEY(F7 ), // 0x76 KEY(F8 ), // 0x77 KEY(F9 ), // 0x78 KEY(F10 ), // 0x79 KEY(F11 ), // 0x7a KEY(F12 ), // 0x7b KEY(F13 ), // 0x7c KEY(F14 ), // 0x7d KEY(F15 ), // 0x7e KEY(F16 ), // 0x7f KEY(F17 ), // 0x80 KEY(F18 ), // 0x81 KEY(F19 ), // 0x82 KEY(F20 ), // 0x83 KEY(F21 ), // 0x84 KEY(F22 ), // 0x85 KEY(F23 ), // 0x86 KEY(F24 ), // 0x87 DUMMY, // 0x88 DUMMY, // 0x89 DUMMY, // 0x8a DUMMY, // 0x8b DUMMY, // 0x8c DUMMY, // 0x8d DUMMY, // 0x8e DUMMY, // 0x8f KEY(NumLock ), // 0x90 KEY(ScrollLock ), // 0x91 DUMMY, // 0x92 DUMMY, // 0x93 DUMMY, // 0x94 DUMMY, // 0x95 DUMMY, // 0x96 DUMMY, // 0x97 DUMMY, // 0x98 DUMMY, // 0x99 DUMMY, // 0x9a DUMMY, // 0x9b DUMMY, // 0x9c DUMMY, // 0x9d DUMMY, // 0x9e DUMMY, // 0x9f KEY(LShift ), // 0xa0 KEY(RShift ), // 0xa1 KEY(LControl ), // 0xa2 KEY(RControl ), // 0xa3 KEY(LMenu ), // 0xa4 KEY(RMenu ), // 0xa5 KEY(BrowserBack ), // 0xa6 KEY(BrowserForward ), // 0xa7 KEY(BrowserRefresh ), // 0xa8 KEY(BrowserStop ), // 0xa9 KEY(BrowserSearch ), // 0xaa KEY(BrowserFavorits ), // 0xab KEY(BrowserHome ), // 0xac KEY(VolumeMute ), // 0xad KEY(VolumeDown ), // 0xae KEY(VolumeUp ), // 0xaf KEY(MediaNextTrack ), // 0xb0 KEY(MediaPrevTrack ), // 0xb1 KEY(MediaStop ), // 0xb2 KEY(MediaPlayPause ), // 0xb3 KEY(LaunchMail ), // 0xb4 KEY(LaunchMediaSelect ), // 0xb5 KEY(LaunchApp1 ), // 0xb6 KEY(LaunchApp2 ), // 0xb7 DUMMY, // 0xb8 DUMMY, // 0xb9 DUMMY, // 0xba KEY(Plus ), // 0xbb KEY(Comma ), // 0xbc KEY(Minus ), // 0xbd KEY(Period ), // 0xbe DUMMY, // 0xbf DUMMY, // 0xc0 DUMMY, // 0xc1 DUMMY, // 0xc2 DUMMY, // 0xc3 DUMMY, // 0xc4 DUMMY, // 0xc5 DUMMY, // 0xc6 DUMMY, // 0xc7 DUMMY, // 0xc8 DUMMY, // 0xc9 DUMMY, // 0xca DUMMY, // 0xcb DUMMY, // 0xcc DUMMY, // 0xcd DUMMY, // 0xce DUMMY, // 0xcf DUMMY, // 0xd0 DUMMY, // 0xd1 DUMMY, // 0xd2 DUMMY, // 0xd3 DUMMY, // 0xd4 DUMMY, // 0xd5 DUMMY, // 0xd6 DUMMY, // 0xd7 DUMMY, // 0xd8 DUMMY, // 0xd9 DUMMY, // 0xda DUMMY, // 0xdb KEY(Exponent ), // 0xdc DUMMY, // 0xdd DUMMY, // 0xde DUMMY, // 0xdf DUMMY, // 0xe0 DUMMY, // 0xe1 DUMMY, // 0xe2 DUMMY, // 0xe3 DUMMY, // 0xe4 DUMMY, // 0xe5 DUMMY, // 0xe6 DUMMY, // 0xe7 DUMMY, // 0xe8 DUMMY, // 0xe9 DUMMY, // 0xea DUMMY, // 0xeb DUMMY, // 0xec DUMMY, // 0xed DUMMY, // 0xee DUMMY, // 0xef DUMMY, // 0xf0 DUMMY, // 0xf1 DUMMY, // 0xf2 DUMMY, // 0xf3 DUMMY, // 0xf4 DUMMY, // 0xf5 KEY(Attn ), // 0xf6 KEY(CrSel ), // 0xf7 KEY(ExSel ), // 0xf8 KEY(ErEOF ), // 0xf9 KEY(Play ), // 0xfa KEY(Zoom ), // 0xfb KEY(NoName ), // 0xfc KEY(PA1 ), // 0xfd KEY(OEMClear ), // 0xfe DUMMY, // 0xff }; #undef KEY #undef DUMMY Key MapKey(unsigned char sysKeyCode) { return win32KeyCodeMap[sysKeyCode]; } } // /namespace LLGL // ================================================================================ <|endoftext|>
<commit_before>/* * This file is part of telepathy-accounts-kcm * * Copyright (C) 2011 Florian Reinhard <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "skype-main-options-widget.h" #include <KCMTelepathyAccounts/ParameterEditModel> #include <KDebug> #include <QVariant> SkypeMainOptionsWidget::SkypeMainOptionsWidget(ParameterEditModel *model, QWidget *parent) : AbstractAccountParametersWidget(model, parent) { kDebug(); // Set up the UI. m_ui = new Ui::SkypeMainOptionsWidget; m_ui->setupUi(this); handleParameter("account", QVariant::String, m_ui->accountLineEdit, m_ui->accountLabel); } SkypeMainOptionsWidget::~SkypeMainOptionsWidget() { kDebug(); delete m_ui; } #include "skype-main-options-widget.moc" <commit_msg>Add Skype account name autocomplete based on $HOME/.Skype/.<commit_after>/* * This file is part of telepathy-accounts-kcm * * Copyright (C) 2011 Florian Reinhard <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "skype-main-options-widget.h" #include <KCMTelepathyAccounts/ParameterEditModel> #include <KDebug> #include <QDir> #include <QVariant> SkypeMainOptionsWidget::SkypeMainOptionsWidget(ParameterEditModel *model, QWidget *parent) : AbstractAccountParametersWidget(model, parent) { kDebug(); // Set up the UI. m_ui = new Ui::SkypeMainOptionsWidget; m_ui->setupUi(this); handleParameter("account", QVariant::String, m_ui->accountLineEdit, m_ui->accountLabel); #ifdef Q_WS_X11 // get autocomplete choices for the accountname // Skype stores data for each account that has been used in $HOME/.Skype/<accountname>/ QDir skypeConfigDir(QDir::home().filePath(".Skype")); skypeConfigDir.setFilter(QDir::Dirs | QDir::NoDotAndDotDot); QFileInfoList folderList = skypeConfigDir.entryInfoList(); KCompletion *completion = new KCompletion; foreach (const QFileInfo info, folderList){ completion->addItem(info.fileName()); } m_ui->accountLineEdit->setCompletionObject(completion); m_ui->accountLineEdit->setAutoDeleteCompletionObject(true); #endif } SkypeMainOptionsWidget::~SkypeMainOptionsWidget() { kDebug(); delete m_ui; } #include "skype-main-options-widget.moc" <|endoftext|>
<commit_before>/* * The Apache Software License, Version 1.1 * * Copyright (c) 2001 The Apache Software 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. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache\@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation, and was * originally based on software copyright (c) 2001, International * Business Machines, Inc., http://www.ibm.com . For more information * on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /* * $Id$ * $Log$ * Revision 1.20 2004/01/29 11:48:46 cargilld * Code cleanup changes to get rid of various compiler diagnostic messages. * * Revision 1.19 2004/01/13 19:50:56 peiyongz * remove parseContent() * * Revision 1.17 2003/12/17 00:18:35 cargilld * Update to memory management so that the static memory manager (one used to call Initialize) is only for static data. * * Revision 1.16 2003/12/11 21:38:12 peiyongz * support for Canonical Representation for Datatype * * Revision 1.15 2003/10/15 14:50:01 peiyongz * Bugzilla#22821: locale-sensitive function used to validate 'double' type, patch * from [email protected] (Jeff Sweeney) * * Revision 1.14 2003/09/23 18:16:07 peiyongz * Inplementation for Serialization/Deserialization * * Revision 1.13 2003/05/18 14:02:05 knoaman * Memory manager implementation: pass per instance manager. * * Revision 1.12 2003/05/16 06:01:53 knoaman * Partial implementation of the configurable memory manager. * * Revision 1.11 2003/05/15 19:07:46 knoaman * Partial implementation of the configurable memory manager. * * Revision 1.10 2003/05/09 15:13:46 peiyongz * Deprecated toString() in XMLNumber family * * Revision 1.9 2003/03/10 20:55:58 peiyongz * Schema Errata E2-40 double/float * * Revision 1.8 2003/02/02 23:54:43 peiyongz * getFormattedString() added to return original and converted value. * * Revision 1.7 2003/01/30 21:55:22 tng * Performance: create getRawData which is similar to toString but return the internal data directly, user is not required to delete the returned memory. * * Revision 1.6 2002/12/11 00:20:02 peiyongz * Doing businesss in value space. Converting out-of-bound value into special values. * * Revision 1.5 2002/11/04 15:22:05 tng * C++ Namespace Support. * * Revision 1.4 2002/03/06 19:13:12 peiyongz * Patch: more valid lexcial representation for positive/negative zero * * Revision 1.3 2002/03/01 18:47:37 peiyongz * fix: more valid lexcial representation forms for "neural zero" * * Revision 1.2 2002/02/20 18:17:02 tng * [Bug 5977] Warnings on generating apiDocs. * * Revision 1.1.1.1 2002/02/01 22:22:14 peiyongz * sane_include * * Revision 1.4 2001/11/28 15:39:26 peiyongz * return Type& for operator= * * Revision 1.3 2001/11/22 21:39:00 peiyongz * Allow "0.0" to be a valid lexcial representation of ZERO. * * Revision 1.2 2001/11/22 20:23:00 peiyongz * _declspec(dllimport) and inline warning C4273 * * Revision 1.1 2001/11/19 21:33:42 peiyongz * Reorganization: Double/Float * * */ #ifndef XML_ABSTRACT_DOUBLE_FLOAT_HPP #define XML_ABSTRACT_DOUBLE_FLOAT_HPP #include <xercesc/util/XMLNumber.hpp> #include <xercesc/util/PlatformUtils.hpp> XERCES_CPP_NAMESPACE_BEGIN /*** * 3.2.5.1 Lexical representation * * double values have a lexical representation consisting of a mantissa followed, * optionally, by the character "E" or "e", followed by an exponent. * * The exponent must be an integer. * The mantissa must be a decimal number. * The representations for exponent and mantissa must follow the lexical rules * for integer and decimal. * * If the "E" or "e" and the following exponent are omitted, * an exponent value of 0 is assumed. ***/ /*** * 3.2.4.1 Lexical representation * * float values have a lexical representation consisting of a mantissa followed, * optionally, by the character "E" or "e", followed by an exponent. * * The exponent must be an integer. * The mantissa must be a decimal number. * The representations for exponent and mantissa must follow the lexical rules * for integer and decimal. * * If the "E" or "e" and the following exponent are omitted, * an exponent value of 0 is assumed. ***/ class XMLUTIL_EXPORT XMLAbstractDoubleFloat : public XMLNumber { public: enum LiteralType { NegINF, PosINF, NaN, SpecialTypeNum, Normal }; virtual ~XMLAbstractDoubleFloat(); static XMLCh* getCanonicalRepresentation ( const XMLCh* const rawData , MemoryManager* const memMgr = XMLPlatformUtils::fgMemoryManager ); /** * * Deprecated: please use getRawData * */ virtual XMLCh* toString() const; virtual XMLCh* getRawData() const; virtual const XMLCh* getFormattedString() const; virtual int getSign() const; MemoryManager* getMemoryManager() const; /*** * * The decimal point delimiter for the schema double/float type is * defined to be a period and is not locale-specific. So, it must * be replaced with the local-specific delimiter before converting * from string to double/float. * ***/ void normalizeDecimalPoint(char* const toNormal); /*** * Support for Serialization/De-serialization ***/ DECL_XSERIALIZABLE(XMLAbstractDoubleFloat) protected: // // To be used by derived class exclusively // XMLAbstractDoubleFloat(MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager); void init(const XMLCh* const strValue); /** * Compares this object to the specified object. * The result is <code>true</code> if and only if the argument is not * <code>null</code> and is an <code>XMLAbstractDoubleFloat</code> object that contains * the same <code>int</code> value as this object. * * @param lValue the object to compare with. * @param rValue the object to compare against. * @return <code>true</code> if the objects are the same; * <code>false</code> otherwise. */ static int compareValues(const XMLAbstractDoubleFloat* const lValue , const XMLAbstractDoubleFloat* const rValue , MemoryManager* const manager); // // to be overwritten by derived class // virtual void checkBoundary(const XMLCh* const strValue) = 0; private: // // Unimplemented // // copy ctor // assignment ctor // XMLAbstractDoubleFloat(const XMLAbstractDoubleFloat& toCopy); XMLAbstractDoubleFloat& operator=(const XMLAbstractDoubleFloat& toAssign); void normalizeZero(XMLCh* const); inline bool isSpecialValue() const; static int compareSpecial(const XMLAbstractDoubleFloat* const specialValue , MemoryManager* const manager); void formatString(); protected: double fValue; LiteralType fType; bool fDataConverted; private: int fSign; XMLCh* fRawData; // // If the original string is not lexcially the same as the five // special value notations, and the value is converted to // special value due underlying platform restriction on data // representation, then this string is constructed and // takes the form "original_string (special_value_notation)", // otherwise it is empty. // XMLCh* fFormattedString; MemoryManager* fMemoryManager; }; inline bool XMLAbstractDoubleFloat::isSpecialValue() const { return (fType < SpecialTypeNum); } inline MemoryManager* XMLAbstractDoubleFloat::getMemoryManager() const { return fMemoryManager; } XERCES_CPP_NAMESPACE_END #endif <commit_msg>getValue()/isDataConverted()<commit_after>/* * The Apache Software License, Version 1.1 * * Copyright (c) 2001 The Apache Software 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. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache\@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation, and was * originally based on software copyright (c) 2001, International * Business Machines, Inc., http://www.ibm.com . For more information * on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /* * $Id$ * $Log$ * Revision 1.21 2004/08/11 16:50:47 peiyongz * getValue()/isDataConverted() * * Revision 1.20 2004/01/29 11:48:46 cargilld * Code cleanup changes to get rid of various compiler diagnostic messages. * * Revision 1.19 2004/01/13 19:50:56 peiyongz * remove parseContent() * * Revision 1.17 2003/12/17 00:18:35 cargilld * Update to memory management so that the static memory manager (one used to call Initialize) is only for static data. * * Revision 1.16 2003/12/11 21:38:12 peiyongz * support for Canonical Representation for Datatype * * Revision 1.15 2003/10/15 14:50:01 peiyongz * Bugzilla#22821: locale-sensitive function used to validate 'double' type, patch * from [email protected] (Jeff Sweeney) * * Revision 1.14 2003/09/23 18:16:07 peiyongz * Inplementation for Serialization/Deserialization * * Revision 1.13 2003/05/18 14:02:05 knoaman * Memory manager implementation: pass per instance manager. * * Revision 1.12 2003/05/16 06:01:53 knoaman * Partial implementation of the configurable memory manager. * * Revision 1.11 2003/05/15 19:07:46 knoaman * Partial implementation of the configurable memory manager. * * Revision 1.10 2003/05/09 15:13:46 peiyongz * Deprecated toString() in XMLNumber family * * Revision 1.9 2003/03/10 20:55:58 peiyongz * Schema Errata E2-40 double/float * * Revision 1.8 2003/02/02 23:54:43 peiyongz * getFormattedString() added to return original and converted value. * * Revision 1.7 2003/01/30 21:55:22 tng * Performance: create getRawData which is similar to toString but return the internal data directly, user is not required to delete the returned memory. * * Revision 1.6 2002/12/11 00:20:02 peiyongz * Doing businesss in value space. Converting out-of-bound value into special values. * * Revision 1.5 2002/11/04 15:22:05 tng * C++ Namespace Support. * * Revision 1.4 2002/03/06 19:13:12 peiyongz * Patch: more valid lexcial representation for positive/negative zero * * Revision 1.3 2002/03/01 18:47:37 peiyongz * fix: more valid lexcial representation forms for "neural zero" * * Revision 1.2 2002/02/20 18:17:02 tng * [Bug 5977] Warnings on generating apiDocs. * * Revision 1.1.1.1 2002/02/01 22:22:14 peiyongz * sane_include * * Revision 1.4 2001/11/28 15:39:26 peiyongz * return Type& for operator= * * Revision 1.3 2001/11/22 21:39:00 peiyongz * Allow "0.0" to be a valid lexcial representation of ZERO. * * Revision 1.2 2001/11/22 20:23:00 peiyongz * _declspec(dllimport) and inline warning C4273 * * Revision 1.1 2001/11/19 21:33:42 peiyongz * Reorganization: Double/Float * * */ #ifndef XML_ABSTRACT_DOUBLE_FLOAT_HPP #define XML_ABSTRACT_DOUBLE_FLOAT_HPP #include <xercesc/util/XMLNumber.hpp> #include <xercesc/util/PlatformUtils.hpp> XERCES_CPP_NAMESPACE_BEGIN /*** * 3.2.5.1 Lexical representation * * double values have a lexical representation consisting of a mantissa followed, * optionally, by the character "E" or "e", followed by an exponent. * * The exponent must be an integer. * The mantissa must be a decimal number. * The representations for exponent and mantissa must follow the lexical rules * for integer and decimal. * * If the "E" or "e" and the following exponent are omitted, * an exponent value of 0 is assumed. ***/ /*** * 3.2.4.1 Lexical representation * * float values have a lexical representation consisting of a mantissa followed, * optionally, by the character "E" or "e", followed by an exponent. * * The exponent must be an integer. * The mantissa must be a decimal number. * The representations for exponent and mantissa must follow the lexical rules * for integer and decimal. * * If the "E" or "e" and the following exponent are omitted, * an exponent value of 0 is assumed. ***/ class XMLUTIL_EXPORT XMLAbstractDoubleFloat : public XMLNumber { public: enum LiteralType { NegINF, PosINF, NaN, SpecialTypeNum, Normal }; virtual ~XMLAbstractDoubleFloat(); static XMLCh* getCanonicalRepresentation ( const XMLCh* const rawData , MemoryManager* const memMgr = XMLPlatformUtils::fgMemoryManager ); /** * * Deprecated: please use getRawData * */ virtual XMLCh* toString() const; virtual XMLCh* getRawData() const; virtual const XMLCh* getFormattedString() const; virtual int getSign() const; MemoryManager* getMemoryManager() const; inline bool isDataConverted() const; inline double getValue() const; /*** * * The decimal point delimiter for the schema double/float type is * defined to be a period and is not locale-specific. So, it must * be replaced with the local-specific delimiter before converting * from string to double/float. * ***/ void normalizeDecimalPoint(char* const toNormal); /*** * Support for Serialization/De-serialization ***/ DECL_XSERIALIZABLE(XMLAbstractDoubleFloat) protected: // // To be used by derived class exclusively // XMLAbstractDoubleFloat(MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager); void init(const XMLCh* const strValue); /** * Compares this object to the specified object. * The result is <code>true</code> if and only if the argument is not * <code>null</code> and is an <code>XMLAbstractDoubleFloat</code> object that contains * the same <code>int</code> value as this object. * * @param lValue the object to compare with. * @param rValue the object to compare against. * @return <code>true</code> if the objects are the same; * <code>false</code> otherwise. */ static int compareValues(const XMLAbstractDoubleFloat* const lValue , const XMLAbstractDoubleFloat* const rValue , MemoryManager* const manager); // // to be overwritten by derived class // virtual void checkBoundary(const XMLCh* const strValue) = 0; private: // // Unimplemented // // copy ctor // assignment ctor // XMLAbstractDoubleFloat(const XMLAbstractDoubleFloat& toCopy); XMLAbstractDoubleFloat& operator=(const XMLAbstractDoubleFloat& toAssign); void normalizeZero(XMLCh* const); inline bool isSpecialValue() const; static int compareSpecial(const XMLAbstractDoubleFloat* const specialValue , MemoryManager* const manager); void formatString(); protected: double fValue; LiteralType fType; bool fDataConverted; private: int fSign; XMLCh* fRawData; // // If the original string is not lexcially the same as the five // special value notations, and the value is converted to // special value due underlying platform restriction on data // representation, then this string is constructed and // takes the form "original_string (special_value_notation)", // otherwise it is empty. // XMLCh* fFormattedString; MemoryManager* fMemoryManager; }; inline bool XMLAbstractDoubleFloat::isSpecialValue() const { return (fType < SpecialTypeNum); } inline MemoryManager* XMLAbstractDoubleFloat::getMemoryManager() const { return fMemoryManager; } inline bool XMLAbstractDoubleFloat::isDataConverted() const { return fDataConverted; } inline double XMLAbstractDoubleFloat::getValue() const { return fValue; } XERCES_CPP_NAMESPACE_END #endif <|endoftext|>
<commit_before>// AMX profiler for SA-MP server: http://sa-mp.com // // Copyright (C) 2011 Sergey Zolotarev // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <algorithm> #include <cassert> #include <map> #include <set> #include <numeric> #include <sstream> #include <string> #include <boost/scoped_ptr.hpp> #include "abstract_printer.h" #include "function.h" #include "function_profile.h" #include "native_function.h" #include "normal_function.h" #include "profiler.h" #include "public_function.h" #include "amx/amx.h" #include "amx/amxdbg.h" namespace { int AMXAPI Debug(AMX *amx) { return samp_profiler::Profiler::Get(amx)->Debug(); } } // anonymous namespace namespace samp_profiler { // statics std::map<AMX*, Profiler*> Profiler::instances_; Profiler::Profiler() { } Profiler::~Profiler() { for (Functions::const_iterator iterator = functions_.begin(); iterator != functions_.end(); ++iterator) { delete iterator->first; } } bool Profiler::IsScriptProfilable(AMX *amx) { uint16_t flags; amx_Flags(amx, &flags); if ((flags & AMX_FLAG_DEBUG) != 0) { return true; } if ((flags & AMX_FLAG_NOCHECKS) == 0) { return true; } return false; } // static void Profiler::Attach(AMX *amx) { Profiler *prof = new Profiler(amx); instances_[amx] = prof; prof->Activate(); } // static void Profiler::Attach(AMX *amx, const DebugInfo &debug_info) { Attach(amx); Get(amx)->SetDebugInfo(debug_info); } // static void Profiler::Detach(AMX *amx) { Profiler *prof = Profiler::Get(amx); if (prof != 0) { prof->Deactivate(); delete prof; } instances_.erase(amx); } // static Profiler *Profiler::Get(AMX *amx) { std::map<AMX*, Profiler*>::iterator it = instances_.find(amx); if (it != instances_.end()) { return it->second; } return 0; } Profiler::Profiler(AMX *amx) : active_(false) , amx_(amx) , debug_(amx->debug) { } void Profiler::SetDebugInfo(const DebugInfo &info) { debug_info_ = info; } void Profiler::Activate() { if (!active_) { active_ = true; amx_SetDebugHook(amx_, ::Debug); } } bool Profiler::IsActive() const { return active_; } void Profiler::Deactivate() { if (active_) { active_ = false; amx_SetDebugHook(amx_, debug_); } } void Profiler::ResetStats() { functions_.clear(); } void Profiler::PrintStats(const std::string &script_name, std::ostream &stream, AbstractPrinter *printer) const { std::vector<const FunctionProfile*> stats; for (Functions::const_iterator iterator = functions_.begin(); iterator != functions_.end(); ++iterator) { stats.push_back(&iterator->second); } printer->Print(script_name, stream, stats); } int Profiler::Debug() { cell prevFrame = amx_->stp; if (!call_stack_.IsEmpty()) { prevFrame = call_stack_.GetTop().frame(); } if (amx_->frm < prevFrame) { cell address = amx_->cip - 2*sizeof(cell); if (call_stack_.GetTop().frame() != amx_->frm) { boost::scoped_ptr<NormalFunction> fn(new NormalFunction(amx_, address, &debug_info_)); EnterFunction(fn.get(), amx_->frm); } } else if (amx_->frm > prevFrame) { const Function *top_fn = call_stack_.GetTop().function(); if (top_fn->type() == "normal") { LeaveFunction(top_fn); } } if (debug_ != 0) { return debug_(amx_); } return AMX_ERR_NONE; } int Profiler::Callback(cell index, cell *result, cell *params) { boost::scoped_ptr<NativeFunction> fn(new NativeFunction(amx_, index)); EnterFunction(fn.get(), amx_->frm); int error = amx_Callback(amx_, index, result, params); LeaveFunction(fn.get()); return error; } int Profiler::Exec(cell *retval, int index) { if (index >= 0 || index == AMX_EXEC_MAIN) { AMX_HEADER *hdr = reinterpret_cast<AMX_HEADER*>(amx_->base); cell address = 0; if (index == AMX_EXEC_MAIN) { address = hdr->cip; } else { AMX_FUNCSTUBNT *publics = reinterpret_cast<AMX_FUNCSTUBNT*>(amx_->base + hdr->publics); address = publics[index].address; } boost::scoped_ptr<PublicFunction> fn(new PublicFunction(amx_, index)); EnterFunction(fn.get(), amx_->stk - 3*sizeof(cell)); int error = amx_Exec(amx_, retval, index); LeaveFunction(fn.get()); return error; } else { return amx_Exec(amx_, retval, index); } } void Profiler::EnterFunction(const Function *fn, ucell frame) { Functions::iterator iterator = functions_.find(const_cast<Function*>(fn)); if (iterator == functions_.end()) { Function *new_fn = fn->Clone(); functions_.insert(std::make_pair(new_fn, FunctionProfile(new_fn))); call_stack_.Push(new_fn, frame); } else { iterator->second.num_calls()++; call_stack_.Push(iterator->second.function(), frame); } } void Profiler::LeaveFunction(const Function *fn) { assert(!call_stack_.IsEmpty()); while (true) { FunctionCall current = call_stack_.Pop(); Functions::iterator current_it = functions_.find(current.function()); if (current.IsRecursive()) { //current_it->second.total_time() += current.timer().child_time(); current_it->second.child_time() -= current.timer().child_time(); } else { current_it->second.total_time() += current.timer().total_time(); } if (!call_stack_.IsEmpty()) { FunctionCall &top = call_stack_.GetTop(); functions_.find(top.function())->second.child_time() += current.timer().total_time(); } if (fn == 0 || (current.function()->type() == fn->type() && current.function()->Compare(fn) == 0)) { break; } } } } // namespace samp_profiler <commit_msg>Turn Function type check into assertion in Profiler::Debug()<commit_after>// AMX profiler for SA-MP server: http://sa-mp.com // // Copyright (C) 2011 Sergey Zolotarev // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <algorithm> #include <cassert> #include <map> #include <set> #include <numeric> #include <sstream> #include <string> #include <boost/scoped_ptr.hpp> #include "abstract_printer.h" #include "function.h" #include "function_profile.h" #include "native_function.h" #include "normal_function.h" #include "profiler.h" #include "public_function.h" #include "amx/amx.h" #include "amx/amxdbg.h" namespace { int AMXAPI Debug(AMX *amx) { return samp_profiler::Profiler::Get(amx)->Debug(); } } // anonymous namespace namespace samp_profiler { // statics std::map<AMX*, Profiler*> Profiler::instances_; Profiler::Profiler() { } Profiler::~Profiler() { for (Functions::const_iterator iterator = functions_.begin(); iterator != functions_.end(); ++iterator) { delete iterator->first; } } bool Profiler::IsScriptProfilable(AMX *amx) { uint16_t flags; amx_Flags(amx, &flags); if ((flags & AMX_FLAG_DEBUG) != 0) { return true; } if ((flags & AMX_FLAG_NOCHECKS) == 0) { return true; } return false; } // static void Profiler::Attach(AMX *amx) { Profiler *prof = new Profiler(amx); instances_[amx] = prof; prof->Activate(); } // static void Profiler::Attach(AMX *amx, const DebugInfo &debug_info) { Attach(amx); Get(amx)->SetDebugInfo(debug_info); } // static void Profiler::Detach(AMX *amx) { Profiler *prof = Profiler::Get(amx); if (prof != 0) { prof->Deactivate(); delete prof; } instances_.erase(amx); } // static Profiler *Profiler::Get(AMX *amx) { std::map<AMX*, Profiler*>::iterator it = instances_.find(amx); if (it != instances_.end()) { return it->second; } return 0; } Profiler::Profiler(AMX *amx) : active_(false) , amx_(amx) , debug_(amx->debug) { } void Profiler::SetDebugInfo(const DebugInfo &info) { debug_info_ = info; } void Profiler::Activate() { if (!active_) { active_ = true; amx_SetDebugHook(amx_, ::Debug); } } bool Profiler::IsActive() const { return active_; } void Profiler::Deactivate() { if (active_) { active_ = false; amx_SetDebugHook(amx_, debug_); } } void Profiler::ResetStats() { functions_.clear(); } void Profiler::PrintStats(const std::string &script_name, std::ostream &stream, AbstractPrinter *printer) const { std::vector<const FunctionProfile*> stats; for (Functions::const_iterator iterator = functions_.begin(); iterator != functions_.end(); ++iterator) { stats.push_back(&iterator->second); } printer->Print(script_name, stream, stats); } int Profiler::Debug() { cell prevFrame = amx_->stp; if (!call_stack_.IsEmpty()) { prevFrame = call_stack_.GetTop().frame(); } if (amx_->frm < prevFrame) { cell address = amx_->cip - 2*sizeof(cell); if (call_stack_.GetTop().frame() != amx_->frm) { boost::scoped_ptr<NormalFunction> fn(new NormalFunction(amx_, address, &debug_info_)); EnterFunction(fn.get(), amx_->frm); } } else if (amx_->frm > prevFrame) { Function *fn = call_stack_.GetTop().function(); assert(fn->type() == "normal" && "Call stack messed up"); LeaveFunction(fn); } if (debug_ != 0) { return debug_(amx_); } return AMX_ERR_NONE; } int Profiler::Callback(cell index, cell *result, cell *params) { boost::scoped_ptr<NativeFunction> fn(new NativeFunction(amx_, index)); EnterFunction(fn.get(), amx_->frm); int error = amx_Callback(amx_, index, result, params); LeaveFunction(fn.get()); return error; } int Profiler::Exec(cell *retval, int index) { if (index >= 0 || index == AMX_EXEC_MAIN) { AMX_HEADER *hdr = reinterpret_cast<AMX_HEADER*>(amx_->base); cell address = 0; if (index == AMX_EXEC_MAIN) { address = hdr->cip; } else { AMX_FUNCSTUBNT *publics = reinterpret_cast<AMX_FUNCSTUBNT*>(amx_->base + hdr->publics); address = publics[index].address; } boost::scoped_ptr<PublicFunction> fn(new PublicFunction(amx_, index)); EnterFunction(fn.get(), amx_->stk - 3*sizeof(cell)); int error = amx_Exec(amx_, retval, index); LeaveFunction(fn.get()); return error; } else { return amx_Exec(amx_, retval, index); } } void Profiler::EnterFunction(const Function *fn, ucell frame) { Functions::iterator iterator = functions_.find(const_cast<Function*>(fn)); if (iterator == functions_.end()) { Function *new_fn = fn->Clone(); functions_.insert(std::make_pair(new_fn, FunctionProfile(new_fn))); call_stack_.Push(new_fn, frame); } else { iterator->second.num_calls()++; call_stack_.Push(iterator->second.function(), frame); } } void Profiler::LeaveFunction(const Function *fn) { assert(!call_stack_.IsEmpty()); while (true) { FunctionCall current = call_stack_.Pop(); Functions::iterator current_it = functions_.find(current.function()); if (current.IsRecursive()) { //current_it->second.total_time() += current.timer().child_time(); current_it->second.child_time() -= current.timer().child_time(); } else { current_it->second.total_time() += current.timer().total_time(); } if (!call_stack_.IsEmpty()) { FunctionCall &top = call_stack_.GetTop(); functions_.find(top.function())->second.child_time() += current.timer().total_time(); } if (fn == 0 || (current.function()->type() == fn->type() && current.function()->Compare(fn) == 0)) { break; } } } } // namespace samp_profiler <|endoftext|>
<commit_before>/* * Copyright © 2012 Intel Corporation * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see <http://www.gnu.org/licenses/>. * * Author: Benjamin Segovia <[email protected]> */ /** * \file profile.hpp * \author Benjamin Segovia <[email protected]> */ #include "ir/profile.hpp" #include "ir/function.hpp" #include "sys/platform.hpp" namespace gbe { namespace ir { namespace ocl { const char *specialRegMean[] = { "local_id_0", "local_id_1", "local_id_2", "group_id_0", "group_id_1", "group_id_2", "num_groups_0", "num_groups_1", "num_groups_2", "local_size_0", "local_size_1", "local_size_2", "global_size_0", "global_size_1", "global_size_2", "global_offset_0", "global_offset_1", "global_offset_2", "stack_pointer", "block_ip", }; #if GBE_DEBUG #define DECL_NEW_REG(FAMILY, REG) \ r = fn.newRegister(FAMILY_DWORD); \ GBE_ASSERT(r == REG); #else #define DECL_NEW_REG(FAMILY, REG) \ fn.newRegister(FAMILY_DWORD); #endif /* GBE_DEBUG */ static void init(Function &fn) { IF_DEBUG(Register r); DECL_NEW_REG(FAMILY_DWORD, lid0); DECL_NEW_REG(FAMILY_DWORD, lid1); DECL_NEW_REG(FAMILY_DWORD, lid2); DECL_NEW_REG(FAMILY_DWORD, groupid0); DECL_NEW_REG(FAMILY_DWORD, groupid1); DECL_NEW_REG(FAMILY_DWORD, groupid2); DECL_NEW_REG(FAMILY_DWORD, numgroup0); DECL_NEW_REG(FAMILY_DWORD, numgroup1); DECL_NEW_REG(FAMILY_DWORD, numgroup2); DECL_NEW_REG(FAMILY_DWORD, lsize0); DECL_NEW_REG(FAMILY_DWORD, lsize1); DECL_NEW_REG(FAMILY_DWORD, lsize2); DECL_NEW_REG(FAMILY_DWORD, gsize0); DECL_NEW_REG(FAMILY_DWORD, gsize1); DECL_NEW_REG(FAMILY_DWORD, gsize2); DECL_NEW_REG(FAMILY_DWORD, goffset0); DECL_NEW_REG(FAMILY_DWORD, goffset1); DECL_NEW_REG(FAMILY_DWORD, goffset2); DECL_NEW_REG(FAMILY_DWORD, stackptr); DECL_NEW_REG(FAMILY_WORD, blockip); DECL_NEW_REG(FAMILY_DWORD, barrierid); DECL_NEW_REG(FAMILY_DWORD, threadn); } #undef DECL_NEW_REG } /* namespace ocl */ void initProfile(Function &fn) { const Profile profile = fn.getProfile(); switch (profile) { case PROFILE_C: GBE_ASSERTM(false, "Unsupported profile"); break; case PROFILE_OCL: ocl::init(fn); }; } } /* namespace ir */ } /* namespace gbe */ <commit_msg>Fix crash when output IR<commit_after>/* * Copyright © 2012 Intel Corporation * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see <http://www.gnu.org/licenses/>. * * Author: Benjamin Segovia <[email protected]> */ /** * \file profile.hpp * \author Benjamin Segovia <[email protected]> */ #include "ir/profile.hpp" #include "ir/function.hpp" #include "sys/platform.hpp" namespace gbe { namespace ir { namespace ocl { const char *specialRegMean[] = { "local_id_0", "local_id_1", "local_id_2", "group_id_0", "group_id_1", "group_id_2", "num_groups_0", "num_groups_1", "num_groups_2", "local_size_0", "local_size_1", "local_size_2", "global_size_0", "global_size_1", "global_size_2", "global_offset_0", "global_offset_1", "global_offset_2", "stack_pointer", "block_ip", "barrier_id", "thread_number", }; #if GBE_DEBUG #define DECL_NEW_REG(FAMILY, REG) \ r = fn.newRegister(FAMILY_DWORD); \ GBE_ASSERT(r == REG); #else #define DECL_NEW_REG(FAMILY, REG) \ fn.newRegister(FAMILY_DWORD); #endif /* GBE_DEBUG */ static void init(Function &fn) { IF_DEBUG(Register r); DECL_NEW_REG(FAMILY_DWORD, lid0); DECL_NEW_REG(FAMILY_DWORD, lid1); DECL_NEW_REG(FAMILY_DWORD, lid2); DECL_NEW_REG(FAMILY_DWORD, groupid0); DECL_NEW_REG(FAMILY_DWORD, groupid1); DECL_NEW_REG(FAMILY_DWORD, groupid2); DECL_NEW_REG(FAMILY_DWORD, numgroup0); DECL_NEW_REG(FAMILY_DWORD, numgroup1); DECL_NEW_REG(FAMILY_DWORD, numgroup2); DECL_NEW_REG(FAMILY_DWORD, lsize0); DECL_NEW_REG(FAMILY_DWORD, lsize1); DECL_NEW_REG(FAMILY_DWORD, lsize2); DECL_NEW_REG(FAMILY_DWORD, gsize0); DECL_NEW_REG(FAMILY_DWORD, gsize1); DECL_NEW_REG(FAMILY_DWORD, gsize2); DECL_NEW_REG(FAMILY_DWORD, goffset0); DECL_NEW_REG(FAMILY_DWORD, goffset1); DECL_NEW_REG(FAMILY_DWORD, goffset2); DECL_NEW_REG(FAMILY_DWORD, stackptr); DECL_NEW_REG(FAMILY_WORD, blockip); DECL_NEW_REG(FAMILY_DWORD, barrierid); DECL_NEW_REG(FAMILY_DWORD, threadn); } #undef DECL_NEW_REG } /* namespace ocl */ void initProfile(Function &fn) { const Profile profile = fn.getProfile(); switch (profile) { case PROFILE_C: GBE_ASSERTM(false, "Unsupported profile"); break; case PROFILE_OCL: ocl::init(fn); }; } } /* namespace ir */ } /* namespace gbe */ <|endoftext|>
<commit_before>// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2015 The Syscoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "rpc/client.h" #include "rpc/protocol.h" #include "util.h" #include <set> #include <stdint.h> #include <boost/algorithm/string/case_conv.hpp> // for to_lower() #include <univalue.h> using namespace std; class CRPCConvertParam { public: std::string methodName; //!< method whose params want conversion int paramIdx; //!< 0-based idx of param to convert }; static const CRPCConvertParam vRPCConvertParams[] = { { "stop", 0 }, { "setmocktime", 0 }, { "getaddednodeinfo", 0 }, { "generate", 0 }, { "generate", 1 }, { "generatetoaddress", 0 }, { "generatetoaddress", 2 }, { "getnetworkhashps", 0 }, { "getnetworkhashps", 1 }, { "sendtoaddress", 1 }, { "sendtoaddress", 4 }, { "settxfee", 0 }, { "getreceivedbyaddress", 1 }, { "getreceivedbyaccount", 1 }, { "listreceivedbyaddress", 0 }, { "listreceivedbyaddress", 1 }, { "listreceivedbyaddress", 2 }, { "listreceivedbyaccount", 0 }, { "listreceivedbyaccount", 1 }, { "listreceivedbyaccount", 2 }, { "getbalance", 1 }, { "getbalance", 2 }, { "getblockhash", 0 }, { "move", 2 }, { "move", 3 }, { "sendfrom", 2 }, { "sendfrom", 3 }, { "listtransactions", 1 }, { "listtransactions", 2 }, { "listtransactions", 3 }, { "listaccounts", 0 }, { "listaccounts", 1 }, { "walletpassphrase", 1 }, { "getblocktemplate", 0 }, { "listsinceblock", 1 }, { "listsinceblock", 2 }, { "sendmany", 1 }, { "sendmany", 2 }, { "sendmany", 4 }, { "aliaspay", 1 }, { "aliaspay", 2 }, { "addmultisigaddress", 0 }, { "addmultisigaddress", 1 }, { "createmultisig", 0 }, { "createmultisig", 1 }, { "listunspent", 0 }, { "listunspent", 1 }, { "listunspent", 2 }, { "getblock", 1 }, { "getblockheader", 1 }, { "gettransaction", 1 }, { "getrawtransaction", 1 }, { "createrawtransaction", 0 }, { "createrawtransaction", 1 }, { "createrawtransaction", 2 }, { "signrawtransaction", 1 }, { "signrawtransaction", 2 }, { "sendrawtransaction", 1 }, { "fundrawtransaction", 1 }, { "gettxout", 1 }, { "gettxout", 2 }, { "gettxoutproof", 0 }, { "lockunspent", 0 }, { "lockunspent", 1 }, { "importprivkey", 2 }, { "importaddress", 2 }, { "importaddress", 3 }, { "importpubkey", 2 }, { "verifychain", 0 }, { "verifychain", 1 }, { "keypoolrefill", 0 }, { "getrawmempool", 0 }, { "estimatefee", 0 }, { "estimatepriority", 0 }, { "estimatesmartfee", 0 }, { "estimatesmartpriority", 0 }, { "prioritisetransaction", 1 }, { "prioritisetransaction", 2 }, { "setban", 2 }, { "setban", 3 }, { "getmempoolancestors", 1 }, { "getmempooldescendants", 1 }, { "aliasnew", 9 }, { "aliasupdate", 10 }, { "offerlist", 0 }, }; class CRPCConvertTable { private: std::set<std::pair<std::string, int> > members; public: CRPCConvertTable(); bool convert(const std::string& method, int idx) { return (members.count(std::make_pair(method, idx)) > 0); } }; CRPCConvertTable::CRPCConvertTable() { const unsigned int n_elem = (sizeof(vRPCConvertParams) / sizeof(vRPCConvertParams[0])); for (unsigned int i = 0; i < n_elem; i++) { members.insert(std::make_pair(vRPCConvertParams[i].methodName, vRPCConvertParams[i].paramIdx)); } } static CRPCConvertTable rpcCvtTable; /** Non-RFC4627 JSON parser, accepts internal values (such as numbers, true, false, null) * as well as objects and arrays. */ UniValue ParseNonRFCJSONValue(const std::string& strVal) { UniValue jVal; if (!jVal.read(std::string("[")+strVal+std::string("]")) || !jVal.isArray() || jVal.size()!=1) throw runtime_error(string("Error parsing JSON:")+strVal); return jVal[0]; } /** Convert strings to command-specific RPC representation */ UniValue RPCConvertValues(const std::string &strMethod, const std::vector<std::string> &strParams) { UniValue params(UniValue::VARR); for (unsigned int idx = 0; idx < strParams.size(); idx++) { const std::string& strVal = strParams[idx]; if (!rpcCvtTable.convert(strMethod, idx)) { // insert string value directly params.push_back(strVal); } else { // parse string as JSON, insert bool/number/object/etc. value params.push_back(ParseNonRFCJSONValue(strVal)); } } return params; } <commit_msg>remove convert<commit_after>// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2015 The Syscoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "rpc/client.h" #include "rpc/protocol.h" #include "util.h" #include <set> #include <stdint.h> #include <boost/algorithm/string/case_conv.hpp> // for to_lower() #include <univalue.h> using namespace std; class CRPCConvertParam { public: std::string methodName; //!< method whose params want conversion int paramIdx; //!< 0-based idx of param to convert }; static const CRPCConvertParam vRPCConvertParams[] = { { "stop", 0 }, { "setmocktime", 0 }, { "getaddednodeinfo", 0 }, { "generate", 0 }, { "generate", 1 }, { "generatetoaddress", 0 }, { "generatetoaddress", 2 }, { "getnetworkhashps", 0 }, { "getnetworkhashps", 1 }, { "sendtoaddress", 1 }, { "sendtoaddress", 4 }, { "settxfee", 0 }, { "getreceivedbyaddress", 1 }, { "getreceivedbyaccount", 1 }, { "listreceivedbyaddress", 0 }, { "listreceivedbyaddress", 1 }, { "listreceivedbyaddress", 2 }, { "listreceivedbyaccount", 0 }, { "listreceivedbyaccount", 1 }, { "listreceivedbyaccount", 2 }, { "getbalance", 1 }, { "getbalance", 2 }, { "getblockhash", 0 }, { "move", 2 }, { "move", 3 }, { "sendfrom", 2 }, { "sendfrom", 3 }, { "listtransactions", 1 }, { "listtransactions", 2 }, { "listtransactions", 3 }, { "listaccounts", 0 }, { "listaccounts", 1 }, { "walletpassphrase", 1 }, { "getblocktemplate", 0 }, { "listsinceblock", 1 }, { "listsinceblock", 2 }, { "sendmany", 1 }, { "sendmany", 2 }, { "sendmany", 4 }, { "aliaspay", 1 }, { "aliaspay", 2 }, { "addmultisigaddress", 0 }, { "addmultisigaddress", 1 }, { "createmultisig", 0 }, { "createmultisig", 1 }, { "listunspent", 0 }, { "listunspent", 1 }, { "listunspent", 2 }, { "getblock", 1 }, { "getblockheader", 1 }, { "gettransaction", 1 }, { "getrawtransaction", 1 }, { "createrawtransaction", 0 }, { "createrawtransaction", 1 }, { "createrawtransaction", 2 }, { "signrawtransaction", 1 }, { "signrawtransaction", 2 }, { "sendrawtransaction", 1 }, { "fundrawtransaction", 1 }, { "gettxout", 1 }, { "gettxout", 2 }, { "gettxoutproof", 0 }, { "lockunspent", 0 }, { "lockunspent", 1 }, { "importprivkey", 2 }, { "importaddress", 2 }, { "importaddress", 3 }, { "importpubkey", 2 }, { "verifychain", 0 }, { "verifychain", 1 }, { "keypoolrefill", 0 }, { "getrawmempool", 0 }, { "estimatefee", 0 }, { "estimatepriority", 0 }, { "estimatesmartfee", 0 }, { "estimatesmartpriority", 0 }, { "prioritisetransaction", 1 }, { "prioritisetransaction", 2 }, { "setban", 2 }, { "setban", 3 }, { "getmempoolancestors", 1 }, { "getmempooldescendants", 1 }, { "aliasnew", 9 }, { "aliasupdate", 10 } }; class CRPCConvertTable { private: std::set<std::pair<std::string, int> > members; public: CRPCConvertTable(); bool convert(const std::string& method, int idx) { return (members.count(std::make_pair(method, idx)) > 0); } }; CRPCConvertTable::CRPCConvertTable() { const unsigned int n_elem = (sizeof(vRPCConvertParams) / sizeof(vRPCConvertParams[0])); for (unsigned int i = 0; i < n_elem; i++) { members.insert(std::make_pair(vRPCConvertParams[i].methodName, vRPCConvertParams[i].paramIdx)); } } static CRPCConvertTable rpcCvtTable; /** Non-RFC4627 JSON parser, accepts internal values (such as numbers, true, false, null) * as well as objects and arrays. */ UniValue ParseNonRFCJSONValue(const std::string& strVal) { UniValue jVal; if (!jVal.read(std::string("[")+strVal+std::string("]")) || !jVal.isArray() || jVal.size()!=1) throw runtime_error(string("Error parsing JSON:")+strVal); return jVal[0]; } /** Convert strings to command-specific RPC representation */ UniValue RPCConvertValues(const std::string &strMethod, const std::vector<std::string> &strParams) { UniValue params(UniValue::VARR); for (unsigned int idx = 0; idx < strParams.size(); idx++) { const std::string& strVal = strParams[idx]; if (!rpcCvtTable.convert(strMethod, idx)) { // insert string value directly params.push_back(strVal); } else { // parse string as JSON, insert bool/number/object/etc. value params.push_back(ParseNonRFCJSONValue(strVal)); } } return params; } <|endoftext|>
<commit_before>// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "rpc/client.h" #include "rpc/protocol.h" #include "util.h" #include <set> #include <stdint.h> #include <boost/algorithm/string/case_conv.hpp> // for to_lower() #include <univalue.h> using namespace std; class CRPCConvertParam { public: std::string methodName; //!< method whose params want conversion int paramIdx; //!< 0-based idx of param to convert }; static const CRPCConvertParam vRPCConvertParams[] = { { "stop", 0 }, { "setmocktime", 0 }, { "getaddednodeinfo", 0 }, { "generate", 0 }, { "generate", 1 }, { "generatetoaddress", 0 }, { "generatetoaddress", 2 }, { "getnetworkhashps", 0 }, { "getnetworkhashps", 1 }, { "sendtoaddress", 1 }, { "sendtoaddress", 4 }, { "settxfee", 0 }, { "getreceivedbyaddress", 1 }, { "getreceivedbyaccount", 1 }, { "listreceivedbyaddress", 0 }, { "listreceivedbyaddress", 1 }, { "listreceivedbyaddress", 2 }, { "listreceivedbyaccount", 0 }, { "listreceivedbyaccount", 1 }, { "listreceivedbyaccount", 2 }, { "getbalance", 1 }, { "getbalance", 2 }, { "getblockhash", 0 }, { "move", 2 }, { "move", 3 }, { "sendfrom", 2 }, { "sendfrom", 3 }, { "listtransactions", 1 }, { "listtransactions", 2 }, { "listtransactions", 3 }, { "listaccounts", 0 }, { "listaccounts", 1 }, { "walletpassphrase", 1 }, { "getblocktemplate", 0 }, { "listsinceblock", 1 }, { "listsinceblock", 2 }, { "sendmany", 1 }, { "sendmany", 2 }, { "sendmany", 4 }, { "addmultisigaddress", 0 }, { "addmultisigaddress", 1 }, { "createmultisig", 0 }, { "createmultisig", 1 }, { "listunspent", 0 }, { "listunspent", 1 }, { "listunspent", 2 }, { "getblock", 1 }, { "getblockheader", 1 }, { "gettransaction", 1 }, { "getrawtransaction", 1 }, { "createrawtransaction", 0 }, { "createrawtransaction", 1 }, { "createrawtransaction", 2 }, { "signrawtransaction", 1 }, { "signrawtransaction", 2 }, { "sendrawtransaction", 1 }, { "fundrawtransaction", 1 }, { "gettxout", 1 }, { "gettxout", 2 }, { "gettxoutproof", 0 }, { "lockunspent", 0 }, { "lockunspent", 1 }, { "importprivkey", 2 }, { "importaddress", 2 }, { "importaddress", 3 }, { "importpubkey", 2 }, { "verifychain", 0 }, { "verifychain", 1 }, { "keypoolrefill", 0 }, { "getrawmempool", 0 }, { "estimatefee", 0 }, { "estimatepriority", 0 }, { "estimatesmartfee", 0 }, { "estimatesmartpriority", 0 }, { "prioritisetransaction", 1 }, { "prioritisetransaction", 2 }, { "setban", 2 }, { "setban", 3 }, { "getmempoolancestors", 1 }, { "getmempooldescendants", 1 }, { "getblockhashes", 0 }, { "getblockhashes", 1 }, { "getspentinfo", 0}, { "getaddresstxids", 0}, { "getaddressbalance", 0}, { "getaddressdeltas", 0}, { "getaddressutxos", 0}, { "getaddressmempool", 0}, //[zcoin] { "setmininput", 0 }, { "mint", 0 }, { "mintzerocoin", 0 }, { "spendzerocoin", 0 }, { "spendmanyzerocoin", 0 }, { "spendmany", 1 }, { "spendmany", 2 }, { "spendmany", 4 }, { "setgenerate", 0 }, { "setgenerate", 1 }, { "setmintzerocoinstatus", 2 }, { "setmintzerocoinstatus", 1 }, { "listmintzerocoins", 0 }, { "listpubcoins", 0 }, { "listspendzerocoins", 0 }, { "listspendzerocoins", 1 }, { "spendallzerocoin", 0 }, /* Exodus - data retrieval calls */ { "exodus_gettradehistoryforaddress", 1 }, { "exodus_gettradehistoryforaddress", 2 }, { "exodus_gettradehistoryforpair", 0 }, { "exodus_gettradehistoryforpair", 1 }, { "exodus_gettradehistoryforpair", 2 }, { "exodus_setautocommit", 0 }, { "exodus_getcrowdsale", 0 }, { "exodus_getcrowdsale", 1 }, { "exodus_getgrants", 0 }, { "exodus_getbalance", 1 }, { "exodus_getproperty", 0 }, { "exodus_listtransactions", 1 }, { "exodus_listtransactions", 2 }, { "exodus_listtransactions", 3 }, { "exodus_listtransactions", 4 }, { "exodus_getallbalancesforid", 0 }, { "exodus_listblocktransactions", 0 }, { "exodus_getorderbook", 0 }, { "exodus_getorderbook", 1 }, { "exodus_getseedblocks", 0 }, { "exodus_getseedblocks", 1 }, { "exodus_getmetadexhash", 0 }, { "exodus_getfeecache", 0 }, { "exodus_getfeeshare", 1 }, { "exodus_getfeetrigger", 0 }, { "exodus_getfeedistribution", 0 }, { "exodus_getfeedistributions", 0 }, { "exodus_getbalanceshash", 0 }, /* Exodus - transaction calls */ { "exodus_send", 2 }, { "exodus_sendsto", 1 }, { "exodus_sendsto", 4 }, { "exodus_sendall", 2 }, { "exodus_sendtrade", 1 }, { "exodus_sendtrade", 3 }, { "exodus_sendcanceltradesbyprice", 1 }, { "exodus_sendcanceltradesbyprice", 3 }, { "exodus_sendcanceltradesbypair", 1 }, { "exodus_sendcanceltradesbypair", 2 }, { "exodus_sendcancelalltrades", 1 }, { "exodus_sendissuancefixed", 1 }, { "exodus_sendissuancefixed", 2 }, { "exodus_sendissuancefixed", 3 }, { "exodus_sendissuancemanaged", 1 }, { "exodus_sendissuancemanaged", 2 }, { "exodus_sendissuancemanaged", 3 }, { "exodus_sendissuancecrowdsale", 1 }, { "exodus_sendissuancecrowdsale", 2 }, { "exodus_sendissuancecrowdsale", 3 }, { "exodus_sendissuancecrowdsale", 9 }, { "exodus_sendissuancecrowdsale", 11 }, { "exodus_sendissuancecrowdsale", 12 }, { "exodus_sendissuancecrowdsale", 13 }, { "exodus_senddexsell", 1 }, { "exodus_senddexsell", 4 }, { "exodus_senddexsell", 6 }, { "exodus_senddexaccept", 2 }, { "exodus_senddexaccept", 4 }, { "exodus_sendclosecrowdsale", 1 }, { "exodus_sendgrant", 2 }, { "exodus_sendrevoke", 1 }, { "exodus_sendchangeissuer", 2 }, { "exodus_sendenablefreezing", 1 }, { "exodus_senddisablefreezing", 1 }, { "exodus_sendfreeze", 2 }, { "exodus_sendunfreeze", 2 }, { "exodus_senddeactivation", 1 }, { "exodus_sendactivation", 1 }, { "exodus_sendactivation", 2 }, { "exodus_sendactivation", 3 }, { "exodus_sendalert", 1 }, { "exodus_sendalert", 2 }, /* Exodus - raw transaction calls */ { "exodus_decodetransaction", 1 }, { "exodus_decodetransaction", 2 }, { "exodus_createrawtx_reference", 2 }, { "exodus_createrawtx_input", 2 }, { "exodus_createrawtx_change", 1 }, { "exodus_createrawtx_change", 3 }, { "exodus_createrawtx_change", 4 }, /* Exodus - payload creation */ { "exodus_createpayload_simplesend", 0 }, { "exodus_createpayload_sendall", 0 }, { "exodus_createpayload_dexsell", 0 }, { "exodus_createpayload_dexsell", 3 }, { "exodus_createpayload_dexsell", 5 }, { "exodus_createpayload_dexaccept", 0 }, { "exodus_createpayload_sto", 0 }, { "exodus_createpayload_sto", 2 }, { "exodus_createpayload_issuancefixed", 0 }, { "exodus_createpayload_issuancefixed", 1 }, { "exodus_createpayload_issuancefixed", 2 }, { "exodus_createpayload_issuancemanaged", 0 }, { "exodus_createpayload_issuancemanaged", 1 }, { "exodus_createpayload_issuancemanaged", 2 }, { "exodus_createpayload_issuancecrowdsale", 0 }, { "exodus_createpayload_issuancecrowdsale", 1 }, { "exodus_createpayload_issuancecrowdsale", 2 }, { "exodus_createpayload_issuancecrowdsale", 8 }, { "exodus_createpayload_issuancecrowdsale", 10 }, { "exodus_createpayload_issuancecrowdsale", 11 }, { "exodus_createpayload_issuancecrowdsale", 12 }, { "exodus_createpayload_closecrowdsale", 0 }, { "exodus_createpayload_grant", 0 }, { "exodus_createpayload_revoke", 0 }, { "exodus_createpayload_changeissuer", 0 }, { "exodus_createpayload_trade", 0 }, { "exodus_createpayload_trade", 2 }, { "exodus_createpayload_canceltradesbyprice", 0 }, { "exodus_createpayload_canceltradesbyprice", 2 }, { "exodus_createpayload_canceltradesbypair", 0 }, { "exodus_createpayload_canceltradesbypair", 1 }, { "exodus_createpayload_cancelalltrades", 0 }, /* Exodus - backwards compatibility */ { "getcrowdsale_MP", 0 }, { "getcrowdsale_MP", 1 }, { "getgrants_MP", 0 }, { "send_MP", 2 }, { "getbalance_MP", 1 }, { "sendtoowners_MP", 1 }, { "getproperty_MP", 0 }, { "listtransactions_MP", 1 }, { "listtransactions_MP", 2 }, { "listtransactions_MP", 3 }, { "listtransactions_MP", 4 }, { "getallbalancesforid_MP", 0 }, { "listblocktransactions_MP", 0 }, { "getorderbook_MP", 0 }, { "getorderbook_MP", 1 }, { "trade_MP", 1 }, // depreciated { "trade_MP", 3 }, // depreciated { "trade_MP", 5 }, // depreciated }; class CRPCConvertTable { private: std::set<std::pair<std::string, int> > members; public: CRPCConvertTable(); bool convert(const std::string& method, int idx) { return (members.count(std::make_pair(method, idx)) > 0); } }; CRPCConvertTable::CRPCConvertTable() { const unsigned int n_elem = (sizeof(vRPCConvertParams) / sizeof(vRPCConvertParams[0])); for (unsigned int i = 0; i < n_elem; i++) { members.insert(std::make_pair(vRPCConvertParams[i].methodName, vRPCConvertParams[i].paramIdx)); } } static CRPCConvertTable rpcCvtTable; /** Non-RFC4627 JSON parser, accepts internal values (such as numbers, true, false, null) * as well as objects and arrays. */ UniValue ParseNonRFCJSONValue(const std::string& strVal) { UniValue jVal; if (!jVal.read(std::string("[")+strVal+std::string("]")) || !jVal.isArray() || jVal.size()!=1) throw runtime_error(string("Error parsing JSON:")+strVal); return jVal[0]; } /** Convert strings to command-specific RPC representation */ UniValue RPCConvertValues(const std::string &strMethod, const std::vector<std::string> &strParams) { UniValue params(UniValue::VARR); for (unsigned int idx = 0; idx < strParams.size(); idx++) { const std::string& strVal = strParams[idx]; if (!rpcCvtTable.convert(strMethod, idx)) { // insert string value directly params.push_back(strVal); } else { // parse string as JSON, insert bool/number/object/etc. value params.push_back(ParseNonRFCJSONValue(strVal)); } } return params; } <commit_msg>Changes for RPC calls.<commit_after>// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "rpc/client.h" #include "rpc/protocol.h" #include "util.h" #include <set> #include <stdint.h> #include <boost/algorithm/string/case_conv.hpp> // for to_lower() #include <univalue.h> using namespace std; class CRPCConvertParam { public: std::string methodName; //!< method whose params want conversion int paramIdx; //!< 0-based idx of param to convert }; static const CRPCConvertParam vRPCConvertParams[] = { { "stop", 0 }, { "setmocktime", 0 }, { "getaddednodeinfo", 0 }, { "generate", 0 }, { "generate", 1 }, { "generatetoaddress", 0 }, { "generatetoaddress", 2 }, { "getnetworkhashps", 0 }, { "getnetworkhashps", 1 }, { "sendtoaddress", 1 }, { "sendtoaddress", 4 }, { "settxfee", 0 }, { "getreceivedbyaddress", 1 }, { "getreceivedbyaccount", 1 }, { "listreceivedbyaddress", 0 }, { "listreceivedbyaddress", 1 }, { "listreceivedbyaddress", 2 }, { "listreceivedbyaccount", 0 }, { "listreceivedbyaccount", 1 }, { "listreceivedbyaccount", 2 }, { "getbalance", 1 }, { "getbalance", 2 }, { "getblockhash", 0 }, { "move", 2 }, { "move", 3 }, { "sendfrom", 2 }, { "sendfrom", 3 }, { "listtransactions", 1 }, { "listtransactions", 2 }, { "listtransactions", 3 }, { "listaccounts", 0 }, { "listaccounts", 1 }, { "walletpassphrase", 1 }, { "getblocktemplate", 0 }, { "listsinceblock", 1 }, { "listsinceblock", 2 }, { "sendmany", 1 }, { "sendmany", 2 }, { "sendmany", 4 }, { "addmultisigaddress", 0 }, { "addmultisigaddress", 1 }, { "createmultisig", 0 }, { "createmultisig", 1 }, { "listunspent", 0 }, { "listunspent", 1 }, { "listunspent", 2 }, { "listunspentmintzerocoins", 0 }, { "listunspentmintzerocoins", 1 }, { "listunspentmintzerocoins", 2 }, { "listunspentsigmamints", 0 }, { "listunspentsigmamints", 1 }, { "listunspentsigmamints", 2 }, { "getblock", 1 }, { "getblockheader", 1 }, { "gettransaction", 1 }, { "getrawtransaction", 1 }, { "createrawtransaction", 0 }, { "createrawtransaction", 1 }, { "createrawtransaction", 2 }, { "signrawtransaction", 1 }, { "signrawtransaction", 2 }, { "sendrawtransaction", 1 }, { "fundrawtransaction", 1 }, { "gettxout", 1 }, { "gettxout", 2 }, { "gettxoutproof", 0 }, { "lockunspent", 0 }, { "lockunspent", 1 }, { "importprivkey", 2 }, { "importaddress", 2 }, { "importaddress", 3 }, { "importpubkey", 2 }, { "verifychain", 0 }, { "verifychain", 1 }, { "keypoolrefill", 0 }, { "getrawmempool", 0 }, { "estimatefee", 0 }, { "estimatepriority", 0 }, { "estimatesmartfee", 0 }, { "estimatesmartpriority", 0 }, { "prioritisetransaction", 1 }, { "prioritisetransaction", 2 }, { "setban", 2 }, { "setban", 3 }, { "getmempoolancestors", 1 }, { "getmempooldescendants", 1 }, { "getblockhashes", 0 }, { "getblockhashes", 1 }, { "getspentinfo", 0}, { "getaddresstxids", 0}, { "getaddressbalance", 0}, { "getaddressdeltas", 0}, { "getaddressutxos", 0}, { "getaddressmempool", 0}, //[zcoin] { "setmininput", 0 }, { "mint", 0 }, { "mintzerocoin", 0 }, { "spendzerocoin", 0 }, { "spendmanyzerocoin", 0 }, { "spendmany", 1 }, { "spendmany", 2 }, { "spendmany", 4 }, { "setgenerate", 0 }, { "setgenerate", 1 }, { "setmintzerocoinstatus", 2 }, { "setmintzerocoinstatus", 1 }, { "listmintzerocoins", 0 }, { "listsigmamints", 0 }, { "listpubcoins", 0 }, { "listsigmapubcoins", 0 }, { "listspendzerocoins", 0 }, { "listspendzerocoins", 1 }, { "listsigmaspends", 0 }, { "listsigmaspends", 1 }, { "spendallzerocoin", 0 }, /* Exodus - data retrieval calls */ { "exodus_gettradehistoryforaddress", 1 }, { "exodus_gettradehistoryforaddress", 2 }, { "exodus_gettradehistoryforpair", 0 }, { "exodus_gettradehistoryforpair", 1 }, { "exodus_gettradehistoryforpair", 2 }, { "exodus_setautocommit", 0 }, { "exodus_getcrowdsale", 0 }, { "exodus_getcrowdsale", 1 }, { "exodus_getgrants", 0 }, { "exodus_getbalance", 1 }, { "exodus_getproperty", 0 }, { "exodus_listtransactions", 1 }, { "exodus_listtransactions", 2 }, { "exodus_listtransactions", 3 }, { "exodus_listtransactions", 4 }, { "exodus_getallbalancesforid", 0 }, { "exodus_listblocktransactions", 0 }, { "exodus_getorderbook", 0 }, { "exodus_getorderbook", 1 }, { "exodus_getseedblocks", 0 }, { "exodus_getseedblocks", 1 }, { "exodus_getmetadexhash", 0 }, { "exodus_getfeecache", 0 }, { "exodus_getfeeshare", 1 }, { "exodus_getfeetrigger", 0 }, { "exodus_getfeedistribution", 0 }, { "exodus_getfeedistributions", 0 }, { "exodus_getbalanceshash", 0 }, /* Exodus - transaction calls */ { "exodus_send", 2 }, { "exodus_sendsto", 1 }, { "exodus_sendsto", 4 }, { "exodus_sendall", 2 }, { "exodus_sendtrade", 1 }, { "exodus_sendtrade", 3 }, { "exodus_sendcanceltradesbyprice", 1 }, { "exodus_sendcanceltradesbyprice", 3 }, { "exodus_sendcanceltradesbypair", 1 }, { "exodus_sendcanceltradesbypair", 2 }, { "exodus_sendcancelalltrades", 1 }, { "exodus_sendissuancefixed", 1 }, { "exodus_sendissuancefixed", 2 }, { "exodus_sendissuancefixed", 3 }, { "exodus_sendissuancemanaged", 1 }, { "exodus_sendissuancemanaged", 2 }, { "exodus_sendissuancemanaged", 3 }, { "exodus_sendissuancecrowdsale", 1 }, { "exodus_sendissuancecrowdsale", 2 }, { "exodus_sendissuancecrowdsale", 3 }, { "exodus_sendissuancecrowdsale", 9 }, { "exodus_sendissuancecrowdsale", 11 }, { "exodus_sendissuancecrowdsale", 12 }, { "exodus_sendissuancecrowdsale", 13 }, { "exodus_senddexsell", 1 }, { "exodus_senddexsell", 4 }, { "exodus_senddexsell", 6 }, { "exodus_senddexaccept", 2 }, { "exodus_senddexaccept", 4 }, { "exodus_sendclosecrowdsale", 1 }, { "exodus_sendgrant", 2 }, { "exodus_sendrevoke", 1 }, { "exodus_sendchangeissuer", 2 }, { "exodus_sendenablefreezing", 1 }, { "exodus_senddisablefreezing", 1 }, { "exodus_sendfreeze", 2 }, { "exodus_sendunfreeze", 2 }, { "exodus_senddeactivation", 1 }, { "exodus_sendactivation", 1 }, { "exodus_sendactivation", 2 }, { "exodus_sendactivation", 3 }, { "exodus_sendalert", 1 }, { "exodus_sendalert", 2 }, /* Exodus - raw transaction calls */ { "exodus_decodetransaction", 1 }, { "exodus_decodetransaction", 2 }, { "exodus_createrawtx_reference", 2 }, { "exodus_createrawtx_input", 2 }, { "exodus_createrawtx_change", 1 }, { "exodus_createrawtx_change", 3 }, { "exodus_createrawtx_change", 4 }, /* Exodus - payload creation */ { "exodus_createpayload_simplesend", 0 }, { "exodus_createpayload_sendall", 0 }, { "exodus_createpayload_dexsell", 0 }, { "exodus_createpayload_dexsell", 3 }, { "exodus_createpayload_dexsell", 5 }, { "exodus_createpayload_dexaccept", 0 }, { "exodus_createpayload_sto", 0 }, { "exodus_createpayload_sto", 2 }, { "exodus_createpayload_issuancefixed", 0 }, { "exodus_createpayload_issuancefixed", 1 }, { "exodus_createpayload_issuancefixed", 2 }, { "exodus_createpayload_issuancemanaged", 0 }, { "exodus_createpayload_issuancemanaged", 1 }, { "exodus_createpayload_issuancemanaged", 2 }, { "exodus_createpayload_issuancecrowdsale", 0 }, { "exodus_createpayload_issuancecrowdsale", 1 }, { "exodus_createpayload_issuancecrowdsale", 2 }, { "exodus_createpayload_issuancecrowdsale", 8 }, { "exodus_createpayload_issuancecrowdsale", 10 }, { "exodus_createpayload_issuancecrowdsale", 11 }, { "exodus_createpayload_issuancecrowdsale", 12 }, { "exodus_createpayload_closecrowdsale", 0 }, { "exodus_createpayload_grant", 0 }, { "exodus_createpayload_revoke", 0 }, { "exodus_createpayload_changeissuer", 0 }, { "exodus_createpayload_trade", 0 }, { "exodus_createpayload_trade", 2 }, { "exodus_createpayload_canceltradesbyprice", 0 }, { "exodus_createpayload_canceltradesbyprice", 2 }, { "exodus_createpayload_canceltradesbypair", 0 }, { "exodus_createpayload_canceltradesbypair", 1 }, { "exodus_createpayload_cancelalltrades", 0 }, /* Exodus - backwards compatibility */ { "getcrowdsale_MP", 0 }, { "getcrowdsale_MP", 1 }, { "getgrants_MP", 0 }, { "send_MP", 2 }, { "getbalance_MP", 1 }, { "sendtoowners_MP", 1 }, { "getproperty_MP", 0 }, { "listtransactions_MP", 1 }, { "listtransactions_MP", 2 }, { "listtransactions_MP", 3 }, { "listtransactions_MP", 4 }, { "getallbalancesforid_MP", 0 }, { "listblocktransactions_MP", 0 }, { "getorderbook_MP", 0 }, { "getorderbook_MP", 1 }, { "trade_MP", 1 }, // depreciated { "trade_MP", 3 }, // depreciated { "trade_MP", 5 }, // depreciated }; class CRPCConvertTable { private: std::set<std::pair<std::string, int> > members; public: CRPCConvertTable(); bool convert(const std::string& method, int idx) { return (members.count(std::make_pair(method, idx)) > 0); } }; CRPCConvertTable::CRPCConvertTable() { const unsigned int n_elem = (sizeof(vRPCConvertParams) / sizeof(vRPCConvertParams[0])); for (unsigned int i = 0; i < n_elem; i++) { members.insert(std::make_pair(vRPCConvertParams[i].methodName, vRPCConvertParams[i].paramIdx)); } } static CRPCConvertTable rpcCvtTable; /** Non-RFC4627 JSON parser, accepts internal values (such as numbers, true, false, null) * as well as objects and arrays. */ UniValue ParseNonRFCJSONValue(const std::string& strVal) { UniValue jVal; if (!jVal.read(std::string("[")+strVal+std::string("]")) || !jVal.isArray() || jVal.size()!=1) throw runtime_error(string("Error parsing JSON:")+strVal); return jVal[0]; } /** Convert strings to command-specific RPC representation */ UniValue RPCConvertValues(const std::string &strMethod, const std::vector<std::string> &strParams) { UniValue params(UniValue::VARR); for (unsigned int idx = 0; idx < strParams.size(); idx++) { const std::string& strVal = strParams[idx]; if (!rpcCvtTable.convert(strMethod, idx)) { // insert string value directly params.push_back(strVal); } else { // parse string as JSON, insert bool/number/object/etc. value params.push_back(ParseNonRFCJSONValue(strVal)); } } return params; } <|endoftext|>
<commit_before>/* -------------------------------------------------------------------------- */ /* Copyright 2002-2018, OpenNebula Project, OpenNebula Systems */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); you may */ /* not use this file except in compliance with the License. You may obtain */ /* a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ /* See the License for the specific language governing permissions and */ /* limitations under the License. */ /* -------------------------------------------------------------------------- */ #include "RequestManagerRename.h" #include "PoolObjectSQL.h" #include "NebulaLog.h" #include "Nebula.h" /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ void RequestManagerRename::request_execute(xmlrpc_c::paramList const& paramList, RequestAttributes& att) { int oid = xmlrpc_c::value_int(paramList.getInt(1)); string new_name = xmlrpc_c::value_string(paramList.getString(2)); int rc; string old_name; PoolObjectAuth operms; PoolObjectSQL * object; if (test_and_set_rename(oid) == false) { att.resp_msg = "Object is being renamed"; failure_response(INTERNAL, att); return; } rc = get_info(pool, oid, auth_object, att, operms, old_name, true); if ( rc == -1 ) { clear_rename(oid); return; } if (old_name == new_name) { success_response(oid, att); clear_rename(oid); return; } // ------------- Set authorization request for non-oneadmin's -------------- if ( att.uid != 0 ) { AuthRequest ar(att.uid, att.group_ids); ar.add_auth(auth_op, operms); // MANAGE OBJECT if (UserPool::authorize(ar) == -1) { att.resp_msg = ar.message; failure_response(AUTHORIZATION, att); clear_rename(oid); return; } } // ----------------------- Check name uniqueness --------------------------- int db_id = exist(new_name, operms.uid); if ( db_id !=-1 ) { ostringstream oss; oss << object_name(auth_object) << " cannot be renamed to " << new_name << " because it collides with " << object_name(auth_object) << " " << db_id; att.resp_msg = oss.str(); failure_response(ACTION, att); clear_rename(oid); return; } // -------------------------- Update the object ---------------------------- object = pool->get(oid); if ( object == 0 ) { att.resp_id = oid; failure_response(NO_EXISTS, att); clear_rename(oid); return; } if ( object->set_name(new_name, att.resp_msg) != 0 ) { object->unlock(); failure_response(ACTION, att); clear_rename(oid); return; } pool->update(object); object->unlock(); batch_rename(oid); success_response(oid, att); clear_rename(oid); return; } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ void ClusterRename::batch_rename(int oid) { Cluster * cluster = static_cast<ClusterPool *>(pool)->get(oid); if (cluster == 0) { return; } const set<int> & hosts = cluster->get_host_ids(); string cluster_name = cluster->get_name(); cluster->unlock(); Host * host; HostPool* hpool = Nebula::instance().get_hpool(); for (set<int>::iterator it = hosts.begin(); it != hosts.end(); it++) { host = hpool->get(*it); if (host != 0) { if (host->get_cluster_id() == oid) { host->set_cluster(oid, cluster_name); hpool->update(host); } host->unlock(); } } } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ void DatastoreRename::batch_rename(int oid) { Datastore * datastore = static_cast<DatastorePool*>(pool)->get(oid); if (datastore == 0) { return; } const set<int> & images = datastore->get_image_ids(); set<int>::iterator it; string image_name = datastore->get_name(); datastore->unlock(); Image * image; ImagePool * ipool = Nebula::instance().get_ipool(); for (it = images.begin(); it != images.end(); it++) { image = ipool->get(*it); if (image != 0) { if (image->get_ds_id() == oid) { image->set_ds_name(image_name); ipool->update(image); } image->unlock(); } } } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ void HostRename::batch_rename(int oid) { Host * host = static_cast<HostPool*>(pool)->get(oid); if (host == 0) { return; } const set<int> & vms = host->get_vm_ids(); set<int>::iterator it; string host_name = host->get_name(); host->unlock(); VirtualMachine * vm; VirtualMachinePool * vmpool = Nebula::instance().get_vmpool(); for (it = vms.begin(); it != vms.end(); it++) { vm = vmpool->get(*it); if (vm != 0) { if (vm->hasHistory() && vm->get_hid() == oid) { vm->set_hostname(host_name); vmpool->update(vm); } vm->unlock(); } } } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ void MarketPlaceRename::batch_rename(int oid) { MarketPlace * market = static_cast<MarketPlacePool*>(pool)->get(oid); if (market == 0) { return; } const std::set<int> & apps = market->get_marketapp_ids(); std::set<int>::iterator it; std::string market_name = market->get_name(); market->unlock(); MarketPlaceApp * app; MarketPlaceAppPool * apppool = Nebula::instance().get_apppool(); for (it = apps.begin(); it != apps.end(); it++) { app = apppool->get(*it); if (app != 0) { if (app->get_market_id() == oid) { app->set_market_name(market_name); apppool->update(app); } app->unlock(); } } } <commit_msg>B #1893: Fixed bug when update hostname (#1894)<commit_after>/* -------------------------------------------------------------------------- */ /* Copyright 2002-2018, OpenNebula Project, OpenNebula Systems */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); you may */ /* not use this file except in compliance with the License. You may obtain */ /* a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ /* See the License for the specific language governing permissions and */ /* limitations under the License. */ /* -------------------------------------------------------------------------- */ #include "RequestManagerRename.h" #include "PoolObjectSQL.h" #include "NebulaLog.h" #include "Nebula.h" /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ void RequestManagerRename::request_execute(xmlrpc_c::paramList const& paramList, RequestAttributes& att) { int oid = xmlrpc_c::value_int(paramList.getInt(1)); string new_name = xmlrpc_c::value_string(paramList.getString(2)); int rc; string old_name; PoolObjectAuth operms; PoolObjectSQL * object; if (test_and_set_rename(oid) == false) { att.resp_msg = "Object is being renamed"; failure_response(INTERNAL, att); return; } rc = get_info(pool, oid, auth_object, att, operms, old_name, true); if ( rc == -1 ) { clear_rename(oid); return; } if (old_name == new_name) { success_response(oid, att); clear_rename(oid); return; } // ------------- Set authorization request for non-oneadmin's -------------- if ( att.uid != 0 ) { AuthRequest ar(att.uid, att.group_ids); ar.add_auth(auth_op, operms); // MANAGE OBJECT if (UserPool::authorize(ar) == -1) { att.resp_msg = ar.message; failure_response(AUTHORIZATION, att); clear_rename(oid); return; } } // ----------------------- Check name uniqueness --------------------------- int db_id = exist(new_name, operms.uid); if ( db_id !=-1 ) { ostringstream oss; oss << object_name(auth_object) << " cannot be renamed to " << new_name << " because it collides with " << object_name(auth_object) << " " << db_id; att.resp_msg = oss.str(); failure_response(ACTION, att); clear_rename(oid); return; } // -------------------------- Update the object ---------------------------- object = pool->get(oid); if ( object == 0 ) { att.resp_id = oid; failure_response(NO_EXISTS, att); clear_rename(oid); return; } if ( object->set_name(new_name, att.resp_msg) != 0 ) { object->unlock(); failure_response(ACTION, att); clear_rename(oid); return; } pool->update(object); object->unlock(); batch_rename(oid); success_response(oid, att); clear_rename(oid); return; } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ void ClusterRename::batch_rename(int oid) { Cluster * cluster = static_cast<ClusterPool *>(pool)->get(oid); if (cluster == 0) { return; } const set<int> & hosts = cluster->get_host_ids(); string cluster_name = cluster->get_name(); cluster->unlock(); Host * host; HostPool* hpool = Nebula::instance().get_hpool(); for (set<int>::iterator it = hosts.begin(); it != hosts.end(); it++) { host = hpool->get(*it); if (host != 0) { if (host->get_cluster_id() == oid) { host->set_cluster(oid, cluster_name); hpool->update(host); } host->unlock(); } } } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ void DatastoreRename::batch_rename(int oid) { Datastore * datastore = static_cast<DatastorePool*>(pool)->get(oid); if (datastore == 0) { return; } const set<int> & images = datastore->get_image_ids(); set<int>::iterator it; string image_name = datastore->get_name(); datastore->unlock(); Image * image; ImagePool * ipool = Nebula::instance().get_ipool(); for (it = images.begin(); it != images.end(); it++) { image = ipool->get(*it); if (image != 0) { if (image->get_ds_id() == oid) { image->set_ds_name(image_name); ipool->update(image); } image->unlock(); } } } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ void HostRename::batch_rename(int oid) { Host * host = static_cast<HostPool*>(pool)->get(oid); if (host == 0) { return; } const set<int> & vms = host->get_vm_ids(); set<int>::iterator it; string host_name = host->get_name(); host->unlock(); VirtualMachine * vm; VirtualMachinePool * vmpool = Nebula::instance().get_vmpool(); for (it = vms.begin(); it != vms.end(); it++) { vm = vmpool->get(*it); if (vm != 0) { if (vm->hasHistory() && vm->get_hid() == oid) { vm->set_hostname(host_name); vmpool->update_history(vm); } vm->unlock(); } } } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ void MarketPlaceRename::batch_rename(int oid) { MarketPlace * market = static_cast<MarketPlacePool*>(pool)->get(oid); if (market == 0) { return; } const std::set<int> & apps = market->get_marketapp_ids(); std::set<int>::iterator it; std::string market_name = market->get_name(); market->unlock(); MarketPlaceApp * app; MarketPlaceAppPool * apppool = Nebula::instance().get_apppool(); for (it = apps.begin(); it != apps.end(); it++) { app = apppool->get(*it); if (app != 0) { if (app->get_market_id() == oid) { app->set_market_name(market_name); apppool->update(app); } app->unlock(); } } } <|endoftext|>
<commit_before>/************************************************************************** ** ** Copyright (C) 2012, 2013 BlackBerry Limited. All rights reserved ** ** Contact: BlackBerry ([email protected]) ** Contact: KDAB ([email protected]) ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "qnxutils.h" #include "qnxabstractqtversion.h" #include <utils/hostosinfo.h> #include <QDir> #include <QDesktopServices> #include <QDomDocument> using namespace Qnx; using namespace Qnx::Internal; QString QnxUtils::addQuotes(const QString &string) { return QLatin1Char('"') + string + QLatin1Char('"'); } Qnx::QnxArchitecture QnxUtils::cpudirToArch(const QString &cpuDir) { if (cpuDir == QLatin1String("x86")) return Qnx::X86; else if (cpuDir == QLatin1String("armle-v7")) return Qnx::ArmLeV7; else return Qnx::UnknownArch; } QStringList QnxUtils::searchPaths(QnxAbstractQtVersion *qtVersion) { const QDir pluginDir(qtVersion->versionInfo().value(QLatin1String("QT_INSTALL_PLUGINS"))); const QStringList pluginSubDirs = pluginDir.entryList(QDir::Dirs | QDir::NoDotAndDotDot); QStringList searchPaths; Q_FOREACH (const QString &dir, pluginSubDirs) { searchPaths << qtVersion->versionInfo().value(QLatin1String("QT_INSTALL_PLUGINS")) + QLatin1Char('/') + dir; } searchPaths << qtVersion->versionInfo().value(QLatin1String("QT_INSTALL_LIBS")); searchPaths << qtVersion->qnxTarget() + QLatin1Char('/') + qtVersion->archString().toLower() + QLatin1String("/lib"); searchPaths << qtVersion->qnxTarget() + QLatin1Char('/') + qtVersion->archString().toLower() + QLatin1String("/usr/lib"); return searchPaths; } QList<Utils::EnvironmentItem> QnxUtils::qnxEnvironmentFromNdkFile(const QString &fileName) { QList <Utils::EnvironmentItem> items; QFile file(fileName); if (!file.open(QIODevice::ReadOnly)) return items; QTextStream str(&file); QMap<QString, QString> fileContent; while (!str.atEnd()) { QString line = str.readLine(); if (!line.contains(QLatin1Char('='))) continue; int equalIndex = line.indexOf(QLatin1Char('=')); QString var = line.left(equalIndex); //Remove set in front if (var.startsWith(QLatin1String("set "))) var = var.right(var.size() - 4); QString value = line.mid(equalIndex + 1); // BASE_DIR (and BASE_DIR_REPLACED in some recent internal versions) variable is // evaluated when souring the bbnk-env script // BASE_DIR="$( cd "$(dirname "${BASH_SOURCE[0]}" )" && pwd )" // We already know the NDK path so we can set the variable value // TODO: Do not parse bbnk-env! if (var == QLatin1String("BASE_DIR") || var == QLatin1String("BASE_DIR_REPLACED")) value = QFileInfo(fileName).dir().absolutePath(); // LATEST_LINUX_JRE is evaluated when sourcing the file script // TODO: run the script and get environment instead of parsing it(?) if (var == QLatin1String("LATEST_LINUX_JRE")) continue; if (Utils::HostOsInfo::isWindowsHost()) { QRegExp systemVarRegExp(QLatin1String("IF NOT DEFINED ([\\w\\d]+)\\s+set ([\\w\\d]+)=([\\w\\d]+)")); if (line.contains(systemVarRegExp)) { var = systemVarRegExp.cap(2); Utils::Environment sysEnv = Utils::Environment::systemEnvironment(); QString sysVar = systemVarRegExp.cap(1); if (sysEnv.hasKey(sysVar)) value = sysEnv.value(sysVar); else value = systemVarRegExp.cap(3); } } else if (Utils::HostOsInfo::isAnyUnixHost()) { QRegExp systemVarRegExp(QLatin1String("\\$\\{([\\w\\d]+):=([\\w\\d]+)\\}")); // to match e.g. "${QNX_HOST_VERSION:=10_0_9_52}" if (value.contains(systemVarRegExp)) { Utils::Environment sysEnv = Utils::Environment::systemEnvironment(); QString sysVar = systemVarRegExp.cap(1); if (sysEnv.hasKey(sysVar)) value = sysEnv.value(sysVar); else value = systemVarRegExp.cap(2); } } if (value.startsWith(QLatin1Char('"'))) value = value.mid(1); if (value.endsWith(QLatin1Char('"'))) value = value.left(value.size() - 1); fileContent[var] = value; } file.close(); QMapIterator<QString, QString> it(fileContent); while (it.hasNext()) { it.next(); QStringList values; if (Utils::HostOsInfo::isWindowsHost()) values = it.value().split(QLatin1Char(';')); else if (Utils::HostOsInfo::isAnyUnixHost()) values = it.value().split(QLatin1Char(':')); QString key = it.key(); QStringList modifiedValues; foreach (const QString &value, values) { const QString ownKeyAsWindowsVar = QLatin1Char('%') + key + QLatin1Char('%'); const QString ownKeyAsUnixVar = QLatin1Char('$') + key; if (value == ownKeyAsUnixVar) { // e.g. $PATH ==> ${PATH} QString val = key; val.prepend(QLatin1String("${")); val.append(QLatin1Char('}')); modifiedValues.append(val); } else if (value == ownKeyAsWindowsVar) { modifiedValues.append(value); } else { if (value.contains(QLatin1String("LATEST_LINUX_JRE"))) // Skip evaluated LATEST_LINUX_JRE variable continue; QString val = value; if (val.contains(QLatin1Char('%')) || val.contains(QLatin1Char('$'))) { QMapIterator<QString, QString> replaceIt(fileContent); while (replaceIt.hasNext()) { replaceIt.next(); const QString replaceKey = replaceIt.key(); if (replaceKey == key) continue; const QString keyAsWindowsVar = QLatin1Char('%') + replaceKey + QLatin1Char('%'); const QString keyAsUnixVar = QLatin1Char('$') + replaceKey; if (val.contains(keyAsWindowsVar)) val.replace(keyAsWindowsVar, replaceIt.value()); if (val.contains(keyAsUnixVar)) val.replace(keyAsUnixVar, replaceIt.value()); } } // This variable will be properly set based on the qt version architecture if (key == QLatin1String("CPUVARDIR")) continue; modifiedValues.append(val); } } items.append(Utils::EnvironmentItem(key, modifiedValues.join(QString(Utils::HostOsInfo::pathListSeparator())))); } return items; } bool QnxUtils::isValidNdkPath(const QString &ndkPath) { return (QFileInfo(envFilePath(ndkPath)).exists()); } QString QnxUtils::envFilePath(const QString &ndkPath, const QString &targetVersion) { QString envFile; if (Utils::HostOsInfo::isWindowsHost()) envFile = ndkPath + QLatin1String("/bbndk-env.bat"); else if (Utils::HostOsInfo::isAnyUnixHost()) envFile = ndkPath + QLatin1String("/bbndk-env.sh"); if (!QFileInfo(envFile).exists()) { QString version = targetVersion.isEmpty() ? defaultTargetVersion(ndkPath) : targetVersion; version = version.replace(QLatin1Char('.'), QLatin1Char('_')); if (Utils::HostOsInfo::isWindowsHost()) envFile = ndkPath + QLatin1String("/bbndk-env_") + version + QLatin1String(".bat"); else if (Utils::HostOsInfo::isAnyUnixHost()) envFile = ndkPath + QLatin1String("/bbndk-env_") + version + QLatin1String(".sh"); } return envFile; } Utils::FileName QnxUtils::executableWithExtension(const Utils::FileName &fileName) { Utils::FileName result = fileName; if (Utils::HostOsInfo::isWindowsHost()) result.append(QLatin1String(".exe")); return result; } QString QnxUtils::dataDirPath() { const QString homeDir = QDir::homePath(); if (Utils::HostOsInfo::isMacHost()) return homeDir + QLatin1String("/Library/Research in Motion"); if (Utils::HostOsInfo::isAnyUnixHost()) return homeDir + QLatin1String("/.rim"); if (Utils::HostOsInfo::isWindowsHost()) { // Get the proper storage location on Windows using QDesktopServices, // to not hardcode "AppData/Local", as it might refer to "AppData/Roaming". QString dataDir = QDesktopServices::storageLocation(QDesktopServices::DataLocation); dataDir = dataDir.left(dataDir.indexOf(QCoreApplication::organizationName())); dataDir.append(QLatin1String("Research in Motion")); return dataDir; } return QString(); } QString QnxUtils::qConfigPath() { if (Utils::HostOsInfo::isMacHost() || Utils::HostOsInfo::isWindowsHost()) { return dataDirPath() + QLatin1String("/BlackBerry Native SDK/qconfig"); } else { return dataDirPath() + QLatin1String("/bbndk/qconfig"); } } QString QnxUtils::defaultTargetVersion(const QString &ndkPath) { foreach (const NdkInstallInformation &ndkInfo, installedNdks()) { if (!ndkInfo.path.compare(ndkPath, Utils::HostOsInfo::fileNameCaseSensitivity())) return ndkInfo.version; } return QString(); } QList<NdkInstallInformation> QnxUtils::installedNdks() { QList<NdkInstallInformation> ndkList; QString ndkConfigPath = qConfigPath(); if (!QDir(ndkConfigPath).exists()) return ndkList; QFileInfoList ndkfileList = QDir(ndkConfigPath).entryInfoList(QStringList() << QLatin1String("*.xml"), QDir::Files, QDir::Time); foreach (const QFileInfo &ndkFile, ndkfileList) { QFile xmlFile(ndkFile.absoluteFilePath()); if (!xmlFile.open(QIODevice::ReadOnly)) continue; QDomDocument doc; if (!doc.setContent(&xmlFile)) // Skip error message continue; QDomElement docElt = doc.documentElement(); if (docElt.tagName() != QLatin1String("qnxSystemDefinition")) continue; QDomElement childElt = docElt.firstChildElement(QLatin1String("installation")); // The file contains only one installation node if (!childElt.isNull()) { // The file contains only one base node NdkInstallInformation ndkInfo; ndkInfo.path = childElt.firstChildElement(QLatin1String("base")).text(); ndkInfo.name = childElt.firstChildElement(QLatin1String("name")).text(); ndkInfo.host = childElt.firstChildElement(QLatin1String("host")).text(); ndkInfo.target = childElt.firstChildElement(QLatin1String("target")).text(); ndkInfo.version = childElt.firstChildElement(QLatin1String("version")).text(); ndkList.append(ndkInfo); } } return ndkList; } QString QnxUtils::sdkInstallerPath(const QString &ndkPath) { QString sdkinstallPath; if (Utils::HostOsInfo::isWindowsHost()) sdkinstallPath = ndkPath + QLatin1String("/qde.exe"); else sdkinstallPath = ndkPath + QLatin1String("/qde"); if (QFileInfo(sdkinstallPath).exists()) return sdkinstallPath; return QString(); } // The resulting process when launching sdkinstall QString QnxUtils::qdeInstallProcess(const QString &ndkPath, const QString &option, const QString &version) { QString installerPath = sdkInstallerPath(ndkPath); if (ndkPath.isEmpty()) return QString(); return QString::fromLatin1("%1 -nosplash -application com.qnx.tools.ide.sdk.manager.core.SDKInstallerApplication " "%2 %3 -vmargs -Dosgi.console=:none").arg(installerPath, option, version); } QList<Utils::EnvironmentItem> QnxUtils::qnxEnvironment(const QString &sdkPath) { // Mimic what the SDP installer puts into the system environment QList<Utils::EnvironmentItem> environmentItems; if (Utils::HostOsInfo::isWindowsHost()) { // TODO: //environment.insert(QLatin1String("QNX_CONFIGURATION"), QLatin1String("/etc/qnx")); environmentItems.append(Utils::EnvironmentItem(QLatin1String(Constants::QNX_TARGET_KEY), sdkPath + QLatin1String("/target/qnx6"))); environmentItems.append(Utils::EnvironmentItem(QLatin1String(Constants::QNX_HOST_KEY), sdkPath + QLatin1String("/host/win32/x86"))); environmentItems.append(Utils::EnvironmentItem(QLatin1String("PATH"), sdkPath + QLatin1String("/host/win32/x86/usr/bin;%PATH%"))); // TODO: //environment.insert(QLatin1String("PATH"), QLatin1String("/etc/qnx/bin")); } else if (Utils::HostOsInfo::isAnyUnixHost()) { environmentItems.append(Utils::EnvironmentItem(QLatin1String("QNX_CONFIGURATION"), QLatin1String("/etc/qnx"))); environmentItems.append(Utils::EnvironmentItem(QLatin1String(Constants::QNX_TARGET_KEY), sdkPath + QLatin1String("/target/qnx6"))); environmentItems.append(Utils::EnvironmentItem(QLatin1String(Constants::QNX_HOST_KEY), sdkPath + QLatin1String("/host/linux/x86"))); environmentItems.append(Utils::EnvironmentItem(QLatin1String("PATH"), sdkPath + QLatin1String("/host/linux/x86/usr/bin:/etc/qnx/bin:${PATH}"))); environmentItems.append(Utils::EnvironmentItem(QLatin1String("LD_LIBRARY_PATH"), sdkPath + QLatin1String("/host/linux/x86/usr/lib:${LD_LIBRARY_PATH}"))); } environmentItems.append(Utils::EnvironmentItem(QLatin1String("QNX_JAVAHOME"), sdkPath + QLatin1String("/_jvm"))); environmentItems.append(Utils::EnvironmentItem(QLatin1String("MAKEFLAGS"), QLatin1String("-I") + sdkPath + QLatin1String("/target/qnx6/usr/include"))); return environmentItems; } <commit_msg>Qnx: executing instead of parsing bbndk-env script file<commit_after>/************************************************************************** ** ** Copyright (C) 2012, 2013 BlackBerry Limited. All rights reserved ** ** Contact: BlackBerry ([email protected]) ** Contact: KDAB ([email protected]) ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "qnxutils.h" #include "qnxabstractqtversion.h" #include <utils/hostosinfo.h> #include <utils/synchronousprocess.h> #include <QDir> #include <QDesktopServices> #include <QDomDocument> #include <QProcess> #include <QTemporaryFile> #include <QApplication> using namespace Qnx; using namespace Qnx::Internal; namespace { const char *EVAL_ENV_VARS[] = { "QNX_TARGET", "QNX_HOST", "QNX_CONFIGURATION", "MAKEFLAGS", "LD_LIBRARY_PATH", "PATH", "QDE", "CPUVARDIR", "PYTHONPATH" }; } QString QnxUtils::addQuotes(const QString &string) { return QLatin1Char('"') + string + QLatin1Char('"'); } Qnx::QnxArchitecture QnxUtils::cpudirToArch(const QString &cpuDir) { if (cpuDir == QLatin1String("x86")) return Qnx::X86; else if (cpuDir == QLatin1String("armle-v7")) return Qnx::ArmLeV7; else return Qnx::UnknownArch; } QStringList QnxUtils::searchPaths(QnxAbstractQtVersion *qtVersion) { const QDir pluginDir(qtVersion->versionInfo().value(QLatin1String("QT_INSTALL_PLUGINS"))); const QStringList pluginSubDirs = pluginDir.entryList(QDir::Dirs | QDir::NoDotAndDotDot); QStringList searchPaths; Q_FOREACH (const QString &dir, pluginSubDirs) { searchPaths << qtVersion->versionInfo().value(QLatin1String("QT_INSTALL_PLUGINS")) + QLatin1Char('/') + dir; } searchPaths << qtVersion->versionInfo().value(QLatin1String("QT_INSTALL_LIBS")); searchPaths << qtVersion->qnxTarget() + QLatin1Char('/') + qtVersion->archString().toLower() + QLatin1String("/lib"); searchPaths << qtVersion->qnxTarget() + QLatin1Char('/') + qtVersion->archString().toLower() + QLatin1String("/usr/lib"); return searchPaths; } QList<Utils::EnvironmentItem> QnxUtils::qnxEnvironmentFromNdkFile(const QString &fileName) { QList <Utils::EnvironmentItem> items; if (!QFileInfo(fileName).exists()) return items; const bool isWindows = Utils::HostOsInfo::isWindowsHost(); // locking creating bbndk-env file wrapper script QTemporaryFile tmpFile( QDir::tempPath() + QDir::separator() + QLatin1String("bbndk-env-eval-XXXXXX") + QLatin1String(isWindows ? ".bat" : ".sh")); if (!tmpFile.open()) return items; tmpFile.setTextModeEnabled(true); // writing content to wrapper script QTextStream fileContent(&tmpFile); if (isWindows) fileContent << QLatin1String("@echo off\n") << QLatin1String("call ") << fileName << QLatin1Char('\n'); else fileContent << QLatin1String("#!/bin/bash\n") << QLatin1String(". ") << fileName << QLatin1Char('\n'); QString linePattern = QString::fromLatin1(isWindows ? "echo %1=%%1%" : "echo %1=$%1"); for (int i = 0, len = sizeof(EVAL_ENV_VARS) / sizeof(const char *); i < len; ++i) fileContent << linePattern.arg(QLatin1String(EVAL_ENV_VARS[i])) << QLatin1Char('\n'); tmpFile.close(); // running wrapper script QProcess process; if (isWindows) process.start(QLatin1String("cmd.exe"), QStringList() << QLatin1String("/C") << tmpFile.fileName()); else process.start(QLatin1String("/bin/bash"), QStringList() << tmpFile.fileName()); // waiting for finish QApplication::setOverrideCursor(Qt::BusyCursor); bool waitResult = process.waitForFinished(10000); QApplication::restoreOverrideCursor(); if (!waitResult) { Utils::SynchronousProcess::stopProcess(process); return items; } if (process.exitStatus() != QProcess::NormalExit || process.exitCode() != 0) return items; // parsing process output QTextStream str(&process); while (!str.atEnd()) { QString line = str.readLine(); int equalIndex = line.indexOf(QLatin1Char('=')); if (equalIndex < 0) continue; QString var = line.left(equalIndex); QString value = line.mid(equalIndex + 1); items.append(Utils::EnvironmentItem(var, value)); } return items; } bool QnxUtils::isValidNdkPath(const QString &ndkPath) { return (QFileInfo(envFilePath(ndkPath)).exists()); } QString QnxUtils::envFilePath(const QString &ndkPath, const QString &targetVersion) { QString envFile; if (Utils::HostOsInfo::isWindowsHost()) envFile = ndkPath + QLatin1String("/bbndk-env.bat"); else if (Utils::HostOsInfo::isAnyUnixHost()) envFile = ndkPath + QLatin1String("/bbndk-env.sh"); if (!QFileInfo(envFile).exists()) { QString version = targetVersion.isEmpty() ? defaultTargetVersion(ndkPath) : targetVersion; version = version.replace(QLatin1Char('.'), QLatin1Char('_')); if (Utils::HostOsInfo::isWindowsHost()) envFile = ndkPath + QLatin1String("/bbndk-env_") + version + QLatin1String(".bat"); else if (Utils::HostOsInfo::isAnyUnixHost()) envFile = ndkPath + QLatin1String("/bbndk-env_") + version + QLatin1String(".sh"); } return envFile; } Utils::FileName QnxUtils::executableWithExtension(const Utils::FileName &fileName) { Utils::FileName result = fileName; if (Utils::HostOsInfo::isWindowsHost()) result.append(QLatin1String(".exe")); return result; } QString QnxUtils::dataDirPath() { const QString homeDir = QDir::homePath(); if (Utils::HostOsInfo::isMacHost()) return homeDir + QLatin1String("/Library/Research in Motion"); if (Utils::HostOsInfo::isAnyUnixHost()) return homeDir + QLatin1String("/.rim"); if (Utils::HostOsInfo::isWindowsHost()) { // Get the proper storage location on Windows using QDesktopServices, // to not hardcode "AppData/Local", as it might refer to "AppData/Roaming". QString dataDir = QDesktopServices::storageLocation(QDesktopServices::DataLocation); dataDir = dataDir.left(dataDir.indexOf(QCoreApplication::organizationName())); dataDir.append(QLatin1String("Research in Motion")); return dataDir; } return QString(); } QString QnxUtils::qConfigPath() { if (Utils::HostOsInfo::isMacHost() || Utils::HostOsInfo::isWindowsHost()) { return dataDirPath() + QLatin1String("/BlackBerry Native SDK/qconfig"); } else { return dataDirPath() + QLatin1String("/bbndk/qconfig"); } } QString QnxUtils::defaultTargetVersion(const QString &ndkPath) { foreach (const NdkInstallInformation &ndkInfo, installedNdks()) { if (!ndkInfo.path.compare(ndkPath, Utils::HostOsInfo::fileNameCaseSensitivity())) return ndkInfo.version; } return QString(); } QList<NdkInstallInformation> QnxUtils::installedNdks() { QList<NdkInstallInformation> ndkList; QString ndkConfigPath = qConfigPath(); if (!QDir(ndkConfigPath).exists()) return ndkList; QFileInfoList ndkfileList = QDir(ndkConfigPath).entryInfoList(QStringList() << QLatin1String("*.xml"), QDir::Files, QDir::Time); foreach (const QFileInfo &ndkFile, ndkfileList) { QFile xmlFile(ndkFile.absoluteFilePath()); if (!xmlFile.open(QIODevice::ReadOnly)) continue; QDomDocument doc; if (!doc.setContent(&xmlFile)) // Skip error message continue; QDomElement docElt = doc.documentElement(); if (docElt.tagName() != QLatin1String("qnxSystemDefinition")) continue; QDomElement childElt = docElt.firstChildElement(QLatin1String("installation")); // The file contains only one installation node if (!childElt.isNull()) { // The file contains only one base node NdkInstallInformation ndkInfo; ndkInfo.path = childElt.firstChildElement(QLatin1String("base")).text(); ndkInfo.name = childElt.firstChildElement(QLatin1String("name")).text(); ndkInfo.host = childElt.firstChildElement(QLatin1String("host")).text(); ndkInfo.target = childElt.firstChildElement(QLatin1String("target")).text(); ndkInfo.version = childElt.firstChildElement(QLatin1String("version")).text(); ndkList.append(ndkInfo); } } return ndkList; } QString QnxUtils::sdkInstallerPath(const QString &ndkPath) { QString sdkinstallPath; if (Utils::HostOsInfo::isWindowsHost()) sdkinstallPath = ndkPath + QLatin1String("/qde.exe"); else sdkinstallPath = ndkPath + QLatin1String("/qde"); if (QFileInfo(sdkinstallPath).exists()) return sdkinstallPath; return QString(); } // The resulting process when launching sdkinstall QString QnxUtils::qdeInstallProcess(const QString &ndkPath, const QString &option, const QString &version) { QString installerPath = sdkInstallerPath(ndkPath); if (ndkPath.isEmpty()) return QString(); return QString::fromLatin1("%1 -nosplash -application com.qnx.tools.ide.sdk.manager.core.SDKInstallerApplication " "%2 %3 -vmargs -Dosgi.console=:none").arg(installerPath, option, version); } QList<Utils::EnvironmentItem> QnxUtils::qnxEnvironment(const QString &sdkPath) { // Mimic what the SDP installer puts into the system environment QList<Utils::EnvironmentItem> environmentItems; if (Utils::HostOsInfo::isWindowsHost()) { // TODO: //environment.insert(QLatin1String("QNX_CONFIGURATION"), QLatin1String("/etc/qnx")); environmentItems.append(Utils::EnvironmentItem(QLatin1String(Constants::QNX_TARGET_KEY), sdkPath + QLatin1String("/target/qnx6"))); environmentItems.append(Utils::EnvironmentItem(QLatin1String(Constants::QNX_HOST_KEY), sdkPath + QLatin1String("/host/win32/x86"))); environmentItems.append(Utils::EnvironmentItem(QLatin1String("PATH"), sdkPath + QLatin1String("/host/win32/x86/usr/bin;%PATH%"))); // TODO: //environment.insert(QLatin1String("PATH"), QLatin1String("/etc/qnx/bin")); } else if (Utils::HostOsInfo::isAnyUnixHost()) { environmentItems.append(Utils::EnvironmentItem(QLatin1String("QNX_CONFIGURATION"), QLatin1String("/etc/qnx"))); environmentItems.append(Utils::EnvironmentItem(QLatin1String(Constants::QNX_TARGET_KEY), sdkPath + QLatin1String("/target/qnx6"))); environmentItems.append(Utils::EnvironmentItem(QLatin1String(Constants::QNX_HOST_KEY), sdkPath + QLatin1String("/host/linux/x86"))); environmentItems.append(Utils::EnvironmentItem(QLatin1String("PATH"), sdkPath + QLatin1String("/host/linux/x86/usr/bin:/etc/qnx/bin:${PATH}"))); environmentItems.append(Utils::EnvironmentItem(QLatin1String("LD_LIBRARY_PATH"), sdkPath + QLatin1String("/host/linux/x86/usr/lib:${LD_LIBRARY_PATH}"))); } environmentItems.append(Utils::EnvironmentItem(QLatin1String("QNX_JAVAHOME"), sdkPath + QLatin1String("/_jvm"))); environmentItems.append(Utils::EnvironmentItem(QLatin1String("MAKEFLAGS"), QLatin1String("-I") + sdkPath + QLatin1String("/target/qnx6/usr/include"))); return environmentItems; } <|endoftext|>
<commit_before><commit_msg>remove debug output<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: dsitems.hxx,v $ * * $Revision: 1.6 $ * * last change: $Author: fs $ $Date: 2001-02-05 13:57:41 $ * * 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 EXPRESS 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 _DBAUI_DATASOURCEITEMS_HXX_ #define _DBAUI_DATASOURCEITEMS_HXX_ //======================================================================== //= item ids for the data source administration dialog #define DSID_NAME 1 // name of a data source, SfxStringItem #define DSID_ORIGINALNAME 2 // orginal name, internal, SfxStringItem #define DSID_CONNECTURL 3 // connection URL, SfxStringItem #define DSID_TABLEFILTER 4 // table filter, OStringListItem #define DSID_TYPECOLLECTION 5 // collection of data source types, ODsnTypeCollection #define DSID_INVALID_SELECTION 6 // is the selection (thus the set data) invalid?, SfxBoolItem #define DSID_READONLY 7 // is the selection (thus the set data) readonly?, SfxBoolItem #define DSID_USER 8 // the user name used for logon, SfxStringItem #define DSID_PASSWORD 9 // the password used for logon, SfxStringItem #define DSID_ADDITIONALOPTIONS 10 // additional options used for connecting, SfxStringItem #define DSID_CHARSET 11 // character set to use, SfxStringItem by now #define DSID_PASSWORDREQUIRED 12 // is the password required to connect?, SfxBoolItem #define DSID_SHOWDELETEDROWS 13 // show deleted rows?, SfxBoolItem #define DSID_ALLOWLONGTABLENAMES 14 // allow tables names longer than 8.3?, SfxBoolItem #define DSID_JDBCDRIVERCLASS 15 // JDBC driver class, SfxStringItem #define DSID_FIELDDELIMITER 16 // field delimiter, SfxUInt16Item #define DSID_TEXTDELIMITER 17 // text delimiter, SfxUInt16Item #define DSID_DECIMALDELIMITER 18 // decimal delimiter, SfxUInt16Item #define DSID_THOUSANDSDELIMITER 19 // thousands delimiter, SfxUInt16Item #define DSID_TEXTFILEEXTENSION 20 // extension for text files, SfxStringItem #define DSID_TEXTFILEHEADER 21 // the text file contains a header?, SfxBoolItem #define DSID_NEWDATASOURCE 22 // meta data: sal_True if the data source described by the set is new #define DSID_DELETEDDATASOURCE 23 // meta data: sal_True if the data source described by the set is to-be-deleted #define DSID_SUPPRESSVERSIONCL 24 // meta data: sal_True if the data source described by the set is to-be-deleted #define DSID_DATASOURCE_UNO 25 // meta data: OPropertySetItem, the data source the set represents //======================================================================== //= item range. Adjust this if you introduce new items above #define DSID_FIRST_ITEM_ID DSID_NAME #define DSID_LAST_ITEM_ID DSID_DATASOURCE_UNO #endif // _DBAUI_DATASOURCEITEMS_HXX_ /************************************************************************* * history: * $Log: not supported by cvs2svn $ * Revision 1.5 2000/10/20 09:53:17 fs * handling for the SuppresVersionColumns property of a data source * * Revision 1.4 2000/10/12 16:20:42 fs * new implementations ... still under construction * * Revision 1.3 2000/10/11 11:31:03 fs * new implementations - still under construction * * Revision 1.2 2000/10/09 12:39:29 fs * some (a lot of) new imlpementations - still under development * * Revision 1.1 2000/10/05 10:05:55 fs * initial checkin * * * Revision 1.0 22.09.00 08:10:45 fs ************************************************************************/ <commit_msg>impl new page for adabas<commit_after>/************************************************************************* * * $RCSfile: dsitems.hxx,v $ * * $Revision: 1.7 $ * * last change: $Author: oj $ $Date: 2001-03-27 07:34:29 $ * * 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 EXPRESS 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 _DBAUI_DATASOURCEITEMS_HXX_ #define _DBAUI_DATASOURCEITEMS_HXX_ //======================================================================== //= item ids for the data source administration dialog #define DSID_NAME 1 // name of a data source, SfxStringItem #define DSID_ORIGINALNAME 2 // orginal name, internal, SfxStringItem #define DSID_CONNECTURL 3 // connection URL, SfxStringItem #define DSID_TABLEFILTER 4 // table filter, OStringListItem #define DSID_TYPECOLLECTION 5 // collection of data source types, ODsnTypeCollection #define DSID_INVALID_SELECTION 6 // is the selection (thus the set data) invalid?, SfxBoolItem #define DSID_READONLY 7 // is the selection (thus the set data) readonly?, SfxBoolItem #define DSID_USER 8 // the user name used for logon, SfxStringItem #define DSID_PASSWORD 9 // the password used for logon, SfxStringItem #define DSID_ADDITIONALOPTIONS 10 // additional options used for connecting, SfxStringItem #define DSID_CHARSET 11 // character set to use, SfxStringItem by now #define DSID_PASSWORDREQUIRED 12 // is the password required to connect?, SfxBoolItem #define DSID_SHOWDELETEDROWS 13 // show deleted rows?, SfxBoolItem #define DSID_ALLOWLONGTABLENAMES 14 // allow tables names longer than 8.3?, SfxBoolItem #define DSID_JDBCDRIVERCLASS 15 // JDBC driver class, SfxStringItem #define DSID_FIELDDELIMITER 16 // field delimiter, SfxUInt16Item #define DSID_TEXTDELIMITER 17 // text delimiter, SfxUInt16Item #define DSID_DECIMALDELIMITER 18 // decimal delimiter, SfxUInt16Item #define DSID_THOUSANDSDELIMITER 19 // thousands delimiter, SfxUInt16Item #define DSID_TEXTFILEEXTENSION 20 // extension for text files, SfxStringItem #define DSID_TEXTFILEHEADER 21 // the text file contains a header?, SfxBoolItem #define DSID_NEWDATASOURCE 22 // meta data: sal_True if the data source described by the set is new #define DSID_DELETEDDATASOURCE 23 // meta data: sal_True if the data source described by the set is to-be-deleted #define DSID_SUPPRESSVERSIONCL 24 // meta data: sal_True if the data source described by the set is to-be-deleted #define DSID_DATASOURCE_UNO 25 // meta data: OPropertySetItem, the data source the set represents #define DSID_CONN_SHUTSERVICE 26 #define DSID_CONN_DATAINC 27 #define DSID_CONN_CACHESIZE 28 #define DSID_CONN_CTRLUSER 29 #define DSID_CONN_CTRLPWD 30 //======================================================================== //= item range. Adjust this if you introduce new items above #define DSID_FIRST_ITEM_ID DSID_NAME #define DSID_LAST_ITEM_ID DSID_CONN_CTRLPWD #endif // _DBAUI_DATASOURCEITEMS_HXX_ /************************************************************************* * history: * $Log: not supported by cvs2svn $ * Revision 1.6 2001/02/05 13:57:41 fs * #83430# +DSID_DATASOURCE_UNO * * Revision 1.5 2000/10/20 09:53:17 fs * handling for the SuppresVersionColumns property of a data source * * Revision 1.4 2000/10/12 16:20:42 fs * new implementations ... still under construction * * Revision 1.3 2000/10/11 11:31:03 fs * new implementations - still under construction * * Revision 1.2 2000/10/09 12:39:29 fs * some (a lot of) new imlpementations - still under development * * Revision 1.1 2000/10/05 10:05:55 fs * initial checkin * * * Revision 1.0 22.09.00 08:10:45 fs ************************************************************************/ <|endoftext|>
<commit_before>/** * @file * * @brief Read key sets using yaml-cpp * * @copyright BSD License (see LICENSE.md or https://www.libelektra.org) */ #include "read.hpp" #include "yaml-cpp/yaml.h" #include <kdb.hpp> #include <kdblogger.h> #include <kdbplugin.h> #include <sstream> using namespace std; using namespace kdb; namespace { /** * @brief This function converts a given number to an array base name. * * @param index This number specifies the index of the array entry. * * @return A string representing the given indices as Elektra array name. */ string indexToArrayBaseName (uintmax_t const index) { size_t digits = 1; for (uintmax_t value = index; value > 9; digits++) { value /= 10; } return "#" + string (digits - 1, '_') + to_string (index); } /** * @brief This function creates a new key from the given parameters. * * @param name This string specifies the postfix of the name of the key produced by this function. * @param parent This key specifies the prefix of the name of the key produced by this function. * * @returns The function returns a new key that combines the name of the parent key and `name`. */ Key newKey (string const & name, Key const & parent) { ELEKTRA_LOG_DEBUG ("Add new key with base name “%s”", name.c_str ()); Key key{ parent.getFullName (), KEY_BINARY, KEY_END }; key.addBaseName (name); return key; } /** * @brief This function creates a new array key from the given parameters. * * @param arrayKey This argument specifies the key that represents the root of the array. * @param index This parameter specifies the index of the array key this function creates. * * @returns The function returns a new key that is part of the array represented by `arrayKey`. */ Key newArrayKey (Key & arrayKey, uintmax_t const index) { ELEKTRA_LOG_DEBUG ("Add new array element to array parent “%s”", arrayKey.getName ().c_str ()); Key newKey{ arrayKey.getName (), KEY_BINARY, KEY_END }; newKey.addBaseName (indexToArrayBaseName (index)); arrayKey.setMeta ("array", newKey.getBaseName ()); return newKey; } /** * @brief Add metadata saved in a YAML map to the specified key * * @param key This parameter saves the key to which this function should add the metadata stored in `node`. * @param node This YAML node stores a map containing metadata. */ void addMetadata (Key & key, YAML::Node const & node) { for (auto & element : node) { auto metakey = element.first.as<string> (); auto metavalue = element.second.IsNull () ? "" : element.second.as<string> (); ELEKTRA_LOG_DEBUG ("Add metakey “%s: %s”", metakey.c_str (), metavalue.c_str ()); key.setMeta (metakey, metavalue); } } /** * @brief Create a key containing a (possibly empty) value. * * @param node This YAML node stores the data that should be converted to a new `Key`. * @param name This text specifies the name of the key this function creates. * * @return A new key containing the data specified in `node` */ Key createLeafKey (YAML::Node const & node, string const & name) { Key key{ name, KEY_BINARY, KEY_END }; if (!node.IsNull ()) { auto value = node.as<string> (); if (value == "true" || value == "false") { try { key.set<bool> (node.as<bool> ()); } catch (YAML::BadConversion const &) { key.set<string> (value); // Save value as string, if `node` is a quoted scalar } } else { key.set<string> (value); } } if (node.Tag () == "tag:yaml.org,2002:binary") { ELEKTRA_LOG_DEBUG ("Set metadata type of key to binary"); key.setMeta ("type", "binary"); } ELEKTRA_LOG_DEBUG ("Add key “%s: %s”", key.getName ().c_str (), key.getBinarySize () == 0 ? "NULL" : key.isBinary () ? "binary value!" : key.get<string> ().c_str ()); return key; } /** * @brief Convert the key value of a YAML meta node to a key * * @param node This YAML meta node stores the data this function stores in the returned key * @param parent This key stores the prefix for the key name * * @return A key representing the key value stored in `node` */ Key convertMetaNodeToKey (YAML::Node const & node, Key & parent) { auto key = node[0].IsNull () ? Key{ parent.getFullName (), KEY_BINARY, KEY_END } : Key{ parent.getFullName (), KEY_VALUE, node[0].as<string> ().c_str (), KEY_END }; ELEKTRA_LOG_DEBUG ("Add key “%s”: “%s”", key.getName ().c_str (), key.getBinarySize () == 0 ? "NULL" : key.isString () ? key.getString ().c_str () : "binary value!"); return key; } /** * @brief Convert a YAML node to a key set * * @param node This YAML node stores the data that should be added to the keyset `mappings` * @param mappings The key set where the YAML data will be stored * @param parent This key stores the prefix for the key name */ void convertNodeToKeySet (YAML::Node const & node, KeySet & mappings, Key & parent) { if (node.Tag () == "!elektra/meta") { auto key = convertMetaNodeToKey (node, parent); mappings.append (key); addMetadata (key, node[1]); } else if (node.IsScalar () || node.IsNull ()) { auto key = createLeafKey (node, parent.getFullName ()); mappings.append (key); } else if (node.IsMap ()) { for (auto element : node) { Key key = newKey (element.first.as<string> (), parent); convertNodeToKeySet (element.second, mappings, key); } } else if (node.IsSequence ()) { uintmax_t index = 0; uintmax_t lastIndex = 0; for (auto element : node) { if (lastIndex == UINTMAX_MAX) { Key key = newArrayKey (parent, lastIndex); throw std::overflow_error ("Unable to add element after “" + key.getName () + "”" + "in array “" + parent.getName () + "”"); } Key key = newArrayKey (parent, index); mappings.append (parent); // Update array metadata convertNodeToKeySet (element, mappings, key); lastIndex = index++; } } } } // end namespace /** * @brief Read a YAML file and add the resulting data to a given key set * * @param mappings The key set where the YAML data will be stored * @param parent This key stores the path to the YAML data file that should be read */ void yamlcpp::yamlRead (KeySet & mappings, Key & parent) { YAML::Node config = YAML::LoadFile (parent.getString ()); ELEKTRA_LOG_DEBUG ("Read file “%s”", parent.getString ().c_str ()); #ifdef HAVE_LOGGER ostringstream data; data << config; ELEKTRA_LOG_DEBUG ("Read Data:"); ELEKTRA_LOG_DEBUG ("——————————"); istringstream stream (data.str ()); for (string line; std::getline (stream, line);) { ELEKTRA_LOG_DEBUG ("%s", line.c_str ()); } ELEKTRA_LOG_DEBUG ("——————————"); #endif convertNodeToKeySet (config, mappings, parent); ELEKTRA_LOG_DEBUG ("Added %zd key%s", mappings.size (), mappings.size () == 1 ? "" : "s"); } <commit_msg>YAML CPP: Simplify code<commit_after>/** * @file * * @brief Read key sets using yaml-cpp * * @copyright BSD License (see LICENSE.md or https://www.libelektra.org) */ #include "read.hpp" #include "yaml-cpp/yaml.h" #include <kdb.hpp> #include <kdblogger.h> #include <kdbplugin.h> #include <sstream> using namespace std; using namespace kdb; namespace { /** * @brief This function converts a given number to an array base name. * * @param index This number specifies the index of the array entry. * * @return A string representing the given indices as Elektra array name. */ string indexToArrayBaseName (uintmax_t const index) { size_t digits = 1; for (uintmax_t value = index; value > 9; digits++) { value /= 10; } return "#" + string (digits - 1, '_') + to_string (index); } /** * @brief This function creates a new key from the given parameters. * * @param name This string specifies the postfix of the name of the key produced by this function. * @param parent This key specifies the prefix of the name of the key produced by this function. * * @returns The function returns a new key that combines the name of the parent key and `name`. */ Key newKey (string const & name, Key const & parent) { ELEKTRA_LOG_DEBUG ("Add new key with base name “%s”", name.c_str ()); Key key{ parent.getFullName (), KEY_BINARY, KEY_END }; key.addBaseName (name); return key; } /** * @brief This function creates a new array key from the given parameters. * * @param arrayKey This argument specifies the key that represents the root of the array. * @param index This parameter specifies the index of the array key this function creates. * * @returns The function returns a new key that is part of the array represented by `arrayKey`. */ Key newArrayKey (Key & arrayKey, uintmax_t const index) { ELEKTRA_LOG_DEBUG ("Add new array element to array parent “%s”", arrayKey.getName ().c_str ()); Key newKey{ arrayKey.getName (), KEY_BINARY, KEY_END }; newKey.addBaseName (indexToArrayBaseName (index)); arrayKey.setMeta ("array", newKey.getBaseName ()); return newKey; } /** * @brief Add metadata saved in a YAML map to the specified key * * @param key This parameter saves the key to which this function should add the metadata stored in `node`. * @param node This YAML node stores a map containing metadata. */ void addMetadata (Key & key, YAML::Node const & node) { for (auto & element : node) { auto metakey = element.first.as<string> (); auto metavalue = element.second.IsNull () ? "" : element.second.as<string> (); ELEKTRA_LOG_DEBUG ("Add metakey “%s: %s”", metakey.c_str (), metavalue.c_str ()); key.setMeta (metakey, metavalue); } } /** * @brief Create a key containing a (possibly empty) value. * * @param node This YAML node stores the data that should be converted to a new `Key`. * @param name This text specifies the name of the key this function creates. * * @return A new key containing the data specified in `node` */ Key createLeafKey (YAML::Node const & node, string const & name) { Key key{ name, KEY_BINARY, KEY_END }; if (!node.IsNull ()) { auto value = node.as<string> (); if (value == "true" || value == "false") { try { key.set<bool> (node.as<bool> ()); } catch (YAML::BadConversion const &) { key.set<string> (value); // Save value as string, if `node` is a quoted scalar } } else { key.set<string> (value); } } if (node.Tag () == "tag:yaml.org,2002:binary") { ELEKTRA_LOG_DEBUG ("Set metadata type of key to binary"); key.setMeta ("type", "binary"); } ELEKTRA_LOG_DEBUG ("Add key “%s: %s”", key.getName ().c_str (), key.getBinarySize () == 0 ? "NULL" : key.isBinary () ? "binary value!" : key.get<string> ().c_str ()); return key; } /** * @brief Convert the key value of a YAML meta node to a key * * @param node This YAML meta node stores the data this function stores in the returned key * @param parent This key stores the prefix for the key name * * @return A key representing the key value stored in `node` */ Key convertMetaNodeToKey (YAML::Node const & node, Key & parent) { auto key = node[0].IsNull () ? Key{ parent.getFullName (), KEY_BINARY, KEY_END } : Key{ parent.getFullName (), KEY_VALUE, node[0].as<string> ().c_str (), KEY_END }; ELEKTRA_LOG_DEBUG ("Add key “%s”: “%s”", key.getName ().c_str (), key.getBinarySize () == 0 ? "NULL" : key.isString () ? key.getString ().c_str () : "binary value!"); return key; } /** * @brief Convert a YAML node to a key set * * @param node This YAML node stores the data that should be added to the keyset `mappings` * @param mappings The key set where the YAML data will be stored * @param parent This key stores the prefix for the key name */ void convertNodeToKeySet (YAML::Node const & node, KeySet & mappings, Key & parent) { if (node.Tag () == "!elektra/meta") { auto key = convertMetaNodeToKey (node, parent); mappings.append (key); addMetadata (key, node[1]); } else if (node.IsScalar () || node.IsNull ()) { auto key = createLeafKey (node, parent.getFullName ()); mappings.append (key); } else if (node.IsMap ()) { for (auto element : node) { Key key = newKey (element.first.as<string> (), parent); convertNodeToKeySet (element.second, mappings, key); } } else if (node.IsSequence ()) { uintmax_t index = 0; uintmax_t lastIndex = 0; for (auto element : node) { if (lastIndex == UINTMAX_MAX) { Key key = newArrayKey (parent, lastIndex); throw std::overflow_error ("Unable to add element after “" + key.getName () + "” in array “" + parent.getName () + "”"); } Key key = newArrayKey (parent, index); mappings.append (parent); // Update array metadata convertNodeToKeySet (element, mappings, key); lastIndex = index++; } } } } // end namespace /** * @brief Read a YAML file and add the resulting data to a given key set * * @param mappings The key set where the YAML data will be stored * @param parent This key stores the path to the YAML data file that should be read */ void yamlcpp::yamlRead (KeySet & mappings, Key & parent) { YAML::Node config = YAML::LoadFile (parent.getString ()); ELEKTRA_LOG_DEBUG ("Read file “%s”", parent.getString ().c_str ()); #ifdef HAVE_LOGGER ostringstream data; data << config; ELEKTRA_LOG_DEBUG ("Read Data:"); ELEKTRA_LOG_DEBUG ("——————————"); istringstream stream (data.str ()); for (string line; std::getline (stream, line);) { ELEKTRA_LOG_DEBUG ("%s", line.c_str ()); } ELEKTRA_LOG_DEBUG ("——————————"); #endif convertNodeToKeySet (config, mappings, parent); ELEKTRA_LOG_DEBUG ("Added %zd key%s", mappings.size (), mappings.size () == 1 ? "" : "s"); } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: DExport.hxx,v $ * * $Revision: 1.16 $ * * last change: $Author: rt $ $Date: 2006-05-04 08:42:41 $ * * 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 DBAUI_DATABASEEXPORT_HXX #define DBAUI_DATABASEEXPORT_HXX #ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_ #include <com/sun/star/sdbc/XResultSet.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_XRESULTSETMETADATA_HPP_ #include <com/sun/star/sdbc/XResultSetMetaData.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_ #include <com/sun/star/beans/XPropertySet.hpp> #endif #ifndef _COM_SUN_STAR_UTIL_XNUMBERFORMATTER_HPP_ #include <com/sun/star/util/XNumberFormatter.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_ #include <com/sun/star/container/XNameAccess.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XINDEXACCESS_HPP_ #include <com/sun/star/container/XIndexAccess.hpp> #endif #ifndef _COM_SUN_STAR_LANG_LOCALE_HPP_ #include <com/sun/star/lang/Locale.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #include <vector> #ifndef _STRING_HXX #include <tools/string.hxx> #endif #ifndef _COMPHELPER_STLTYPES_HXX_ #include <comphelper/stl_types.hxx> #endif #ifndef DBAUI_TYPEINFO_HXX #include "TypeInfo.hxx" #endif #ifndef _DBAUI_COMMON_TYPES_HXX_ #include "commontypes.hxx" #endif #ifndef DBAUI_IUPDATEHELPER_HXX #include "IUpdateHelper.hxx" #endif namespace com { namespace sun { namespace star { namespace awt{ struct FontDescriptor; } namespace sdbc{ class XPreparedStatement; class XDatabaseMetaData; } }}} class Window; class SvNumberFormatter; namespace dbaui { class OFieldDescription; class OTypeInfo; class OWizTypeSelect; class ODatabaseExport { public: DECLARE_STL_MAP(::rtl::OUString,OFieldDescription*,::comphelper::UStringMixLess,TColumns); typedef ::std::vector<TColumns::const_iterator> TColumnVector; typedef ::std::vector< ::std::pair<sal_Int32,sal_Int32> > TPositions; protected: TPositions m_vColumns; // Welche Spalten "ubernommen werden sollen ::std::vector<sal_Int32> m_vColumnTypes; // FeldTypen f"ur schnelleren Zugriff ::std::vector<sal_Int32> m_vColumnSize; ::std::vector<sal_Int32> m_vFormatKey; ::com::sun::star::lang::Locale m_nLocale; TColumns m_aDestColumns; // container for new created columns TColumnVector m_vDestVector; ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess> m_xColumns; // container ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > m_xTable; // dest table ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess> m_xTables; // container SharedConnection m_xConnection; // dest conn ::boost::shared_ptr<IUpdateHelper> m_pUpdateHelper; ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet > m_xResultSet; // ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSetMetaData > m_xResultSetMetaData; // ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatter > m_xFormatter; // a number formatter working with the connection's NumberFormatsSupplier ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory> m_xFactory; SvNumberFormatter* m_pFormatter; String m_sTextToken; // Zellen Inhalt String m_sNumToken; /// SDNUM value String m_sValToken; /// SDVAL value TOTypeInfoSP m_pTypeInfo; // contains the default type const TColumnVector* m_pColumnList; const OTypeInfoMap* m_pInfoMap; sal_Int32 m_nColumnPos; // aktuelle Spaltenposition sal_Int32 m_nRows; // Anzahl der Zeilen die durchsucht werden sollen sal_Int32 m_nRowCount; // current count of rows rtl_TextEncoding m_nDefToken; // Sprache sal_Bool m_bError; // Fehler und Abbruchstatus sal_Bool m_bInTbl; // Ist gesetzt, wenn der Parser sich in der RTF Tabelle befindet sal_Bool m_bHead; // ist true, wenn die Kopfzeile noch nicht gelesen wurde sal_Bool m_bDontAskAgain;// Falls beim Einf"ugen ein Fehler auftritt, soll die Fehlermeldung nicht sal_Bool m_bIsAutoIncrement; // if PKey is set by user sal_Bool m_bFoundTable; // set to true when a table was found sal_Bool m_bCheckOnly; virtual sal_Bool CreateTable(int nToken) = 0; /** createPage is called when the wizards needs an additional page to show */ virtual OWizTypeSelect* createPage(Window* _pParent) = 0; void CreateDefaultColumn(const ::rtl::OUString& _rColumnName); sal_Int32 CheckString(const String& aToken, sal_Int32 _nOldFormat); void adjustFormat(); void eraseTokens(); void insertValueIntoColumn(); sal_Bool createRowSet(); void showErrorDialog(const ::com::sun::star::sdbc::SQLException& e); void ensureFormatter(); /** executeWizard calls a wizard to create/append data @param _sTableName the tablename @param _aTextColor the text color of the new created table @param _rFont the font of the new table @return true when an error occurs */ sal_Bool executeWizard( const ::rtl::OUString& _sTableName, const ::com::sun::star::uno::Any& _aTextColor, const ::com::sun::star::awt::FontDescriptor& _rFont); virtual ~ODatabaseExport(); public: ODatabaseExport(const SharedConnection& _rxConnection, const ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatter >& _rxNumberF, const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rM, const TColumnVector* rList = 0, const OTypeInfoMap* _pInfoMap = 0); // wird f"ur auto. Typ-Erkennung gebraucht ODatabaseExport(sal_Int32 nRows, const TPositions& _rColumnPositions, const ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatter >& _rxNumberF, const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rM, const TColumnVector* rList, const OTypeInfoMap* _pInfoMap, sal_Bool _bAutoIncrementEnabled); void SetColumnTypes(const TColumnVector* rList,const OTypeInfoMap* _pInfoMap); virtual void release() = 0; void enableCheckOnly() { m_bCheckOnly = sal_True; } sal_Bool isCheckEnabled() const { return m_bCheckOnly; } static ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XPreparedStatement > createPreparedStatment( const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData>& _xMetaData ,const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& _xDestTable ,const TPositions& _rvColumns); }; } #endif // DBAUI_DATABASEEXPORT_HXX <commit_msg>INTEGRATION: CWS warnings01 (1.14.4); FILE MERGED 2006/05/23 23:54:21 sb 1.14.4.2: RESYNC: (1.14-1.16); FILE MERGED 2006/03/24 15:36:14 fs 1.14.4.1: #i57457# warning-free code (unxlngi6/.pro + unxsoli4.pro)<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: DExport.hxx,v $ * * $Revision: 1.17 $ * * last change: $Author: hr $ $Date: 2006-06-20 03:11:09 $ * * 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 DBAUI_DATABASEEXPORT_HXX #define DBAUI_DATABASEEXPORT_HXX #ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_ #include <com/sun/star/sdbc/XResultSet.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_XRESULTSETMETADATA_HPP_ #include <com/sun/star/sdbc/XResultSetMetaData.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_ #include <com/sun/star/beans/XPropertySet.hpp> #endif #ifndef _COM_SUN_STAR_UTIL_XNUMBERFORMATTER_HPP_ #include <com/sun/star/util/XNumberFormatter.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_ #include <com/sun/star/container/XNameAccess.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XINDEXACCESS_HPP_ #include <com/sun/star/container/XIndexAccess.hpp> #endif #ifndef _COM_SUN_STAR_LANG_LOCALE_HPP_ #include <com/sun/star/lang/Locale.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #include <vector> #ifndef _STRING_HXX #include <tools/string.hxx> #endif #ifndef _COMPHELPER_STLTYPES_HXX_ #include <comphelper/stl_types.hxx> #endif #ifndef DBAUI_TYPEINFO_HXX #include "TypeInfo.hxx" #endif #ifndef _DBAUI_COMMON_TYPES_HXX_ #include "commontypes.hxx" #endif #ifndef DBAUI_IUPDATEHELPER_HXX #include "IUpdateHelper.hxx" #endif namespace com { namespace sun { namespace star { namespace awt{ struct FontDescriptor; } namespace sdbc{ class XPreparedStatement; class XDatabaseMetaData; } }}} #define COLUMN_POSITION_NOT_FOUND ((sal_Int32)-1) class Window; class SvNumberFormatter; namespace dbaui { class OFieldDescription; class OTypeInfo; class OWizTypeSelect; class ODatabaseExport { public: DECLARE_STL_MAP(::rtl::OUString,OFieldDescription*,::comphelper::UStringMixLess,TColumns); typedef ::std::vector<TColumns::const_iterator> TColumnVector; typedef ::std::vector< ::std::pair<sal_Int32,sal_Int32> > TPositions; protected: TPositions m_vColumns; // Welche Spalten "ubernommen werden sollen ::std::vector<sal_Int32> m_vColumnTypes; // FeldTypen f"ur schnelleren Zugriff ::std::vector<sal_Int32> m_vColumnSize; ::std::vector<sal_Int32> m_vFormatKey; ::com::sun::star::lang::Locale m_aLocale; TColumns m_aDestColumns; // container for new created columns TColumnVector m_vDestVector; ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > m_xTable; // dest table ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess> m_xTables; // container SharedConnection m_xConnection; // dest conn ::boost::shared_ptr<IUpdateHelper> m_pUpdateHelper; ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet > m_xResultSet; // ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSetMetaData > m_xResultSetMetaData; // ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatter > m_xFormatter; // a number formatter working with the connection's NumberFormatsSupplier ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory> m_xFactory; SvNumberFormatter* m_pFormatter; String m_sTextToken; // Zellen Inhalt String m_sNumToken; /// SDNUM value String m_sValToken; /// SDVAL value TOTypeInfoSP m_pTypeInfo; // contains the default type const TColumnVector* m_pColumnList; const OTypeInfoMap* m_pInfoMap; sal_Int32 m_nColumnPos; // aktuelle Spaltenposition sal_Int32 m_nRows; // Anzahl der Zeilen die durchsucht werden sollen sal_Int32 m_nRowCount; // current count of rows rtl_TextEncoding m_nDefToken; // Sprache sal_Bool m_bError; // Fehler und Abbruchstatus sal_Bool m_bInTbl; // Ist gesetzt, wenn der Parser sich in der RTF Tabelle befindet sal_Bool m_bHead; // ist true, wenn die Kopfzeile noch nicht gelesen wurde sal_Bool m_bDontAskAgain;// Falls beim Einf"ugen ein Fehler auftritt, soll die Fehlermeldung nicht sal_Bool m_bIsAutoIncrement; // if PKey is set by user sal_Bool m_bFoundTable; // set to true when a table was found sal_Bool m_bCheckOnly; virtual sal_Bool CreateTable(int nToken) = 0; /** createPage is called when the wizards needs an additional page to show */ virtual OWizTypeSelect* createPage(Window* _pParent) = 0; void CreateDefaultColumn(const ::rtl::OUString& _rColumnName); sal_Int32 CheckString(const String& aToken, sal_Int32 _nOldFormat); void adjustFormat(); void eraseTokens(); void insertValueIntoColumn(); sal_Bool createRowSet(); void showErrorDialog(const ::com::sun::star::sdbc::SQLException& e); void ensureFormatter(); /** executeWizard calls a wizard to create/append data @param _sTableName the tablename @param _aTextColor the text color of the new created table @param _rFont the font of the new table @return true when an error occurs */ sal_Bool executeWizard( const ::rtl::OUString& _sTableName, const ::com::sun::star::uno::Any& _aTextColor, const ::com::sun::star::awt::FontDescriptor& _rFont); virtual ~ODatabaseExport(); public: ODatabaseExport(const SharedConnection& _rxConnection, const ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatter >& _rxNumberF, const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rM, const TColumnVector* rList = 0, const OTypeInfoMap* _pInfoMap = 0); // wird f"ur auto. Typ-Erkennung gebraucht ODatabaseExport(sal_Int32 nRows, const TPositions& _rColumnPositions, const ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatter >& _rxNumberF, const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rM, const TColumnVector* rList, const OTypeInfoMap* _pInfoMap, sal_Bool _bAutoIncrementEnabled); void SetColumnTypes(const TColumnVector* rList,const OTypeInfoMap* _pInfoMap); virtual void release() = 0; void enableCheckOnly() { m_bCheckOnly = sal_True; } sal_Bool isCheckEnabled() const { return m_bCheckOnly; } static ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XPreparedStatement > createPreparedStatment( const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData>& _xMetaData ,const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& _xDestTable ,const TPositions& _rvColumns); }; } #endif // DBAUI_DATABASEEXPORT_HXX <|endoftext|>
<commit_before>//--------------------------------------------------------------------------- // $Id$ // Version: $Name$ // Author: Toby D. Young, Polish Academy of Sciences, 2008, 2009 // // Copyright (C) 2009 by the deal.II authors // // This file is subject to QPL and may not be distributed // without copyright and license information. Please refer // to the file deal.II/doc/license.html for the text and // further information on this license. // //--------------------------------------------------------------------------- #include <lac/slepc_solver.h> #ifdef DEAL_II_USE_SLEPC # include <lac/petsc_matrix_base.h> # include <lac/petsc_vector_base.h> # include <lac/petsc_vector.h> # include <lac/slepc_spectral_transformation.h> # include <cmath> # include <vector> # include <petscversion.h> DEAL_II_NAMESPACE_OPEN namespace SLEPcWrappers { SolverBase::SolverData::~SolverData () { // Destroy the solver object. int ierr = EPSDestroy (eps); AssertThrow (ierr == 0, ExcSLEPcError(ierr)); } SolverBase::SolverBase (SolverControl &cn, const MPI_Comm &mpi_communicator) : solver_control (cn), mpi_communicator (mpi_communicator), set_which (EPS_LARGEST_MAGNITUDE), opA (NULL), opB (NULL), initial_vector (NULL), transformation (NULL) {} SolverBase::~SolverBase () {} void SolverBase::set_matrices (const PETScWrappers::MatrixBase &A) { // standard eigenspectrum problem opA = &A; opB = NULL; } void SolverBase::set_matrices (const PETScWrappers::MatrixBase &A, const PETScWrappers::MatrixBase &B) { // generalized eigenspectrum problem opA = &A; opB = &B; } void SolverBase::set_initial_vector (const PETScWrappers::VectorBase &set_initial_vector) { initial_vector = (&set_initial_vector); } void SolverBase::set_transformation (SLEPcWrappers::TransformationBase &set_transformation) { transformation = &set_transformation; } void SolverBase::set_which_eigenpairs (const EPSWhich eps_which) { set_which = eps_which; } void SolverBase::solve (const unsigned int n_eigenvectors, unsigned int *n_converged) { int ierr; AssertThrow (solver_data.get() == 0, ExcSLEPcWrappersUsageError()); solver_data.reset (new SolverData()); // create eigensolver context and // set operators ierr = EPSCreate (mpi_communicator, &solver_data->eps); AssertThrow (ierr == 0, ExcSLEPcError(ierr)); // set eigenspectrum problem type // (general/standard) AssertThrow (opA, ExcSLEPcWrappersUsageError()); if (opB) ierr = EPSSetOperators (solver_data->eps, *opA, *opB); else ierr = EPSSetOperators (solver_data->eps, *opA, PETSC_NULL); AssertThrow (ierr == 0, ExcSLEPcError(ierr)); // set the initial vector(s) if any if (initial_vector && initial_vector->size() != 0) { #if DEAL_II_PETSC_VERSION_LT(3,1,0) ierr = EPSSetInitialVector (solver_data->eps, *initial_vector); #else Vec this_vector = *initial_vector; ierr = EPSSetInitialSpace (solver_data->eps, 1, &this_vector); #endif AssertThrow (ierr == 0, ExcSLEPcError(ierr)); } // set transformation type if any if (transformation) transformation->set_context(solver_data->eps); // set runtime options set_solver_type (solver_data->eps); // set which portion of the // eigenspectrum to solve for ierr = EPSSetWhichEigenpairs (solver_data->eps, set_which); AssertThrow (ierr == 0, ExcSLEPcError(ierr)); // set number of eigenvectors to // compute ierr = EPSSetDimensions (solver_data->eps, n_eigenvectors, PETSC_DECIDE, PETSC_DECIDE); AssertThrow (ierr == 0, ExcSLEPcError(ierr)); // set the solve options to the // eigenvalue problem solver // context ierr = EPSSetFromOptions (solver_data->eps); AssertThrow (ierr == 0, ExcSLEPcError(ierr)); // solve the eigensystem ierr = EPSSolve (solver_data->eps); AssertThrow (ierr == 0, ExcSLEPcError(ierr)); // get number of converged // eigenstates ierr = EPSGetConverged (solver_data->eps, #ifdef PETSC_USE_64BIT_INDICES reinterpret_cast<PetscInt *>(n_converged)); #else reinterpret_cast<int *>(n_converged)); #endif AssertThrow (ierr == 0, ExcSLEPcError(ierr)); } void SolverBase::get_eigenpair (const unsigned int index, #ifndef DEAL_II_USE_PETSC_COMPLEX double &kr, #else std::complex<double> &kr, #endif PETScWrappers::VectorBase &vr) { AssertThrow (solver_data.get() != 0, ExcSLEPcWrappersUsageError()); // get converged eigenpair int ierr = EPSGetEigenpair(solver_data->eps, index, &kr, PETSC_NULL, vr, PETSC_NULL); AssertThrow (ierr == 0, ExcSLEPcError(ierr)); } void SolverBase::reset () { AssertThrow (solver_data.get() != 0, ExcSLEPcWrappersUsageError()); // destroy solver object. solver_data.reset (); } EPS * SolverBase::get_EPS () { if( solver_data.get() == 0 ) return NULL; return &solver_data->eps; } /* ---------------------- SolverControls ----------------------- */ SolverControl & SolverBase::control () const { return solver_control; } int SolverBase::convergence_test (EPS /*eps*/, #ifdef PETSC_USE_64BIT_INDICES const PetscInt iteration, #else const int iteration, #endif const PetscReal residual_norm, EPSConvergedReason *reason, void *solver_control_x) { SolverControl &solver_control = *reinterpret_cast<SolverControl*>(solver_control_x); const SolverControl::State state = solver_control.check (iteration, residual_norm); switch (state) { case ::dealii::SolverControl::iterate: *reason = EPS_CONVERGED_ITERATING; break; case ::dealii::SolverControl::success: *reason = static_cast<EPSConvergedReason>(1); break; case ::dealii::SolverControl::failure: if (solver_control.last_step() > solver_control.max_steps()) *reason = EPS_DIVERGED_ITS; break; default: Assert (false, ExcNotImplemented()); } // return without failure. return 0; } /* ---------------------- SolverKrylovSchur ------------------------ */ SolverKrylovSchur::SolverKrylovSchur (SolverControl &cn, const MPI_Comm &mpi_communicator, const AdditionalData &data) : SolverBase (cn, mpi_communicator), additional_data (data) {} void SolverKrylovSchur::set_solver_type (EPS &eps) const { int ierr; ierr = EPSSetType (eps, const_cast<char *>(EPSKRYLOVSCHUR)); AssertThrow (ierr == 0, ExcSLEPcError(ierr)); // hand over the absolute // tolerance and the maximum // number of iteration steps to // the SLEPc convergence // criterion. ierr = EPSSetTolerances(eps, this->solver_control.tolerance(), this->solver_control.max_steps()); AssertThrow (ierr == 0, ExcSLEPcError(ierr)); } /* ---------------------- SolverArnoldi ------------------------ */ SolverArnoldi::SolverArnoldi (SolverControl &cn, const MPI_Comm &mpi_communicator, const AdditionalData &data) : SolverBase (cn, mpi_communicator), additional_data (data) {} void SolverArnoldi::set_solver_type (EPS &eps) const { int ierr; ierr = EPSSetType (eps, const_cast<char *>(EPSARNOLDI)); AssertThrow (ierr == 0, ExcSLEPcError(ierr)); // hand over the absolute // tolerance and the maximum // number of iteration steps to // the SLEPc convergence // criterion. ierr = EPSSetTolerances(eps, this->solver_control.tolerance(), this->solver_control.max_steps()); AssertThrow (ierr == 0, ExcSLEPcError(ierr)); } /* ---------------------- Lanczos ------------------------ */ SolverLanczos::SolverLanczos (SolverControl &cn, const MPI_Comm &mpi_communicator, const AdditionalData &data) : SolverBase (cn, mpi_communicator), additional_data (data) {} void SolverLanczos::set_solver_type (EPS &eps) const { int ierr; ierr = EPSSetType (eps, const_cast<char *>(EPSLANCZOS)); AssertThrow (ierr == 0, ExcSLEPcError(ierr)); // hand over the absolute // tolerance and the maximum // number of iteration steps to // the SLEPc convergence // criterion. ierr = EPSSetTolerances(eps, this->solver_control.tolerance(), this->solver_control.max_steps()); AssertThrow (ierr == 0, ExcSLEPcError(ierr)); } /* ----------------------- Power ------------------------- */ SolverPower::SolverPower (SolverControl &cn, const MPI_Comm &mpi_communicator, const AdditionalData &data) : SolverBase (cn, mpi_communicator), additional_data (data) {} void SolverPower::set_solver_type (EPS &eps) const { int ierr; ierr = EPSSetType (eps, const_cast<char *>(EPSPOWER)); AssertThrow (ierr == 0, ExcSLEPcError(ierr)); // hand over the absolute // tolerance and the maximum // number of iteration steps to // the SLEPc convergence // criterion. ierr = EPSSetTolerances(eps, this->solver_control.tolerance(), this->solver_control.max_steps()); AssertThrow (ierr == 0, ExcSLEPcError(ierr)); } /* ---------------------- Davidson ----------------------- */ #if DEAL_II_PETSC_VERSION_LT(3,1,0) SolverDavidson::SolverDavidson (SolverControl &cn, const MPI_Comm &mpi_communicator, const AdditionalData &data) : SolverBase (cn, mpi_communicator), additional_data (data) {} void SolverDavidson::set_solver_type (EPS &eps) const { int ierr; ierr = EPSSetType (eps, const_cast<char *>(EPSDAVIDSON)); AssertThrow (ierr == 0, ExcSLEPcError(ierr)); // hand over the absolute // tolerance and the maximum // number of iteration steps to // the SLEPc convergence // criterion. ierr = EPSSetTolerances(eps, this->solver_control.tolerance(), this->solver_control.max_steps()); AssertThrow (ierr == 0, ExcSLEPcError(ierr)); } #endif } DEAL_II_NAMESPACE_CLOSE #else // On gcc2.95 on Alpha OSF1, the native assembler does not like empty // files, so provide some dummy code namespace { void dummy () {} } #endif // DEAL_II_USE_SLEPC <commit_msg>Fix error in matching PETSC_VERION<commit_after>//--------------------------------------------------------------------------- // $Id$ // Version: $Name$ // Author: Toby D. Young, Polish Academy of Sciences, 2008, 2009 // // Copyright (C) 2009 by the deal.II authors // // This file is subject to QPL and may not be distributed // without copyright and license information. Please refer // to the file deal.II/doc/license.html for the text and // further information on this license. // //--------------------------------------------------------------------------- #include <lac/slepc_solver.h> #ifdef DEAL_II_USE_SLEPC # include <lac/petsc_matrix_base.h> # include <lac/petsc_vector_base.h> # include <lac/petsc_vector.h> # include <lac/slepc_spectral_transformation.h> # include <cmath> # include <vector> # include <petscversion.h> DEAL_II_NAMESPACE_OPEN namespace SLEPcWrappers { SolverBase::SolverData::~SolverData () { // Destroy the solver object. int ierr = EPSDestroy (eps); AssertThrow (ierr == 0, ExcSLEPcError(ierr)); } SolverBase::SolverBase (SolverControl &cn, const MPI_Comm &mpi_communicator) : solver_control (cn), mpi_communicator (mpi_communicator), set_which (EPS_LARGEST_MAGNITUDE), opA (NULL), opB (NULL), initial_vector (NULL), transformation (NULL) {} SolverBase::~SolverBase () {} void SolverBase::set_matrices (const PETScWrappers::MatrixBase &A) { // standard eigenspectrum problem opA = &A; opB = NULL; } void SolverBase::set_matrices (const PETScWrappers::MatrixBase &A, const PETScWrappers::MatrixBase &B) { // generalized eigenspectrum problem opA = &A; opB = &B; } void SolverBase::set_initial_vector (const PETScWrappers::VectorBase &set_initial_vector) { initial_vector = (&set_initial_vector); } void SolverBase::set_transformation (SLEPcWrappers::TransformationBase &set_transformation) { transformation = &set_transformation; } void SolverBase::set_which_eigenpairs (const EPSWhich eps_which) { set_which = eps_which; } void SolverBase::solve (const unsigned int n_eigenvectors, unsigned int *n_converged) { int ierr; AssertThrow (solver_data.get() == 0, ExcSLEPcWrappersUsageError()); solver_data.reset (new SolverData()); // create eigensolver context and // set operators ierr = EPSCreate (mpi_communicator, &solver_data->eps); AssertThrow (ierr == 0, ExcSLEPcError(ierr)); // set eigenspectrum problem type // (general/standard) AssertThrow (opA, ExcSLEPcWrappersUsageError()); if (opB) ierr = EPSSetOperators (solver_data->eps, *opA, *opB); else ierr = EPSSetOperators (solver_data->eps, *opA, PETSC_NULL); AssertThrow (ierr == 0, ExcSLEPcError(ierr)); // set the initial vector(s) if any if (initial_vector && initial_vector->size() != 0) { #if DEAL_II_PETSC_VERSION_LT(3,1,0) ierr = EPSSetInitialVector (solver_data->eps, *initial_vector); #else Vec this_vector = *initial_vector; ierr = EPSSetInitialSpace (solver_data->eps, 1, &this_vector); #endif AssertThrow (ierr == 0, ExcSLEPcError(ierr)); } // set transformation type if any if (transformation) transformation->set_context(solver_data->eps); // set runtime options set_solver_type (solver_data->eps); // set which portion of the // eigenspectrum to solve for ierr = EPSSetWhichEigenpairs (solver_data->eps, set_which); AssertThrow (ierr == 0, ExcSLEPcError(ierr)); // set number of eigenvectors to // compute ierr = EPSSetDimensions (solver_data->eps, n_eigenvectors, PETSC_DECIDE, PETSC_DECIDE); AssertThrow (ierr == 0, ExcSLEPcError(ierr)); // set the solve options to the // eigenvalue problem solver // context ierr = EPSSetFromOptions (solver_data->eps); AssertThrow (ierr == 0, ExcSLEPcError(ierr)); // solve the eigensystem ierr = EPSSolve (solver_data->eps); AssertThrow (ierr == 0, ExcSLEPcError(ierr)); // get number of converged // eigenstates ierr = EPSGetConverged (solver_data->eps, #ifdef PETSC_USE_64BIT_INDICES reinterpret_cast<PetscInt *>(n_converged)); #else reinterpret_cast<int *>(n_converged)); #endif AssertThrow (ierr == 0, ExcSLEPcError(ierr)); } void SolverBase::get_eigenpair (const unsigned int index, #ifndef DEAL_II_USE_PETSC_COMPLEX double &kr, #else std::complex<double> &kr, #endif PETScWrappers::VectorBase &vr) { AssertThrow (solver_data.get() != 0, ExcSLEPcWrappersUsageError()); // get converged eigenpair int ierr = EPSGetEigenpair(solver_data->eps, index, &kr, PETSC_NULL, vr, PETSC_NULL); AssertThrow (ierr == 0, ExcSLEPcError(ierr)); } void SolverBase::reset () { AssertThrow (solver_data.get() != 0, ExcSLEPcWrappersUsageError()); // destroy solver object. solver_data.reset (); } EPS * SolverBase::get_EPS () { if( solver_data.get() == 0 ) return NULL; return &solver_data->eps; } /* ---------------------- SolverControls ----------------------- */ SolverControl & SolverBase::control () const { return solver_control; } int SolverBase::convergence_test (EPS /*eps*/, #ifdef PETSC_USE_64BIT_INDICES const PetscInt iteration, #else const int iteration, #endif const PetscReal residual_norm, EPSConvergedReason *reason, void *solver_control_x) { SolverControl &solver_control = *reinterpret_cast<SolverControl*>(solver_control_x); const SolverControl::State state = solver_control.check (iteration, residual_norm); switch (state) { case ::dealii::SolverControl::iterate: *reason = EPS_CONVERGED_ITERATING; break; case ::dealii::SolverControl::success: *reason = static_cast<EPSConvergedReason>(1); break; case ::dealii::SolverControl::failure: if (solver_control.last_step() > solver_control.max_steps()) *reason = EPS_DIVERGED_ITS; break; default: Assert (false, ExcNotImplemented()); } // return without failure. return 0; } /* ---------------------- SolverKrylovSchur ------------------------ */ SolverKrylovSchur::SolverKrylovSchur (SolverControl &cn, const MPI_Comm &mpi_communicator, const AdditionalData &data) : SolverBase (cn, mpi_communicator), additional_data (data) {} void SolverKrylovSchur::set_solver_type (EPS &eps) const { int ierr; ierr = EPSSetType (eps, const_cast<char *>(EPSKRYLOVSCHUR)); AssertThrow (ierr == 0, ExcSLEPcError(ierr)); // hand over the absolute // tolerance and the maximum // number of iteration steps to // the SLEPc convergence // criterion. ierr = EPSSetTolerances(eps, this->solver_control.tolerance(), this->solver_control.max_steps()); AssertThrow (ierr == 0, ExcSLEPcError(ierr)); } /* ---------------------- SolverArnoldi ------------------------ */ SolverArnoldi::SolverArnoldi (SolverControl &cn, const MPI_Comm &mpi_communicator, const AdditionalData &data) : SolverBase (cn, mpi_communicator), additional_data (data) {} void SolverArnoldi::set_solver_type (EPS &eps) const { int ierr; ierr = EPSSetType (eps, const_cast<char *>(EPSARNOLDI)); AssertThrow (ierr == 0, ExcSLEPcError(ierr)); // hand over the absolute // tolerance and the maximum // number of iteration steps to // the SLEPc convergence // criterion. ierr = EPSSetTolerances(eps, this->solver_control.tolerance(), this->solver_control.max_steps()); AssertThrow (ierr == 0, ExcSLEPcError(ierr)); } /* ---------------------- Lanczos ------------------------ */ SolverLanczos::SolverLanczos (SolverControl &cn, const MPI_Comm &mpi_communicator, const AdditionalData &data) : SolverBase (cn, mpi_communicator), additional_data (data) {} void SolverLanczos::set_solver_type (EPS &eps) const { int ierr; ierr = EPSSetType (eps, const_cast<char *>(EPSLANCZOS)); AssertThrow (ierr == 0, ExcSLEPcError(ierr)); // hand over the absolute // tolerance and the maximum // number of iteration steps to // the SLEPc convergence // criterion. ierr = EPSSetTolerances(eps, this->solver_control.tolerance(), this->solver_control.max_steps()); AssertThrow (ierr == 0, ExcSLEPcError(ierr)); } /* ----------------------- Power ------------------------- */ SolverPower::SolverPower (SolverControl &cn, const MPI_Comm &mpi_communicator, const AdditionalData &data) : SolverBase (cn, mpi_communicator), additional_data (data) {} void SolverPower::set_solver_type (EPS &eps) const { int ierr; ierr = EPSSetType (eps, const_cast<char *>(EPSPOWER)); AssertThrow (ierr == 0, ExcSLEPcError(ierr)); // hand over the absolute // tolerance and the maximum // number of iteration steps to // the SLEPc convergence // criterion. ierr = EPSSetTolerances(eps, this->solver_control.tolerance(), this->solver_control.max_steps()); AssertThrow (ierr == 0, ExcSLEPcError(ierr)); } #if DEAL_II_PETSC_VERSION_GTE(3,1,0) /* ---------------------- Davidson ----------------------- */ SolverDavidson::SolverDavidson (SolverControl &cn, const MPI_Comm &mpi_communicator, const AdditionalData &data) : SolverBase (cn, mpi_communicator), additional_data (data) {} void SolverDavidson::set_solver_type (EPS &eps) const { int ierr; ierr = EPSSetType (eps, const_cast<char *>(EPSDAVIDSON)); AssertThrow (ierr == 0, ExcSLEPcError(ierr)); // hand over the absolute // tolerance and the maximum // number of iteration steps to // the SLEPc convergence // criterion. ierr = EPSSetTolerances(eps, this->solver_control.tolerance(), this->solver_control.max_steps()); AssertThrow (ierr == 0, ExcSLEPcError(ierr)); } #endif } DEAL_II_NAMESPACE_CLOSE #else // On gcc2.95 on Alpha OSF1, the native assembler does not like empty // files, so provide some dummy code namespace { void dummy () {} } #endif // DEAL_II_USE_SLEPC <|endoftext|>
<commit_before>/* symtable.cc * Hash table representing the symbol table. * the symbol table. * UIdaho CS445 120++ Compiler * author: Chris Waltrip <[email protected]> */ #include <iostream> #include <sstream> #include <string> #include "symtable.hh" #include "exception.hh" /* AbstractSymbol::AbstractSymbol(std::string n, TypenameEntry t) : name(n), type(t) { } */ AbstractSymbol::AbstractSymbol(std::string n, std::string t) : name(n), type(t) { } std::string AbstractSymbol::to_string(std::size_t depth) { std::string spaces = std::string(depth, '>'); return(spaces + this->type + " " + this->name); } /* * The only time that SymbolTable's parent will be NULL is the Global Symbol * Table. Given this and the n-ary tree (represented using std::deque), * resolving scope should be relatively simple. */ SymbolTable::SymbolTable(SymbolTable *p) { this->parent = p; } /* * Just a wrapper function for nesting scopes. */ void SymbolTable::add_sub_table(SymbolTable *k) { this->kids.push_back(k); } /* * This hashing method is identical to the Typename Table hash method. */ std::size_t SymbolTable::hash(std::string name) { std::size_t hash = 0; const char* s = name.c_str(); while(*s) { hash = hash * 101 + *s++; } return hash % this->HASHTABLE_SIZE; } bool SymbolTable::insert(std::string n, AbstractSymbol *s) { if(!this->symbol_exists(n)) { std::size_t h = this->hash(n); this->bucket[h].push_back(s); return true; } throw EDuplicateSymbol(); return false; /* Remove after refactor */ } bool SymbolTable::empty() { for(std::size_t i = 0; i < this->HASHTABLE_SIZE; ++i) { if(!this->bucket[i].empty()) return false; } return true; } AbstractSymbol* SymbolTable::get_symbol(std::string name) { std::size_t h = this->hash(name); std::deque<AbstractSymbol*> b = this->bucket[h]; std::deque<AbstractSymbol*>::iterator it; for(it = b.begin(); it != b.end(); ++it) { std::size_t i = it - b.begin(); if(*(b[i]) == name) { return b[i]; } } throw ENoSymbolEntry(); } /* * Tries to get the symbol from the current scope. If get_symbol throws an * ENoSymbolEntry, then the current scope doesn't have the symbol that is * being search for. If the parent symbol table is NULL then we have reached * the global symbol table and the symbol doesn't exist so throw * ENoSymbolEntry again and let the calling function handle the exception. If * the symbol is found, it's returned. */ AbstractSymbol* SymbolTable::get_scoped_symbol(std::string name) { AbstractSymbol *symb; try { symb = this->get_symbol(name); return symb; } catch(ENoSymbolEntry e) { if(this->parent == NULL) { throw ENoSymbolEntry(); } else { /* Will never be NULL because exception is thrown */ return this->parent->get_scoped_symbol(name); } } } /* * Will return true if a symbol is found. If get_symbol throws * an ENoSymbolEntry exception, then the symbol isn't in the symbol * table. This only checks for the existance in the local symbol table. */ bool SymbolTable::symbol_exists(std::string name) { try { this->get_symbol(name); } catch(ENoSymbolEntry e) { return false; } return true; } void SymbolTable::print_table(std::size_t depth) { std::clog << this->to_string(depth) << std::endl; } std::string SymbolTable::to_string(std::size_t depth) { std::stringstream ss; for(std::size_t i = 0; i < this->HASHTABLE_SIZE; ++i) { std::deque<AbstractSymbol*> b = this->bucket[i]; std::deque<AbstractSymbol*>::iterator it; for(it = b.begin(); it != b.end(); ++it) {\ std::size_t index = it - b.begin(); ss << (*(b[i])).to_string(depth) << std::endl; //ss << (*it)->to_string(depth) << std::endl; } } return ss.str(); } /* Basic Symbol constructor */ BasicSymbol::BasicSymbol(std::string n, std::string t, bool p) : AbstractSymbol(n,t), pointer(p) { } /* Function symbol constructor */ FunctionSymbol::FunctionSymbol(std::string n, std::string t, bool p, bool d) : AbstractSymbol(n,t), pointer(p), def_needed(d) { } std::string FunctionSymbol::to_string(std::size_t depth) { std::stringstream ss; ss << AbstractSymbol::to_string(depth) << std::endl; ss << this->params.to_string(depth+1) << std::endl; ss << this->locals.to_string(depth+1) << std::endl; return ss.str(); }<commit_msg>Fixing segfault when referencing iterator<commit_after>/* symtable.cc * Hash table representing the symbol table. * the symbol table. * UIdaho CS445 120++ Compiler * author: Chris Waltrip <[email protected]> */ #include <iostream> #include <sstream> #include <string> #include "symtable.hh" #include "exception.hh" /* AbstractSymbol::AbstractSymbol(std::string n, TypenameEntry t) : name(n), type(t) { } */ AbstractSymbol::AbstractSymbol(std::string n, std::string t) : name(n), type(t) { } std::string AbstractSymbol::to_string(std::size_t depth) { std::string spaces = std::string(depth, '>'); return(spaces + this->type + " " + this->name); } /* * The only time that SymbolTable's parent will be NULL is the Global Symbol * Table. Given this and the n-ary tree (represented using std::deque), * resolving scope should be relatively simple. */ SymbolTable::SymbolTable(SymbolTable *p) { this->parent = p; } /* * Just a wrapper function for nesting scopes. */ void SymbolTable::add_sub_table(SymbolTable *k) { this->kids.push_back(k); } /* * This hashing method is identical to the Typename Table hash method. */ std::size_t SymbolTable::hash(std::string name) { std::size_t hash = 0; const char* s = name.c_str(); while(*s) { hash = hash * 101 + *s++; } return hash % this->HASHTABLE_SIZE; } bool SymbolTable::insert(std::string n, AbstractSymbol *s) { if(!this->symbol_exists(n)) { std::size_t h = this->hash(n); this->bucket[h].push_back(s); return true; } throw EDuplicateSymbol(); return false; /* Remove after refactor */ } bool SymbolTable::empty() { for(std::size_t i = 0; i < this->HASHTABLE_SIZE; ++i) { if(!this->bucket[i].empty()) return false; } return true; } AbstractSymbol* SymbolTable::get_symbol(std::string name) { std::size_t h = this->hash(name); std::deque<AbstractSymbol*> b = this->bucket[h]; std::deque<AbstractSymbol*>::iterator it; for(it = b.begin(); it != b.end(); ++it) { std::size_t i = it - b.begin(); if(*(b[i]) == name) { return b[i]; } } throw ENoSymbolEntry(); } /* * Tries to get the symbol from the current scope. If get_symbol throws an * ENoSymbolEntry, then the current scope doesn't have the symbol that is * being search for. If the parent symbol table is NULL then we have reached * the global symbol table and the symbol doesn't exist so throw * ENoSymbolEntry again and let the calling function handle the exception. If * the symbol is found, it's returned. */ AbstractSymbol* SymbolTable::get_scoped_symbol(std::string name) { AbstractSymbol *symb; try { symb = this->get_symbol(name); return symb; } catch(ENoSymbolEntry e) { if(this->parent == NULL) { throw ENoSymbolEntry(); } else { /* Will never be NULL because exception is thrown */ return this->parent->get_scoped_symbol(name); } } } /* * Will return true if a symbol is found. If get_symbol throws * an ENoSymbolEntry exception, then the symbol isn't in the symbol * table. This only checks for the existance in the local symbol table. */ bool SymbolTable::symbol_exists(std::string name) { try { this->get_symbol(name); } catch(ENoSymbolEntry e) { return false; } return true; } void SymbolTable::print_table(std::size_t depth) { std::clog << this->to_string(depth) << std::endl; } std::string SymbolTable::to_string(std::size_t depth) { std::stringstream ss; for(std::size_t i = 0; i < this->HASHTABLE_SIZE; ++i) { std::deque<AbstractSymbol*> b = this->bucket[i]; std::deque<AbstractSymbol*>::iterator it; for(it = b.begin(); it != b.end(); ++it) {\ std::size_t index = it - b.begin(); ss << (b[index])->to_string(depth) << std::endl; //ss << (*it)->to_string(depth) << std::endl; } } return ss.str(); } /* Basic Symbol constructor */ BasicSymbol::BasicSymbol(std::string n, std::string t, bool p) : AbstractSymbol(n,t), pointer(p) { } /* Function symbol constructor */ FunctionSymbol::FunctionSymbol(std::string n, std::string t, bool p, bool d) : AbstractSymbol(n,t), pointer(p), def_needed(d) { } std::string FunctionSymbol::to_string(std::size_t depth) { std::stringstream ss; ss << AbstractSymbol::to_string(depth) << std::endl; ss << this->params.to_string(depth+1) << std::endl; ss << this->locals.to_string(depth+1) << std::endl; return ss.str(); }<|endoftext|>
<commit_before>// @(#)root/hist:$Id$ // Author: [email protected] 21/08/2002 /////////////////////////////////////////////////////////////////////////// // // TLimitDataSource // // This class serves as interface to feed data into the TLimit routines // /////////////////////////////////////////////////////////////////////////// #include "TLimitDataSource.h" #include "TH1.h" #include "TVectorD.h" #include "TObjString.h" #include "TRandom3.h" ClassImp(TLimitDataSource) TLimitDataSource::TLimitDataSource() { // Default constructor fDummyTA.SetOwner(); fDummyIds.SetOwner(); } TLimitDataSource::TLimitDataSource(TH1 * s, TH1 * b, TH1 * d) { // Another constructor, directly adds one channel // with signal, background and data given as input. fDummyTA.SetOwner(); fDummyIds.SetOwner(); AddChannel(s, b, d); } TLimitDataSource::TLimitDataSource(TH1 * s, TH1 * b, TH1 * d, TVectorD * es, TVectorD * eb, TObjArray * names) { // Another constructor, directly adds one channel // with signal, background and data given as input. fDummyTA.SetOwner(); fDummyIds.SetOwner(); AddChannel(s, b, d, es, eb, names); } void TLimitDataSource::AddChannel(TH1 * s, TH1 * b, TH1 * d) { // Adds a channel with signal, background and data given as input. TVectorD *empty; TRandom3 generator; fSignal.AddLast(s); fBackground.AddLast(b); fCandidates.AddLast(d); char rndname[20]; sprintf(rndname, "rndname%f", generator.Rndm()); empty = new TVectorD(1); fErrorOnSignal.AddLast(empty); fDummyTA.AddLast(empty); sprintf(rndname, "rndname%f", generator.Rndm()); empty = new TVectorD(1); fErrorOnBackground.AddLast(empty); fDummyTA.AddLast(empty); TObjArray *dummy = new TObjArray(0); fIds.AddLast(dummy); fDummyIds.AddLast(dummy); } void TLimitDataSource::AddChannel(TH1 * s, TH1 * b, TH1 * d, TVectorD * es, TVectorD * eb, TObjArray * names) { // Adds a channel with signal, background and data given as input. // In addition, error sources are defined. // TH1 are here used for convenience: each bin has to be seen as // an error source (relative). // names is an array of strings containing the names of the sources. // Sources with the same name are correlated. fSignal.AddLast(s); fBackground.AddLast(b); fCandidates.AddLast(d); fErrorOnSignal.AddLast(es); fErrorOnBackground.AddLast(eb); fIds.AddLast(names); } void TLimitDataSource::SetOwner(bool swtch) { // Gives to the TLimitDataSource the ownership of the various objects // given as input. // Objects are then deleted by the TLimitDataSource destructor. fSignal.SetOwner(swtch); fBackground.SetOwner(swtch); fCandidates.SetOwner(swtch); fErrorOnSignal.SetOwner(swtch); fErrorOnBackground.SetOwner(swtch); fIds.SetOwner(swtch); fDummyTA.SetOwner(!swtch); fDummyIds.SetOwner(!swtch); } <commit_msg>use snprintf<commit_after>// @(#)root/hist:$Id$ // Author: [email protected] 21/08/2002 /////////////////////////////////////////////////////////////////////////// // // TLimitDataSource // // This class serves as interface to feed data into the TLimit routines // /////////////////////////////////////////////////////////////////////////// #include "TLimitDataSource.h" #include "TH1.h" #include "TVectorD.h" #include "TObjString.h" #include "TRandom3.h" ClassImp(TLimitDataSource) TLimitDataSource::TLimitDataSource() { // Default constructor fDummyTA.SetOwner(); fDummyIds.SetOwner(); } TLimitDataSource::TLimitDataSource(TH1 * s, TH1 * b, TH1 * d) { // Another constructor, directly adds one channel // with signal, background and data given as input. fDummyTA.SetOwner(); fDummyIds.SetOwner(); AddChannel(s, b, d); } TLimitDataSource::TLimitDataSource(TH1 * s, TH1 * b, TH1 * d, TVectorD * es, TVectorD * eb, TObjArray * names) { // Another constructor, directly adds one channel // with signal, background and data given as input. fDummyTA.SetOwner(); fDummyIds.SetOwner(); AddChannel(s, b, d, es, eb, names); } void TLimitDataSource::AddChannel(TH1 * s, TH1 * b, TH1 * d) { // Adds a channel with signal, background and data given as input. TVectorD *empty; TRandom3 generator; fSignal.AddLast(s); fBackground.AddLast(b); fCandidates.AddLast(d); char rndname[20]; snprintf(rndname,20, "rndname%f", generator.Rndm()); empty = new TVectorD(1); fErrorOnSignal.AddLast(empty); fDummyTA.AddLast(empty); snprintf(rndname,20, "rndname%f", generator.Rndm()); empty = new TVectorD(1); fErrorOnBackground.AddLast(empty); fDummyTA.AddLast(empty); TObjArray *dummy = new TObjArray(0); fIds.AddLast(dummy); fDummyIds.AddLast(dummy); } void TLimitDataSource::AddChannel(TH1 * s, TH1 * b, TH1 * d, TVectorD * es, TVectorD * eb, TObjArray * names) { // Adds a channel with signal, background and data given as input. // In addition, error sources are defined. // TH1 are here used for convenience: each bin has to be seen as // an error source (relative). // names is an array of strings containing the names of the sources. // Sources with the same name are correlated. fSignal.AddLast(s); fBackground.AddLast(b); fCandidates.AddLast(d); fErrorOnSignal.AddLast(es); fErrorOnBackground.AddLast(eb); fIds.AddLast(names); } void TLimitDataSource::SetOwner(bool swtch) { // Gives to the TLimitDataSource the ownership of the various objects // given as input. // Objects are then deleted by the TLimitDataSource destructor. fSignal.SetOwner(swtch); fBackground.SetOwner(swtch); fCandidates.SetOwner(swtch); fErrorOnSignal.SetOwner(swtch); fErrorOnBackground.SetOwner(swtch); fIds.SetOwner(swtch); fDummyTA.SetOwner(!swtch); fDummyIds.SetOwner(!swtch); } <|endoftext|>
<commit_before>/* * Copyright 2016 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "src/gpu/GrSurfaceProxy.h" #include "src/gpu/GrSurfaceProxyPriv.h" #include "include/gpu/GrContext.h" #include "include/private/GrRecordingContext.h" #include "src/core/SkMathPriv.h" #include "src/core/SkMipMap.h" #include "src/gpu/GrCaps.h" #include "src/gpu/GrClip.h" #include "src/gpu/GrContextPriv.h" #include "src/gpu/GrGpuResourcePriv.h" #include "src/gpu/GrOpsTask.h" #include "src/gpu/GrProxyProvider.h" #include "src/gpu/GrRecordingContextPriv.h" #include "src/gpu/GrRenderTargetContext.h" #include "src/gpu/GrStencilAttachment.h" #include "src/gpu/GrSurfacePriv.h" #include "src/gpu/GrTexturePriv.h" #include "src/gpu/GrTextureRenderTargetProxy.h" #ifdef SK_DEBUG #include "src/gpu/GrRenderTarget.h" #include "src/gpu/GrRenderTargetPriv.h" static bool is_valid_lazy(const SkISize& dimensions, SkBackingFit fit) { // A "fully" lazy proxy's width and height are not known until instantiation time. // So fully lazy proxies are created with width and height < 0. Regular lazy proxies must be // created with positive widths and heights. The width and height are set to 0 only after a // failed instantiation. The former must be "approximate" fit while the latter can be either. return ((dimensions.fWidth < 0 && dimensions.fHeight < 0 && SkBackingFit::kApprox == fit) || (dimensions.fWidth > 0 && dimensions.fHeight > 0)); } static bool is_valid_non_lazy(SkISize dimensions) { return dimensions.fWidth > 0 && dimensions.fHeight > 0; } #endif // Deferred version GrSurfaceProxy::GrSurfaceProxy(const GrBackendFormat& format, SkISize dimensions, SkBackingFit fit, SkBudgeted budgeted, GrProtected isProtected, GrInternalSurfaceFlags surfaceFlags, UseAllocator useAllocator) : fSurfaceFlags(surfaceFlags) , fFormat(format) , fDimensions(dimensions) , fFit(fit) , fBudgeted(budgeted) , fUseAllocator(useAllocator) , fIsProtected(isProtected) , fGpuMemorySize(kInvalidGpuMemorySize) { SkASSERT(fFormat.isValid()); SkASSERT(is_valid_non_lazy(dimensions)); } // Lazy-callback version GrSurfaceProxy::GrSurfaceProxy(LazyInstantiateCallback&& callback, const GrBackendFormat& format, SkISize dimensions, SkBackingFit fit, SkBudgeted budgeted, GrProtected isProtected, GrInternalSurfaceFlags surfaceFlags, UseAllocator useAllocator) : fSurfaceFlags(surfaceFlags) , fFormat(format) , fDimensions(dimensions) , fFit(fit) , fBudgeted(budgeted) , fUseAllocator(useAllocator) , fLazyInstantiateCallback(std::move(callback)) , fIsProtected(isProtected) , fGpuMemorySize(kInvalidGpuMemorySize) { SkASSERT(fFormat.isValid()); SkASSERT(fLazyInstantiateCallback); SkASSERT(is_valid_lazy(dimensions, fit)); } // Wrapped version GrSurfaceProxy::GrSurfaceProxy(sk_sp<GrSurface> surface, SkBackingFit fit, UseAllocator useAllocator) : fTarget(std::move(surface)) , fSurfaceFlags(fTarget->surfacePriv().flags()) , fFormat(fTarget->backendFormat()) , fDimensions(fTarget->dimensions()) , fFit(fit) , fBudgeted(fTarget->resourcePriv().budgetedType() == GrBudgetedType::kBudgeted ? SkBudgeted::kYes : SkBudgeted::kNo) , fUseAllocator(useAllocator) , fUniqueID(fTarget->uniqueID()) // Note: converting from unique resource ID to a proxy ID! , fIsProtected(fTarget->isProtected() ? GrProtected::kYes : GrProtected::kNo) , fGpuMemorySize(kInvalidGpuMemorySize) { SkASSERT(fFormat.isValid()); } GrSurfaceProxy::~GrSurfaceProxy() { } sk_sp<GrSurface> GrSurfaceProxy::createSurfaceImpl(GrResourceProvider* resourceProvider, int sampleCnt, GrRenderable renderable, GrMipMapped mipMapped) const { SkASSERT(mipMapped == GrMipMapped::kNo || fFit == SkBackingFit::kExact); SkASSERT(!this->isLazy()); SkASSERT(!fTarget); sk_sp<GrSurface> surface; if (SkBackingFit::kApprox == fFit) { surface = resourceProvider->createApproxTexture(fDimensions, fFormat, renderable, sampleCnt, fIsProtected); } else { surface = resourceProvider->createTexture(fDimensions, fFormat, renderable, sampleCnt, mipMapped, fBudgeted, fIsProtected); } if (!surface) { return nullptr; } return surface; } bool GrSurfaceProxy::canSkipResourceAllocator() const { if (fUseAllocator == UseAllocator::kNo) { // Usually an atlas or onFlush proxy return true; } auto peek = this->peekSurface(); if (!peek) { return false; } // If this resource is already allocated and not recyclable then the resource allocator does // not need to do anything with it. return !peek->resourcePriv().getScratchKey().isValid(); } void GrSurfaceProxy::assign(sk_sp<GrSurface> surface) { SkASSERT(!fTarget && surface); SkDEBUGCODE(this->validateSurface(surface.get());) fTarget = std::move(surface); #ifdef SK_DEBUG if (this->asRenderTargetProxy()) { SkASSERT(fTarget->asRenderTarget()); } if (kInvalidGpuMemorySize != this->getRawGpuMemorySize_debugOnly()) { SkASSERT(fTarget->gpuMemorySize() <= this->getRawGpuMemorySize_debugOnly()); } #endif } bool GrSurfaceProxy::instantiateImpl(GrResourceProvider* resourceProvider, int sampleCnt, GrRenderable renderable, GrMipMapped mipMapped, const GrUniqueKey* uniqueKey) { SkASSERT(!this->isLazy()); if (fTarget) { if (uniqueKey && uniqueKey->isValid()) { SkASSERT(fTarget->getUniqueKey().isValid() && fTarget->getUniqueKey() == *uniqueKey); } return true; } sk_sp<GrSurface> surface = this->createSurfaceImpl(resourceProvider, sampleCnt, renderable, mipMapped); if (!surface) { return false; } // If there was an invalidation message pending for this key, we might have just processed it, // causing the key (stored on this proxy) to become invalid. if (uniqueKey && uniqueKey->isValid()) { resourceProvider->assignUniqueKeyToResource(*uniqueKey, surface.get()); } this->assign(std::move(surface)); return true; } void GrSurfaceProxy::deinstantiate() { SkASSERT(this->isInstantiated()); fTarget = nullptr; } void GrSurfaceProxy::computeScratchKey(const GrCaps& caps, GrScratchKey* key) const { SkASSERT(!this->isFullyLazy()); GrRenderable renderable = GrRenderable::kNo; int sampleCount = 1; if (const auto* rtp = this->asRenderTargetProxy()) { renderable = GrRenderable::kYes; sampleCount = rtp->numSamples(); } const GrTextureProxy* tp = this->asTextureProxy(); GrMipMapped mipMapped = GrMipMapped::kNo; if (tp) { mipMapped = tp->mipMapped(); } GrTexturePriv::ComputeScratchKey(caps, this->backendFormat(), this->backingStoreDimensions(), renderable, sampleCount, mipMapped, fIsProtected, key); } SkISize GrSurfaceProxy::backingStoreDimensions() const { SkASSERT(!this->isFullyLazy()); if (fTarget) { return fTarget->dimensions(); } if (SkBackingFit::kExact == fFit) { return fDimensions; } return GrResourceProvider::MakeApprox(fDimensions); } bool GrSurfaceProxy::isFunctionallyExact() const { SkASSERT(!this->isFullyLazy()); return fFit == SkBackingFit::kExact || fDimensions == GrResourceProvider::MakeApprox(fDimensions); } bool GrSurfaceProxy::isFormatCompressed(const GrCaps* caps) const { return caps->isFormatCompressed(this->backendFormat()); } #ifdef SK_DEBUG void GrSurfaceProxy::validate(GrContext_Base* context) const { if (fTarget) { SkASSERT(fTarget->getContext() == context); } } #endif sk_sp<GrSurfaceProxy> GrSurfaceProxy::Copy(GrRecordingContext* context, GrSurfaceProxy* src, GrSurfaceOrigin origin, GrMipMapped mipMapped, SkIRect srcRect, SkBackingFit fit, SkBudgeted budgeted, RectsMustMatch rectsMustMatch) { SkASSERT(!src->isFullyLazy()); int width; int height; SkIPoint dstPoint; if (rectsMustMatch == RectsMustMatch::kYes) { width = src->width(); height = src->height(); dstPoint = {srcRect.fLeft, srcRect.fTop}; } else { width = srcRect.width(); height = srcRect.height(); dstPoint = {0, 0}; } if (!srcRect.intersect(SkIRect::MakeSize(src->dimensions()))) { return {}; } auto format = src->backendFormat().makeTexture2D(); SkASSERT(format.isValid()); if (src->backendFormat().textureType() != GrTextureType::kExternal) { auto dstContext = GrSurfaceContext::Make(context, {width, height}, format, GrRenderable::kNo, 1, mipMapped, src->isProtected(), origin, GrColorType::kUnknown, kUnknown_SkAlphaType, nullptr, fit, budgeted); if (dstContext && dstContext->copy(src, srcRect, dstPoint)) { return dstContext->asSurfaceProxyRef(); } } if (src->asTextureProxy()) { auto dstContext = GrRenderTargetContext::Make( context, GrColorType::kUnknown, nullptr, fit, {width, height}, format, 1, mipMapped, src->isProtected(), origin, budgeted, nullptr); GrSurfaceProxyView view(sk_ref_sp(src), origin, GrSwizzle("rgba")); if (dstContext && dstContext->blitTexture(std::move(view), srcRect, dstPoint)) { return dstContext->asSurfaceProxyRef(); } } // Can't use backend copies or draws. return nullptr; } sk_sp<GrSurfaceProxy> GrSurfaceProxy::Copy(GrRecordingContext* context, GrSurfaceProxy* src, GrSurfaceOrigin origin, GrMipMapped mipMapped, SkBackingFit fit, SkBudgeted budgeted) { SkASSERT(!src->isFullyLazy()); return Copy(context, src, origin, mipMapped, SkIRect::MakeSize(src->dimensions()), fit, budgeted); } #if GR_TEST_UTILS int32_t GrSurfaceProxy::testingOnly_getBackingRefCnt() const { if (fTarget) { return fTarget->testingOnly_getRefCnt(); } return -1; // no backing GrSurface } GrInternalSurfaceFlags GrSurfaceProxy::testingOnly_getFlags() const { return fSurfaceFlags; } #endif void GrSurfaceProxyPriv::exactify(bool allocatedCaseOnly) { SkASSERT(!fProxy->isFullyLazy()); if (this->isExact()) { return; } SkASSERT(SkBackingFit::kApprox == fProxy->fFit); if (fProxy->fTarget) { // The kApprox but already instantiated case. Setting the proxy's width & height to // the instantiated width & height could have side-effects going forward, since we're // obliterating the area of interest information. This call (exactify) only used // when converting an SkSpecialImage to an SkImage so the proxy shouldn't be // used for additional draws. fProxy->fDimensions = fProxy->fTarget->dimensions(); return; } #ifndef SK_CRIPPLE_TEXTURE_REUSE // In the post-implicit-allocation world we can't convert this proxy to be exact fit // at this point. With explicit allocation switching this to exact will result in a // different allocation at flush time. With implicit allocation, allocation would occur // at draw time (rather than flush time) so this pathway was encountered less often (if // at all). if (allocatedCaseOnly) { return; } #endif // The kApprox uninstantiated case. Making this proxy be exact should be okay. // It could mess things up if prior decisions were based on the approximate size. fProxy->fFit = SkBackingFit::kExact; // If fGpuMemorySize is used when caching specialImages for the image filter DAG. If it has // already been computed we want to leave it alone so that amount will be removed when // the special image goes away. If it hasn't been computed yet it might as well compute the // exact amount. } bool GrSurfaceProxyPriv::doLazyInstantiation(GrResourceProvider* resourceProvider) { SkASSERT(fProxy->isLazy()); sk_sp<GrSurface> surface; if (fProxy->asTextureProxy() && fProxy->asTextureProxy()->getUniqueKey().isValid()) { // First try to reattach to a cached version if the proxy is uniquely keyed surface = resourceProvider->findByUniqueKey<GrSurface>( fProxy->asTextureProxy()->getUniqueKey()); } bool syncKey = true; bool releaseCallback = false; if (!surface) { auto result = fProxy->fLazyInstantiateCallback(resourceProvider, fProxy->callbackDesc()); surface = std::move(result.fSurface); syncKey = result.fKeyMode == GrSurfaceProxy::LazyInstantiationKeyMode::kSynced; releaseCallback = surface && result.fReleaseCallback; } if (!surface) { fProxy->fDimensions.setEmpty(); return false; } if (fProxy->isFullyLazy()) { // This was a fully lazy proxy. We need to fill in the width & height. For partially // lazy proxies we must preserve the original width & height since that indicates // the content area. fProxy->fDimensions = surface->dimensions(); } SkASSERT(fProxy->width() <= surface->width()); SkASSERT(fProxy->height() <= surface->height()); if (GrTextureProxy* texProxy = fProxy->asTextureProxy()) { texProxy->setTargetKeySync(syncKey); if (syncKey) { const GrUniqueKey& key = texProxy->getUniqueKey(); if (key.isValid()) { if (!surface->asTexture()->getUniqueKey().isValid()) { // If 'surface' is newly created, attach the unique key resourceProvider->assignUniqueKeyToResource(key, surface.get()); } else { // otherwise we had better have reattached to a cached version SkASSERT(surface->asTexture()->getUniqueKey() == key); } } else { SkASSERT(!surface->getUniqueKey().isValid()); } } } this->assign(std::move(surface)); if (releaseCallback) { fProxy->fLazyInstantiateCallback = nullptr; } return true; } #ifdef SK_DEBUG void GrSurfaceProxy::validateSurface(const GrSurface* surface) { SkASSERT(surface->backendFormat() == fFormat); this->onValidateSurface(surface); } #endif <commit_msg>Allow surfaces to validate against matching contexts, not ptr equality<commit_after>/* * Copyright 2016 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "src/gpu/GrSurfaceProxy.h" #include "src/gpu/GrSurfaceProxyPriv.h" #include "include/gpu/GrContext.h" #include "include/private/GrRecordingContext.h" #include "src/core/SkMathPriv.h" #include "src/core/SkMipMap.h" #include "src/gpu/GrCaps.h" #include "src/gpu/GrClip.h" #include "src/gpu/GrContextPriv.h" #include "src/gpu/GrGpuResourcePriv.h" #include "src/gpu/GrOpsTask.h" #include "src/gpu/GrProxyProvider.h" #include "src/gpu/GrRecordingContextPriv.h" #include "src/gpu/GrRenderTargetContext.h" #include "src/gpu/GrStencilAttachment.h" #include "src/gpu/GrSurfacePriv.h" #include "src/gpu/GrTexturePriv.h" #include "src/gpu/GrTextureRenderTargetProxy.h" #ifdef SK_DEBUG #include "src/gpu/GrRenderTarget.h" #include "src/gpu/GrRenderTargetPriv.h" static bool is_valid_lazy(const SkISize& dimensions, SkBackingFit fit) { // A "fully" lazy proxy's width and height are not known until instantiation time. // So fully lazy proxies are created with width and height < 0. Regular lazy proxies must be // created with positive widths and heights. The width and height are set to 0 only after a // failed instantiation. The former must be "approximate" fit while the latter can be either. return ((dimensions.fWidth < 0 && dimensions.fHeight < 0 && SkBackingFit::kApprox == fit) || (dimensions.fWidth > 0 && dimensions.fHeight > 0)); } static bool is_valid_non_lazy(SkISize dimensions) { return dimensions.fWidth > 0 && dimensions.fHeight > 0; } #endif // Deferred version GrSurfaceProxy::GrSurfaceProxy(const GrBackendFormat& format, SkISize dimensions, SkBackingFit fit, SkBudgeted budgeted, GrProtected isProtected, GrInternalSurfaceFlags surfaceFlags, UseAllocator useAllocator) : fSurfaceFlags(surfaceFlags) , fFormat(format) , fDimensions(dimensions) , fFit(fit) , fBudgeted(budgeted) , fUseAllocator(useAllocator) , fIsProtected(isProtected) , fGpuMemorySize(kInvalidGpuMemorySize) { SkASSERT(fFormat.isValid()); SkASSERT(is_valid_non_lazy(dimensions)); } // Lazy-callback version GrSurfaceProxy::GrSurfaceProxy(LazyInstantiateCallback&& callback, const GrBackendFormat& format, SkISize dimensions, SkBackingFit fit, SkBudgeted budgeted, GrProtected isProtected, GrInternalSurfaceFlags surfaceFlags, UseAllocator useAllocator) : fSurfaceFlags(surfaceFlags) , fFormat(format) , fDimensions(dimensions) , fFit(fit) , fBudgeted(budgeted) , fUseAllocator(useAllocator) , fLazyInstantiateCallback(std::move(callback)) , fIsProtected(isProtected) , fGpuMemorySize(kInvalidGpuMemorySize) { SkASSERT(fFormat.isValid()); SkASSERT(fLazyInstantiateCallback); SkASSERT(is_valid_lazy(dimensions, fit)); } // Wrapped version GrSurfaceProxy::GrSurfaceProxy(sk_sp<GrSurface> surface, SkBackingFit fit, UseAllocator useAllocator) : fTarget(std::move(surface)) , fSurfaceFlags(fTarget->surfacePriv().flags()) , fFormat(fTarget->backendFormat()) , fDimensions(fTarget->dimensions()) , fFit(fit) , fBudgeted(fTarget->resourcePriv().budgetedType() == GrBudgetedType::kBudgeted ? SkBudgeted::kYes : SkBudgeted::kNo) , fUseAllocator(useAllocator) , fUniqueID(fTarget->uniqueID()) // Note: converting from unique resource ID to a proxy ID! , fIsProtected(fTarget->isProtected() ? GrProtected::kYes : GrProtected::kNo) , fGpuMemorySize(kInvalidGpuMemorySize) { SkASSERT(fFormat.isValid()); } GrSurfaceProxy::~GrSurfaceProxy() { } sk_sp<GrSurface> GrSurfaceProxy::createSurfaceImpl(GrResourceProvider* resourceProvider, int sampleCnt, GrRenderable renderable, GrMipMapped mipMapped) const { SkASSERT(mipMapped == GrMipMapped::kNo || fFit == SkBackingFit::kExact); SkASSERT(!this->isLazy()); SkASSERT(!fTarget); sk_sp<GrSurface> surface; if (SkBackingFit::kApprox == fFit) { surface = resourceProvider->createApproxTexture(fDimensions, fFormat, renderable, sampleCnt, fIsProtected); } else { surface = resourceProvider->createTexture(fDimensions, fFormat, renderable, sampleCnt, mipMapped, fBudgeted, fIsProtected); } if (!surface) { return nullptr; } return surface; } bool GrSurfaceProxy::canSkipResourceAllocator() const { if (fUseAllocator == UseAllocator::kNo) { // Usually an atlas or onFlush proxy return true; } auto peek = this->peekSurface(); if (!peek) { return false; } // If this resource is already allocated and not recyclable then the resource allocator does // not need to do anything with it. return !peek->resourcePriv().getScratchKey().isValid(); } void GrSurfaceProxy::assign(sk_sp<GrSurface> surface) { SkASSERT(!fTarget && surface); SkDEBUGCODE(this->validateSurface(surface.get());) fTarget = std::move(surface); #ifdef SK_DEBUG if (this->asRenderTargetProxy()) { SkASSERT(fTarget->asRenderTarget()); } if (kInvalidGpuMemorySize != this->getRawGpuMemorySize_debugOnly()) { SkASSERT(fTarget->gpuMemorySize() <= this->getRawGpuMemorySize_debugOnly()); } #endif } bool GrSurfaceProxy::instantiateImpl(GrResourceProvider* resourceProvider, int sampleCnt, GrRenderable renderable, GrMipMapped mipMapped, const GrUniqueKey* uniqueKey) { SkASSERT(!this->isLazy()); if (fTarget) { if (uniqueKey && uniqueKey->isValid()) { SkASSERT(fTarget->getUniqueKey().isValid() && fTarget->getUniqueKey() == *uniqueKey); } return true; } sk_sp<GrSurface> surface = this->createSurfaceImpl(resourceProvider, sampleCnt, renderable, mipMapped); if (!surface) { return false; } // If there was an invalidation message pending for this key, we might have just processed it, // causing the key (stored on this proxy) to become invalid. if (uniqueKey && uniqueKey->isValid()) { resourceProvider->assignUniqueKeyToResource(*uniqueKey, surface.get()); } this->assign(std::move(surface)); return true; } void GrSurfaceProxy::deinstantiate() { SkASSERT(this->isInstantiated()); fTarget = nullptr; } void GrSurfaceProxy::computeScratchKey(const GrCaps& caps, GrScratchKey* key) const { SkASSERT(!this->isFullyLazy()); GrRenderable renderable = GrRenderable::kNo; int sampleCount = 1; if (const auto* rtp = this->asRenderTargetProxy()) { renderable = GrRenderable::kYes; sampleCount = rtp->numSamples(); } const GrTextureProxy* tp = this->asTextureProxy(); GrMipMapped mipMapped = GrMipMapped::kNo; if (tp) { mipMapped = tp->mipMapped(); } GrTexturePriv::ComputeScratchKey(caps, this->backendFormat(), this->backingStoreDimensions(), renderable, sampleCount, mipMapped, fIsProtected, key); } SkISize GrSurfaceProxy::backingStoreDimensions() const { SkASSERT(!this->isFullyLazy()); if (fTarget) { return fTarget->dimensions(); } if (SkBackingFit::kExact == fFit) { return fDimensions; } return GrResourceProvider::MakeApprox(fDimensions); } bool GrSurfaceProxy::isFunctionallyExact() const { SkASSERT(!this->isFullyLazy()); return fFit == SkBackingFit::kExact || fDimensions == GrResourceProvider::MakeApprox(fDimensions); } bool GrSurfaceProxy::isFormatCompressed(const GrCaps* caps) const { return caps->isFormatCompressed(this->backendFormat()); } #ifdef SK_DEBUG void GrSurfaceProxy::validate(GrContext_Base* context) const { if (fTarget) { SkASSERT(fTarget->getContext()->priv().matches(context)); } } #endif sk_sp<GrSurfaceProxy> GrSurfaceProxy::Copy(GrRecordingContext* context, GrSurfaceProxy* src, GrSurfaceOrigin origin, GrMipMapped mipMapped, SkIRect srcRect, SkBackingFit fit, SkBudgeted budgeted, RectsMustMatch rectsMustMatch) { SkASSERT(!src->isFullyLazy()); int width; int height; SkIPoint dstPoint; if (rectsMustMatch == RectsMustMatch::kYes) { width = src->width(); height = src->height(); dstPoint = {srcRect.fLeft, srcRect.fTop}; } else { width = srcRect.width(); height = srcRect.height(); dstPoint = {0, 0}; } if (!srcRect.intersect(SkIRect::MakeSize(src->dimensions()))) { return {}; } auto format = src->backendFormat().makeTexture2D(); SkASSERT(format.isValid()); if (src->backendFormat().textureType() != GrTextureType::kExternal) { auto dstContext = GrSurfaceContext::Make(context, {width, height}, format, GrRenderable::kNo, 1, mipMapped, src->isProtected(), origin, GrColorType::kUnknown, kUnknown_SkAlphaType, nullptr, fit, budgeted); if (dstContext && dstContext->copy(src, srcRect, dstPoint)) { return dstContext->asSurfaceProxyRef(); } } if (src->asTextureProxy()) { auto dstContext = GrRenderTargetContext::Make( context, GrColorType::kUnknown, nullptr, fit, {width, height}, format, 1, mipMapped, src->isProtected(), origin, budgeted, nullptr); GrSurfaceProxyView view(sk_ref_sp(src), origin, GrSwizzle("rgba")); if (dstContext && dstContext->blitTexture(std::move(view), srcRect, dstPoint)) { return dstContext->asSurfaceProxyRef(); } } // Can't use backend copies or draws. return nullptr; } sk_sp<GrSurfaceProxy> GrSurfaceProxy::Copy(GrRecordingContext* context, GrSurfaceProxy* src, GrSurfaceOrigin origin, GrMipMapped mipMapped, SkBackingFit fit, SkBudgeted budgeted) { SkASSERT(!src->isFullyLazy()); return Copy(context, src, origin, mipMapped, SkIRect::MakeSize(src->dimensions()), fit, budgeted); } #if GR_TEST_UTILS int32_t GrSurfaceProxy::testingOnly_getBackingRefCnt() const { if (fTarget) { return fTarget->testingOnly_getRefCnt(); } return -1; // no backing GrSurface } GrInternalSurfaceFlags GrSurfaceProxy::testingOnly_getFlags() const { return fSurfaceFlags; } #endif void GrSurfaceProxyPriv::exactify(bool allocatedCaseOnly) { SkASSERT(!fProxy->isFullyLazy()); if (this->isExact()) { return; } SkASSERT(SkBackingFit::kApprox == fProxy->fFit); if (fProxy->fTarget) { // The kApprox but already instantiated case. Setting the proxy's width & height to // the instantiated width & height could have side-effects going forward, since we're // obliterating the area of interest information. This call (exactify) only used // when converting an SkSpecialImage to an SkImage so the proxy shouldn't be // used for additional draws. fProxy->fDimensions = fProxy->fTarget->dimensions(); return; } #ifndef SK_CRIPPLE_TEXTURE_REUSE // In the post-implicit-allocation world we can't convert this proxy to be exact fit // at this point. With explicit allocation switching this to exact will result in a // different allocation at flush time. With implicit allocation, allocation would occur // at draw time (rather than flush time) so this pathway was encountered less often (if // at all). if (allocatedCaseOnly) { return; } #endif // The kApprox uninstantiated case. Making this proxy be exact should be okay. // It could mess things up if prior decisions were based on the approximate size. fProxy->fFit = SkBackingFit::kExact; // If fGpuMemorySize is used when caching specialImages for the image filter DAG. If it has // already been computed we want to leave it alone so that amount will be removed when // the special image goes away. If it hasn't been computed yet it might as well compute the // exact amount. } bool GrSurfaceProxyPriv::doLazyInstantiation(GrResourceProvider* resourceProvider) { SkASSERT(fProxy->isLazy()); sk_sp<GrSurface> surface; if (fProxy->asTextureProxy() && fProxy->asTextureProxy()->getUniqueKey().isValid()) { // First try to reattach to a cached version if the proxy is uniquely keyed surface = resourceProvider->findByUniqueKey<GrSurface>( fProxy->asTextureProxy()->getUniqueKey()); } bool syncKey = true; bool releaseCallback = false; if (!surface) { auto result = fProxy->fLazyInstantiateCallback(resourceProvider, fProxy->callbackDesc()); surface = std::move(result.fSurface); syncKey = result.fKeyMode == GrSurfaceProxy::LazyInstantiationKeyMode::kSynced; releaseCallback = surface && result.fReleaseCallback; } if (!surface) { fProxy->fDimensions.setEmpty(); return false; } if (fProxy->isFullyLazy()) { // This was a fully lazy proxy. We need to fill in the width & height. For partially // lazy proxies we must preserve the original width & height since that indicates // the content area. fProxy->fDimensions = surface->dimensions(); } SkASSERT(fProxy->width() <= surface->width()); SkASSERT(fProxy->height() <= surface->height()); if (GrTextureProxy* texProxy = fProxy->asTextureProxy()) { texProxy->setTargetKeySync(syncKey); if (syncKey) { const GrUniqueKey& key = texProxy->getUniqueKey(); if (key.isValid()) { if (!surface->asTexture()->getUniqueKey().isValid()) { // If 'surface' is newly created, attach the unique key resourceProvider->assignUniqueKeyToResource(key, surface.get()); } else { // otherwise we had better have reattached to a cached version SkASSERT(surface->asTexture()->getUniqueKey() == key); } } else { SkASSERT(!surface->getUniqueKey().isValid()); } } } this->assign(std::move(surface)); if (releaseCallback) { fProxy->fLazyInstantiateCallback = nullptr; } return true; } #ifdef SK_DEBUG void GrSurfaceProxy::validateSurface(const GrSurface* surface) { SkASSERT(surface->backendFormat() == fFormat); this->onValidateSurface(surface); } #endif <|endoftext|>
<commit_before>#include <QCoreApplication> #include <QtDebug> #include <iostream> #include <fstream> //#include <stdio.h> #include <stdlib.h> #include <time.h> #include <cerrno> #include <cmath> #include <thread> #include <mutex> #define OUTPUT_FILE "./trials.csv" #define NUMBER_THREADS 1 #define USE_MULTIPLE_THREADS // create a mutex that is used to protect the writing of the data to // the file. std::mutex writeToFile; #ifndef M_PI #define M_PI 3.14159265359 #endif #define SHOW_PROGRESS //#define SHOW_INTERMEDIATE //#define THREAD_DEBUG #define BASE_DT 0.00001 #define RADIUS 0.06 #ifndef Q_OS_UNIX double drand48() { return((double)(rand())/((double)RAND_MAX)); } #endif void normalDistRand(double stdDev,double* randomNumbers) { /* Generate a random number in polar coordinates */ double radius = sqrt(-2.0*log(drand48())); double angle = 2.0*M_PI*drand48(); /* transform the number back into cartesian coordinates */ randomNumbers[0] = stdDev*radius*sin(angle); randomNumbers[1] = stdDev*radius*cos(angle); } void printToCSVFile(double dt, double beta, double g,double tau, double q, double theta, double h,double s, double *x,std::ofstream *fp) { std::lock_guard<std::mutex> guard(writeToFile); // Make sure that // this routine // can only // access the file once // at any one time. *fp << dt << "," << beta << "," << g << "," << tau << "," << q+1 << "," << theta << "," << h << "," << s << "," << 1-h-s << "," << x[0] << "," << x[1] << "," << 1-x[0]-x[1] << "," << x[2] << "," << x[3] << "," << 1-x[2]-x[3] << std::endl; (*fp).flush(); } void linear(long steps, double a,double gamma,double r,double d,double g, double *x,double *y,double *z, double dt, int n, double beta,double tau, std::ofstream *fp, int q, double h,double s,double *v,double *w, double theta) { long m=n-1; long p=0; double B[2]; int calcRandom=0; #ifdef THREAD_DEBUG std::cout << "My thread id: " << std::this_thread::get_id() << std::endl; #endif // Step through every time step. for (long k=0;k<steps;k++) { // Calculate a new set of random numbers if necessary. if(calcRandom==0) normalDistRand(sqrt(dt),B); //noise in most recent time step //x[0]=y[m]+(y[m]*(gamma-gamma*y[m]+(a-gamma)*z[m])-(g*y[p]/(1-z[p])))*dt //x[0]=x[0]+beta*y[m]*(1-y[m])+0.5*beta*y[m]*(1-y[m])*beta*(1-2*y[m])*(B[calcRandom]*B[calcRandom]-dt); //Computes the deterministic component for Macroalgae x[0] = y[m]+(y[m]*(gamma-gamma*y[m]+(a-gamma)*z[m])-(g*y[p]/(1-z[p])))*dt; //Adds in the noise //x[0]=x[0]+beta*y[m]*B[calcRandom]+0.5*beta*y[m]*beta*(B[calcRandom]*B[calcRandom]-dt); x[0] += beta*y[m]*B[calcRandom]+0.5*beta*beta*y[m]*(B[calcRandom]*B[calcRandom]-dt); //Computes the deterministic component for Coral x[1] = z[m]+(z[m]*(r-d-(a+r)*y[m]-r*z[m]))*dt; x[2] = v[m]+(v[m]*(gamma-gamma*v[m]+(a-gamma)*w[m])-(g*v[p]/(1-w[p])))*dt; x[2] += beta*v[m]*(1-v[m])*B[calcRandom]+0.5*beta*(1-2*v[m])*beta*v[m]*(1-v[m])*(B[calcRandom]*B[calcRandom]-dt); x[3] = w[m]+(w[m]*(r-d-(a+r)*v[m]-r*w[m]))*dt; /**************************************************************** Account for extinction and overgrowing!! ****************************************************************/ for(int i=0;i<4;++i) { if(x[i]<0.0) x[i] = 0.0; else if (x[i]>1.0) x[i] = 1.0; } //Updates delay and cell index m=(m+1)%n; p=(p+1)%n; y[m]=x[0]; z[m]=x[1]; v[m]=x[2]; w[m]=x[3]; calcRandom = (calcRandom+1)%2; // update which random number to use. } //printf("%f\t%f\t%f\t%f\t%f\n",dt,beta,tau,x[0],x[1]); printToCSVFile(dt,beta,g,tau,q,theta,h,s,x,fp); #ifdef SHOW_INTERMEDIATE qDebug() << dt << "," << beta << "," << g << "," << tau << "," << q+1 << "," << h << "," << s << "," << 1-h-s << "," << x[0] << "," << x[1] << "," << 1-x[0]-x[1] << "," << x[2] << "," << x[3] << "," << 1-x[2]-x[3]; qDebug() << errno << EDOM << ERANGE; #endif } /* **************************************************************** main The main function. Called at the start of the program. **************************************************************** */ int main(int argc, char *argv[]) { QCoreApplication b(argc, argv); long steps; // The number of steps to take in a single simulation. double *v,*w,*x,*y,*z; // The variables used for the state of the system. /* Define the constants. These are the parameters that are used in the operator for the differential equations. */ double a = 0.1; double g ;// = 0.3; double gamma = 0.8; double r = 1.0; double d = 0.44; double tau; double beta ;// = .5; // double gZero = ((d*a*r+d*d)*(gamma-a))/(r*r); // double gOne = (gamma*(a+d))/(a+r); // double chi = r*gamma/(r+a)-gamma+a; //Intermediate Step // double xi = -(d*gamma/(r+a)+a); //Intermediate Step // double cbar = (-xi-sqrt(xi*xi-4*chi*g))/(2*chi); //Intermediate Step // double coralSaddle = 1-cbar; //Saddle point value for coral // double macroSaddle = (r-r*coralSaddle-d)/(r+a); //Saddle point value for macroalgae // long numberDT; // The current iteration for the number assocated with the value of dt. // double omega = sqrt((r*r*(g*g-gZero*gZero))/(d*d)); // double tauZero = (1/omega)*acos(gZero/g); double dt = BASE_DT; // Set the initial time step double final; // The final time for each simulation. long trials; // The number of simulations to make. final=50.0; // Set the final time. trials=400; // Set the number of trials to perform. // Set the time delay, tau //double tau = 0.5; // set up the variables for using different approximations on different threads. std::thread simulation[NUMBER_THREADS]; int numberThreads = 0; // Sets the seed for the random numbers #ifdef Q_OS_UNIX srand48(time(NULL)); //qDebug() << "This is a POSIX system!" ; #else srand(time(NULL)); #endif // Create a CSV File std::ofstream fp; //String fileName = "trials-g" + std::toString(g) + "-tau" + std::toString(tau); fp.open(OUTPUT_FILE,std::ios::out | std::ios::trunc); fp << "dt,beta,g,tau,trial,theta,initMacro,initCoral,initTurf,macroalgae,coral,turf,lgMacro,lgCoral,lgTurf" << std::endl; for(tau = .2; tau <= .4; tau += .2 ){ // Determine the number of time steps required to move back to the delay in time. // The number of cells needed for the delay (changes with dt) int n; if(tau != 0) n=(int)(tau/BASE_DT+0.5); else n = 1; // Allocate the space for the states of the system x=(double *) calloc(4,sizeof(double)); y=(double *) calloc(n,sizeof(double)); //macroalgae for multiplicative noise z=(double *) calloc(n,sizeof(double)); //coral for multiplicative noise v=(double *) calloc(n,sizeof(double)); //macroalgae for logistic noise w=(double *) calloc(n,sizeof(double)); //coral for logistic noise for(g=.2; g<.8; g += .2) { //double omega = sqrt((r*r*(g*g-gZero*gZero))/(d*d)); // double tauZero = (1/omega)*acos(gZero/g); // Make different approximations for different values of beta. for(beta=.2;beta<=1; beta += .2) { #ifdef SHOW_PROGRESS std::cout << "dt = " << dt << std::endl; #endif //index = tau/dt; //printf("%i\n",n); steps=(long)(final/dt); for (double theta=0;theta<=M_PI/2;theta+=(M_PI*0.5)*0.025) { // Make an approximation for different initial conditions. // Make an arc through 0 to pi/2 radians from the origin. for (int k=0;k<trials;k++) { y[0] = RADIUS*cos(theta); //initial Macroalgae level z[0] = RADIUS*sin(theta); //initial Coral level v[0] = RADIUS*cos(theta); w[0] = RADIUS*sin(theta); for (int l=1;l<n;l++) //fills in the past times for y, z, v, and w { y[l]=y[0]; z[l]=z[0]; v[l]=v[0]; w[l]=w[0]; } //fprintf(fp,"%f,%f,%f,%f,%f,%f\n",y[0],z[0],1-y[0]-z[0],v[0],w[0],1-v[0]-w[0]); #ifdef USE_MULTIPLE_THREADS // Make a simulation for each of the available threads. // First check to see how many threads are running. if(numberThreads >= NUMBER_THREADS) { // There are too many threads. Wait for each run to end. while(numberThreads>0) { #ifdef THREAD_DEBUG std::cout << "Waiting on thread " << simulation[numberThreads-1].get_id() << std::endl; #endif simulation[--numberThreads].join(); } } // if(numberThreads) // Make a run in a separate thread. simulation[numberThreads++] = std::thread(linear, steps,a,gamma,r,d,g,x,y,z,dt,n,beta,tau,&fp,k,y[0],z[0],v,w,theta); #else // Ignore the different threads. Just make one approximation in this one thread. linear(steps,a,gamma,r,d,g,x,y,z,dt,n,beta,tau,&fp,k,y[0],z[0],v,w,theta); #endif #ifdef SHOW_PROGRESS if(k%20 == 0) std::cout << " Simulation number " << k << std::endl; #endif } // for(k<trials) } // for(theta<pi/2 } } // Free up the allocated memory. free(x); free(y); free(z); free(v); free(w); } fp.close(); #ifdef SHOW_PROGRESS std::cout << "all done" << std::endl; #endif return b.exec(); } <commit_msg>Added a check to make sure the memory could be allocated for the delay<commit_after>#include <QCoreApplication> #include <QtDebug> #include <iostream> #include <fstream> //#include <stdio.h> #include <stdlib.h> #include <time.h> #include <cerrno> #include <cmath> #include <thread> #include <mutex> #define OUTPUT_FILE "./trials.csv" #define NUMBER_THREADS 1 #define USE_MULTIPLE_THREADS // create a mutex that is used to protect the writing of the data to // the file. std::mutex writeToFile; #ifndef M_PI #define M_PI 3.14159265359 #endif #define SHOW_PROGRESS //#define SHOW_INTERMEDIATE //#define THREAD_DEBUG #define BASE_DT 0.00001 #define RADIUS 0.06 #ifndef Q_OS_UNIX double drand48() { return((double)(rand())/((double)RAND_MAX)); } #endif void normalDistRand(double stdDev,double* randomNumbers) { /* Generate a random number in polar coordinates */ double radius = sqrt(-2.0*log(drand48())); double angle = 2.0*M_PI*drand48(); /* transform the number back into cartesian coordinates */ randomNumbers[0] = stdDev*radius*sin(angle); randomNumbers[1] = stdDev*radius*cos(angle); } void printToCSVFile(double dt, double beta, double g,double tau, double q, double theta, double h,double s, double *x,std::ofstream *fp) { std::lock_guard<std::mutex> guard(writeToFile); // Make sure that // this routine // can only // access the file once // at any one time. *fp << dt << "," << beta << "," << g << "," << tau << "," << q+1 << "," << theta << "," << h << "," << s << "," << 1-h-s << "," << x[0] << "," << x[1] << "," << 1-x[0]-x[1] << "," << x[2] << "," << x[3] << "," << 1-x[2]-x[3] << std::endl; (*fp).flush(); } void linear(long steps, double a,double gamma,double r,double d,double g, double *x,double *y,double *z, double dt, int n, double beta,double tau, std::ofstream *fp, int q, double h,double s,double *v,double *w, double theta) { long m=n-1; long p=0; double B[2]; int calcRandom=0; #ifdef THREAD_DEBUG std::cout << "My thread id: " << std::this_thread::get_id() << std::endl; #endif // Step through every time step. for (long k=0;k<steps;k++) { // Calculate a new set of random numbers if necessary. if(calcRandom==0) normalDistRand(sqrt(dt),B); //noise in most recent time step //x[0]=y[m]+(y[m]*(gamma-gamma*y[m]+(a-gamma)*z[m])-(g*y[p]/(1-z[p])))*dt //x[0]=x[0]+beta*y[m]*(1-y[m])+0.5*beta*y[m]*(1-y[m])*beta*(1-2*y[m])*(B[calcRandom]*B[calcRandom]-dt); //Computes the deterministic component for Macroalgae x[0] = y[m]+(y[m]*(gamma-gamma*y[m]+(a-gamma)*z[m])-(g*y[p]/(1-z[p])))*dt; //Adds in the noise //x[0]=x[0]+beta*y[m]*B[calcRandom]+0.5*beta*y[m]*beta*(B[calcRandom]*B[calcRandom]-dt); x[0] += beta*y[m]*B[calcRandom]+0.5*beta*beta*y[m]*(B[calcRandom]*B[calcRandom]-dt); //Computes the deterministic component for Coral x[1] = z[m]+(z[m]*(r-d-(a+r)*y[m]-r*z[m]))*dt; x[2] = v[m]+(v[m]*(gamma-gamma*v[m]+(a-gamma)*w[m])-(g*v[p]/(1-w[p])))*dt; x[2] += beta*v[m]*(1-v[m])*B[calcRandom]+0.5*beta*(1-2*v[m])*beta*v[m]*(1-v[m])*(B[calcRandom]*B[calcRandom]-dt); x[3] = w[m]+(w[m]*(r-d-(a+r)*v[m]-r*w[m]))*dt; /**************************************************************** Account for extinction and overgrowing!! ****************************************************************/ for(int i=0;i<4;++i) { if(x[i]<0.0) x[i] = 0.0; else if (x[i]>1.0) x[i] = 1.0; } //Updates delay and cell index m=(m+1)%n; p=(p+1)%n; y[m]=x[0]; z[m]=x[1]; v[m]=x[2]; w[m]=x[3]; calcRandom = (calcRandom+1)%2; // update which random number to use. } //printf("%f\t%f\t%f\t%f\t%f\n",dt,beta,tau,x[0],x[1]); printToCSVFile(dt,beta,g,tau,q,theta,h,s,x,fp); #ifdef SHOW_INTERMEDIATE qDebug() << dt << "," << beta << "," << g << "," << tau << "," << q+1 << "," << h << "," << s << "," << 1-h-s << "," << x[0] << "," << x[1] << "," << 1-x[0]-x[1] << "," << x[2] << "," << x[3] << "," << 1-x[2]-x[3]; qDebug() << errno << EDOM << ERANGE; #endif } /* **************************************************************** main The main function. Called at the start of the program. **************************************************************** */ int main(int argc, char *argv[]) { QCoreApplication b(argc, argv); long steps; // The number of steps to take in a single simulation. double *v,*w,*x,*y,*z; // The variables used for the state of the system. /* Define the constants. These are the parameters that are used in the operator for the differential equations. */ double a = 0.1; double g ;// = 0.3; double gamma = 0.8; double r = 1.0; double d = 0.44; double tau; double beta ;// = .5; // double gZero = ((d*a*r+d*d)*(gamma-a))/(r*r); // double gOne = (gamma*(a+d))/(a+r); // double chi = r*gamma/(r+a)-gamma+a; //Intermediate Step // double xi = -(d*gamma/(r+a)+a); //Intermediate Step // double cbar = (-xi-sqrt(xi*xi-4*chi*g))/(2*chi); //Intermediate Step // double coralSaddle = 1-cbar; //Saddle point value for coral // double macroSaddle = (r-r*coralSaddle-d)/(r+a); //Saddle point value for macroalgae // long numberDT; // The current iteration for the number assocated with the value of dt. // double omega = sqrt((r*r*(g*g-gZero*gZero))/(d*d)); // double tauZero = (1/omega)*acos(gZero/g); double dt = BASE_DT; // Set the initial time step double final; // The final time for each simulation. long trials; // The number of simulations to make. final=50.0; // Set the final time. trials=400; // Set the number of trials to perform. // Set the time delay, tau //double tau = 0.5; // set up the variables for using different approximations on different threads. std::thread simulation[NUMBER_THREADS]; int numberThreads = 0; // Sets the seed for the random numbers #ifdef Q_OS_UNIX srand48(time(NULL)); //qDebug() << "This is a POSIX system!" ; #else srand(time(NULL)); #endif // Create a CSV File std::ofstream fp; //String fileName = "trials-g" + std::toString(g) + "-tau" + std::toString(tau); fp.open(OUTPUT_FILE,std::ios::out | std::ios::trunc); fp << "dt,beta,g,tau,trial,theta,initMacro,initCoral,initTurf,macroalgae,coral,turf,lgMacro,lgCoral,lgTurf" << std::endl; for(tau = .2; tau <= .4; tau += .2 ) { // Determine the number of time steps required to move back to the delay in time. // The number of cells needed for the delay (changes with dt) int n; if(tau > 0.0) n=(int)(tau/BASE_DT+0.5); else n = 1; // Allocate the space for the states of the system x=(double *) calloc(4,sizeof(double)); y=(double *) calloc(n,sizeof(double)); //macroalgae for multiplicative noise z=(double *) calloc(n,sizeof(double)); //coral for multiplicative noise v=(double *) calloc(n,sizeof(double)); //macroalgae for logistic noise w=(double *) calloc(n,sizeof(double)); //coral for logistic noise if((x==NULL) || (y==NULL) || (z==NULL) || (w==NULL)) { std::cout << "Error - unable to allocate necessary memory." << std::endl; free(x); free(y); free(z); free(v); free(w); return b.exec(); } for(g=.2; g<.8; g += .2) { //double omega = sqrt((r*r*(g*g-gZero*gZero))/(d*d)); // double tauZero = (1/omega)*acos(gZero/g); // Make different approximations for different values of beta. for(beta=.2;beta<=1.0; beta += .2) { #ifdef SHOW_PROGRESS std::cout << "dt = " << dt << std::endl; #endif //index = tau/dt; //printf("%i\n",n); steps=(long)(final/dt); for (double theta=0;theta<=M_PI/2;theta+=(M_PI*0.5)*0.025) { // Make an approximation for different initial conditions. // Make an arc through 0 to pi/2 radians from the origin. for (int k=0;k<trials;k++) { y[0] = RADIUS*cos(theta); //initial Macroalgae level z[0] = RADIUS*sin(theta); //initial Coral level v[0] = RADIUS*cos(theta); w[0] = RADIUS*sin(theta); for (int l=1;l<n;l++) //fills in the past times for y, z, v, and w { y[l]=y[0]; z[l]=z[0]; v[l]=v[0]; w[l]=w[0]; } //fprintf(fp,"%f,%f,%f,%f,%f,%f\n",y[0],z[0],1-y[0]-z[0],v[0],w[0],1-v[0]-w[0]); #ifdef USE_MULTIPLE_THREADS // Make a simulation for each of the available threads. // First check to see how many threads are running. if(numberThreads >= NUMBER_THREADS) { // There are too many threads. Wait for each run to end. while(numberThreads>0) { #ifdef THREAD_DEBUG std::cout << "Waiting on thread " << simulation[numberThreads-1].get_id() << std::endl; #endif simulation[--numberThreads].join(); } } // if(numberThreads) // Make a run in a separate thread. simulation[numberThreads++] = std::thread(linear, steps,a,gamma,r,d,g,x,y,z,dt,n,beta,tau,&fp,k,y[0],z[0],v,w,theta); #else // Ignore the different threads. Just make one approximation in this one thread. linear(steps,a,gamma,r,d,g,x,y,z,dt,n,beta,tau,&fp,k,y[0],z[0],v,w,theta); #endif #ifdef SHOW_PROGRESS if(k%20 == 0) std::cout << " Simulation number " << k << std::endl; #endif } // for(k<trials) } // for(theta<pi/2 } } // Free up the allocated memory. free(x); free(y); free(z); free(v); free(w); } fp.close(); #ifdef SHOW_PROGRESS std::cout << "all done" << std::endl; #endif return b.exec(); } <|endoftext|>
<commit_before>extern "C" { #include "postgres.h" #include "fmgr.h" #include "catalog/pg_type.h" #include "utils/uuid.h" #include "executor/spi.h" #include "provsql_shmem.h" #include "provsql_utils.h" PG_FUNCTION_INFO_V1(probability_evaluate); } #include <set> #include <cmath> #include <csignal> #include "BooleanCircuit.h" #include "provsql_utils_cpp.h" #include "dDNNFTreeDecompositionBuilder.h" #include <sstream> using namespace std; static void provsql_sigint_handler (int) { provsql_interrupted = true; } bool operator<(const pg_uuid_t a, const pg_uuid_t b) { return memcmp(&a, &b, sizeof(pg_uuid_t))<0; } static Datum probability_evaluate_internal (pg_uuid_t token, const string &method, const string &args) { std::set<pg_uuid_t> to_process, processed; to_process.insert(token); BooleanCircuit c; LWLockAcquire(provsql_shared_state->lock, LW_SHARED); while(!to_process.empty()) { pg_uuid_t uuid = *to_process.begin(); to_process.erase(to_process.begin()); processed.insert(uuid); std::string f{uuid2string(uuid)}; bool found; provsqlHashEntry *entry = (provsqlHashEntry *) hash_search(provsql_hash, &uuid, HASH_FIND, &found); gate_t id; if(!found) id = c.setGate(f, BooleanGate::MULVAR); else { switch(entry->type) { case gate_input: if(isnan(entry->prob)) { LWLockRelease(provsql_shared_state->lock); elog(ERROR, "Missing probability for input token"); } id = c.setGate(f, BooleanGate::IN, entry->prob); break; case gate_mulinput: if(isnan(entry->prob)) { LWLockRelease(provsql_shared_state->lock); elog(ERROR, "Missing probability for input token"); } id = c.setGate(f, BooleanGate::MULIN, entry->prob); c.addWire( id, c.getGate(uuid2string(provsql_shared_state->wires[entry->children_idx]))); c.setInfo(id, entry->info1); break; case gate_times: case gate_project: case gate_eq: case gate_monus: case gate_one: id = c.setGate(f, BooleanGate::AND); break; case gate_plus: case gate_zero: id = c.setGate(f, BooleanGate::OR); break; default: elog(ERROR, "Wrong type of gate in circuit"); } if(entry->nb_children > 0) { if(entry->type == gate_monus) { auto id_not = c.setGate(BooleanGate::NOT); auto child1 = provsql_shared_state->wires[entry->children_idx]; auto child2 = provsql_shared_state->wires[entry->children_idx+1]; c.addWire( id, c.getGate(uuid2string(child1))); c.addWire(id, id_not); c.addWire( id_not, c.getGate(uuid2string(child2))); if(processed.find(child1)==processed.end()) to_process.insert(child1); if(processed.find(child2)==processed.end()) to_process.insert(child2); } else { for(unsigned i=0;i<entry->nb_children;++i) { auto child = provsql_shared_state->wires[entry->children_idx+i]; c.addWire( id, c.getGate(uuid2string(child))); if(processed.find(child)==processed.end()) to_process.insert(child); } } } } } LWLockRelease(provsql_shared_state->lock); // Display the circuit for debugging: // elog(WARNING, "%s", c.toString(c.getGate(UUIDDatum2string(token))).c_str()); double result; auto gate = c.getGate(uuid2string(token)); provsql_interrupted = false; void (*prev_sigint_handler)(int); prev_sigint_handler = signal(SIGINT, provsql_sigint_handler); try { bool processed=false; if(method=="independent") { result = c.independentEvaluation(gate); processed = true; } else if(method=="") { // Default evaluation, use independent, tree-decomposition, and // compilation in order until one works try { result = c.independentEvaluation(gate); processed = true; } catch(CircuitException &) {} } if(!processed) { // Other methods do not deal with multivalued input gates, they // need to be rewritten c.rewriteMultivaluedGates(); if(method=="monte-carlo") { int samples=0; try { samples = stoi(args); } catch(std::invalid_argument &e) { } if(samples<=0) elog(ERROR, "Invalid number of samples: '%s'", args.c_str()); result = c.monteCarlo(gate, samples); } else if(method=="possible-worlds") { if(!args.empty()) elog(WARNING, "Argument '%s' ignored for method possible-worlds", args.c_str()); result = c.possibleWorlds(gate); } else if(method=="compilation") { result = c.compilation(gate, args); } else if(method=="weightmc") { result = c.WeightMC(gate, args); } else if(method=="tree-decomposition") { try { TreeDecomposition td(c); auto dnnf{ dDNNFTreeDecompositionBuilder{ c, uuid2string(token), td}.build() }; result = dnnf.dDNNFEvaluation(dnnf.getGate("root")); elog(WARNING, "%d", dnnf.getGate("root")); } catch(TreeDecompositionException &) { elog(ERROR, "Treewidth greater than %u", TreeDecomposition::MAX_TREEWIDTH); } } else if(method=="") { try { TreeDecomposition td(c); auto dnnf{ dDNNFTreeDecompositionBuilder{ c, uuid2string(token), td}.build() }; result = dnnf.dDNNFEvaluation(dnnf.getGate("root")); } catch(TreeDecompositionException &) { result = c.compilation(gate, "d4"); } } else { elog(ERROR, "Wrong method '%s' for probability evaluation", method.c_str()); } } } catch(CircuitException &e) { elog(ERROR, "%s", e.what()); } provsql_interrupted = false; signal (SIGINT, prev_sigint_handler); PG_RETURN_FLOAT8(result); } Datum probability_evaluate(PG_FUNCTION_ARGS) { try { Datum token = PG_GETARG_DATUM(0); string method; string args; if(PG_ARGISNULL(0)) PG_RETURN_NULL(); if(!PG_ARGISNULL(1)) { text *t = PG_GETARG_TEXT_P(1); method = string(VARDATA(t),VARSIZE(t)-VARHDRSZ); } if(!PG_ARGISNULL(2)) { text *t = PG_GETARG_TEXT_P(2); args = string(VARDATA(t),VARSIZE(t)-VARHDRSZ); } return probability_evaluate_internal(*DatumGetUUIDP(token), method, args); } catch(const std::exception &e) { elog(ERROR, "probability_evaluate: %s", e.what()); } catch(...) { elog(ERROR, "probability_evaluate: Unknown exception"); } PG_RETURN_NULL(); } <commit_msg>More debug info<commit_after>extern "C" { #include "postgres.h" #include "fmgr.h" #include "catalog/pg_type.h" #include "utils/uuid.h" #include "executor/spi.h" #include "provsql_shmem.h" #include "provsql_utils.h" PG_FUNCTION_INFO_V1(probability_evaluate); } #include <set> #include <cmath> #include <csignal> #include "BooleanCircuit.h" #include "provsql_utils_cpp.h" #include "dDNNFTreeDecompositionBuilder.h" #include <sstream> using namespace std; static void provsql_sigint_handler (int) { provsql_interrupted = true; } bool operator<(const pg_uuid_t a, const pg_uuid_t b) { return memcmp(&a, &b, sizeof(pg_uuid_t))<0; } static Datum probability_evaluate_internal (pg_uuid_t token, const string &method, const string &args) { std::set<pg_uuid_t> to_process, processed; to_process.insert(token); BooleanCircuit c; LWLockAcquire(provsql_shared_state->lock, LW_SHARED); while(!to_process.empty()) { pg_uuid_t uuid = *to_process.begin(); to_process.erase(to_process.begin()); processed.insert(uuid); std::string f{uuid2string(uuid)}; bool found; provsqlHashEntry *entry = (provsqlHashEntry *) hash_search(provsql_hash, &uuid, HASH_FIND, &found); gate_t id; if(!found) id = c.setGate(f, BooleanGate::MULVAR); else { switch(entry->type) { case gate_input: if(isnan(entry->prob)) { LWLockRelease(provsql_shared_state->lock); elog(ERROR, "Missing probability for input token"); } id = c.setGate(f, BooleanGate::IN, entry->prob); break; case gate_mulinput: if(isnan(entry->prob)) { LWLockRelease(provsql_shared_state->lock); elog(ERROR, "Missing probability for input token"); } id = c.setGate(f, BooleanGate::MULIN, entry->prob); c.addWire( id, c.getGate(uuid2string(provsql_shared_state->wires[entry->children_idx]))); c.setInfo(id, entry->info1); break; case gate_times: case gate_project: case gate_eq: case gate_monus: case gate_one: id = c.setGate(f, BooleanGate::AND); break; case gate_plus: case gate_zero: id = c.setGate(f, BooleanGate::OR); break; default: elog(ERROR, "Wrong type of gate in circuit"); } if(entry->nb_children > 0) { if(entry->type == gate_monus) { auto id_not = c.setGate(BooleanGate::NOT); auto child1 = provsql_shared_state->wires[entry->children_idx]; auto child2 = provsql_shared_state->wires[entry->children_idx+1]; c.addWire( id, c.getGate(uuid2string(child1))); c.addWire(id, id_not); c.addWire( id_not, c.getGate(uuid2string(child2))); if(processed.find(child1)==processed.end()) to_process.insert(child1); if(processed.find(child2)==processed.end()) to_process.insert(child2); } else { for(unsigned i=0;i<entry->nb_children;++i) { auto child = provsql_shared_state->wires[entry->children_idx+i]; c.addWire( id, c.getGate(uuid2string(child))); if(processed.find(child)==processed.end()) to_process.insert(child); } } } } } LWLockRelease(provsql_shared_state->lock); // Display the circuit for debugging: // elog(WARNING, "%s", c.toString(c.getGate(UUIDDatum2string(token))).c_str()); double result; auto gate = c.getGate(uuid2string(token)); provsql_interrupted = false; void (*prev_sigint_handler)(int); prev_sigint_handler = signal(SIGINT, provsql_sigint_handler); try { bool processed=false; if(method=="independent") { result = c.independentEvaluation(gate); processed = true; } else if(method=="") { // Default evaluation, use independent, tree-decomposition, and // compilation in order until one works try { result = c.independentEvaluation(gate); processed = true; } catch(CircuitException &) {} } if(!processed) { // Other methods do not deal with multivalued input gates, they // need to be rewritten c.rewriteMultivaluedGates(); if(method=="monte-carlo") { int samples=0; try { samples = stoi(args); } catch(std::invalid_argument &e) { } if(samples<=0) elog(ERROR, "Invalid number of samples: '%s'", args.c_str()); result = c.monteCarlo(gate, samples); } else if(method=="possible-worlds") { if(!args.empty()) elog(WARNING, "Argument '%s' ignored for method possible-worlds", args.c_str()); result = c.possibleWorlds(gate); } else if(method=="compilation") { result = c.compilation(gate, args); } else if(method=="weightmc") { result = c.WeightMC(gate, args); } else if(method=="tree-decomposition") { try { TreeDecomposition td(c); auto dnnf{ dDNNFTreeDecompositionBuilder{ c, uuid2string(token), td}.build() }; elog(WARNING, "%d %d %d %s", c.getNbGates(), td.getTreewidth(), dnnf.getNbGates(), td.toDot().c_str()); result = dnnf.dDNNFEvaluation(dnnf.getGate("root")); elog(WARNING, "%d", dnnf.getGate("root")); } catch(TreeDecompositionException &) { elog(ERROR, "Treewidth greater than %u", TreeDecomposition::MAX_TREEWIDTH); } } else if(method=="") { try { TreeDecomposition td(c); auto dnnf{ dDNNFTreeDecompositionBuilder{ c, uuid2string(token), td}.build() }; result = dnnf.dDNNFEvaluation(dnnf.getGate("root")); } catch(TreeDecompositionException &) { result = c.compilation(gate, "d4"); } } else { elog(ERROR, "Wrong method '%s' for probability evaluation", method.c_str()); } } } catch(CircuitException &e) { elog(ERROR, "%s", e.what()); } provsql_interrupted = false; signal (SIGINT, prev_sigint_handler); PG_RETURN_FLOAT8(result); } Datum probability_evaluate(PG_FUNCTION_ARGS) { try { Datum token = PG_GETARG_DATUM(0); string method; string args; if(PG_ARGISNULL(0)) PG_RETURN_NULL(); if(!PG_ARGISNULL(1)) { text *t = PG_GETARG_TEXT_P(1); method = string(VARDATA(t),VARSIZE(t)-VARHDRSZ); } if(!PG_ARGISNULL(2)) { text *t = PG_GETARG_TEXT_P(2); args = string(VARDATA(t),VARSIZE(t)-VARHDRSZ); } return probability_evaluate_internal(*DatumGetUUIDP(token), method, args); } catch(const std::exception &e) { elog(ERROR, "probability_evaluate: %s", e.what()); } catch(...) { elog(ERROR, "probability_evaluate: Unknown exception"); } PG_RETURN_NULL(); } <|endoftext|>
<commit_before>// // libavg - Media Playback Engine. // Copyright (C) 2003-2011 Ulrich von Zadow // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Current versions can be found at www.libavg.de // #include "GLTexture.h" #include "../base/Exception.h" #include "../base/StringHelper.h" #include "../base/MathHelper.h" #include "../base/ObjectCounter.h" #include "GLContext.h" #include "TextureMover.h" #include "PBO.h" #include "FBO.h" #include "Filterfliprgb.h" #include <string.h> #include <iostream> namespace avg { using namespace std; // We assign our own texture ids and never reuse them instead of using glGenTextures. // That works very well, except that other components (e.g. Ogre3d) with shared gl // contexts don't know anything about our ids and thus use the same ones. // Somewhat hackish solution: Assign ids starting with a very high id, so the id ranges // don't overlap. unsigned GLTexture::s_LastTexID = 10000000; GLTexture::GLTexture(const IntPoint& size, PixelFormat pf, bool bMipmap, int potBorderColor, unsigned wrapSMode, unsigned wrapTMode, bool bForcePOT) : m_Size(size), m_pf(pf), m_bMipmap(bMipmap), m_bDeleteTex(true) { m_pGLContext = GLContext::getCurrent(); ObjectCounter::get()->incRef(&typeid(*this)); m_bUsePOT = m_pGLContext->usePOTTextures() || bForcePOT; if (m_pGLContext->isGLES() && bMipmap) { m_bUsePOT = true; } if (m_bUsePOT) { m_GLSize.x = nextpow2(m_Size.x); m_GLSize.y = nextpow2(m_Size.y); } else { m_GLSize = m_Size; } int maxTexSize = m_pGLContext->getMaxTexSize(); if (m_Size.x > maxTexSize || m_Size.y > maxTexSize) { throw Exception(AVG_ERR_VIDEO_GENERAL, "Texture too large (" + toString(m_Size) + "). Maximum supported by graphics card is " + toString(maxTexSize)); } if (getGLType(m_pf) == GL_FLOAT && !isFloatFormatSupported()) { throw Exception(AVG_ERR_UNSUPPORTED, "Float textures not supported by OpenGL configuration."); } s_LastTexID++; m_TexID = s_LastTexID; m_pGLContext->bindTexture(GL_TEXTURE0, m_TexID); if (bMipmap) { glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); } else { glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); } glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapSMode); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapTMode); glTexImage2D(GL_TEXTURE_2D, 0, getGLInternalFormat(), m_GLSize.x, m_GLSize.y, 0, getGLFormat(m_pf), getGLType(m_pf), 0); GLContext::checkError("GLTexture: glTexImage2D()"); if (m_bUsePOT) { // Make sure the texture is transparent and black before loading stuff // into it to avoid garbage at the borders. // In the case of UV textures, we set the border color to 128... int TexMemNeeded = m_GLSize.x*m_GLSize.y*getBytesPerPixel(m_pf); char * pPixels = new char[TexMemNeeded]; memset(pPixels, potBorderColor, TexMemNeeded); glTexImage2D(GL_TEXTURE_2D, 0, getGLInternalFormat(), m_GLSize.x, m_GLSize.y, 0, getGLFormat(m_pf), getGLType(m_pf), pPixels); GLContext::checkError("PBOTexture::createTexture: glTexImage2D()"); delete[] pPixels; } } GLTexture::GLTexture(unsigned glTexID, const IntPoint& size, PixelFormat pf, bool bMipmap, bool bDeleteTex) : m_Size(size), m_GLSize(size), m_pf(pf), m_bMipmap(bMipmap), m_bDeleteTex(bDeleteTex), m_bUsePOT(false), m_TexID(glTexID) { m_pGLContext = GLContext::getCurrent(); ObjectCounter::get()->incRef(&typeid(*this)); } GLTexture::~GLTexture() { if (m_bDeleteTex) { glDeleteTextures(1, &m_TexID); GLContext::checkError("GLTexture: DeleteTextures()"); } ObjectCounter::get()->decRef(&typeid(*this)); } void GLTexture::activate(int textureUnit) { m_pGLContext->bindTexture(textureUnit, m_TexID); } void GLTexture::generateMipmaps() { if (m_bMipmap) { activate(); glproc::GenerateMipmap(GL_TEXTURE_2D); GLContext::checkError("GLTexture::generateMipmaps()"); } } void GLTexture::setWrapMode(unsigned wrapSMode, unsigned wrapTMode) { activate(); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapSMode); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapTMode); } void GLTexture::enableStreaming() { m_pMover = TextureMover::create(m_Size, m_pf, GL_STREAM_DRAW); } BitmapPtr GLTexture::lockStreamingBmp() { AVG_ASSERT(m_pMover); return m_pMover->lock(); } void GLTexture::unlockStreamingBmp(bool bUpdated) { AVG_ASSERT(m_pMover); m_pMover->unlock(); if (bUpdated) { m_pMover->moveToTexture(*this); } } void GLTexture::moveBmpToTexture(BitmapPtr pBmp) { TextureMoverPtr pMover = TextureMover::create(m_Size, m_pf, GL_DYNAMIC_DRAW); pMover->moveBmpToTexture(pBmp, *this); } BitmapPtr GLTexture::moveTextureToBmp() { if (GLContext::getCurrent()->getMemoryModeSupported() == MM_PBO) { return PBO(m_GLSize, m_pf, GL_DYNAMIC_READ).moveTextureToBmp(*this); } else { unsigned fbo = GLContext::getCurrent()->genFBO(); glproc::BindFramebuffer(GL_FRAMEBUFFER_EXT, fbo); glproc::FramebufferTexture2D(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, m_TexID, 0); FBO::checkError("moveTextureToBmp"); BitmapPtr pBmp(new Bitmap(m_Size, m_pf)); glReadPixels(0, 0, m_Size.x, m_Size.y, GL_RGBA, GL_UNSIGNED_BYTE, pBmp->getPixels()); FilterFlipRGB().applyInPlace(pBmp); return pBmp; } } const IntPoint& GLTexture::getSize() const { return m_Size; } const IntPoint& GLTexture::getGLSize() const { return m_GLSize; } PixelFormat GLTexture::getPF() const { return m_pf; } unsigned GLTexture::getID() const { return m_TexID; } IntPoint GLTexture::getMipmapSize(int level) const { AVG_ASSERT(!m_bUsePOT); IntPoint size = m_Size; for (int i=0; i<level; ++i) { size.x = max(1, size.x >> 1); size.y = max(1, size.y >> 1); } return size; } bool GLTexture::isFloatFormatSupported() { #ifdef __APPLE__ string sVendor ((const char*)glGetString(GL_VENDOR)); if (sVendor.find("Intel") != string::npos) { // Avoid buggy Mac Book Air(Intel HD) issues under lion return false; } #endif return queryOGLExtension("GL_ARB_texture_float"); } int GLTexture::getGLFormat(PixelFormat pf) { switch (pf) { case I8: case I32F: return GL_LUMINANCE; case A8: return GL_ALPHA; case R8G8B8A8: case R8G8B8X8: return GL_RGBA; case B8G8R8A8: case B8G8R8X8: case R32G32B32A32F: return GL_BGRA; case B5G6R5: return GL_RGB; default: AVG_ASSERT(false); return 0; } } int GLTexture::getGLType(PixelFormat pf) { switch (pf) { case I8: case A8: return GL_UNSIGNED_BYTE; case R8G8B8A8: case R8G8B8X8: case B8G8R8A8: case B8G8R8X8: #ifdef __APPLE__ return GL_UNSIGNED_INT_8_8_8_8_REV; #else return GL_UNSIGNED_BYTE; #endif case R32G32B32A32F: case I32F: return GL_FLOAT; case B5G6R5: return GL_UNSIGNED_SHORT_5_6_5; default: AVG_ASSERT(false); return 0; } } int GLTexture::getGLInternalFormat() const { switch (m_pf) { case I8: return GL_LUMINANCE; case I32F: return GL_LUMINANCE32F_ARB; case A8: return GL_ALPHA; case R8G8B8A8: case R8G8B8X8: case B8G8R8A8: case B8G8R8X8: return GL_RGBA; case R32G32B32A32F: return GL_RGBA32F_ARB; case B5G6R5: return GL_RGB; default: AVG_ASSERT(false); return 0; } } void GLTexture::setDirty() { m_bIsDirty = true; } bool GLTexture::isDirty() const { return m_bIsDirty; } void GLTexture::resetDirty() { m_bIsDirty = false; } } <commit_msg>gles branch: Fixed compressed texture readback.<commit_after>// // libavg - Media Playback Engine. // Copyright (C) 2003-2011 Ulrich von Zadow // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Current versions can be found at www.libavg.de // #include "GLTexture.h" #include "../base/Exception.h" #include "../base/StringHelper.h" #include "../base/MathHelper.h" #include "../base/ObjectCounter.h" #include "GLContext.h" #include "TextureMover.h" #include "PBO.h" #include "FBO.h" #include "Filterfliprgb.h" #include <string.h> #include <iostream> namespace avg { using namespace std; // We assign our own texture ids and never reuse them instead of using glGenTextures. // That works very well, except that other components (e.g. Ogre3d) with shared gl // contexts don't know anything about our ids and thus use the same ones. // Somewhat hackish solution: Assign ids starting with a very high id, so the id ranges // don't overlap. unsigned GLTexture::s_LastTexID = 10000000; GLTexture::GLTexture(const IntPoint& size, PixelFormat pf, bool bMipmap, int potBorderColor, unsigned wrapSMode, unsigned wrapTMode, bool bForcePOT) : m_Size(size), m_pf(pf), m_bMipmap(bMipmap), m_bDeleteTex(true) { m_pGLContext = GLContext::getCurrent(); ObjectCounter::get()->incRef(&typeid(*this)); m_bUsePOT = m_pGLContext->usePOTTextures() || bForcePOT; if (m_pGLContext->isGLES() && bMipmap) { m_bUsePOT = true; } if (m_bUsePOT) { m_GLSize.x = nextpow2(m_Size.x); m_GLSize.y = nextpow2(m_Size.y); } else { m_GLSize = m_Size; } int maxTexSize = m_pGLContext->getMaxTexSize(); if (m_Size.x > maxTexSize || m_Size.y > maxTexSize) { throw Exception(AVG_ERR_VIDEO_GENERAL, "Texture too large (" + toString(m_Size) + "). Maximum supported by graphics card is " + toString(maxTexSize)); } if (getGLType(m_pf) == GL_FLOAT && !isFloatFormatSupported()) { throw Exception(AVG_ERR_UNSUPPORTED, "Float textures not supported by OpenGL configuration."); } s_LastTexID++; m_TexID = s_LastTexID; m_pGLContext->bindTexture(GL_TEXTURE0, m_TexID); if (bMipmap) { glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); } else { glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); } glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapSMode); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapTMode); glTexImage2D(GL_TEXTURE_2D, 0, getGLInternalFormat(), m_GLSize.x, m_GLSize.y, 0, getGLFormat(m_pf), getGLType(m_pf), 0); GLContext::checkError("GLTexture: glTexImage2D()"); if (m_bUsePOT) { // Make sure the texture is transparent and black before loading stuff // into it to avoid garbage at the borders. // In the case of UV textures, we set the border color to 128... int TexMemNeeded = m_GLSize.x*m_GLSize.y*getBytesPerPixel(m_pf); char * pPixels = new char[TexMemNeeded]; memset(pPixels, potBorderColor, TexMemNeeded); glTexImage2D(GL_TEXTURE_2D, 0, getGLInternalFormat(), m_GLSize.x, m_GLSize.y, 0, getGLFormat(m_pf), getGLType(m_pf), pPixels); GLContext::checkError("PBOTexture::createTexture: glTexImage2D()"); delete[] pPixels; } } GLTexture::GLTexture(unsigned glTexID, const IntPoint& size, PixelFormat pf, bool bMipmap, bool bDeleteTex) : m_Size(size), m_GLSize(size), m_pf(pf), m_bMipmap(bMipmap), m_bDeleteTex(bDeleteTex), m_bUsePOT(false), m_TexID(glTexID) { m_pGLContext = GLContext::getCurrent(); ObjectCounter::get()->incRef(&typeid(*this)); } GLTexture::~GLTexture() { if (m_bDeleteTex) { glDeleteTextures(1, &m_TexID); GLContext::checkError("GLTexture: DeleteTextures()"); } ObjectCounter::get()->decRef(&typeid(*this)); } void GLTexture::activate(int textureUnit) { m_pGLContext->bindTexture(textureUnit, m_TexID); } void GLTexture::generateMipmaps() { if (m_bMipmap) { activate(); glproc::GenerateMipmap(GL_TEXTURE_2D); GLContext::checkError("GLTexture::generateMipmaps()"); } } void GLTexture::setWrapMode(unsigned wrapSMode, unsigned wrapTMode) { activate(); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapSMode); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapTMode); } void GLTexture::enableStreaming() { m_pMover = TextureMover::create(m_Size, m_pf, GL_STREAM_DRAW); } BitmapPtr GLTexture::lockStreamingBmp() { AVG_ASSERT(m_pMover); return m_pMover->lock(); } void GLTexture::unlockStreamingBmp(bool bUpdated) { AVG_ASSERT(m_pMover); m_pMover->unlock(); if (bUpdated) { m_pMover->moveToTexture(*this); } } void GLTexture::moveBmpToTexture(BitmapPtr pBmp) { TextureMoverPtr pMover = TextureMover::create(m_Size, m_pf, GL_DYNAMIC_DRAW); pMover->moveBmpToTexture(pBmp, *this); } BitmapPtr GLTexture::moveTextureToBmp() { if (GLContext::getCurrent()->getMemoryModeSupported() == MM_PBO) { return PBO(m_GLSize, m_pf, GL_DYNAMIC_READ).moveTextureToBmp(*this); } else { unsigned fbo = GLContext::getCurrent()->genFBO(); glproc::BindFramebuffer(GL_FRAMEBUFFER_EXT, fbo); glproc::FramebufferTexture2D(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, m_TexID, 0); FBO::checkError("moveTextureToBmp"); BitmapPtr pBmp(new Bitmap(m_Size, m_pf)); glReadPixels(0, 0, m_Size.x, m_Size.y, getGLFormat(m_pf), getGLType(m_pf), pBmp->getPixels()); if (m_pf == R8G8B8A8 || m_pf == R8G8B8) { FilterFlipRGB().applyInPlace(pBmp); } return pBmp; } } const IntPoint& GLTexture::getSize() const { return m_Size; } const IntPoint& GLTexture::getGLSize() const { return m_GLSize; } PixelFormat GLTexture::getPF() const { return m_pf; } unsigned GLTexture::getID() const { return m_TexID; } IntPoint GLTexture::getMipmapSize(int level) const { AVG_ASSERT(!m_bUsePOT); IntPoint size = m_Size; for (int i=0; i<level; ++i) { size.x = max(1, size.x >> 1); size.y = max(1, size.y >> 1); } return size; } bool GLTexture::isFloatFormatSupported() { #ifdef __APPLE__ string sVendor ((const char*)glGetString(GL_VENDOR)); if (sVendor.find("Intel") != string::npos) { // Avoid buggy Mac Book Air(Intel HD) issues under lion return false; } #endif return queryOGLExtension("GL_ARB_texture_float"); } int GLTexture::getGLFormat(PixelFormat pf) { switch (pf) { case I8: case I32F: return GL_LUMINANCE; case A8: return GL_ALPHA; case R8G8B8A8: case R8G8B8X8: return GL_RGBA; case B8G8R8A8: case B8G8R8X8: case R32G32B32A32F: return GL_BGRA; case B5G6R5: return GL_RGB; default: AVG_ASSERT(false); return 0; } } int GLTexture::getGLType(PixelFormat pf) { switch (pf) { case I8: case A8: return GL_UNSIGNED_BYTE; case R8G8B8A8: case R8G8B8X8: case B8G8R8A8: case B8G8R8X8: #ifdef __APPLE__ return GL_UNSIGNED_INT_8_8_8_8_REV; #else return GL_UNSIGNED_BYTE; #endif case R32G32B32A32F: case I32F: return GL_FLOAT; case B5G6R5: return GL_UNSIGNED_SHORT_5_6_5; default: AVG_ASSERT(false); return 0; } } int GLTexture::getGLInternalFormat() const { switch (m_pf) { case I8: return GL_LUMINANCE; case I32F: return GL_LUMINANCE32F_ARB; case A8: return GL_ALPHA; case R8G8B8A8: case R8G8B8X8: case B8G8R8A8: case B8G8R8X8: return GL_RGBA; case R32G32B32A32F: return GL_RGBA32F_ARB; case B5G6R5: return GL_RGB; default: AVG_ASSERT(false); return 0; } } void GLTexture::setDirty() { m_bIsDirty = true; } bool GLTexture::isDirty() const { return m_bIsDirty; } void GLTexture::resetDirty() { m_bIsDirty = false; } } <|endoftext|>
<commit_before>#include "renderer.h" #include "player.h" #include "coord.h" #include <SFML/Graphics.hpp> GLuint Texture = 0; Renderer::Renderer(Terrain initterrain) : terrain(initterrain) { // Set color and depth clear value glClearDepth(1.f); glClearColor(0.f, 0.f, 0.f, 1.f); // black // Enable Z-buffer read and write glEnable(GL_DEPTH_TEST); glDepthMask(GL_TRUE); // Face culling to render half the polys glEnable(GL_CULL_FACE); // Setup a perspective projection glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(90.f, 1.f, 1.f, 500.f); // Lighting GLfloat LightAmbient[] = { 0.5f, 0.5f, 0.5f, 1.0f }; // Ambient Light Values GLfloat LightDiffuse[] = { 1.0f, 1.0f, 1.0f, 1.0f }; // Diffuse Light Values GLfloat LightPosition[] = { 0.0f, 0.0f, 2.0f, 1.0f }; // Light Position glLightfv(GL_LIGHT1, GL_AMBIENT, LightAmbient); // Setup The Ambient Light glLightfv(GL_LIGHT1, GL_DIFFUSE, LightDiffuse); // Setup The Diffuse Light glLightfv(GL_LIGHT1, GL_POSITION,LightPosition); // Position The Light glEnable(GL_LIGHT1); // Enable Light One //glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE); // Let glcolor work with lighting //glEnable(GL_COLOR_MATERIAL); // Enable lighting glEnable(GL_TEXTURE_2D); // Enable textures //glEnable(GL_LIGHTING); // Enable lighting glShadeModel(GL_SMOOTH); // Enable Smooth Shading sf::Image Image; if (!Image.LoadFromFile("data/tiles.png")) return; glGenTextures(1, &Texture); glBindTexture(GL_TEXTURE_2D, Texture); gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGBA, Image.GetWidth(), Image.GetHeight(), GL_RGBA, GL_UNSIGNED_BYTE, Image.GetPixelsPtr()); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); } // Don't forget to destroy our texture //glDeleteTextures(1, &Texture); void drawCube(float x, float y, float z, float length) { float sublength = length / 2; glPushMatrix(); // Preserve world matrix // Apply some transformations glTranslatef(x + sublength, y + sublength, z + sublength); glScalef(sublength, sublength, sublength); glBindTexture(GL_TEXTURE_2D, Texture); glBegin(GL_QUADS); // Top Face: Grass Top glNormal3f( 0.0f, 0.0f, 1.0f); // Normal Pointing Towards Viewer glTexCoord2f(0.0f, 0.0f ); glVertex3f(-1.0f, -1.0f, 1.0f); // Point 1 (Front) glTexCoord2f(0.125f, 0.0f ); glVertex3f( 1.0f, -1.0f, 1.0f); // Point 2 (Front) glTexCoord2f(0.125f, 0.125f); glVertex3f( 1.0f, 1.0f, 1.0f); // Point 3 (Front) glTexCoord2f(0.0f, 0.125f); glVertex3f(-1.0f, 1.0f, 1.0f); // Point 4 (Front) // Bottom Face: Dirt glNormal3f( 0.0f, 0.0f,-1.0f); // Normal Pointing Away From Viewer glTexCoord2f(0.125f, 0.25f ); glVertex3f(-1.0f, -1.0f, -1.0f); // Point 1 (Back) glTexCoord2f(0.125f, 0.375f); glVertex3f(-1.0f, 1.0f, -1.0f); // Point 2 (Back) glTexCoord2f(0.0f, 0.25f ); glVertex3f( 1.0f, 1.0f, -1.0f); // Point 3 (Back) glTexCoord2f(0.0f, 0.375f); glVertex3f( 1.0f, -1.0f, -1.0f); // Point 4 (Back) // Front Face: Grass Side glNormal3f( 0.0f, 1.0f, 0.0f); // Normal Pointing Up glTexCoord2f(0.0f, 0.25f ); glVertex3f(-1.0f, 1.0f, -1.0f); // Point 1 (Top) glTexCoord2f(0.0f, 0.125f); glVertex3f(-1.0f, 1.0f, 1.0f); // Point 2 (Top) glTexCoord2f(0.125f, 0.125f); glVertex3f( 1.0f, 1.0f, 1.0f); // Point 3 (Top) glTexCoord2f(0.125f, 0.25f ); glVertex3f( 1.0f, 1.0f, -1.0f); // Point 4 (Top) // Back Face: Grass Side glNormal3f( 0.0f,-1.0f, 0.0f); // Normal Pointing Down glTexCoord2f(0.125f, 0.25f ); glVertex3f(-1.0f, -1.0f, -1.0f); // Point 1 (Bottom) glTexCoord2f(0.0f, 0.25f ); glVertex3f( 1.0f, -1.0f, -1.0f); // Point 2 (Bottom) glTexCoord2f(0.0f, 0.125f); glVertex3f( 1.0f, -1.0f, 1.0f); // Point 3 (Bottom) glTexCoord2f(0.125f, 0.125f); glVertex3f(-1.0f, -1.0f, 1.0f); // Point 4 (Bottom) // Left face: Grass Side glNormal3f( 1.0f, 0.0f, 0.0f); // Normal Pointing Right glTexCoord2f(0.125f, 0.25f ); glVertex3f( 1.0f, -1.0f, -1.0f); // Point 1 (Right) glTexCoord2f(0.0f, 0.25f ); glVertex3f( 1.0f, 1.0f, -1.0f); // Point 2 (Right) glTexCoord2f(0.0f, 0.125f); glVertex3f( 1.0f, 1.0f, 1.0f); // Point 3 (Right) glTexCoord2f(0.125f, 0.125f); glVertex3f( 1.0f, -1.0f, 1.0f); // Point 4 (Right) // Right Face: Grass Side glNormal3f(-1.0f, 0.0f, 0.0f); // Normal Pointing Left glTexCoord2f(0.0f, 0.25f ); glVertex3f(-1.0f, -1.0f, -1.0f); // Point 1 (Left) glTexCoord2f(0.0f, 0.125f); glVertex3f(-1.0f, -1.0f, 1.0f); // Point 2 (Left) glTexCoord2f(0.125f, 0.125f); glVertex3f(-1.0f, 1.0f, 1.0f); // Point 3 (Left) glTexCoord2f(0.125f, 0.25f ); glVertex3f(-1.0f, 1.0f, -1.0f); // Point 4 (Left) glEnd(); // Done Drawing Quads glPopMatrix(); // Undo the translations } void renderNode(Octree<bool> terrain, float x, float y, float z, float size) { if (terrain.hasChildren) { float subsize = size / 2; renderNode(terrain.children[0], x, y, z, subsize); renderNode(terrain.children[1], x+subsize, y, z, subsize); renderNode(terrain.children[2], x, y+subsize, z, subsize); renderNode(terrain.children[3], x+subsize, y+subsize, z, subsize); renderNode(terrain.children[4], x, y, z+subsize, subsize); renderNode(terrain.children[5], x+subsize, y, z+subsize, subsize); renderNode(terrain.children[6], x, y+subsize, z+subsize, subsize); renderNode(terrain.children[7], x+subsize, y+subsize, z+subsize, subsize); } else if (terrain.value) { drawCube(x, y, z, size); } } void Renderer::render(Player player) { // Clear color and depth buffer glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_MODELVIEW); // Apply some transformations glLoadIdentity(); glRotatef(-90 + player.Yrot, 1.f, 0.f, 0.f); glRotatef(player.Zrot, 0.f, 0.f, 1.f); glTranslatef(-player.X, -player.Y, -player.Z); // Translate The Scene Based On Player Position renderNode(terrain.GeneratedTerrain[Coord(0,0,0)], 0.f, 0.f, 0.f, 50.f); } <commit_msg>Looks like a step backwords, but the FPS is up<commit_after>#include "renderer.h" #include "player.h" #include "coord.h" #include <SFML/Graphics.hpp> GLuint Texture = 0; GLdouble norm = 1 / sqrt( 3 ); GLdouble x = 0; GLdouble y = 0; GLdouble z = 0; GLdouble radius = 1; GLdouble vertices[24] = { x - radius, y - radius, z + radius, x + radius, y - radius, z + radius, x + radius, y + radius, z + radius, x - radius, y + radius, z + radius, x - radius, y - radius, z - radius, x + radius, y - radius, z - radius, x + radius, y + radius, z - radius, x - radius, y + radius, z - radius }; GLdouble normals[24] = { -norm, -norm, norm, norm, -norm, norm, norm, norm, norm, -norm, norm, norm, -norm, -norm, -norm, norm, -norm, -norm, norm, norm, -norm, -norm, norm, -norm }; GLdouble colors[24] = { 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0 }; /*GLubyte indices[24] = { 4, 5, 6, 7, 1, 2, 6, 5, 0, 1, 5, 4, 0, 3, 2, 1, 0, 4, 7, 3, 2, 3, 7, 6 };*/ GLubyte indices[24] = { 7, 6, 5, 4, 5, 6, 2, 1, 4, 5, 1, 0, 1, 2, 3, 0, 3, 7, 4, 0, 6, 7, 3, 2 }; Renderer::Renderer(Terrain initterrain) : terrain(initterrain) { // Set color and depth clear value glClearDepth(1.f); glClearColor(0.f, 0.f, 0.f, 1.f); // black // Enable Z-buffer read and write glEnable(GL_DEPTH_TEST); glDepthMask(GL_TRUE); // Face culling to render half the polys glEnable(GL_CULL_FACE); // Setup a perspective projection glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(90.f, 1.f, 1.f, 500.f); // Lighting GLfloat LightAmbient[] = { 0.5f, 0.5f, 0.5f, 1.0f }; // Ambient Light Values GLfloat LightDiffuse[] = { 1.0f, 1.0f, 1.0f, 1.0f }; // Diffuse Light Values GLfloat LightPosition[] = { 0.0f, 0.0f, 2.0f, 1.0f }; // Light Position glLightfv(GL_LIGHT1, GL_AMBIENT, LightAmbient); // Setup The Ambient Light glLightfv(GL_LIGHT1, GL_DIFFUSE, LightDiffuse); // Setup The Diffuse Light glLightfv(GL_LIGHT1, GL_POSITION,LightPosition); // Position The Light glEnable(GL_LIGHT1); // Enable Light One //glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE); // Let glcolor work with lighting //glEnable(GL_COLOR_MATERIAL); // Enable lighting glEnable(GL_TEXTURE_2D); // Enable textures //glEnable(GL_LIGHTING); // Enable lighting glShadeModel(GL_SMOOTH); // Enable Smooth Shading sf::Image Image; if (!Image.LoadFromFile("data/tiles.png")) return; glGenTextures(1, &Texture); glBindTexture(GL_TEXTURE_2D, Texture); gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGBA, Image.GetWidth(), Image.GetHeight(), GL_RGBA, GL_UNSIGNED_BYTE, Image.GetPixelsPtr()); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); } // Don't forget to destroy our texture //glDeleteTextures(1, &Texture); void drawCube(float x, float y, float z, float length) { float sublength = length / 2; glPushMatrix(); // Preserve world matrix // Apply some transformations glTranslatef(x + sublength, y + sublength, z + sublength); glScalef(sublength, sublength, sublength); glBindTexture(GL_TEXTURE_2D, Texture); glEnableClientState( GL_VERTEX_ARRAY ); glEnableClientState( GL_NORMAL_ARRAY ); glEnableClientState( GL_COLOR_ARRAY ); glVertexPointer( 3, GL_DOUBLE, 0, &vertices[0] ); glNormalPointer( GL_DOUBLE, 0, &normals[0] ); glColorPointer( 3, GL_DOUBLE, 0, &normals[0] ); glDrawElements( GL_QUADS, 24, GL_UNSIGNED_BYTE, indices ); glDisableClientState( GL_VERTEX_ARRAY ); glDisableClientState( GL_NORMAL_ARRAY ); glDisableClientState( GL_COLOR_ARRAY ); glPopMatrix(); // Undo the translations } void drawCube2(float x, float y, float z, float length) { float sublength = length / 2; glPushMatrix(); // Preserve world matrix // Apply some transformations glTranslatef(x + sublength, y + sublength, z + sublength); glScalef(sublength, sublength, sublength); glBindTexture(GL_TEXTURE_2D, Texture); glBegin(GL_QUADS); // Top Face: Grass Top glNormal3f( 0.0f, 0.0f, 1.0f); // Normal Pointing Towards Viewer glTexCoord2f(0.0f, 0.0f ); glVertex3f(-1.0f, -1.0f, 1.0f); // Point 1 (Front) glTexCoord2f(0.125f, 0.0f ); glVertex3f( 1.0f, -1.0f, 1.0f); // Point 2 (Front) glTexCoord2f(0.125f, 0.125f); glVertex3f( 1.0f, 1.0f, 1.0f); // Point 3 (Front) glTexCoord2f(0.0f, 0.125f); glVertex3f(-1.0f, 1.0f, 1.0f); // Point 4 (Front) // Bottom Face: Dirt glNormal3f( 0.0f, 0.0f,-1.0f); // Normal Pointing Away From Viewer glTexCoord2f(0.125f, 0.25f ); glVertex3f(-1.0f, -1.0f, -1.0f); // Point 1 (Back) glTexCoord2f(0.125f, 0.375f); glVertex3f(-1.0f, 1.0f, -1.0f); // Point 2 (Back) glTexCoord2f(0.0f, 0.25f ); glVertex3f( 1.0f, 1.0f, -1.0f); // Point 3 (Back) glTexCoord2f(0.0f, 0.375f); glVertex3f( 1.0f, -1.0f, -1.0f); // Point 4 (Back) // Front Face: Grass Side glNormal3f( 0.0f, 1.0f, 0.0f); // Normal Pointing Up glTexCoord2f(0.0f, 0.25f ); glVertex3f(-1.0f, 1.0f, -1.0f); // Point 1 (Top) glTexCoord2f(0.0f, 0.125f); glVertex3f(-1.0f, 1.0f, 1.0f); // Point 2 (Top) glTexCoord2f(0.125f, 0.125f); glVertex3f( 1.0f, 1.0f, 1.0f); // Point 3 (Top) glTexCoord2f(0.125f, 0.25f ); glVertex3f( 1.0f, 1.0f, -1.0f); // Point 4 (Top) // Back Face: Grass Side glNormal3f( 0.0f,-1.0f, 0.0f); // Normal Pointing Down glTexCoord2f(0.125f, 0.25f ); glVertex3f(-1.0f, -1.0f, -1.0f); // Point 1 (Bottom) glTexCoord2f(0.0f, 0.25f ); glVertex3f( 1.0f, -1.0f, -1.0f); // Point 2 (Bottom) glTexCoord2f(0.0f, 0.125f); glVertex3f( 1.0f, -1.0f, 1.0f); // Point 3 (Bottom) glTexCoord2f(0.125f, 0.125f); glVertex3f(-1.0f, -1.0f, 1.0f); // Point 4 (Bottom) // Left face: Grass Side glNormal3f( 1.0f, 0.0f, 0.0f); // Normal Pointing Right glTexCoord2f(0.125f, 0.25f ); glVertex3f( 1.0f, -1.0f, -1.0f); // Point 1 (Right) glTexCoord2f(0.0f, 0.25f ); glVertex3f( 1.0f, 1.0f, -1.0f); // Point 2 (Right) glTexCoord2f(0.0f, 0.125f); glVertex3f( 1.0f, 1.0f, 1.0f); // Point 3 (Right) glTexCoord2f(0.125f, 0.125f); glVertex3f( 1.0f, -1.0f, 1.0f); // Point 4 (Right) // Right Face: Grass Side glNormal3f(-1.0f, 0.0f, 0.0f); // Normal Pointing Left glTexCoord2f(0.0f, 0.25f ); glVertex3f(-1.0f, -1.0f, -1.0f); // Point 1 (Left) glTexCoord2f(0.0f, 0.125f); glVertex3f(-1.0f, -1.0f, 1.0f); // Point 2 (Left) glTexCoord2f(0.125f, 0.125f); glVertex3f(-1.0f, 1.0f, 1.0f); // Point 3 (Left) glTexCoord2f(0.125f, 0.25f ); glVertex3f(-1.0f, 1.0f, -1.0f); // Point 4 (Left) glEnd(); // Done Drawing Quads glPopMatrix(); // Undo the translations } void renderNode(Octree<bool> terrain, float x, float y, float z, float size) { if (terrain.hasChildren) { float subsize = size / 2; renderNode(terrain.children[0], x, y, z, subsize); renderNode(terrain.children[1], x+subsize, y, z, subsize); renderNode(terrain.children[2], x, y+subsize, z, subsize); renderNode(terrain.children[3], x+subsize, y+subsize, z, subsize); renderNode(terrain.children[4], x, y, z+subsize, subsize); renderNode(terrain.children[5], x+subsize, y, z+subsize, subsize); renderNode(terrain.children[6], x, y+subsize, z+subsize, subsize); renderNode(terrain.children[7], x+subsize, y+subsize, z+subsize, subsize); } else if (terrain.value) { drawCube(x, y, z, size); } } void Renderer::render(Player player) { // Clear color and depth buffer glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_MODELVIEW); // Apply some transformations glLoadIdentity(); glRotatef(-90 + player.Yrot, 1.f, 0.f, 0.f); glRotatef(player.Zrot, 0.f, 0.f, 1.f); glTranslatef(-player.X, -player.Y, -player.Z); // Translate The Scene Based On Player Position renderNode(terrain.GeneratedTerrain[Coord(0,0,0)], 0.f, 0.f, 0.f, 50.f); } <|endoftext|>
<commit_before>#include <SFML/Graphics.hpp> #include <iostream> #include <fstream> #include <string> #include <stdio.h> #include "renderer.h" #include "player.h" #include "coord.h" GLuint Texture = 0; GLdouble vertices[96] = { -1, 1, -1, 1, 1, -1, 1, -1, -1, -1, -1, -1, 1, -1, -1, 1, 1, -1, 1, 1, 1, 1, -1, 1, -1, -1, -1, 1, -1, -1, 1, -1, 1, -1, -1, 1, 1, -1, 1, 1, 1, 1, -1, 1, 1, -1, -1, 1, -1, 1, 1, -1, 1, -1, -1, -1, -1, -1, -1, 1, 1, 1, -1, -1, 1, -1, -1, 1, 1, 1, 1, 1, }; // For grass GLdouble texcoords[96] = { // Bottom 0.125, 0.375, 0.0, 0.0, 0.375, 0.0, 0.0, 0.25, 0.0, 0.125, 0.25, 0.0, // Back 0.125, 0.25, 0.0, 0.0, 0.25, 0.0, 0.0, 0.125, 0.0, 0.125, 0.125, 0.0, // Right 0.125, 0.25, 0.0, 0.0, 0.25, 0.0, 0.0, 0.125, 0.0, 0.125, 0.125, 0.0, // Top 0.0, 0.0, 0.0, 0.125, 0.0, 0.0, 0.125, 0.125, 0.0, 0.0, 0.125, 0.0, // Front 0.125, 0.125, 0.0, 0.125, 0.25, 0.0, 0.0, 0.25, 0.0, 0.0, 0.125, 0.0, // Left 0.125, 0.25, 0.0, 0.0, 0.25, 0.0, 0.0, 0.125, 0.0, 0.125, 0.125, 0.0, }; Renderer::Renderer(Terrain initterrain, Player* player) : terrain(initterrain), player(player) { InitGraphics(); } void Renderer::InitGraphics() { // Set color and depth clear value glClearDepth(1.f); glClearColor(0.f, 0.f, 0.f, 1.f); // black // Enable Z-buffer read and write glEnable(GL_DEPTH_TEST); glDepthMask(GL_TRUE); // Face culling to render half the polys //glEnable(GL_CULL_FACE); // Lighting GLfloat LightAmbient[] = { 0.5f, 0.5f, 0.5f, 1.0f }; // Ambient Light Values GLfloat LightDiffuse[] = { 1.0f, 1.0f, 1.0f, 1.0f }; // Diffuse Light Values GLfloat LightPosition[] = { 0.0f, 0.0f, 2.0f, 1.0f }; // Light Position glLightfv(GL_LIGHT1, GL_AMBIENT, LightAmbient); // Setup The Ambient Light glLightfv(GL_LIGHT1, GL_DIFFUSE, LightDiffuse); // Setup The Diffuse Light glLightfv(GL_LIGHT1, GL_POSITION,LightPosition); // Position The Light glEnable(GL_LIGHT1); // Enable Light One //glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE); // Let glcolor work with lighting //glEnable(GL_COLOR_MATERIAL); // Enable lighting colors //glEnable(GL_LIGHTING); // Enable lighting glEnable(GL_TEXTURE_2D); // Enable textures glShadeModel(GL_SMOOTH); // Enable Smooth Shading // Load texture sf::Image Image; if (!Image.LoadFromFile("data/tiles.png")) return; glGenTextures(1, &Texture); glBindTexture(GL_TEXTURE_2D, Texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGBA, Image.GetWidth(), Image.GetHeight(), GL_RGBA, GL_UNSIGNED_BYTE, Image.GetPixelsPtr()); } // Don't forget to destroy our texture //glDeleteTextures(1, &Texture); void Renderer::drawCube(Block *block, float x, float y, float z, float length) { float subsize = length / 2; // Apply some transformations glLoadIdentity(); glTranslatef(x + subsize, y + subsize, z + subsize); glScalef(subsize, subsize, subsize); /* if (block->faces & 0x01 > 0 && player->Z < z) glDrawElements( GL_QUADS, 4, GL_UNSIGNED_BYTE, &indices[0] ); if (block->faces & 0x02 > 0 && player->X > x) glDrawElements( GL_QUADS, 4, GL_UNSIGNED_BYTE, &indices[4] ); if (block->faces & 0x04 > 0 && player->Y < y) glDrawElements( GL_QUADS, 4, GL_UNSIGNED_BYTE, &indices[8] ); if (block->faces & 0x08 > 0 && player->Z > z) glDrawElements( GL_QUADS, 4, GL_UNSIGNED_BYTE, &indices[12] ); if (block->faces & 0x10 > 0 && player->X < x) glDrawElements( GL_QUADS, 4, GL_UNSIGNED_BYTE, &indices[16] ); if (block->faces & 0x20 > 0 && player->Y > y) glDrawElements( GL_QUADS, 4, GL_UNSIGNED_BYTE, &indices[20] ); */ if (player->Z < z) glDrawArrays(GL_QUADS, 0, 4); if (player->X > x) glDrawArrays(GL_QUADS, 4, 4); if (player->Y < y) glDrawArrays(GL_QUADS, 8, 4); if (player->Z > z) glDrawArrays(GL_QUADS, 12, 4); if (player->X < x) glDrawArrays(GL_QUADS, 16, 4); if (player->Y > y) glDrawArrays(GL_QUADS, 20, 4); } bool current; void Renderer::renderNode(Octree<Block*> terrain, float x, float y, float z, float size) { if (terrain.hasChildren) { float subsize = size / 2; renderNode(terrain.children[0], x, y, z, subsize); renderNode(terrain.children[1], x+subsize, y, z, subsize); renderNode(terrain.children[2], x, y+subsize, z, subsize); renderNode(terrain.children[3], x+subsize, y+subsize, z, subsize); renderNode(terrain.children[4], x, y, z+subsize, subsize); renderNode(terrain.children[5], x+subsize, y, z+subsize, subsize); renderNode(terrain.children[6], x, y+subsize, z+subsize, subsize); renderNode(terrain.children[7], x+subsize, y+subsize, z+subsize, subsize); } else if (terrain.value->Type == 0) { // Collision check against player if (player->X > x && player->Y > y && player->Z - 2.f > z && player->X <= x + size && player->Y <= y + size && player->Z - 2.f <= z + size) { player->StandingOn = &terrain; player->SurfaceZ = z + size; } drawCube(terrain.value, x, y, z, size); } } void Renderer::render() { // Clear color and depth buffer glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Apply some transformations glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(90.f, 1.f, 1.f, 500.f); glRotatef(-90 + player->Yrot, 1.f, 0.f, 0.f); glRotatef(player->Zrot, 0.f, 0.f, 1.f); glTranslatef(-player->X, -player->Y, -player->Z); // Translate The Scene Based On Player Position glMatrixMode(GL_MODELVIEW); glBindTexture(GL_TEXTURE_2D, Texture); glEnableClientState( GL_VERTEX_ARRAY ); //glEnableClientState( GL_NORMAL_ARRAY ); glEnableClientState( GL_TEXTURE_COORD_ARRAY ); glVertexPointer( 3, GL_DOUBLE, 0, &vertices[0] ); //glNormalPointer( GL_DOUBLE, 0, &vertices[0] ); glTexCoordPointer( 3, GL_DOUBLE, 0, &texcoords[0] ); player->StandingOn = NULL; // Loop through chunks and render them int i, j, k; for(i = 0; i < terrain.sizeX; i++) for(j = 0; j < terrain.sizeY; j++) for(k = 0; k < terrain.sizeZ; k++) renderNode(terrain.GeneratedTerrain[Coord(i,j,k)], i*terrain.chunkSize, j*terrain.chunkSize, k*terrain.chunkSize, terrain.chunkSize); glDisableClientState(GL_VERTEX_ARRAY); //glDisableClientState(GL_NORMAL_ARRAY); glDisableClientState(GL_TEXTURE_COORD_ARRAY); } <commit_msg>Reduce texcoords array to 64 items<commit_after>#include <SFML/Graphics.hpp> #include <iostream> #include <fstream> #include <string> #include <stdio.h> #include "renderer.h" #include "player.h" #include "coord.h" GLuint Texture = 0; GLdouble vertices[96] = { -1, 1, -1, 1, 1, -1, 1, -1, -1, -1, -1, -1, 1, -1, -1, 1, 1, -1, 1, 1, 1, 1, -1, 1, -1, -1, -1, 1, -1, -1, 1, -1, 1, -1, -1, 1, 1, -1, 1, 1, 1, 1, -1, 1, 1, -1, -1, 1, -1, 1, 1, -1, 1, -1, -1, -1, -1, -1, -1, 1, 1, 1, -1, -1, 1, -1, -1, 1, 1, 1, 1, 1, }; // For grass GLdouble texcoords[64] = { // Bottom 0.125, 0.375, 0.0, 0.375, 0.0, 0.25, 0.125, 0.25, // Back 0.125, 0.25, 0.0, 0.25, 0.0, 0.125, 0.125, 0.125, // Right 0.125, 0.25, 0.0, 0.25, 0.0, 0.125, 0.125, 0.125, // Top 0.0, 0.0, 0.125, 0.0, 0.125, 0.125, 0.0, 0.125, // Front 0.125, 0.125, 0.125, 0.25, 0.0, 0.25, 0.0, 0.125, // Left 0.125, 0.25, 0.0, 0.25, 0.0, 0.125, 0.125, 0.125, }; Renderer::Renderer(Terrain initterrain, Player* player) : terrain(initterrain), player(player) { InitGraphics(); } void Renderer::InitGraphics() { // Set color and depth clear value glClearDepth(1.f); glClearColor(0.f, 0.f, 0.f, 1.f); // black // Enable Z-buffer read and write glEnable(GL_DEPTH_TEST); glDepthMask(GL_TRUE); // Face culling to render half the polys //glEnable(GL_CULL_FACE); // Lighting GLfloat LightAmbient[] = { 0.5f, 0.5f, 0.5f, 1.0f }; // Ambient Light Values GLfloat LightDiffuse[] = { 1.0f, 1.0f, 1.0f, 1.0f }; // Diffuse Light Values GLfloat LightPosition[] = { 0.0f, 0.0f, 2.0f, 1.0f }; // Light Position glLightfv(GL_LIGHT1, GL_AMBIENT, LightAmbient); // Setup The Ambient Light glLightfv(GL_LIGHT1, GL_DIFFUSE, LightDiffuse); // Setup The Diffuse Light glLightfv(GL_LIGHT1, GL_POSITION,LightPosition); // Position The Light glEnable(GL_LIGHT1); // Enable Light One //glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE); // Let glcolor work with lighting //glEnable(GL_COLOR_MATERIAL); // Enable lighting colors //glEnable(GL_LIGHTING); // Enable lighting glEnable(GL_TEXTURE_2D); // Enable textures glShadeModel(GL_SMOOTH); // Enable Smooth Shading // Load texture sf::Image Image; if (!Image.LoadFromFile("data/tiles.png")) return; glGenTextures(1, &Texture); glBindTexture(GL_TEXTURE_2D, Texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGBA, Image.GetWidth(), Image.GetHeight(), GL_RGBA, GL_UNSIGNED_BYTE, Image.GetPixelsPtr()); } // Don't forget to destroy our texture //glDeleteTextures(1, &Texture); void Renderer::drawCube(Block *block, float x, float y, float z, float length) { float subsize = length / 2; // Apply some transformations glLoadIdentity(); glTranslatef(x + subsize, y + subsize, z + subsize); glScalef(subsize, subsize, subsize); /* if (block->faces & 0x01 > 0 && player->Z < z) glDrawElements( GL_QUADS, 4, GL_UNSIGNED_BYTE, &indices[0] ); if (block->faces & 0x02 > 0 && player->X > x) glDrawElements( GL_QUADS, 4, GL_UNSIGNED_BYTE, &indices[4] ); if (block->faces & 0x04 > 0 && player->Y < y) glDrawElements( GL_QUADS, 4, GL_UNSIGNED_BYTE, &indices[8] ); if (block->faces & 0x08 > 0 && player->Z > z) glDrawElements( GL_QUADS, 4, GL_UNSIGNED_BYTE, &indices[12] ); if (block->faces & 0x10 > 0 && player->X < x) glDrawElements( GL_QUADS, 4, GL_UNSIGNED_BYTE, &indices[16] ); if (block->faces & 0x20 > 0 && player->Y > y) glDrawElements( GL_QUADS, 4, GL_UNSIGNED_BYTE, &indices[20] ); */ if (player->Z < z) glDrawArrays(GL_QUADS, 0, 4); if (player->X > x) glDrawArrays(GL_QUADS, 4, 4); if (player->Y < y) glDrawArrays(GL_QUADS, 8, 4); if (player->Z > z) glDrawArrays(GL_QUADS, 12, 4); if (player->X < x) glDrawArrays(GL_QUADS, 16, 4); if (player->Y > y) glDrawArrays(GL_QUADS, 20, 4); } bool current; void Renderer::renderNode(Octree<Block*> terrain, float x, float y, float z, float size) { if (terrain.hasChildren) { float subsize = size / 2; renderNode(terrain.children[0], x, y, z, subsize); renderNode(terrain.children[1], x+subsize, y, z, subsize); renderNode(terrain.children[2], x, y+subsize, z, subsize); renderNode(terrain.children[3], x+subsize, y+subsize, z, subsize); renderNode(terrain.children[4], x, y, z+subsize, subsize); renderNode(terrain.children[5], x+subsize, y, z+subsize, subsize); renderNode(terrain.children[6], x, y+subsize, z+subsize, subsize); renderNode(terrain.children[7], x+subsize, y+subsize, z+subsize, subsize); } else if (terrain.value->Type == 0) { // Collision check against player if (player->X > x && player->Y > y && player->Z - 2.f > z && player->X <= x + size && player->Y <= y + size && player->Z - 2.f <= z + size) { player->StandingOn = &terrain; player->SurfaceZ = z + size; } drawCube(terrain.value, x, y, z, size); } } void Renderer::render() { // Clear color and depth buffer glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Apply some transformations glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(90.f, 1.f, 1.f, 500.f); glRotatef(-90 + player->Yrot, 1.f, 0.f, 0.f); glRotatef(player->Zrot, 0.f, 0.f, 1.f); glTranslatef(-player->X, -player->Y, -player->Z); // Translate The Scene Based On Player Position glMatrixMode(GL_MODELVIEW); glBindTexture(GL_TEXTURE_2D, Texture); glEnableClientState( GL_VERTEX_ARRAY ); //glEnableClientState( GL_NORMAL_ARRAY ); glEnableClientState( GL_TEXTURE_COORD_ARRAY ); glVertexPointer( 3, GL_DOUBLE, 0, &vertices[0] ); //glNormalPointer( GL_DOUBLE, 0, &vertices[0] ); glTexCoordPointer( 2, GL_DOUBLE, 0, &texcoords[0] ); player->StandingOn = NULL; // Loop through chunks and render them int i, j, k; for(i = 0; i < terrain.sizeX; i++) for(j = 0; j < terrain.sizeY; j++) for(k = 0; k < terrain.sizeZ; k++) renderNode(terrain.GeneratedTerrain[Coord(i,j,k)], i*terrain.chunkSize, j*terrain.chunkSize, k*terrain.chunkSize, terrain.chunkSize); glDisableClientState(GL_VERTEX_ARRAY); //glDisableClientState(GL_NORMAL_ARRAY); glDisableClientState(GL_TEXTURE_COORD_ARRAY); } <|endoftext|>
<commit_before>/* Copyright (c) 2015-2016 Advanced Micro Devices, Inc. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* HIT_START * BUILD: %t %s ../test_common.cpp * RUN: %t * HIT_END */ #include <hip/hip_runtime.h> #include <hip/math_functions.h> #include "test_common.h" #pragma GCC diagnostic ignored "-Wall" #pragma clang diagnostic ignored "-Wunused-variable" __device__ void single_precision_math_functions() { int iX; float fX, fY; acosf(1.0f); acoshf(1.0f); asinf(0.0f); asinhf(0.0f); atan2f(0.0f, 1.0f); atanf(0.0f); atanhf(0.0f); cbrtf(0.0f); ceilf(0.0f); copysignf(1.0f, -2.0f); cosf(0.0f); coshf(0.0f); cospif(0.0f); //cyl_bessel_i0f(0.0f); //cyl_bessel_i1f(0.0f); erfcf(0.0f); erfcinvf(2.0f); erfcxf(0.0f); erff(0.0f); erfinvf(1.0f); exp10f(0.0f); exp2f(0.0f); expf(0.0f); expm1f(0.0f); fabsf(1.0f); fdimf(1.0f, 0.0f); fdividef(0.0f, 1.0f); floorf(0.0f); fmaf(1.0f, 2.0f, 3.0f); fmaxf(0.0f, 0.0f); fminf(0.0f, 0.0f); fmodf(0.0f, 1.0f); //frexpf(0.0f, &iX); hypotf(1.0f, 0.0f); ilogbf(1.0f); isfinite(0.0f); isinf(0.0f); isnan(0.0f); j0f(0.0f); j1f(0.0f); jnf(-1.0f, 1.0f); ldexpf(0.0f, 0); //lgammaf(1.0f); llrintf(0.0f); llroundf(0.0f); log10f(1.0f); log1pf(-1.0f); log2f(1.0f); logbf(1.0f); logf(1.0f); lrintf(0.0f); lroundf(0.0f); //modff(0.0f, &fX); nanf("1"); nearbyintf(0.0f); //nextafterf(0.0f); norm3df(1.0f, 0.0f, 0.0f); norm4df(1.0f, 0.0f, 0.0f, 0.0f); normcdff(0.0f); normcdfinvf(1.0f); fX = 1.0f; normf(1, &fX); powf(1.0f, 0.0f); rcbrtf(1.0f); remainderf(2.0f, 1.0f); //remquof(1.0f, 2.0f, &iX); rhypotf(0.0f, 1.0f); rintf(1.0f); rnorm3df(0.0f, 0.0f, 1.0f); rnorm4df(0.0f, 0.0f, 0.0f, 1.0f); fX = 1.0f; rnormf(1, &fX); roundf(0.0f); rsqrtf(1.0f); scalblnf(0.0f, 1); scalbnf(0.0f, 1); signbit(1.0f); sincosf(0.0f, &fX, &fY); sincospif(0.0f, &fX, &fY); sinf(0.0f); sinhf(0.0f); sinpif(0.0f); sqrtf(0.0f); tanf(0.0f); tanhf(0.0f); tgammaf(2.0f); truncf(0.0f); y0f(1.0f); y1f(1.0f); ynf(1, 1.0f); } __global__ void compileSinglePrecisionMathOnDevice(hipLaunchParm lp, int ignored) { single_precision_math_functions(); } int main() { hipLaunchKernel(compileSinglePrecisionMathOnDevice, dim3(1,1,1), dim3(1,1,1), 0, 0, 1); passed(); } <commit_msg>Disable rcbrtf, scalblnf, scalbnf in single precision device test<commit_after>/* Copyright (c) 2015-2016 Advanced Micro Devices, Inc. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* HIT_START * BUILD: %t %s ../test_common.cpp * RUN: %t * HIT_END */ #include <hip/hip_runtime.h> #include <hip/math_functions.h> #include "test_common.h" #pragma GCC diagnostic ignored "-Wall" #pragma clang diagnostic ignored "-Wunused-variable" __device__ void single_precision_math_functions() { int iX; float fX, fY; acosf(1.0f); acoshf(1.0f); asinf(0.0f); asinhf(0.0f); atan2f(0.0f, 1.0f); atanf(0.0f); atanhf(0.0f); cbrtf(0.0f); ceilf(0.0f); copysignf(1.0f, -2.0f); cosf(0.0f); coshf(0.0f); cospif(0.0f); //cyl_bessel_i0f(0.0f); //cyl_bessel_i1f(0.0f); erfcf(0.0f); erfcinvf(2.0f); erfcxf(0.0f); erff(0.0f); erfinvf(1.0f); exp10f(0.0f); exp2f(0.0f); expf(0.0f); expm1f(0.0f); fabsf(1.0f); fdimf(1.0f, 0.0f); fdividef(0.0f, 1.0f); floorf(0.0f); fmaf(1.0f, 2.0f, 3.0f); fmaxf(0.0f, 0.0f); fminf(0.0f, 0.0f); fmodf(0.0f, 1.0f); //frexpf(0.0f, &iX); hypotf(1.0f, 0.0f); ilogbf(1.0f); isfinite(0.0f); isinf(0.0f); isnan(0.0f); j0f(0.0f); j1f(0.0f); jnf(-1.0f, 1.0f); ldexpf(0.0f, 0); //lgammaf(1.0f); llrintf(0.0f); llroundf(0.0f); log10f(1.0f); log1pf(-1.0f); log2f(1.0f); logbf(1.0f); logf(1.0f); lrintf(0.0f); lroundf(0.0f); //modff(0.0f, &fX); nanf("1"); nearbyintf(0.0f); //nextafterf(0.0f); norm3df(1.0f, 0.0f, 0.0f); norm4df(1.0f, 0.0f, 0.0f, 0.0f); normcdff(0.0f); normcdfinvf(1.0f); fX = 1.0f; normf(1, &fX); powf(1.0f, 0.0f); //rcbrtf(1.0f); remainderf(2.0f, 1.0f); //remquof(1.0f, 2.0f, &iX); rhypotf(0.0f, 1.0f); rintf(1.0f); rnorm3df(0.0f, 0.0f, 1.0f); rnorm4df(0.0f, 0.0f, 0.0f, 1.0f); fX = 1.0f; rnormf(1, &fX); roundf(0.0f); rsqrtf(1.0f); //scalblnf(0.0f, 1); //scalbnf(0.0f, 1); signbit(1.0f); sincosf(0.0f, &fX, &fY); sincospif(0.0f, &fX, &fY); sinf(0.0f); sinhf(0.0f); sinpif(0.0f); sqrtf(0.0f); tanf(0.0f); tanhf(0.0f); tgammaf(2.0f); truncf(0.0f); y0f(1.0f); y1f(1.0f); ynf(1, 1.0f); } __global__ void compileSinglePrecisionMathOnDevice(hipLaunchParm lp, int ignored) { single_precision_math_functions(); } int main() { hipLaunchKernel(compileSinglePrecisionMathOnDevice, dim3(1,1,1), dim3(1,1,1), 0, 0, 1); passed(); } <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkMinMaxCurvatureFlowImageFilterTest.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2002 Insight Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm 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 "itkMinMaxCurvatureFlowImageFilter.h" #include "itkOutputWindow.h" #include "itkCommand.h" #include "itkImage.h" #include "itkImageRegionIterator.h" #include "vnl/vnl_math.h" #include "vnl/vnl_sample.h" // The following class is used to support callbacks // on the filter in the pipeline that follows later class ShowProgressObject { public: ShowProgressObject(itk::ProcessObject* o) {m_Process = o;} void ShowProgress() {std::cout << "Progress " << m_Process->GetProgress() << std::endl;} itk::ProcessObject::Pointer m_Process; }; #define MAXRUNS 5 // maximum number of runs template<unsigned int VImageDimension> int testMinMaxCurvatureFlow( itk::Size<VImageDimension> & size, double radius, int numberOfRuns, unsigned int niter[], unsigned long radii[] ); /** * This file tests the functionality of the MinMaxCurvatureFlowImageFilter. * The test uses a binary image of a circle/sphere with intensity value * of 0 (black). The background is white ( intensity = 255 ). * X% salt and pepper noise is added to the the input image. Specifically, * X% of the pixels is replaced with a value choosen from a uniform * distribution between 0 and 255. * * We then test the ability of MinMaxCurvatureFlowImageFilter to denoise * the image. */ int main() { double radius; int numberOfRuns; unsigned int niter[MAXRUNS]; unsigned long radii[MAXRUNS]; itk::Size<2> size2D; size2D[0] = 64; size2D[1] = 64; radius = 20.0; numberOfRuns = 2; niter[0] = 100; niter[1] = 100; radii[0] = 1; radii[1] = 3; int err2D = testMinMaxCurvatureFlow( size2D, radius, numberOfRuns, niter, radii ); itk::Size<3> size3D; size3D[0] = 32; size3D[1] = 32; size3D[2] = 32; radius = 10.0; numberOfRuns = 1; niter[0] = 10; radii[1] = 1; int err3D = testMinMaxCurvatureFlow( size3D, radius, numberOfRuns, niter, radii ); itk::Size<4> size4D; size4D[0] = 8; size4D[1] = 8; size4D[2] = 8; size4D[3] = 8; radius = 2.6; numberOfRuns = 1; niter[0] = 5; radii[1] = 1; int err4D = testMinMaxCurvatureFlow( size4D, radius, numberOfRuns, niter, radii ); if ( err2D || err3D || err4D ) { return EXIT_FAILURE; } return EXIT_SUCCESS; } template<unsigned int VImageDimension> int testMinMaxCurvatureFlow( itk::Size<VImageDimension> & size, // ND image size double radius, // ND-sphere radius int numberOfRuns, // number of times to run the filter unsigned int niter[], // number of iterations unsigned long radii[] // stencil radius ) { typedef float PixelType; enum { ImageDimension = VImageDimension }; typedef itk::Image<PixelType, ImageDimension> ImageType; typedef itk::ImageRegionIterator<ImageType> IteratorType; typedef itk::MinMaxCurvatureFlowImageFilter<ImageType,ImageType> DenoiserType; DenoiserType::Pointer denoiser = DenoiserType::New(); int j; /** * Create an image containing a circle/sphere with intensity of 0 * and background of 255 with added salt and pepper noise. */ double sqrRadius = vnl_math_sqr( radius ); // radius of the circle/sphere double fractionNoise = 0.30; // salt & pepper noise fraction PixelType foreground = 0.0; // intensity value of the foreground PixelType background = 255.0; // intensity value of the background std::cout << "Create an image of circle/sphere with noise" << std::endl; ImageType::Pointer circleImage = ImageType::New(); ImageType::RegionType region; region.SetSize( size ); circleImage->SetLargestPossibleRegion( region ); circleImage->SetBufferedRegion( region ); circleImage->Allocate(); IteratorType circleIter( circleImage, circleImage->GetBufferedRegion() ); for ( ; !circleIter.IsAtEnd() ; ++circleIter ) { ImageType::IndexType index = circleIter.GetIndex(); float value; double lhs = 0.0; for ( j = 0; j < ImageDimension; j++ ) { lhs += vnl_math_sqr( (double) index[j] - (double) size[j] * 0.5 ); } if ( lhs < sqrRadius ) { value = foreground; } else { value = background; } if ( vnl_sample_uniform( 0.0, 1.0 ) < fractionNoise ) { value = vnl_sample_uniform( vnl_math_min(foreground,background), vnl_math_max(foreground,background) ); } circleIter.Set( value ); } /** * Run MinMaxCurvatureFlowImageFilter several times using the previous * output as the input in the next run. */ std::cout << "Run MinMaxCurvatureFlowImageFiler.." << std::endl; // set other denoiser parameters here denoiser->SetTimeStep( 0.15 ); // attach a progress watcher to the denoiser ShowProgressObject progressWatch(denoiser); itk::SimpleMemberCommand<ShowProgressObject>::Pointer command; command = itk::SimpleMemberCommand<ShowProgressObject>::New(); command->SetCallbackFunction(&progressWatch, &ShowProgressObject::ShowProgress); denoiser->AddObserver( itk::ProgressEvent(), command); ImageType::Pointer swapPointer = circleImage; for ( int j = 0; j < numberOfRuns; j++ ) { denoiser->SetInput( swapPointer ); // set the stencil radius and number of iterations denoiser->SetStencilRadius( radii[j] ); denoiser->SetNumberOfIterations( niter[j] ); std::cout << " Run: " << j; std::cout << " Radius: " << denoiser->GetStencilRadius(); std::cout << " Iter: " << denoiser->GetNumberOfIterations(); std::cout << std::endl; // run the filter denoiser->Update(); swapPointer = denoiser->GetOutput(); swapPointer->DisconnectPipeline(); } /** * Check the quality of the output by comparing it against a * clean image of the circle/sphere. * An output pixel is okay if it is within * 0.1 * |foreground - background| of the true value. * This test is considered as passed if the fraction of wrong * pixels is less than the original noise fraction. */ std::cout << "Checking the output..." << std::endl; IteratorType outIter( swapPointer, swapPointer->GetBufferedRegion() ); PixelType tolerance = vnl_math_abs( foreground - background ) * 0.1; unsigned long numPixelsWrong = 0; for ( ; !outIter.IsAtEnd(); ++outIter ) { ImageType::IndexType index = outIter.GetIndex(); PixelType value = outIter.Get(); double lhs = 0.0; for ( j = 0; j < ImageDimension; j++ ) { lhs += vnl_math_sqr( (double) index[j] - (double) size[j] * 0.5 ); } if ( lhs < sqrRadius ) { if ( vnl_math_abs( foreground - value ) > tolerance ) { numPixelsWrong++; } } else if ( vnl_math_abs( background - value ) > tolerance ) { numPixelsWrong++; } } double fractionWrong = (double) numPixelsWrong / (double) region.GetNumberOfPixels(); std::cout << "Noise reduced from " << fractionNoise << " to "; std::cout << fractionWrong << std::endl; bool passed = true; if ( fractionWrong > fractionNoise ) { passed = false; } /** * Exercise other member functions here */ denoiser->Print( std::cout ); if ( !passed ) { std::cout << "Test failed." << std::endl; return EXIT_FAILURE; } std::cout << "Test passed." << std::endl; return EXIT_SUCCESS; } <commit_msg><commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkMinMaxCurvatureFlowImageFilterTest.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2002 Insight Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm 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 "itkMinMaxCurvatureFlowImageFilter.h" #include "itkOutputWindow.h" #include "itkCommand.h" #include "itkImage.h" #include "itkImageRegionIterator.h" #include "vnl/vnl_math.h" #include "vnl/vnl_sample.h" // The following class is used to support callbacks // on the filter in the pipeline that follows later class ShowProgressObject { public: ShowProgressObject(itk::ProcessObject* o) {m_Process = o;} void ShowProgress() {std::cout << "Progress " << m_Process->GetProgress() << std::endl;} itk::ProcessObject::Pointer m_Process; }; #define MAXRUNS 5 // maximum number of runs template<unsigned int VImageDimension> int testMinMaxCurvatureFlow( itk::Size<VImageDimension> & size, double radius, int numberOfRuns, unsigned int niter[], unsigned long radii[] ); /** * This file tests the functionality of the MinMaxCurvatureFlowImageFilter. * The test uses a binary image of a circle/sphere with intensity value * of 0 (black). The background is white ( intensity = 255 ). * X% salt and pepper noise is added to the the input image. Specifically, * X% of the pixels is replaced with a value choosen from a uniform * distribution between 0 and 255. * * We then test the ability of MinMaxCurvatureFlowImageFilter to denoise * the image. */ int main() { double radius; int numberOfRuns; unsigned int niter[MAXRUNS]; unsigned long radii[MAXRUNS]; itk::Size<2> size2D; size2D[0] = 64; size2D[1] = 64; radius = 20.0; numberOfRuns = 2; niter[0] = 100; niter[1] = 100; radii[0] = 1; radii[1] = 3; int err2D = testMinMaxCurvatureFlow( size2D, radius, numberOfRuns, niter, radii ); itk::Size<3> size3D; size3D[0] = 32; size3D[1] = 32; size3D[2] = 32; radius = 10.0; numberOfRuns = 1; niter[0] = 20; radii[1] = 1; int err3D = testMinMaxCurvatureFlow( size3D, radius, numberOfRuns, niter, radii ); itk::Size<4> size4D; size4D[0] = 8; size4D[1] = 8; size4D[2] = 8; size4D[3] = 8; radius = 2.6; numberOfRuns = 1; niter[0] = 20; radii[1] = 1; int err4D = testMinMaxCurvatureFlow( size4D, radius, numberOfRuns, niter, radii ); if ( err2D || err3D || err4D ) { return EXIT_FAILURE; } return EXIT_SUCCESS; } template<unsigned int VImageDimension> int testMinMaxCurvatureFlow( itk::Size<VImageDimension> & size, // ND image size double radius, // ND-sphere radius int numberOfRuns, // number of times to run the filter unsigned int niter[], // number of iterations unsigned long radii[] // stencil radius ) { typedef float PixelType; enum { ImageDimension = VImageDimension }; typedef itk::Image<PixelType, ImageDimension> ImageType; typedef itk::ImageRegionIterator<ImageType> IteratorType; typedef itk::MinMaxCurvatureFlowImageFilter<ImageType,ImageType> DenoiserType; DenoiserType::Pointer denoiser = DenoiserType::New(); int j; /** * Create an image containing a circle/sphere with intensity of 0 * and background of 255 with added salt and pepper noise. */ double sqrRadius = vnl_math_sqr( radius ); // radius of the circle/sphere double fractionNoise = 0.30; // salt & pepper noise fraction PixelType foreground = 0.0; // intensity value of the foreground PixelType background = 255.0; // intensity value of the background std::cout << "Create an image of circle/sphere with noise" << std::endl; ImageType::Pointer circleImage = ImageType::New(); ImageType::RegionType region; region.SetSize( size ); circleImage->SetLargestPossibleRegion( region ); circleImage->SetBufferedRegion( region ); circleImage->Allocate(); IteratorType circleIter( circleImage, circleImage->GetBufferedRegion() ); for ( ; !circleIter.IsAtEnd() ; ++circleIter ) { ImageType::IndexType index = circleIter.GetIndex(); float value; double lhs = 0.0; for ( j = 0; j < ImageDimension; j++ ) { lhs += vnl_math_sqr( (double) index[j] - (double) size[j] * 0.5 ); } if ( lhs < sqrRadius ) { value = foreground; } else { value = background; } if ( vnl_sample_uniform( 0.0, 1.0 ) < fractionNoise ) { value = vnl_sample_uniform( vnl_math_min(foreground,background), vnl_math_max(foreground,background) ); } circleIter.Set( value ); } /** * Run MinMaxCurvatureFlowImageFilter several times using the previous * output as the input in the next run. */ std::cout << "Run MinMaxCurvatureFlowImageFiler.." << std::endl; // set other denoiser parameters here denoiser->SetTimeStep( 0.15 ); // attach a progress watcher to the denoiser ShowProgressObject progressWatch(denoiser); itk::SimpleMemberCommand<ShowProgressObject>::Pointer command; command = itk::SimpleMemberCommand<ShowProgressObject>::New(); command->SetCallbackFunction(&progressWatch, &ShowProgressObject::ShowProgress); denoiser->AddObserver( itk::ProgressEvent(), command); ImageType::Pointer swapPointer = circleImage; for ( int j = 0; j < numberOfRuns; j++ ) { denoiser->SetInput( swapPointer ); // set the stencil radius and number of iterations denoiser->SetStencilRadius( radii[j] ); denoiser->SetNumberOfIterations( niter[j] ); std::cout << " Run: " << j; std::cout << " Radius: " << denoiser->GetStencilRadius(); std::cout << " Iter: " << denoiser->GetNumberOfIterations(); std::cout << std::endl; // run the filter denoiser->Update(); swapPointer = denoiser->GetOutput(); swapPointer->DisconnectPipeline(); } /** * Check the quality of the output by comparing it against a * clean image of the circle/sphere. * An output pixel is okay if it is within * 0.1 * |foreground - background| of the true value. * This test is considered as passed if the fraction of wrong * pixels is less than the original noise fraction. */ std::cout << "Checking the output..." << std::endl; IteratorType outIter( swapPointer, swapPointer->GetBufferedRegion() ); PixelType tolerance = vnl_math_abs( foreground - background ) * 0.1; unsigned long numPixelsWrong = 0; for ( ; !outIter.IsAtEnd(); ++outIter ) { ImageType::IndexType index = outIter.GetIndex(); PixelType value = outIter.Get(); double lhs = 0.0; for ( j = 0; j < ImageDimension; j++ ) { lhs += vnl_math_sqr( (double) index[j] - (double) size[j] * 0.5 ); } if ( lhs < sqrRadius ) { if ( vnl_math_abs( foreground - value ) > tolerance ) { numPixelsWrong++; } } else if ( vnl_math_abs( background - value ) > tolerance ) { numPixelsWrong++; } } double fractionWrong = (double) numPixelsWrong / (double) region.GetNumberOfPixels(); std::cout << "Noise reduced from " << fractionNoise << " to "; std::cout << fractionWrong << std::endl; bool passed = true; if ( fractionWrong > fractionNoise ) { passed = false; } /** * Exercise other member functions here */ denoiser->Print( std::cout ); if ( !passed ) { std::cout << "Test failed." << std::endl; return EXIT_FAILURE; } std::cout << "Test passed." << std::endl; return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/*** * Copyright (c) 2013, Dan Hasting * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the organization nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ***/ #include "thegamesdbscraper.h" #include "../global.h" #include "../common.h" #include <QDir> #include <QEventLoop> #include <QMessageBox> #include <QTextStream> #include <QTimer> #include <QUrl> #include <QtNetwork/QNetworkAccessManager> #include <QtNetwork/QNetworkReply> #include <QtNetwork/QNetworkRequest> #include <QtXml/QDomDocument> TheGamesDBScraper::TheGamesDBScraper(QWidget *parent, bool force) : QObject(parent) { this->parent = parent; this->force = force; this->keepGoing = true; } void TheGamesDBScraper::deleteGameInfo(QString fileName, QString identifier) { QString text; text = QString(tr("<b>NOTE:</b> If you are deleting this game's information because the game doesn't ")) + tr("exist on TheGamesDB and <AppName> pulled the information for different game, it's ") + tr("better to create an account on")+" <a href=\"http://thegamesdb.net/\">TheGamesDB</a> " + tr("and add the game so other users can benefit as well.") + "<br /><br />" + tr("This will cause <AppName> to not update the information for this game until you ") + tr("force it with \"Download/Update Info...\"") + "<br /><br />" + tr("Delete the current information for") + " <b>" + fileName + "</b>?"; text.replace("<AppName>",AppName); int answer = QMessageBox::question(parent, tr("Delete Game Information"), text, QMessageBox::Yes | QMessageBox::No); if (answer == QMessageBox::Yes) { QString gameCache = getDataLocation() + "/cache/" + identifier.toLower(); QString dataFile = gameCache + "/data.xml"; QFile file(dataFile); // Remove game information file.open(QIODevice::WriteOnly); QTextStream stream(&file); stream << "NULL"; file.close(); // Remove cover image QString coverFile = gameCache + "/boxart-front."; QFile coverJPG(coverFile + "jpg"); QFile coverPNG(coverFile + "png"); if (coverJPG.exists()) coverJPG.remove(); if (coverPNG.exists()) coverPNG.remove(); coverJPG.open(QIODevice::WriteOnly); QTextStream streamImage(&coverJPG); streamImage << ""; coverJPG.close(); } } void TheGamesDBScraper::downloadGameInfo(QString identifier, QString searchName, QString gameID) { if (keepGoing && identifier != "") { if (force) parent->setEnabled(false); bool updated = false; QString gameCache = getDataLocation() + "/cache/" + identifier.toLower(); QDir cache(gameCache); if (!cache.exists()) { cache.mkpath(gameCache); } //Get game XML info from thegamesdb.net QString dataFile = gameCache + "/data.xml"; QFile file(dataFile); if (!file.exists() || file.size() == 0 || force) { QUrl url; //Remove [!], (U), etc. from GoodName for searching searchName.remove(QRegExp("\\W*(\\(|\\[).+(\\)|\\])\\W*")); //Few game specific hacks //TODO: Contact thegamesdb.net and see if these can be fixed on their end if (searchName == "Legend of Zelda, The - Majora's Mask") searchName = "Majora's Mask"; else if (searchName == "Legend of Zelda, The - Ocarina of Time - Master Quest") searchName = "Master Quest"; else if (searchName == "Legend of Zelda, The - Ocarina of Time" || searchName == "THE LEGEND OF ZELDA") searchName = "Ocarina of Time"; else if (searchName.toLower() == "f-zero x") gameID = "10836"; //If user submits gameID, use that if (gameID != "") url.setUrl("http://thegamesdb.net/api/GetGame.php?id=" + gameID + "&platform=Nintendo 64"); else url.setUrl("http://thegamesdb.net/api/GetGame.php?name=" + searchName + "&platform=Nintendo 64"); QString dom = getUrlContents(url); QDomDocument xml; xml.setContent(dom); QDomNode node = xml.elementsByTagName("Data").at(0).firstChildElement("Game"); int count = 0, found = 0; while(!node.isNull()) { QDomElement element = node.firstChildElement("GameTitle").toElement(); if (force) { //from user dialog QDomElement date = node.firstChildElement("ReleaseDate").toElement(); QString check = "Game: " + element.text(); check.remove(QRegExp(QString("[^A-Za-z 0-9 \\.,\\?'""!@#\\$%\\^&\\*\\") + "(\\)-_=\\+;:<>\\/\\\\|\\}\\{\\[\\]`~]*")); if (date.text() != "") check += "\n" + tr("Released on: ") + date.text(); check += "\n\n" + tr("Does this look correct?"); int answer = QMessageBox::question(parent, QObject::tr("Game Information Download"), check, QMessageBox::Yes | QMessageBox::No); if (answer == QMessageBox::Yes) { found = count; updated = true; break; } } else { //We only want one game, so search for a perfect match in the GameTitle element. //Otherwise this will default to 0 (the first game found) if(element.text() == searchName) found = count; } node = node.nextSibling(); count++; } if (!force || updated) { file.open(QIODevice::WriteOnly); QTextStream stream(&file); QDomNodeList gameList = xml.elementsByTagName("Game"); gameList.at(found).save(stream, QDomNode::EncodingFromDocument); file.close(); } if (force && !updated) { QString message; if (count == 0) message = QObject::tr("No results found."); else message = QObject::tr("No more results found."); QMessageBox::information(parent, QObject::tr("Game Information Download"), message); } } //Get front cover QString boxartURL = ""; QString boxartExt = ""; QString coverFile = gameCache + "/boxart-front."; QFile coverJPG(coverFile + "jpg"); QFile coverPNG(coverFile + "png"); if ((!coverJPG.exists() && !coverPNG.exists()) || (force && updated)) { file.open(QIODevice::ReadOnly); QString dom = file.readAll(); file.close(); QDomDocument xml; xml.setContent(dom); QDomNode node = xml.elementsByTagName("Game").at(0).firstChildElement("Images").firstChild(); while(!node.isNull()) { QDomElement element = node.toElement(); if(element.tagName() == "boxart" && element.attribute("side") == "front") boxartURL = element.attribute("thumb"); node = node.nextSibling(); } if (boxartURL != "") { QUrl url("http://thegamesdb.net/banners/" + boxartURL); //Check to save as JPG or PNG boxartExt = QFileInfo(boxartURL).completeSuffix().toLower(); QFile cover(coverFile + boxartExt); cover.open(QIODevice::WriteOnly); cover.write(getUrlContents(url)); cover.close(); } } if (updated) QMessageBox::information(parent, QObject::tr("Game Information Download"), QObject::tr("Download Complete!")); if (force) parent->setEnabled(true); } } QByteArray TheGamesDBScraper::getUrlContents(QUrl url) { QNetworkAccessManager *manager = new QNetworkAccessManager; QNetworkRequest request; request.setUrl(url); request.setRawHeader("User-Agent", AppName.toUtf8().constData()); QNetworkReply *reply = manager->get(request); QTimer timer; timer.setSingleShot(true); QEventLoop loop; connect(reply, SIGNAL(finished()), &loop, SLOT(quit())); connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit())); timer.start(10000); loop.exec(); if(timer.isActive()) { //Got reply timer.stop(); if(reply->error() > 0) showError(reply->errorString()); else return reply->readAll(); } else //Request timed out showError(tr("Request timed out. Check your network settings.")); return QByteArray(); } void TheGamesDBScraper::showError(QString error) { QString question = "\n\n" + tr("Continue scraping information?"); if (force) QMessageBox::information(parent, tr("Network Error"), error); else { int answer = QMessageBox::question(parent, tr("Network Error"), error + question, QMessageBox::Yes | QMessageBox::No); if (answer == QMessageBox::No) keepGoing = false; } } <commit_msg>Allow configuration of network timeout (dh4/mupen64plus-qt#27)<commit_after>/*** * Copyright (c) 2013, Dan Hasting * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the organization nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ***/ #include "thegamesdbscraper.h" #include "../global.h" #include "../common.h" #include <QDir> #include <QEventLoop> #include <QMessageBox> #include <QTextStream> #include <QTimer> #include <QUrl> #include <QtNetwork/QNetworkAccessManager> #include <QtNetwork/QNetworkReply> #include <QtNetwork/QNetworkRequest> #include <QtXml/QDomDocument> TheGamesDBScraper::TheGamesDBScraper(QWidget *parent, bool force) : QObject(parent) { this->parent = parent; this->force = force; this->keepGoing = true; } void TheGamesDBScraper::deleteGameInfo(QString fileName, QString identifier) { QString text; text = QString(tr("<b>NOTE:</b> If you are deleting this game's information because the game doesn't ")) + tr("exist on TheGamesDB and <AppName> pulled the information for different game, it's ") + tr("better to create an account on")+" <a href=\"http://thegamesdb.net/\">TheGamesDB</a> " + tr("and add the game so other users can benefit as well.") + "<br /><br />" + tr("This will cause <AppName> to not update the information for this game until you ") + tr("force it with \"Download/Update Info...\"") + "<br /><br />" + tr("Delete the current information for") + " <b>" + fileName + "</b>?"; text.replace("<AppName>",AppName); int answer = QMessageBox::question(parent, tr("Delete Game Information"), text, QMessageBox::Yes | QMessageBox::No); if (answer == QMessageBox::Yes) { QString gameCache = getDataLocation() + "/cache/" + identifier.toLower(); QString dataFile = gameCache + "/data.xml"; QFile file(dataFile); // Remove game information file.open(QIODevice::WriteOnly); QTextStream stream(&file); stream << "NULL"; file.close(); // Remove cover image QString coverFile = gameCache + "/boxart-front."; QFile coverJPG(coverFile + "jpg"); QFile coverPNG(coverFile + "png"); if (coverJPG.exists()) coverJPG.remove(); if (coverPNG.exists()) coverPNG.remove(); coverJPG.open(QIODevice::WriteOnly); QTextStream streamImage(&coverJPG); streamImage << ""; coverJPG.close(); } } void TheGamesDBScraper::downloadGameInfo(QString identifier, QString searchName, QString gameID) { if (keepGoing && identifier != "") { if (force) parent->setEnabled(false); bool updated = false; QString gameCache = getDataLocation() + "/cache/" + identifier.toLower(); QDir cache(gameCache); if (!cache.exists()) { cache.mkpath(gameCache); } //Get game XML info from thegamesdb.net QString dataFile = gameCache + "/data.xml"; QFile file(dataFile); if (!file.exists() || file.size() == 0 || force) { QUrl url; //Remove [!], (U), etc. from GoodName for searching searchName.remove(QRegExp("\\W*(\\(|\\[).+(\\)|\\])\\W*")); //Few game specific hacks //TODO: Contact thegamesdb.net and see if these can be fixed on their end if (searchName == "Legend of Zelda, The - Majora's Mask") searchName = "Majora's Mask"; else if (searchName == "Legend of Zelda, The - Ocarina of Time - Master Quest") searchName = "Master Quest"; else if (searchName == "Legend of Zelda, The - Ocarina of Time" || searchName == "THE LEGEND OF ZELDA") searchName = "Ocarina of Time"; else if (searchName.toLower() == "f-zero x") gameID = "10836"; //If user submits gameID, use that if (gameID != "") url.setUrl("http://thegamesdb.net/api/GetGame.php?id=" + gameID + "&platform=Nintendo 64"); else url.setUrl("http://thegamesdb.net/api/GetGame.php?name=" + searchName + "&platform=Nintendo 64"); QString dom = getUrlContents(url); QDomDocument xml; xml.setContent(dom); QDomNode node = xml.elementsByTagName("Data").at(0).firstChildElement("Game"); int count = 0, found = 0; while(!node.isNull()) { QDomElement element = node.firstChildElement("GameTitle").toElement(); if (force) { //from user dialog QDomElement date = node.firstChildElement("ReleaseDate").toElement(); QString check = "Game: " + element.text(); check.remove(QRegExp(QString("[^A-Za-z 0-9 \\.,\\?'""!@#\\$%\\^&\\*\\") + "(\\)-_=\\+;:<>\\/\\\\|\\}\\{\\[\\]`~]*")); if (date.text() != "") check += "\n" + tr("Released on: ") + date.text(); check += "\n\n" + tr("Does this look correct?"); int answer = QMessageBox::question(parent, QObject::tr("Game Information Download"), check, QMessageBox::Yes | QMessageBox::No); if (answer == QMessageBox::Yes) { found = count; updated = true; break; } } else { //We only want one game, so search for a perfect match in the GameTitle element. //Otherwise this will default to 0 (the first game found) if(element.text() == searchName) found = count; } node = node.nextSibling(); count++; } if (!force || updated) { file.open(QIODevice::WriteOnly); QTextStream stream(&file); QDomNodeList gameList = xml.elementsByTagName("Game"); gameList.at(found).save(stream, QDomNode::EncodingFromDocument); file.close(); } if (force && !updated) { QString message; if (count == 0) message = QObject::tr("No results found."); else message = QObject::tr("No more results found."); QMessageBox::information(parent, QObject::tr("Game Information Download"), message); } } //Get front cover QString boxartURL = ""; QString boxartExt = ""; QString coverFile = gameCache + "/boxart-front."; QFile coverJPG(coverFile + "jpg"); QFile coverPNG(coverFile + "png"); if ((!coverJPG.exists() && !coverPNG.exists()) || (force && updated)) { file.open(QIODevice::ReadOnly); QString dom = file.readAll(); file.close(); QDomDocument xml; xml.setContent(dom); QDomNode node = xml.elementsByTagName("Game").at(0).firstChildElement("Images").firstChild(); while(!node.isNull()) { QDomElement element = node.toElement(); if(element.tagName() == "boxart" && element.attribute("side") == "front") boxartURL = element.attribute("thumb"); node = node.nextSibling(); } if (boxartURL != "") { QUrl url("http://thegamesdb.net/banners/" + boxartURL); //Check to save as JPG or PNG boxartExt = QFileInfo(boxartURL).completeSuffix().toLower(); QFile cover(coverFile + boxartExt); cover.open(QIODevice::WriteOnly); cover.write(getUrlContents(url)); cover.close(); } } if (updated) QMessageBox::information(parent, QObject::tr("Game Information Download"), QObject::tr("Download Complete!")); if (force) parent->setEnabled(true); } } QByteArray TheGamesDBScraper::getUrlContents(QUrl url) { QNetworkAccessManager *manager = new QNetworkAccessManager; QNetworkRequest request; request.setUrl(url); request.setRawHeader("User-Agent", AppName.toUtf8().constData()); QNetworkReply *reply = manager->get(request); QTimer timer; timer.setSingleShot(true); QEventLoop loop; connect(reply, SIGNAL(finished()), &loop, SLOT(quit())); connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit())); int time = SETTINGS.value("Other/networktimeout", 10).toInt(); if (time == 0) time = 10; time *= 1000; timer.start(time); loop.exec(); if(timer.isActive()) { //Got reply timer.stop(); if(reply->error() > 0) showError(reply->errorString()); else return reply->readAll(); } else //Request timed out showError(tr("Request timed out. Check your network settings.")); return QByteArray(); } void TheGamesDBScraper::showError(QString error) { QString question = "\n\n" + tr("Continue scraping information?"); if (force) QMessageBox::information(parent, tr("Network Error"), error); else { int answer = QMessageBox::question(parent, tr("Network Error"), error + question, QMessageBox::Yes | QMessageBox::No); if (answer == QMessageBox::No) keepGoing = false; } } <|endoftext|>
<commit_before>/** * Render Pipeline C++ * * Copyright (c) 2014-2016 tobspr <[email protected]> * Copyright (c) 2016-2017 Center of Human-centered Interaction for Coexistence. * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software * and associated documentation files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial * portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT * LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "rpcore/gui/pipe_viewer.hpp" #include <boost/algorithm/string.hpp> #include "render_pipeline/rppanda/showbase/showbase.hpp" #include "render_pipeline/rppanda/gui/direct_scrolled_frame.hpp" #include "render_pipeline/rpcore/globals.hpp" #include "render_pipeline/rpcore/render_pipeline.hpp" #include "render_pipeline/rpcore/stage_manager.hpp" #include "render_pipeline/rpcore/render_stage.hpp" #include "render_pipeline/rpcore/gui/sprite.hpp" #include "render_pipeline/rpcore/util/generic.hpp" #include "render_pipeline/rpcore/util/shader_input_blocks.hpp" #include "rpcore/util/display_shader_builder.hpp" namespace rpcore { PipeViewer::PipeViewer(RenderPipeline* pipeline, NodePath parent): DraggableWindow(1300, 900, "Pipeline Visualizer", parent), _pipeline(pipeline) { create_components(); hide(); } void PipeViewer::toggle() { if (_visible) { Globals::base->remove_task("UpdatePipeViewer"); hide(); } else { Globals::base->add_task(update_task, this, "RP_GUI_UpdatePipeViewer"); if (!_created) populate_content(); show(); } } AsyncTask::DoneStatus PipeViewer::update_task(GenericAsyncTask* task, void* user_data) { PipeViewer* pv = reinterpret_cast<PipeViewer*>(user_data); float scroll_value = pv->_content_frame->get_horizontal_scroll()->get_value(); scroll_value *= 2.45f; pv->_pipe_descriptions.set_x(scroll_value * 2759.0f); return AsyncTask::DS_cont; } void PipeViewer::create_components() { DraggableWindow::create_components(); auto content_frame_options = std::make_shared<rppanda::DirectScrolledFrame::Options>(); content_frame_options->frame_size = LVecBase4f(0, _width - 40, 0, _height - 80); content_frame_options->canvas_size = LVecBase4f(0, _scroll_width, 0, _scroll_height); content_frame_options->auto_hide_scroll_bars = false; content_frame_options->scroll_bar_width = 20.0f; content_frame_options->frame_color = LColorf(0); content_frame_options->vertical_scroll_options->relief = PGFrameStyle::Type(0); content_frame_options->horizontal_scroll_options->relief = PGFrameStyle::Type(0); content_frame_options->pos = LVecBase3f(20, 1, -_height + 20); _content_frame = new rppanda::DirectScrolledFrame(_node, content_frame_options); _content_node = _content_frame->get_canvas().attach_new_node("PipeComponents"); _content_node.set_scale(1, 1, -1); _content_node.set_z(_scroll_height); } void PipeViewer::populate_content() { _created = true; _pipe_node = _content_node.attach_new_node("pipes"); _pipe_node.set_scale(1, 1, -1); _stage_node = _content_node.attach_new_node("stages"); std::vector<std::string> current_pipes; const int pipe_pixel_size = 3; const int pipe_height = 100; // Generate stages const auto& stages = _pipeline->get_stage_mgr()->get_stages(); for (size_t offs=0, offs_end=stages.size(); offs < offs_end; ++offs) { const std::shared_ptr<RenderStage>& stage = stages[offs]; NodePath node = _content_node.attach_new_node("stage"); node.set_pos(220 + offs * 200.0, 0, 20); node.set_scale(1, 1, -1); { auto df_options = std::make_shared<rppanda::DirectFrame::Options>(); df_options->frame_size = LVecBase4(10, 150, 0, -3600); df_options->frame_color = LColor(0.2, 0.2, 0.2, 1); rppanda::DirectFrame df(node, df_options); } std::string stage_name(stage->get_debug_name()); const std::string key("Stage"); stage_name.replace(stage_name.find(key), key.length(), ""); Text stage_text(stage_name, node, 20, 25, 15); for (const auto& pipe_tex: stage->get_produced_pipes()) { const ShaderInput* shader_input_data = nullptr; const std::shared_ptr<SimpleInputBlock>* simple_input_data = nullptr; const std::shared_ptr<GroupedInputBlock>* group_input_data = nullptr; std::string output_pipe; if (shader_input_data = boost::get<ShaderInput>(&pipe_tex)) output_pipe = shader_input_data->get_name()->get_name(); else if (simple_input_data = boost::get<std::shared_ptr<SimpleInputBlock>>(&pipe_tex)) output_pipe = (*simple_input_data)->get_name(); else if (group_input_data = boost::get<std::shared_ptr<GroupedInputBlock>>(&pipe_tex)) output_pipe = (*group_input_data)->get_name(); long long pipe_idx = 0; const LVecBase3f& rgb = rgb_from_string(output_pipe); auto pipe_iter = std::find(current_pipes.begin(), current_pipes.end(), output_pipe); if (pipe_iter != current_pipes.end()) { pipe_idx = std::distance(current_pipes.begin(), pipe_iter); } else { current_pipes.push_back(output_pipe); pipe_idx = current_pipes.size() - 1; auto df_options = std::make_shared<rppanda::DirectFrame::Options>(); df_options->frame_size = LVecBase4(0, 8000, pipe_pixel_size / 2.0f, -pipe_pixel_size / 2.0f); df_options->frame_color = LColor(rgb, 1); df_options->pos = LVecBase3(10, 1, -95 - pipe_idx * pipe_height); rppanda::DirectFrame output_pipe_df(node, df_options); } const float w = 160; const float h = Globals::native_resolution.get_y() / float(Globals::native_resolution.get_x()) * w; auto df_options = std::make_shared<rppanda::DirectFrame::Options>(); df_options->frame_size = LVecBase4(-pipe_pixel_size, w + pipe_pixel_size, h / 2.0f + pipe_pixel_size, -h / 2.0f - pipe_pixel_size); df_options->frame_color = LColor(rgb, 1); df_options->pos = LVecBase3(0, 1, -95 - pipe_idx * pipe_height); rppanda::DirectFrame pipe_df(node, df_options); std::string icon_file = ""; Texture* pipe_texture = nullptr; if (shader_input_data) pipe_texture = shader_input_data->get_texture(); if (simple_input_data || group_input_data) { icon_file = "/$$rp/data/gui/icon_ubo.png"; } else if (pipe_texture->get_z_size() > 1) { icon_file = "/$$rp/data/gui/icon_texture.png"; } else if (pipe_texture->get_texture_type() == Texture::TextureType::TT_buffer_texture) { icon_file = "/$$rp/data/gui/icon_buffer_texture.png"; } else { Sprite preview(pipe_texture, w, h, node, 0, 50 + pipe_idx * pipe_height, false, true, false); auto preview_np = preview.get_node(); PT(Shader) preview_shader = DisplayShaderBuilder::build(pipe_texture, int(w), int(h)); preview_np->set_shader(preview_shader); preview_np->set_shader_input("mipmap", 0); preview_np->set_shader_input("slice", 0); preview_np->set_shader_input("brightness", 1); preview_np->set_shader_input("tonemap", false); } if (!icon_file.empty()) { Sprite(icon_file, 48, 48, node, 55, 65 + pipe_idx * pipe_height, true, false); std::string tex_desc; if (simple_input_data || group_input_data) { tex_desc = "UBO"; } else { tex_desc = pipe_texture->format_texture_type(pipe_texture->get_texture_type()); tex_desc += std::string(" - ") + boost::to_upper_copy(pipe_texture->format_format(pipe_texture->get_format())); } Text tex_desc_text(tex_desc, node, 55+48/2.0f, 130+pipe_idx*pipe_height, 12, "center", LVecBase3f(0.2f)); } } for (const auto& input_pipe: stage->get_required_pipes()) { auto pipe_iter = std::find(current_pipes.begin(), current_pipes.end(), input_pipe); if (pipe_iter == current_pipes.end()) { warn(std::string("Pipe not found: ") + input_pipe); continue; } long long idx = std::distance(current_pipes.begin(), pipe_iter); const LVecBase3& rgb = rgb_from_string(input_pipe); auto df_options = std::make_shared<rppanda::DirectFrame::Options>(); df_options->frame_size = LVecBase4(0, 10, 40, -40); df_options->frame_color = LColor(rgb, 1); df_options->pos = LVecBase3(5, 1, -95 - idx * pipe_height); rppanda::DirectFrame input_pipe_df(node, df_options); } } _pipe_descriptions = _content_node.attach_new_node("PipeDescriptions"); _pipe_descriptions.set_scale(1, 1, -1); { auto df_options = std::make_shared<rppanda::DirectFrame::Options>(); df_options->frame_size = LVecBase4(0, 190, 0, -5000); df_options->frame_color = LColor(0.1, 0.1, 0.1, 1.0); rppanda::DirectFrame desc_df(_pipe_descriptions, df_options); } // Generate the pipe descriptions for (size_t idx=0, idx_end=current_pipes.size(); idx < idx_end; ++idx) { const LVecBase3& rgb = rgb_from_string(current_pipes[idx]); auto df_options = std::make_shared<rppanda::DirectFrame::Options>(); df_options->frame_size = LVecBase4(0, 180, -95, -135); df_options->frame_color = LColor(rgb, 1.0); df_options->pos = LVecBase3(0, 1, -(long long)(idx) * pipe_height); rppanda::DirectFrame pipe_desc_df(_pipe_descriptions, df_options); Text pipe_text(current_pipes[idx], _pipe_descriptions, 42, 121 + idx * pipe_height, 15, "left", LVecBase3f(0.1)); Sprite("/$$rp/data/gui/icon_pipe.png", _pipe_descriptions, 9, 103 + idx * pipe_height, true, false); } } } <commit_msg>Fix different task name<commit_after>/** * Render Pipeline C++ * * Copyright (c) 2014-2016 tobspr <[email protected]> * Copyright (c) 2016-2017 Center of Human-centered Interaction for Coexistence. * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software * and associated documentation files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial * portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT * LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "rpcore/gui/pipe_viewer.hpp" #include <boost/algorithm/string.hpp> #include "render_pipeline/rppanda/showbase/showbase.hpp" #include "render_pipeline/rppanda/gui/direct_scrolled_frame.hpp" #include "render_pipeline/rpcore/globals.hpp" #include "render_pipeline/rpcore/render_pipeline.hpp" #include "render_pipeline/rpcore/stage_manager.hpp" #include "render_pipeline/rpcore/render_stage.hpp" #include "render_pipeline/rpcore/gui/sprite.hpp" #include "render_pipeline/rpcore/util/generic.hpp" #include "render_pipeline/rpcore/util/shader_input_blocks.hpp" #include "rpcore/util/display_shader_builder.hpp" namespace rpcore { PipeViewer::PipeViewer(RenderPipeline* pipeline, NodePath parent): DraggableWindow(1300, 900, "Pipeline Visualizer", parent), _pipeline(pipeline) { create_components(); hide(); } void PipeViewer::toggle() { static const std::string task_name("RP_GUI_UpdatePipeViewer"); if (_visible) { Globals::base->remove_task(task_name); hide(); } else { Globals::base->add_task(update_task, this, task_name); if (!_created) populate_content(); show(); } } AsyncTask::DoneStatus PipeViewer::update_task(GenericAsyncTask* task, void* user_data) { PipeViewer* pv = reinterpret_cast<PipeViewer*>(user_data); float scroll_value = pv->_content_frame->get_horizontal_scroll()->get_value(); scroll_value *= 2.45f; pv->_pipe_descriptions.set_x(scroll_value * 2759.0f); return AsyncTask::DS_cont; } void PipeViewer::create_components() { DraggableWindow::create_components(); auto content_frame_options = std::make_shared<rppanda::DirectScrolledFrame::Options>(); content_frame_options->frame_size = LVecBase4f(0, _width - 40, 0, _height - 80); content_frame_options->canvas_size = LVecBase4f(0, _scroll_width, 0, _scroll_height); content_frame_options->auto_hide_scroll_bars = false; content_frame_options->scroll_bar_width = 20.0f; content_frame_options->frame_color = LColorf(0); content_frame_options->vertical_scroll_options->relief = PGFrameStyle::Type(0); content_frame_options->horizontal_scroll_options->relief = PGFrameStyle::Type(0); content_frame_options->pos = LVecBase3f(20, 1, -_height + 20); _content_frame = new rppanda::DirectScrolledFrame(_node, content_frame_options); _content_node = _content_frame->get_canvas().attach_new_node("PipeComponents"); _content_node.set_scale(1, 1, -1); _content_node.set_z(_scroll_height); } void PipeViewer::populate_content() { _created = true; _pipe_node = _content_node.attach_new_node("pipes"); _pipe_node.set_scale(1, 1, -1); _stage_node = _content_node.attach_new_node("stages"); std::vector<std::string> current_pipes; const int pipe_pixel_size = 3; const int pipe_height = 100; // Generate stages const auto& stages = _pipeline->get_stage_mgr()->get_stages(); for (size_t offs=0, offs_end=stages.size(); offs < offs_end; ++offs) { const std::shared_ptr<RenderStage>& stage = stages[offs]; NodePath node = _content_node.attach_new_node("stage"); node.set_pos(220 + offs * 200.0, 0, 20); node.set_scale(1, 1, -1); { auto df_options = std::make_shared<rppanda::DirectFrame::Options>(); df_options->frame_size = LVecBase4(10, 150, 0, -3600); df_options->frame_color = LColor(0.2, 0.2, 0.2, 1); rppanda::DirectFrame df(node, df_options); } std::string stage_name(stage->get_debug_name()); const std::string key("Stage"); stage_name.replace(stage_name.find(key), key.length(), ""); Text stage_text(stage_name, node, 20, 25, 15); for (const auto& pipe_tex: stage->get_produced_pipes()) { const ShaderInput* shader_input_data = nullptr; const std::shared_ptr<SimpleInputBlock>* simple_input_data = nullptr; const std::shared_ptr<GroupedInputBlock>* group_input_data = nullptr; std::string output_pipe; if (shader_input_data = boost::get<ShaderInput>(&pipe_tex)) output_pipe = shader_input_data->get_name()->get_name(); else if (simple_input_data = boost::get<std::shared_ptr<SimpleInputBlock>>(&pipe_tex)) output_pipe = (*simple_input_data)->get_name(); else if (group_input_data = boost::get<std::shared_ptr<GroupedInputBlock>>(&pipe_tex)) output_pipe = (*group_input_data)->get_name(); long long pipe_idx = 0; const LVecBase3f& rgb = rgb_from_string(output_pipe); auto pipe_iter = std::find(current_pipes.begin(), current_pipes.end(), output_pipe); if (pipe_iter != current_pipes.end()) { pipe_idx = std::distance(current_pipes.begin(), pipe_iter); } else { current_pipes.push_back(output_pipe); pipe_idx = current_pipes.size() - 1; auto df_options = std::make_shared<rppanda::DirectFrame::Options>(); df_options->frame_size = LVecBase4(0, 8000, pipe_pixel_size / 2.0f, -pipe_pixel_size / 2.0f); df_options->frame_color = LColor(rgb, 1); df_options->pos = LVecBase3(10, 1, -95 - pipe_idx * pipe_height); rppanda::DirectFrame output_pipe_df(node, df_options); } const float w = 160; const float h = Globals::native_resolution.get_y() / float(Globals::native_resolution.get_x()) * w; auto df_options = std::make_shared<rppanda::DirectFrame::Options>(); df_options->frame_size = LVecBase4(-pipe_pixel_size, w + pipe_pixel_size, h / 2.0f + pipe_pixel_size, -h / 2.0f - pipe_pixel_size); df_options->frame_color = LColor(rgb, 1); df_options->pos = LVecBase3(0, 1, -95 - pipe_idx * pipe_height); rppanda::DirectFrame pipe_df(node, df_options); std::string icon_file = ""; Texture* pipe_texture = nullptr; if (shader_input_data) pipe_texture = shader_input_data->get_texture(); if (simple_input_data || group_input_data) { icon_file = "/$$rp/data/gui/icon_ubo.png"; } else if (pipe_texture->get_z_size() > 1) { icon_file = "/$$rp/data/gui/icon_texture.png"; } else if (pipe_texture->get_texture_type() == Texture::TextureType::TT_buffer_texture) { icon_file = "/$$rp/data/gui/icon_buffer_texture.png"; } else { Sprite preview(pipe_texture, w, h, node, 0, 50 + pipe_idx * pipe_height, false, true, false); auto preview_np = preview.get_node(); PT(Shader) preview_shader = DisplayShaderBuilder::build(pipe_texture, int(w), int(h)); preview_np->set_shader(preview_shader); preview_np->set_shader_input("mipmap", 0); preview_np->set_shader_input("slice", 0); preview_np->set_shader_input("brightness", 1); preview_np->set_shader_input("tonemap", false); } if (!icon_file.empty()) { Sprite(icon_file, 48, 48, node, 55, 65 + pipe_idx * pipe_height, true, false); std::string tex_desc; if (simple_input_data || group_input_data) { tex_desc = "UBO"; } else { tex_desc = pipe_texture->format_texture_type(pipe_texture->get_texture_type()); tex_desc += std::string(" - ") + boost::to_upper_copy(pipe_texture->format_format(pipe_texture->get_format())); } Text tex_desc_text(tex_desc, node, 55+48/2.0f, 130+pipe_idx*pipe_height, 12, "center", LVecBase3f(0.2f)); } } for (const auto& input_pipe: stage->get_required_pipes()) { auto pipe_iter = std::find(current_pipes.begin(), current_pipes.end(), input_pipe); if (pipe_iter == current_pipes.end()) { warn(std::string("Pipe not found: ") + input_pipe); continue; } long long idx = std::distance(current_pipes.begin(), pipe_iter); const LVecBase3& rgb = rgb_from_string(input_pipe); auto df_options = std::make_shared<rppanda::DirectFrame::Options>(); df_options->frame_size = LVecBase4(0, 10, 40, -40); df_options->frame_color = LColor(rgb, 1); df_options->pos = LVecBase3(5, 1, -95 - idx * pipe_height); rppanda::DirectFrame input_pipe_df(node, df_options); } } _pipe_descriptions = _content_node.attach_new_node("PipeDescriptions"); _pipe_descriptions.set_scale(1, 1, -1); { auto df_options = std::make_shared<rppanda::DirectFrame::Options>(); df_options->frame_size = LVecBase4(0, 190, 0, -5000); df_options->frame_color = LColor(0.1, 0.1, 0.1, 1.0); rppanda::DirectFrame desc_df(_pipe_descriptions, df_options); } // Generate the pipe descriptions for (size_t idx=0, idx_end=current_pipes.size(); idx < idx_end; ++idx) { const LVecBase3& rgb = rgb_from_string(current_pipes[idx]); auto df_options = std::make_shared<rppanda::DirectFrame::Options>(); df_options->frame_size = LVecBase4(0, 180, -95, -135); df_options->frame_color = LColor(rgb, 1.0); df_options->pos = LVecBase3(0, 1, -(long long)(idx) * pipe_height); rppanda::DirectFrame pipe_desc_df(_pipe_descriptions, df_options); Text pipe_text(current_pipes[idx], _pipe_descriptions, 42, 121 + idx * pipe_height, 15, "left", LVecBase3f(0.1)); Sprite("/$$rp/data/gui/icon_pipe.png", _pipe_descriptions, 9, 103 + idx * pipe_height, true, false); } } } <|endoftext|>
<commit_before>//--------------------------------------------------------------------*- C++ -*- // CLING - the C++ LLVM-based InterpreterG :) // author: Axel Naumann <[email protected]> // // This file is dual-licensed: you can choose to license it under the University // of Illinois Open Source License or the GNU Lesser General Public License. See // LICENSE.TXT for details. //------------------------------------------------------------------------------ #include "IncrementalExecutor.h" #include "IncrementalJIT.h" #include "cling/Interpreter/Value.h" #include "cling/Interpreter/Transaction.h" #include "clang/Basic/Diagnostic.h" #include "llvm/IR/Constants.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/Module.h" #include "llvm/PassManager.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/ADT/Triple.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Support/DynamicLibrary.h" #include "llvm/Support/Host.h" #include "llvm/Support/TargetRegistry.h" #include "llvm/Target/TargetMachine.h" using namespace llvm; namespace cling { IncrementalExecutor::IncrementalExecutor(clang::DiagnosticsEngine& diags): m_CurrentAtExitModule(0) #if 0 : m_Diags(diags) #endif { m_AtExitFuncs.reserve(256); m_JIT.reset(new IncrementalJIT(*this, std::move(CreateHostTargetMachine()))); } // Keep in source: ~unique_ptr<ClingJIT> needs ClingJIT IncrementalExecutor::~IncrementalExecutor() {} std::unique_ptr<TargetMachine> IncrementalExecutor::CreateHostTargetMachine() const { // TODO: make this configurable. Triple TheTriple(sys::getProcessTriple()); std::string Error; const Target *TheTarget = TargetRegistry::lookupTarget(TheTriple.getTriple(), Error); if (!TheTarget) { llvm::errs() << "cling::IncrementalExecutor: unable to find target:\n" << Error; } std::string MCPU; std::string FeaturesStr; TargetOptions Options = TargetOptions(); Options.NoFramePointerElim = 1; Options.JITEmitDebugInfo = 1; Reloc::Model RelocModel = Reloc::Default; CodeModel::Model CMModel = CodeModel::JITDefault; CodeGenOpt::Level OptLevel = CodeGenOpt::Default; std::unique_ptr<TargetMachine> TM; TM.reset(TheTarget->createTargetMachine(TheTriple.getTriple(), MCPU, FeaturesStr, Options, RelocModel, CMModel, OptLevel)); return std::move(TM); } void IncrementalExecutor::shuttingDown() { for (size_t I = 0, N = m_AtExitFuncs.size(); I < N; ++I) { const CXAAtExitElement& AEE = m_AtExitFuncs[N - I - 1]; (*AEE.m_Func)(AEE.m_Arg); } } void IncrementalExecutor::AddAtExitFunc(void (*func) (void*), void* arg) { // Register a CXAAtExit function m_AtExitFuncs.push_back(CXAAtExitElement(func, arg, m_CurrentAtExitModule)); } void unresolvedSymbol() { // throw exception? llvm::errs() << "IncrementalExecutor: calling unresolved symbol, " "see previous error message!\n"; } void* IncrementalExecutor::HandleMissingFunction(const std::string& mangled_name) { // Not found in the map, add the symbol in the list of unresolved symbols if (m_unresolvedSymbols.insert(mangled_name).second) { //llvm::errs() << "IncrementalExecutor: use of undefined symbol '" // << mangled_name << "'!\n"; } // Avoid "ISO C++ forbids casting between pointer-to-function and // pointer-to-object": return (void*)reinterpret_cast<size_t>(unresolvedSymbol); } void* IncrementalExecutor::NotifyLazyFunctionCreators(const std::string& mangled_name) { for (std::vector<LazyFunctionCreatorFunc_t>::iterator it = m_lazyFuncCreator.begin(), et = m_lazyFuncCreator.end(); it != et; ++it) { void* ret = (void*)((LazyFunctionCreatorFunc_t)*it)(mangled_name); if (ret) return ret; } return HandleMissingFunction(mangled_name); } static void freeCallersOfUnresolvedSymbols(llvm::SmallVectorImpl<llvm::Function*>& funcsToFree, llvm::ExecutionEngine* engine) { llvm::SmallPtrSet<llvm::Function*, 40> funcsToFreeUnique; for (size_t i = 0; i < funcsToFree.size(); ++i) { llvm::Function* func = funcsToFree[i]; assert(func && "Cannot free NULL function"); if (funcsToFreeUnique.insert(func).second) { for (llvm::Value::use_iterator IU = func->use_begin(), EU = func->use_end(); IU != EU; ++IU) { llvm::Instruction* instUser = llvm::dyn_cast<llvm::Instruction>(*IU); if (!instUser) continue; if (!instUser->getParent()) continue; if (llvm::Function* userFunc = instUser->getParent()->getParent()) funcsToFree.push_back(userFunc); } } } for (llvm::SmallPtrSet<llvm::Function*, 40>::iterator I = funcsToFreeUnique.begin(), E = funcsToFreeUnique.end(); I != E; ++I) { // This should force the JIT to recompile the function. But the stubs stay, // and the JIT reuses the stubs now pointing nowhere, i.e. without updating // the machine code address. Fix the JIT, or hope that MCJIT helps. //engine->freeMachineCodeForFunction(*I); engine->updateGlobalMapping(*I, 0); } } IncrementalExecutor::ExecutionResult IncrementalExecutor::runStaticInitializersOnce(const Transaction& T) { llvm::Module* m = T.getModule(); assert(m && "Module must not be null"); // Set m_CurrentAtExitModule to the Module, unset to 0 once done. struct AtExitModuleSetterRAII { llvm::Module*& m_AEM; AtExitModuleSetterRAII(llvm::Module* M, llvm::Module*& AEM): m_AEM(AEM) { AEM = M; } ~AtExitModuleSetterRAII() { m_AEM = 0; } } DSOHandleSetter(m, m_CurrentAtExitModule); // We don't care whether something was unresolved before. m_unresolvedSymbols.clear(); // check if there is any unresolved symbol in the list if (diagnoseUnresolvedSymbols("static initializers")) return kExeUnresolvedSymbols; llvm::GlobalVariable* GV = m->getGlobalVariable("llvm.global_ctors", true); // Nothing to do is good, too. if (!GV) return kExeSuccess; // Close similarity to // m_engine->runStaticConstructorsDestructors(false) aka // llvm::ExecutionEngine::runStaticConstructorsDestructors() // is intentional; we do an extra pass to check whether the JIT // managed to collect all the symbols needed by the niitializers. // Should be an array of '{ i32, void ()* }' structs. The first value is // the init priority, which we ignore. llvm::ConstantArray *InitList = llvm::dyn_cast<llvm::ConstantArray>(GV->getInitializer()); // We need to delete it here just in case we have recursive inits, otherwise // it will call inits multiple times. GV->eraseFromParent(); if (InitList == 0) return kExeSuccess; SmallVector<Function*, 2> initFuncs; for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) { llvm::ConstantStruct *CS = llvm::dyn_cast<llvm::ConstantStruct>(InitList->getOperand(i)); if (CS == 0) continue; llvm::Constant *FP = CS->getOperand(1); if (FP->isNullValue()) continue; // Found a sentinal value, ignore. // Strip off constant expression casts. if (llvm::ConstantExpr *CE = llvm::dyn_cast<llvm::ConstantExpr>(FP)) if (CE->isCast()) FP = CE->getOperand(0); // Execute the ctor/dtor function! if (llvm::Function *F = llvm::dyn_cast<llvm::Function>(FP)) { executeInit(F->getName()); initFuncs.push_back(F); if (F->getName().startswith("_GLOBAL__sub_I__")) { BasicBlock& BB = F->getEntryBlock(); for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I) if (CallInst* call = dyn_cast<CallInst>(I)) initFuncs.push_back(call->getCalledFunction()); } } } for (SmallVector<Function*,2>::iterator I = initFuncs.begin(), E = initFuncs.end(); I != E; ++I) { // Cleanup also the dangling init functions. They are in the form: // define internal void @_GLOBAL__I_aN() section "..."{ // entry: // call void @__cxx_global_var_init(N-1)() // call void @__cxx_global_var_initM() // ret void // } // // define internal void @__cxx_global_var_init(N-1)() section "..." { // entry: // call void @_ZN7MyClassC1Ev(%struct.MyClass* @n) // ret void // } // Erase __cxx_global_var_init(N-1)() first. (*I)->removeDeadConstantUsers(); (*I)->eraseFromParent(); } return kExeSuccess; } void IncrementalExecutor::runAndRemoveStaticDestructors(Transaction* T) { assert(T && "Must be set"); // Collect all the dtors bound to this transaction. AtExitFunctions boundToT; for (AtExitFunctions::iterator I = m_AtExitFuncs.begin(); I != m_AtExitFuncs.end();) if (I->m_FromM == T->getModule()) { boundToT.push_back(*I); I = m_AtExitFuncs.erase(I); } else ++I; // 'Unload' the cxa_atexit entities. for (AtExitFunctions::reverse_iterator I = boundToT.rbegin(), E = boundToT.rend(); I != E; ++I) { const CXAAtExitElement& AEE = *I; (*AEE.m_Func)(AEE.m_Arg); } } void IncrementalExecutor::installLazyFunctionCreator(LazyFunctionCreatorFunc_t fp) { m_lazyFuncCreator.push_back(fp); } bool IncrementalExecutor::addSymbol(const char* symbolName, void* symbolAddress) { void* actualAddress = llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(symbolName); if (actualAddress) return false; llvm::sys::DynamicLibrary::AddSymbol(symbolName, symbolAddress); return true; } void* IncrementalExecutor::getAddressOfGlobal(llvm::StringRef symbolName, bool* fromJIT /*=0*/) { // Return a symbol's address, and whether it was jitted. void* address = llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(symbolName); // It's not from the JIT if it's in a dylib. if (fromJIT) *fromJIT = !address; if (!address) return (void*)m_JIT->getSymbolAddress(symbolName); return address; } void* IncrementalExecutor::getPointerToGlobalFromJIT(const llvm::GlobalValue& GV) { // Get the function / variable pointer referenced by GV. // We don't care whether something was unresolved before. m_unresolvedSymbols.clear(); void* addr = (void*)m_JIT->getSymbolAddress(GV.getName()); if (diagnoseUnresolvedSymbols(GV.getName(), "symbol")) return 0; return addr; } bool IncrementalExecutor::diagnoseUnresolvedSymbols(llvm::StringRef trigger, llvm::StringRef title) { if (m_unresolvedSymbols.empty()) return false; llvm::SmallVector<llvm::Function*, 128> funcsToFree; for (std::set<std::string>::const_iterator i = m_unresolvedSymbols.begin(), e = m_unresolvedSymbols.end(); i != e; ++i) { #if 0 // FIXME: This causes a lot of test failures, for some reason it causes // the call to HandleMissingFunction to be elided. unsigned diagID = m_Diags.getCustomDiagID(clang::DiagnosticsEngine::Error, "%0 unresolved while jitting %1"); (void)diagID; //m_Diags.Report(diagID) << *i << funcname; // TODO: demangle the names. #endif llvm::errs() << "IncrementalExecutor::executeFunction: symbol '" << *i << "' unresolved while linking "; if (!title.empty()) llvm::errs() << title << "'"; llvm::errs() << trigger; if (!title.empty()) llvm::errs() << "'"; llvm::errs() << "!\n"; //llvm::Function *ff = m_engine->FindFunctionNamed(i->c_str()); // i could also reference a global variable, in which case ff == 0. //if (ff) // funcsToFree.push_back(ff); } //freeCallersOfUnresolvedSymbols(funcsToFree, m_engine.get()); m_unresolvedSymbols.clear(); return true; } }// end namespace cling <commit_msg>Silence warning but keep code - we still need it.<commit_after>//--------------------------------------------------------------------*- C++ -*- // CLING - the C++ LLVM-based InterpreterG :) // author: Axel Naumann <[email protected]> // // This file is dual-licensed: you can choose to license it under the University // of Illinois Open Source License or the GNU Lesser General Public License. See // LICENSE.TXT for details. //------------------------------------------------------------------------------ #include "IncrementalExecutor.h" #include "IncrementalJIT.h" #include "cling/Interpreter/Value.h" #include "cling/Interpreter/Transaction.h" #include "clang/Basic/Diagnostic.h" #include "llvm/IR/Constants.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/Module.h" #include "llvm/PassManager.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/ADT/Triple.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Support/DynamicLibrary.h" #include "llvm/Support/Host.h" #include "llvm/Support/TargetRegistry.h" #include "llvm/Target/TargetMachine.h" using namespace llvm; namespace cling { IncrementalExecutor::IncrementalExecutor(clang::DiagnosticsEngine& diags): m_CurrentAtExitModule(0) #if 0 : m_Diags(diags) #endif { m_AtExitFuncs.reserve(256); m_JIT.reset(new IncrementalJIT(*this, std::move(CreateHostTargetMachine()))); } // Keep in source: ~unique_ptr<ClingJIT> needs ClingJIT IncrementalExecutor::~IncrementalExecutor() {} std::unique_ptr<TargetMachine> IncrementalExecutor::CreateHostTargetMachine() const { // TODO: make this configurable. Triple TheTriple(sys::getProcessTriple()); std::string Error; const Target *TheTarget = TargetRegistry::lookupTarget(TheTriple.getTriple(), Error); if (!TheTarget) { llvm::errs() << "cling::IncrementalExecutor: unable to find target:\n" << Error; } std::string MCPU; std::string FeaturesStr; TargetOptions Options = TargetOptions(); Options.NoFramePointerElim = 1; Options.JITEmitDebugInfo = 1; Reloc::Model RelocModel = Reloc::Default; CodeModel::Model CMModel = CodeModel::JITDefault; CodeGenOpt::Level OptLevel = CodeGenOpt::Default; std::unique_ptr<TargetMachine> TM; TM.reset(TheTarget->createTargetMachine(TheTriple.getTriple(), MCPU, FeaturesStr, Options, RelocModel, CMModel, OptLevel)); return std::move(TM); } void IncrementalExecutor::shuttingDown() { for (size_t I = 0, N = m_AtExitFuncs.size(); I < N; ++I) { const CXAAtExitElement& AEE = m_AtExitFuncs[N - I - 1]; (*AEE.m_Func)(AEE.m_Arg); } } void IncrementalExecutor::AddAtExitFunc(void (*func) (void*), void* arg) { // Register a CXAAtExit function m_AtExitFuncs.push_back(CXAAtExitElement(func, arg, m_CurrentAtExitModule)); } void unresolvedSymbol() { // throw exception? llvm::errs() << "IncrementalExecutor: calling unresolved symbol, " "see previous error message!\n"; } void* IncrementalExecutor::HandleMissingFunction(const std::string& mangled_name) { // Not found in the map, add the symbol in the list of unresolved symbols if (m_unresolvedSymbols.insert(mangled_name).second) { //llvm::errs() << "IncrementalExecutor: use of undefined symbol '" // << mangled_name << "'!\n"; } // Avoid "ISO C++ forbids casting between pointer-to-function and // pointer-to-object": return (void*)reinterpret_cast<size_t>(unresolvedSymbol); } void* IncrementalExecutor::NotifyLazyFunctionCreators(const std::string& mangled_name) { for (std::vector<LazyFunctionCreatorFunc_t>::iterator it = m_lazyFuncCreator.begin(), et = m_lazyFuncCreator.end(); it != et; ++it) { void* ret = (void*)((LazyFunctionCreatorFunc_t)*it)(mangled_name); if (ret) return ret; } return HandleMissingFunction(mangled_name); } #if 0 // FIXME: employ to empty module dependencies *within* the *current* module. static void freeCallersOfUnresolvedSymbols(llvm::SmallVectorImpl<llvm::Function*>& funcsToFree, llvm::ExecutionEngine* engine) { llvm::SmallPtrSet<llvm::Function*, 40> funcsToFreeUnique; for (size_t i = 0; i < funcsToFree.size(); ++i) { llvm::Function* func = funcsToFree[i]; assert(func && "Cannot free NULL function"); if (funcsToFreeUnique.insert(func).second) { for (llvm::Value::use_iterator IU = func->use_begin(), EU = func->use_end(); IU != EU; ++IU) { llvm::Instruction* instUser = llvm::dyn_cast<llvm::Instruction>(*IU); if (!instUser) continue; if (!instUser->getParent()) continue; if (llvm::Function* userFunc = instUser->getParent()->getParent()) funcsToFree.push_back(userFunc); } } } for (llvm::SmallPtrSet<llvm::Function*, 40>::iterator I = funcsToFreeUnique.begin(), E = funcsToFreeUnique.end(); I != E; ++I) { // This should force the JIT to recompile the function. But the stubs stay, // and the JIT reuses the stubs now pointing nowhere, i.e. without updating // the machine code address. Fix the JIT, or hope that MCJIT helps. //engine->freeMachineCodeForFunction(*I); engine->updateGlobalMapping(*I, 0); } } #endif IncrementalExecutor::ExecutionResult IncrementalExecutor::runStaticInitializersOnce(const Transaction& T) { llvm::Module* m = T.getModule(); assert(m && "Module must not be null"); // Set m_CurrentAtExitModule to the Module, unset to 0 once done. struct AtExitModuleSetterRAII { llvm::Module*& m_AEM; AtExitModuleSetterRAII(llvm::Module* M, llvm::Module*& AEM): m_AEM(AEM) { AEM = M; } ~AtExitModuleSetterRAII() { m_AEM = 0; } } DSOHandleSetter(m, m_CurrentAtExitModule); // We don't care whether something was unresolved before. m_unresolvedSymbols.clear(); // check if there is any unresolved symbol in the list if (diagnoseUnresolvedSymbols("static initializers")) return kExeUnresolvedSymbols; llvm::GlobalVariable* GV = m->getGlobalVariable("llvm.global_ctors", true); // Nothing to do is good, too. if (!GV) return kExeSuccess; // Close similarity to // m_engine->runStaticConstructorsDestructors(false) aka // llvm::ExecutionEngine::runStaticConstructorsDestructors() // is intentional; we do an extra pass to check whether the JIT // managed to collect all the symbols needed by the niitializers. // Should be an array of '{ i32, void ()* }' structs. The first value is // the init priority, which we ignore. llvm::ConstantArray *InitList = llvm::dyn_cast<llvm::ConstantArray>(GV->getInitializer()); // We need to delete it here just in case we have recursive inits, otherwise // it will call inits multiple times. GV->eraseFromParent(); if (InitList == 0) return kExeSuccess; SmallVector<Function*, 2> initFuncs; for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) { llvm::ConstantStruct *CS = llvm::dyn_cast<llvm::ConstantStruct>(InitList->getOperand(i)); if (CS == 0) continue; llvm::Constant *FP = CS->getOperand(1); if (FP->isNullValue()) continue; // Found a sentinal value, ignore. // Strip off constant expression casts. if (llvm::ConstantExpr *CE = llvm::dyn_cast<llvm::ConstantExpr>(FP)) if (CE->isCast()) FP = CE->getOperand(0); // Execute the ctor/dtor function! if (llvm::Function *F = llvm::dyn_cast<llvm::Function>(FP)) { executeInit(F->getName()); initFuncs.push_back(F); if (F->getName().startswith("_GLOBAL__sub_I__")) { BasicBlock& BB = F->getEntryBlock(); for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I) if (CallInst* call = dyn_cast<CallInst>(I)) initFuncs.push_back(call->getCalledFunction()); } } } for (SmallVector<Function*,2>::iterator I = initFuncs.begin(), E = initFuncs.end(); I != E; ++I) { // Cleanup also the dangling init functions. They are in the form: // define internal void @_GLOBAL__I_aN() section "..."{ // entry: // call void @__cxx_global_var_init(N-1)() // call void @__cxx_global_var_initM() // ret void // } // // define internal void @__cxx_global_var_init(N-1)() section "..." { // entry: // call void @_ZN7MyClassC1Ev(%struct.MyClass* @n) // ret void // } // Erase __cxx_global_var_init(N-1)() first. (*I)->removeDeadConstantUsers(); (*I)->eraseFromParent(); } return kExeSuccess; } void IncrementalExecutor::runAndRemoveStaticDestructors(Transaction* T) { assert(T && "Must be set"); // Collect all the dtors bound to this transaction. AtExitFunctions boundToT; for (AtExitFunctions::iterator I = m_AtExitFuncs.begin(); I != m_AtExitFuncs.end();) if (I->m_FromM == T->getModule()) { boundToT.push_back(*I); I = m_AtExitFuncs.erase(I); } else ++I; // 'Unload' the cxa_atexit entities. for (AtExitFunctions::reverse_iterator I = boundToT.rbegin(), E = boundToT.rend(); I != E; ++I) { const CXAAtExitElement& AEE = *I; (*AEE.m_Func)(AEE.m_Arg); } } void IncrementalExecutor::installLazyFunctionCreator(LazyFunctionCreatorFunc_t fp) { m_lazyFuncCreator.push_back(fp); } bool IncrementalExecutor::addSymbol(const char* symbolName, void* symbolAddress) { void* actualAddress = llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(symbolName); if (actualAddress) return false; llvm::sys::DynamicLibrary::AddSymbol(symbolName, symbolAddress); return true; } void* IncrementalExecutor::getAddressOfGlobal(llvm::StringRef symbolName, bool* fromJIT /*=0*/) { // Return a symbol's address, and whether it was jitted. void* address = llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(symbolName); // It's not from the JIT if it's in a dylib. if (fromJIT) *fromJIT = !address; if (!address) return (void*)m_JIT->getSymbolAddress(symbolName); return address; } void* IncrementalExecutor::getPointerToGlobalFromJIT(const llvm::GlobalValue& GV) { // Get the function / variable pointer referenced by GV. // We don't care whether something was unresolved before. m_unresolvedSymbols.clear(); void* addr = (void*)m_JIT->getSymbolAddress(GV.getName()); if (diagnoseUnresolvedSymbols(GV.getName(), "symbol")) return 0; return addr; } bool IncrementalExecutor::diagnoseUnresolvedSymbols(llvm::StringRef trigger, llvm::StringRef title) { if (m_unresolvedSymbols.empty()) return false; llvm::SmallVector<llvm::Function*, 128> funcsToFree; for (std::set<std::string>::const_iterator i = m_unresolvedSymbols.begin(), e = m_unresolvedSymbols.end(); i != e; ++i) { #if 0 // FIXME: This causes a lot of test failures, for some reason it causes // the call to HandleMissingFunction to be elided. unsigned diagID = m_Diags.getCustomDiagID(clang::DiagnosticsEngine::Error, "%0 unresolved while jitting %1"); (void)diagID; //m_Diags.Report(diagID) << *i << funcname; // TODO: demangle the names. #endif llvm::errs() << "IncrementalExecutor::executeFunction: symbol '" << *i << "' unresolved while linking "; if (!title.empty()) llvm::errs() << title << "'"; llvm::errs() << trigger; if (!title.empty()) llvm::errs() << "'"; llvm::errs() << "!\n"; //llvm::Function *ff = m_engine->FindFunctionNamed(i->c_str()); // i could also reference a global variable, in which case ff == 0. //if (ff) // funcsToFree.push_back(ff); } //freeCallersOfUnresolvedSymbols(funcsToFree, m_engine.get()); m_unresolvedSymbols.clear(); return true; } }// end namespace cling <|endoftext|>
<commit_before><commit_msg>Fix type printing of array template args Apply patch to interpreter/llvm/src/tools/clang/lib/AST/TemplateBase.cpp as suggested here: https://reviews.llvm.org/D36368<commit_after><|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 "QmitkVolumeVisualization.h" #include "QmitkVolumeVisualizationControls.h" #include "QmitkTransferFunctionWidget.h" #include <qaction.h> #include <qcheckbox.h> #include "icon.xpm" #include "QmitkDataTreeComboBox.h" #include <mitkDataTreeNode.h> #include <mitkProperties.h> #include <mitkRenderingManager.h> QmitkVolumeVisualization::QmitkVolumeVisualization(QObject *parent, const char *name, QmitkStdMultiWidget *mitkStdMultiWidget, mitk::DataTreeIteratorBase* it) : QmitkFunctionality(parent, name, it) , m_MultiWidget(mitkStdMultiWidget) ,m_Controls(NULL) { SetAvailability(true); } QmitkVolumeVisualization::~QmitkVolumeVisualization() {} QWidget * QmitkVolumeVisualization::CreateMainWidget(QWidget*) { return NULL; } QWidget * QmitkVolumeVisualization::CreateControlWidget(QWidget *parent) { if (m_Controls == NULL) { m_Controls = new QmitkVolumeVisualizationControls(parent); } return m_Controls; } void QmitkVolumeVisualization::CreateConnections() { if ( m_Controls ) { connect( (QObject*)(m_Controls->m_TreeNodeSelector), SIGNAL(activated(const mitk::DataTreeFilter::Item*)),(QObject*) this, SLOT(ImageSelected(const mitk::DataTreeFilter::Item*)) ); m_Controls->m_TreeNodeSelector->SetDataTree(this->GetDataTreeIterator()); connect( (QObject*)(m_Controls), SIGNAL(EnableRenderingToggled(bool)),(QObject*) this, SLOT(EnableRendering(bool))); //TF-Auswahl connect( (QObject*)(m_Controls), SIGNAL(Choice(int)),(QObject*) this, SLOT(GetChoice(int))); //Color TF connect( (QObject*)(m_Controls), SIGNAL(StyleChoice(int)),(QObject*) this, SLOT(GetCStyle(int))); //Preset-TF connect( (QObject*)(m_Controls), SIGNAL(PresetTF(int)),(QObject*) this, SLOT(GetPreset(int))); //***Preferences*** //Shading connect( (QObject*)(m_Controls), SIGNAL(EnableShadingToggled(bool, int)),(QObject*) this, SLOT(SetShading(bool, int))); //Clipping plane connect( (QObject*)(m_Controls), SIGNAL(EnableCPToggled(bool)),(QObject*) this, SLOT(EnableClippingPlane(bool))); //Immediate Update connect( (QObject*)(m_Controls), SIGNAL(ImmUpdate(bool)),(QObject*) this, SLOT(ImmediateUpdate(bool))); } } QAction * QmitkVolumeVisualization::CreateAction(QActionGroup *parent) { QAction* action; action = new QAction( tr( "VolumeVisualization" ), QPixmap((const char**)icon_xpm), tr( "VolumeVisualization" ), 0, parent, "VolumeVisualization" ); return action; } void QmitkVolumeVisualization::TreeChanged() { m_Controls->m_TreeNodeSelector->Update(); } void QmitkVolumeVisualization::Activated() { QmitkFunctionality::Activated(); } void QmitkVolumeVisualization::ImageSelected(const mitk::DataTreeFilter::Item* item) { mitk::DataTreeNode* node = const_cast<mitk::DataTreeNode*>(item->GetNode()); bool enabled = false; if (node) { node->GetBoolProperty("volumerendering",enabled); m_Controls->m_TransferFunctionWidget->SetDataTreeNode(node); m_Controls->m_TransferFunctionWidget_2->SetDataTreeNode(node); } m_Controls->m_EnableRenderingCB->setChecked(enabled); } void QmitkVolumeVisualization::EnableRendering(bool state) { std::cout << "EnableRendering:" << state << std::endl; image_ok = false; const mitk::DataTreeFilter::Item* item = m_Controls->m_TreeNodeSelector->GetFilter()->GetSelectedItem(); if (item) { mitk::DataTreeNode* node = const_cast<mitk::DataTreeNode*>(item->GetNode()); if (state && node) { node->SetProperty("volumerendering",new mitk::BoolProperty(true)); mitk::Image* image = dynamic_cast<mitk::Image*>(node->GetData()); if (!image) return; image_ok = true; m_Controls->m_TransferFunctionWidget->SetDataTreeNode(node); m_Controls->m_TransferFunctionWidget_2->SetDataTreeNode(node); } else if (!state && node) { node->SetProperty("volumerendering",new mitk::BoolProperty(false)); } } } void QmitkVolumeVisualization::GetChoice(int number) { if(image_ok) { m_Controls->m_TransferFunctionWidget->ChooseTF(number); m_Controls->m_TransferFunctionWidget_2->ChooseTF(number); } else { std::cout<<"No image selected!\n"; } } void QmitkVolumeVisualization::GetCStyle(int number) { if(image_ok) { m_Controls->m_TransferFunctionWidget->ChooseCS(number); m_Controls->m_TransferFunctionWidget_2->ChooseCS(number); } else { std::cout<<"No image selected!\n"; } } void QmitkVolumeVisualization::GetPreset(int number) { if(image_ok) { m_Controls->m_TransferFunctionWidget->ChooseTF(number); m_Controls->m_TransferFunctionWidget_2->ChooseTF(number); } else { std::cout<<"No image selected!\n"; } } void QmitkVolumeVisualization::SetShading(bool state, int lod) { mitk::RenderingManager::GetInstance()->SetShading(state, lod); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkVolumeVisualization::ImmediateUpdate(bool state) { m_Controls->m_TransferFunctionWidget->ImmediateUpdate(state); } void QmitkVolumeVisualization::EnableClippingPlane(bool state) { mitk::RenderingManager::GetInstance()->SetClippingPlaneStatus(state); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } <commit_msg>FIX: volumerendering didn't work in debug mode + empty data test<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 "QmitkVolumeVisualization.h" #include "QmitkVolumeVisualizationControls.h" #include "QmitkTransferFunctionWidget.h" #include <qaction.h> #include <qcheckbox.h> #include "icon.xpm" #include "QmitkDataTreeComboBox.h" #include <mitkDataTreeNode.h> #include <mitkProperties.h> #include <mitkRenderingManager.h> QmitkVolumeVisualization::QmitkVolumeVisualization(QObject *parent, const char *name, QmitkStdMultiWidget *mitkStdMultiWidget, mitk::DataTreeIteratorBase* it) : QmitkFunctionality(parent, name, it) , m_MultiWidget(mitkStdMultiWidget) ,m_Controls(NULL) { SetAvailability(true); } QmitkVolumeVisualization::~QmitkVolumeVisualization() {} QWidget * QmitkVolumeVisualization::CreateMainWidget(QWidget*) { return NULL; } QWidget * QmitkVolumeVisualization::CreateControlWidget(QWidget *parent) { if (m_Controls == NULL) { m_Controls = new QmitkVolumeVisualizationControls(parent); } return m_Controls; } void QmitkVolumeVisualization::CreateConnections() { if ( m_Controls ) { connect( (QObject*)(m_Controls->m_TreeNodeSelector), SIGNAL(activated(const mitk::DataTreeFilter::Item*)),(QObject*) this, SLOT(ImageSelected(const mitk::DataTreeFilter::Item*)) ); m_Controls->m_TreeNodeSelector->SetDataTree(this->GetDataTreeIterator()); connect( (QObject*)(m_Controls), SIGNAL(EnableRenderingToggled(bool)),(QObject*) this, SLOT(EnableRendering(bool))); //TF-Auswahl connect( (QObject*)(m_Controls), SIGNAL(Choice(int)),(QObject*) this, SLOT(GetChoice(int))); //Color TF connect( (QObject*)(m_Controls), SIGNAL(StyleChoice(int)),(QObject*) this, SLOT(GetCStyle(int))); //Preset-TF connect( (QObject*)(m_Controls), SIGNAL(PresetTF(int)),(QObject*) this, SLOT(GetPreset(int))); //***Preferences*** //Shading connect( (QObject*)(m_Controls), SIGNAL(EnableShadingToggled(bool, int)),(QObject*) this, SLOT(SetShading(bool, int))); //Clipping plane connect( (QObject*)(m_Controls), SIGNAL(EnableCPToggled(bool)),(QObject*) this, SLOT(EnableClippingPlane(bool))); //Immediate Update connect( (QObject*)(m_Controls), SIGNAL(ImmUpdate(bool)),(QObject*) this, SLOT(ImmediateUpdate(bool))); } } QAction * QmitkVolumeVisualization::CreateAction(QActionGroup *parent) { QAction* action; action = new QAction( tr( "VolumeVisualization" ), QPixmap((const char**)icon_xpm), tr( "VolumeVisualization" ), 0, parent, "VolumeVisualization" ); return action; } void QmitkVolumeVisualization::TreeChanged() { m_Controls->m_TreeNodeSelector->Update(); } void QmitkVolumeVisualization::Activated() { QmitkFunctionality::Activated(); } void QmitkVolumeVisualization::ImageSelected(const mitk::DataTreeFilter::Item* item) { mitk::DataTreeNode* node = const_cast<mitk::DataTreeNode*>(item->GetNode()); bool enabled = false; if (node) { node->GetBoolProperty("volumerendering",enabled); if(node->GetProperty("TransferFunction")) { m_Controls->m_TransferFunctionWidget->SetDataTreeNode(node); m_Controls->m_TransferFunctionWidget_2->SetDataTreeNode(node); } } m_Controls->m_EnableRenderingCB->setChecked(enabled); } void QmitkVolumeVisualization::EnableRendering(bool state) { std::cout << "EnableRendering:" << state << std::endl; image_ok = false; const mitk::DataTreeFilter::Item* item = m_Controls->m_TreeNodeSelector->GetFilter()->GetSelectedItem(); if (item) { mitk::DataTreeNode* node = const_cast<mitk::DataTreeNode*>(item->GetNode()); if (state && node) { node->SetProperty("volumerendering",new mitk::BoolProperty(true)); mitk::Image* image = dynamic_cast<mitk::Image*>(node->GetData()); if (!image) return; image_ok = true; m_Controls->m_TransferFunctionWidget->SetDataTreeNode(node); m_Controls->m_TransferFunctionWidget_2->SetDataTreeNode(node); } else if (!state && node) { node->SetProperty("volumerendering",new mitk::BoolProperty(false)); } } } void QmitkVolumeVisualization::GetChoice(int number) { if(image_ok) { m_Controls->m_TransferFunctionWidget->ChooseTF(number); m_Controls->m_TransferFunctionWidget_2->ChooseTF(number); } else { std::cout<<"No image selected!\n"; } } void QmitkVolumeVisualization::GetCStyle(int number) { if(image_ok) { m_Controls->m_TransferFunctionWidget->ChooseCS(number); m_Controls->m_TransferFunctionWidget_2->ChooseCS(number); } else { std::cout<<"No image selected!\n"; } } void QmitkVolumeVisualization::GetPreset(int number) { if(image_ok) { m_Controls->m_TransferFunctionWidget->ChooseTF(number); m_Controls->m_TransferFunctionWidget_2->ChooseTF(number); } else { std::cout<<"No image selected!\n"; } } void QmitkVolumeVisualization::SetShading(bool state, int lod) { mitk::RenderingManager::GetInstance()->SetShading(state, lod); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkVolumeVisualization::ImmediateUpdate(bool state) { m_Controls->m_TransferFunctionWidget->ImmediateUpdate(state); } void QmitkVolumeVisualization::EnableClippingPlane(bool state) { mitk::RenderingManager::GetInstance()->SetClippingPlaneStatus(state); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } <|endoftext|>
<commit_before>/** * @file SyncedWait.cpp * @brief SyncedWait class implementation. * @author zer0 * @date 2019-09-11 */ #include <libtbag/time/SyncedWait.hpp> #include <libtbag/time/Time.hpp> #include <cassert> #include <chrono> // ------------------- NAMESPACE_LIBTBAG_OPEN // ------------------- namespace time { SyncedWait::SyncedWait() : _state(State::S_READY) { // EMPTY. } SyncedWait::~SyncedWait() { try { done(); } catch (...) { COMMENT("Remove the exception") } } void SyncedWait::__set_running() { Guard const G(_mutex); _state = State::S_RUNNING; } SyncedWait::State SyncedWait::state() const { Guard const G(_mutex); return _state; } char const * SyncedWait::getStateName(State s) TBAG_NOEXCEPT { // clang-format off switch (s) { case State::S_INITIALIZING: return STATE_INITIALIZING; case State::S_RUNNING: return STATE_RUNNING; case State::S_DONE: return STATE_DONE; case State::S_ERROR: return STATE_ERROR; default: return STATE_READY; } // clang-format on } SyncedWait::State SyncedWait::getState(std::string const & s) TBAG_NOEXCEPT { if (s == STATE_INITIALIZING) { return State::S_INITIALIZING; } else if (s == STATE_RUNNING) { return State::S_RUNNING; } else if (s == STATE_DONE) { return State::S_DONE; } else if (s == STATE_ERROR) { return State::S_ERROR; } assert(s == STATE_READY); return State::S_READY; } Err SyncedWait::run(Callback const & cb, unsigned timeout_ms, unsigned tick_ms) { _mutex.lock(); bool illegal_state; if (_state != State::S_READY) { illegal_state = true; } else { illegal_state = false; _state = State::S_INITIALIZING; _future = std::async(std::launch::async, [&, cb]() -> Err { RunningSignal signal(*this); auto const code = cb ? cb(signal) : E_ILLARGS; Guard const G(_mutex); _state = isSuccess(code) ? State::S_DONE : State::S_ERROR; return code; }); } _mutex.unlock(); if (illegal_state) { return E_ILLSTATE; } using namespace std::chrono; auto const begin = system_clock::now(); auto const timeout = milliseconds(timeout_ms); auto const tick = milliseconds(tick_ms); auto const result = syncedWait(begin, timeout, tick, [&]() -> bool { Guard const G(_mutex); return _state != State::S_INITIALIZING; }); return result ? E_SUCCESS : E_TIMEOUT; } Err SyncedWait::done() { _mutex.lock(); bool illegal_state; std::future<Err> future; if (_state == State::S_READY) { illegal_state = true; } else { illegal_state = false; future.swap(_future); assert(!_future.valid()); } _mutex.unlock(); if (illegal_state) { return E_ILLSTATE; } assert(future.valid()); auto const code = future.get(); _mutex.lock(); assert(_state == State::S_DONE || _state == State::S_ERROR); assert(!_future.valid()); _state = State::S_READY; _mutex.unlock(); return code; } std::string SyncedWait::toString() const { return getStateName(state()); } } // namespace time // -------------------- NAMESPACE_LIBTBAG_CLOSE // -------------------- <commit_msg>Create the _DISABLE_FUTURE_SWAP macro in the SyncedWait package.<commit_after>/** * @file SyncedWait.cpp * @brief SyncedWait class implementation. * @author zer0 * @date 2019-09-11 */ #include <libtbag/time/SyncedWait.hpp> #include <libtbag/time/Time.hpp> #include <cassert> #include <chrono> #define _DISABLE_FUTURE_SWAP // ------------------- NAMESPACE_LIBTBAG_OPEN // ------------------- namespace time { SyncedWait::SyncedWait() : _state(State::S_READY) { // EMPTY. } SyncedWait::~SyncedWait() { try { done(); } catch (...) { COMMENT("Remove the exception") } } void SyncedWait::__set_running() { Guard const G(_mutex); _state = State::S_RUNNING; } SyncedWait::State SyncedWait::state() const { Guard const G(_mutex); return _state; } char const * SyncedWait::getStateName(State s) TBAG_NOEXCEPT { // clang-format off switch (s) { case State::S_INITIALIZING: return STATE_INITIALIZING; case State::S_RUNNING: return STATE_RUNNING; case State::S_DONE: return STATE_DONE; case State::S_ERROR: return STATE_ERROR; default: return STATE_READY; } // clang-format on } SyncedWait::State SyncedWait::getState(std::string const & s) TBAG_NOEXCEPT { if (s == STATE_INITIALIZING) { return State::S_INITIALIZING; } else if (s == STATE_RUNNING) { return State::S_RUNNING; } else if (s == STATE_DONE) { return State::S_DONE; } else if (s == STATE_ERROR) { return State::S_ERROR; } assert(s == STATE_READY); return State::S_READY; } Err SyncedWait::run(Callback const & cb, unsigned timeout_ms, unsigned tick_ms) { _mutex.lock(); bool illegal_state; if (_state != State::S_READY) { illegal_state = true; } else { illegal_state = false; _state = State::S_INITIALIZING; _future = std::async(std::launch::async, [&, cb]() -> Err { RunningSignal signal(*this); auto const code = cb ? cb(signal) : E_ILLARGS; Guard const G(_mutex); _state = isSuccess(code) ? State::S_DONE : State::S_ERROR; return code; }); } _mutex.unlock(); if (illegal_state) { return E_ILLSTATE; } using namespace std::chrono; auto const begin = system_clock::now(); auto const timeout = milliseconds(timeout_ms); auto const tick = milliseconds(tick_ms); auto const result = syncedWait(begin, timeout, tick, [&]() -> bool { Guard const G(_mutex); return _state != State::S_INITIALIZING; }); return result ? E_SUCCESS : E_TIMEOUT; } Err SyncedWait::done() { _mutex.lock(); bool illegal_state; std::future<Err> future; if (_state == State::S_READY) { illegal_state = true; } else { illegal_state = false; // Don't use the future.swap() method in MSVC. // error C2039: 'swap': is not a member of 'std::future' #if defined(_DISABLE_FUTURE_SWAP) future = std::move(_future); _future = {}; #else future.swap(_future); #endif assert(!_future.valid()); } _mutex.unlock(); if (illegal_state) { return E_ILLSTATE; } assert(future.valid()); auto const code = future.get(); _mutex.lock(); assert(_state == State::S_DONE || _state == State::S_ERROR); assert(!_future.valid()); _state = State::S_READY; _mutex.unlock(); return code; } std::string SyncedWait::toString() const { return getStateName(state()); } } // namespace time // -------------------- NAMESPACE_LIBTBAG_CLOSE // -------------------- <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the plugins of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QtDeclarative/qdeclarativeextensionplugin.h> #include <QtDeclarative/qdeclarative.h> #include <QtMultimedia/private/qsoundeffect_p.h> #include "qdeclarativevideo_p.h" #include "qdeclarativeaudio_p.h" QT_BEGIN_NAMESPACE QML_DECLARE_TYPE(QSoundEffect) class QMultimediaDeclarativeModule : public QDeclarativeExtensionPlugin { Q_OBJECT public: virtual void registerTypes(const char *uri) { Q_ASSERT(QLatin1String(uri) == QLatin1String("Qt.multimedia")); qmlRegisterType<QSoundEffect>(uri, 4, 7, "SoundEffect"); qmlRegisterType<QDeclarativeAudio>(uri, 4, 7, "Audio"); qmlRegisterType<QDeclarativeVideo>(uri, 4, 7, "Video"); } }; QT_END_NAMESPACE #include "multimedia.moc" Q_EXPORT_PLUGIN2(qmultimediadeclarativemodule, QT_PREPEND_NAMESPACE(QMultimediaDeclarativeModule)); <commit_msg>Fix namespace qml decleration.<commit_after>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the plugins of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QtDeclarative/qdeclarativeextensionplugin.h> #include <QtDeclarative/qdeclarative.h> #include <QtMultimedia/private/qsoundeffect_p.h> #include "qdeclarativevideo_p.h" #include "qdeclarativeaudio_p.h" QML_DECLARE_TYPE(QSoundEffect) QT_BEGIN_NAMESPACE class QMultimediaDeclarativeModule : public QDeclarativeExtensionPlugin { Q_OBJECT public: virtual void registerTypes(const char *uri) { Q_ASSERT(QLatin1String(uri) == QLatin1String("Qt.multimedia")); qmlRegisterType<QSoundEffect>(uri, 4, 7, "SoundEffect"); qmlRegisterType<QDeclarativeAudio>(uri, 4, 7, "Audio"); qmlRegisterType<QDeclarativeVideo>(uri, 4, 7, "Video"); } }; QT_END_NAMESPACE #include "multimedia.moc" Q_EXPORT_PLUGIN2(qmultimediadeclarativemodule, QT_PREPEND_NAMESPACE(QMultimediaDeclarativeModule)); <|endoftext|>
<commit_before>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation ([email protected]) ** ** ** GNU Lesser General Public License Usage ** ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this file. ** Please review the following information to ensure the GNU Lesser General ** Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** Other Usage ** ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** **************************************************************************/ #include "toolbox.h" #include "utils/styledbar.h" #include "utils/crumblepath.h" #include <QToolBar> #include <QHBoxLayout> #include <QPainter> #include <QtDebug> #include <QFile> #include <QFrame> #include <QVariant> namespace QmlDesigner { ToolBox::ToolBox(QWidget *parentWidget) : Utils::StyledBar(parentWidget), m_leftToolBar(new QToolBar("LeftSidebar", this)), m_rightToolBar(new QToolBar("RightSidebar", this)) { setSingleRow(false); QFrame *frame = new QFrame(this); m_crumblePath = new Utils::CrumblePath(frame); frame->setStyleSheet("background-color: #4e4e4e;"); frame->setFrameShape(QFrame::NoFrame); QHBoxLayout *layout = new QHBoxLayout(frame); layout->setMargin(0); layout->setSpacing(0); frame->setLayout(layout); layout->addWidget(m_crumblePath); frame->setProperty("panelwidget", true); frame->setProperty("panelwidget_singlerow", false); QVBoxLayout *verticalLayout = new QVBoxLayout(this); verticalLayout->setMargin(0); verticalLayout->setSpacing(0); QHBoxLayout *horizontalLayout = new QHBoxLayout(); verticalLayout->addLayout(horizontalLayout); verticalLayout->addWidget(frame); horizontalLayout->setMargin(0); horizontalLayout->setSpacing(0); m_leftToolBar->setFloatable(true); m_leftToolBar->setMovable(true); m_leftToolBar->setOrientation(Qt::Horizontal); m_leftToolBar->setIconSize(QSize(24, 24)); QToolBar *stretchToolbar = new QToolBar(this); setSingleRow(false); m_leftToolBar->setProperty("panelwidget", true); m_leftToolBar->setProperty("panelwidget_singlerow", false); m_rightToolBar->setProperty("panelwidget", true); m_rightToolBar->setProperty("panelwidget_singlerow", false); stretchToolbar->setProperty("panelwidget", true); stretchToolbar->setProperty("panelwidget_singlerow", false); stretchToolbar->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding); m_rightToolBar->setOrientation(Qt::Horizontal); m_rightToolBar->setIconSize(QSize(24, 24)); horizontalLayout->addWidget(m_leftToolBar); horizontalLayout->addWidget(stretchToolbar); horizontalLayout->addWidget(m_rightToolBar); } void ToolBox::setLeftSideActions(const QList<QAction*> &actions) { m_leftToolBar->clear(); m_leftToolBar->addActions(actions); resize(sizeHint()); } void ToolBox::setRightSideActions(const QList<QAction*> &actions) { m_rightToolBar->clear(); m_rightToolBar->addActions(actions); resize(sizeHint()); } void ToolBox::addLeftSideAction(QAction *action) { m_leftToolBar->addAction(action); } void ToolBox::addRightSideAction(QAction *action) { m_rightToolBar->addAction(action); } QList<QAction*> ToolBox::actions() const { return QList<QAction*>() << m_leftToolBar->actions() << m_rightToolBar->actions(); } Utils::CrumblePath *ToolBox::crumblePath() const { return m_crumblePath; } } // namespace QmlDesigner <commit_msg>QmlDesigner.formEditor: layoutfix for full screen mode<commit_after>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation ([email protected]) ** ** ** GNU Lesser General Public License Usage ** ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this file. ** Please review the following information to ensure the GNU Lesser General ** Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** Other Usage ** ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** **************************************************************************/ #include "toolbox.h" #include "utils/styledbar.h" #include "utils/crumblepath.h" #include <QToolBar> #include <QHBoxLayout> #include <QPainter> #include <QtDebug> #include <QFile> #include <QFrame> #include <QVariant> namespace QmlDesigner { ToolBox::ToolBox(QWidget *parentWidget) : Utils::StyledBar(parentWidget), m_leftToolBar(new QToolBar("LeftSidebar", this)), m_rightToolBar(new QToolBar("RightSidebar", this)) { setMaximumHeight(44); setSingleRow(false); QFrame *frame = new QFrame(this); m_crumblePath = new Utils::CrumblePath(frame); frame->setStyleSheet("background-color: #4e4e4e;"); frame->setFrameShape(QFrame::NoFrame); QHBoxLayout *layout = new QHBoxLayout(frame); layout->setMargin(0); layout->setSpacing(0); frame->setLayout(layout); layout->addWidget(m_crumblePath); frame->setProperty("panelwidget", true); frame->setProperty("panelwidget_singlerow", false); QVBoxLayout *verticalLayout = new QVBoxLayout(this); verticalLayout->setMargin(0); verticalLayout->setSpacing(0); QHBoxLayout *horizontalLayout = new QHBoxLayout(); verticalLayout->addLayout(horizontalLayout); verticalLayout->addWidget(frame); horizontalLayout->setMargin(0); horizontalLayout->setSpacing(0); m_leftToolBar->setFloatable(true); m_leftToolBar->setMovable(true); m_leftToolBar->setOrientation(Qt::Horizontal); m_leftToolBar->setIconSize(QSize(24, 24)); QToolBar *stretchToolbar = new QToolBar(this); setSingleRow(false); m_leftToolBar->setProperty("panelwidget", true); m_leftToolBar->setProperty("panelwidget_singlerow", false); m_rightToolBar->setProperty("panelwidget", true); m_rightToolBar->setProperty("panelwidget_singlerow", false); stretchToolbar->setProperty("panelwidget", true); stretchToolbar->setProperty("panelwidget_singlerow", false); stretchToolbar->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding); m_rightToolBar->setOrientation(Qt::Horizontal); m_rightToolBar->setIconSize(QSize(24, 24)); horizontalLayout->addWidget(m_leftToolBar); horizontalLayout->addWidget(stretchToolbar); horizontalLayout->addWidget(m_rightToolBar); } void ToolBox::setLeftSideActions(const QList<QAction*> &actions) { m_leftToolBar->clear(); m_leftToolBar->addActions(actions); resize(sizeHint()); } void ToolBox::setRightSideActions(const QList<QAction*> &actions) { m_rightToolBar->clear(); m_rightToolBar->addActions(actions); resize(sizeHint()); } void ToolBox::addLeftSideAction(QAction *action) { m_leftToolBar->addAction(action); } void ToolBox::addRightSideAction(QAction *action) { m_rightToolBar->addAction(action); } QList<QAction*> ToolBox::actions() const { return QList<QAction*>() << m_leftToolBar->actions() << m_rightToolBar->actions(); } Utils::CrumblePath *ToolBox::crumblePath() const { return m_crumblePath; } } // namespace QmlDesigner <|endoftext|>
<commit_before>#include "config.h" #include <stdint.h> #include <stdlib.h> #include <sys/types.h> #ifdef RBX_WINDOWS #include <winsock2.h> #else #include <sys/socket.h> #include <sys/un.h> #include <netinet/in.h> #include <netdb.h> #endif #include <sys/stat.h> #include <errno.h> #include <time.h> #include <math.h> #include "windows_compat.h" #include "ffi_util.hpp" extern "C" { extern char** environ; int ffi_errno() { return errno; } char** ffi_environ() { return environ; } void ffi_set_errno(int n) { errno = n; } uintptr_t ffi_address(void *ptr) { return (uintptr_t)ptr; } int ffi_write_int(int *ptr, int val) { *ptr = val; return val; } int ffi_read_int(int *ptr) { return *ptr; } long ffi_write_long(long *ptr, long val) { *ptr = val; return val; } long ffi_read_long(long *ptr) { return *ptr; } double ffi_write_float(double *ptr, double val) { *ptr = val; return val; } double ffi_read_float(double *ptr) { return *ptr; } char *ffi_read_string(char *ptr) { return ptr; } void *ffi_read_pointer(void **ptr) { return *ptr; } void *ffi_add_ptr(char *ptr, int offset) { return (void*)(ptr + offset); } int ffi_type_size(int type) { switch(type) { case RBX_FFI_TYPE_CHAR: case RBX_FFI_TYPE_UCHAR: case RBX_FFI_TYPE_BOOL: return sizeof(char); case RBX_FFI_TYPE_SHORT: case RBX_FFI_TYPE_USHORT: return sizeof(short); case RBX_FFI_TYPE_INT: case RBX_FFI_TYPE_UINT: return sizeof(int); case RBX_FFI_TYPE_LONG: case RBX_FFI_TYPE_ULONG: return sizeof(long); case RBX_FFI_TYPE_LONG_LONG: case RBX_FFI_TYPE_ULONG_LONG: return sizeof(long long); case RBX_FFI_TYPE_FLOAT: return sizeof(float); case RBX_FFI_TYPE_DOUBLE: return sizeof(double); case RBX_FFI_TYPE_PTR: case RBX_FFI_TYPE_STRING: case RBX_FFI_TYPE_STRPTR: case RBX_FFI_TYPE_CALLBACK: case RBX_FFI_TYPE_ENUM: return sizeof(void*); default: return -1; } } int ffi_cb_test(int (*thing)(int)) { return (*thing)(42); } unsigned int ffi_cast(unsigned int val) { return val; } #ifndef major #define major(x) x #endif #ifndef minor #define minor(x) 0 #endif long ffi_major(dev_t n) { return major(n); } long ffi_minor(dev_t n) { return minor(n); } int ffi_signbit(double x) { return signbit(x); } } <commit_msg>Cleanup unused FFI helper functions<commit_after>#include "config.h" #include <stdint.h> #include <stdlib.h> #include <sys/types.h> #ifdef RBX_WINDOWS #include <winsock2.h> #else #include <sys/socket.h> #include <sys/un.h> #include <netinet/in.h> #include <netdb.h> #endif #include <sys/stat.h> #include <errno.h> #include <time.h> #include <math.h> #include "windows_compat.h" #include "ffi_util.hpp" extern "C" { extern char** environ; int ffi_errno() { return errno; } char** ffi_environ() { return environ; } void ffi_set_errno(int n) { errno = n; } #ifndef major #define major(x) x #endif #ifndef minor #define minor(x) 0 #endif long ffi_major(dev_t n) { return major(n); } long ffi_minor(dev_t n) { return minor(n); } int ffi_signbit(double x) { return signbit(x); } } <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c+mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko, Jean-Francois Doyon * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ //$Id$ // boost #include <boost/python.hpp> // mapnik #include <mapnik/stroke.hpp> #include "mapnik_enumeration.hpp" using namespace mapnik; namespace { using namespace boost::python; list get_dashes_list(const stroke& stroke) { list l; if (stroke.has_dash()) { mapnik::dash_array const& dash = stroke.get_dash_array(); mapnik::dash_array::const_iterator iter = dash.begin(); mapnik::dash_array::const_iterator end = dash.end(); for (; iter != end; ++iter) { l.append(make_tuple(iter->first, iter->second)); } } return l; } } struct stroke_pickle_suite : boost::python::pickle_suite { static boost::python::tuple getinitargs(const stroke& s) { return boost::python::make_tuple(s.get_color(),s.get_width()); } static boost::python::tuple getstate(const stroke& s) { boost::python::list dashes = get_dashes_list(s); return boost::python::make_tuple(s.get_opacity(),dashes,s.get_line_cap(),s.get_line_join()); } static void setstate (stroke& s, boost::python::tuple state) { using namespace boost::python; if (len(state) != 4) { PyErr_SetObject(PyExc_ValueError, ("expected 4-item tuple in call to __setstate__; got %s" % state).ptr() ); throw_error_already_set(); } s.set_opacity(extract<float>(state[0])); if (state[1]) { list dashes = extract<list>(state[1]); for(boost::python::ssize_t i=0; i<len(dashes); i++) { double ds1 = extract<double>(dashes[i][0]); double ds2 = extract<double>(dashes[i][1]); s.add_dash(ds1,ds2); } } s.set_line_cap(extract<line_cap_e>(state[2])); s.set_line_join(extract<line_join_e>(state[3])); } }; void export_stroke () { using namespace boost::python; enumeration_<line_cap_e>("line_cap", "The possible values for a line cap used when drawing\n" "with a stroke.\n") .value("BUTT_CAP",BUTT_CAP) .value("SQUARE_CAP",SQUARE_CAP) .value("ROUND_CAP",ROUND_CAP) ; enumeration_<line_join_e>("line_join", "The possible values for the line joining mode\n" "when drawing with a stroke.\n") .value("MITER_JOIN",MITER_JOIN) .value("MITER_REVERT_JOIN",MITER_REVERT_JOIN) .value("ROUND_JOIN",ROUND_JOIN) .value("BEVEL_JOIN",BEVEL_JOIN) ; class_<stroke>("Stroke",init<>( "Creates a new default black stroke with the width of 1.\n")) .def(init<color,float>( (arg("color"),arg("width")), "Creates a new stroke object with a specified color and width.\n") ) .def_pickle(stroke_pickle_suite()) .add_property("color",make_function (&stroke::get_color,return_value_policy<copy_const_reference>()), &stroke::set_color, "Gets or sets the stroke color.\n" "Returns a new Color object on retrieval.\n") .add_property("width", &stroke::get_width, &stroke::set_width, "Gets or sets the stroke width in pixels.\n") .add_property("opacity", &stroke::get_opacity, &stroke::set_opacity, "Gets or sets the opacity of this stroke.\n" "The value is a float between 0 and 1.\n") .add_property("line_cap", &stroke::get_line_cap, &stroke::set_line_cap, "Gets or sets the line cap of this stroke.\n") .add_property("line_join", &stroke::get_line_join, &stroke::set_line_join, "Returns the line join mode of this stroke.\n") // todo consider providing a single get/set property .def("add_dash",&stroke::add_dash, (arg("length"),arg("gap")), "Adds a dash segment to the dash patterns of this stroke.\n") .def("get_dashes", get_dashes_list, "Returns the list of dash segments for this stroke.\n") ; } <commit_msg>+ reflect dash_offset as property in python<commit_after>/***************************************************************************** * * This file is part of Mapnik (c+mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko, Jean-Francois Doyon * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ //$Id$ // boost #include <boost/python.hpp> // mapnik #include <mapnik/stroke.hpp> #include "mapnik_enumeration.hpp" using namespace mapnik; namespace { using namespace boost::python; list get_dashes_list(const stroke& stroke) { list l; if (stroke.has_dash()) { mapnik::dash_array const& dash = stroke.get_dash_array(); mapnik::dash_array::const_iterator iter = dash.begin(); mapnik::dash_array::const_iterator end = dash.end(); for (; iter != end; ++iter) { l.append(make_tuple(iter->first, iter->second)); } } return l; } } struct stroke_pickle_suite : boost::python::pickle_suite { static boost::python::tuple getinitargs(const stroke& s) { return boost::python::make_tuple(s.get_color(),s.get_width()); } static boost::python::tuple getstate(const stroke& s) { boost::python::list dashes = get_dashes_list(s); return boost::python::make_tuple(s.get_opacity(),dashes,s.get_line_cap(),s.get_line_join()); } static void setstate (stroke& s, boost::python::tuple state) { using namespace boost::python; if (len(state) != 4) { PyErr_SetObject(PyExc_ValueError, ("expected 4-item tuple in call to __setstate__; got %s" % state).ptr() ); throw_error_already_set(); } s.set_opacity(extract<float>(state[0])); if (state[1]) { list dashes = extract<list>(state[1]); for(boost::python::ssize_t i=0; i<len(dashes); i++) { double ds1 = extract<double>(dashes[i][0]); double ds2 = extract<double>(dashes[i][1]); s.add_dash(ds1,ds2); } } s.set_line_cap(extract<line_cap_e>(state[2])); s.set_line_join(extract<line_join_e>(state[3])); } }; void export_stroke () { using namespace boost::python; enumeration_<line_cap_e>("line_cap", "The possible values for a line cap used when drawing\n" "with a stroke.\n") .value("BUTT_CAP",BUTT_CAP) .value("SQUARE_CAP",SQUARE_CAP) .value("ROUND_CAP",ROUND_CAP) ; enumeration_<line_join_e>("line_join", "The possible values for the line joining mode\n" "when drawing with a stroke.\n") .value("MITER_JOIN",MITER_JOIN) .value("MITER_REVERT_JOIN",MITER_REVERT_JOIN) .value("ROUND_JOIN",ROUND_JOIN) .value("BEVEL_JOIN",BEVEL_JOIN) ; class_<stroke>("Stroke",init<>( "Creates a new default black stroke with the width of 1.\n")) .def(init<color,float>( (arg("color"),arg("width")), "Creates a new stroke object with a specified color and width.\n") ) .def_pickle(stroke_pickle_suite()) .add_property("color",make_function (&stroke::get_color,return_value_policy<copy_const_reference>()), &stroke::set_color, "Gets or sets the stroke color.\n" "Returns a new Color object on retrieval.\n") .add_property("width", &stroke::get_width, &stroke::set_width, "Gets or sets the stroke width in pixels.\n") .add_property("opacity", &stroke::get_opacity, &stroke::set_opacity, "Gets or sets the opacity of this stroke.\n" "The value is a float between 0 and 1.\n") .add_property("line_cap", &stroke::get_line_cap, &stroke::set_line_cap, "Gets or sets the line cap of this stroke.\n") .add_property("line_join", &stroke::get_line_join, &stroke::set_line_join, "Returns the line join mode of this stroke.\n") // todo consider providing a single get/set property .def("add_dash",&stroke::add_dash, (arg("length"),arg("gap")), "Adds a dash segment to the dash patterns of this stroke.\n") .def("get_dashes", get_dashes_list, "Returns the list of dash segments for this stroke.\n") .add_property("dash_offset", &stroke::dash_offset, &stroke::set_dash_offset, "Gets or sets dash offset of this stroke.\n") ; } <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c+mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko, Jean-Francois Doyon * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ //$Id$ // boost #include <boost/python.hpp> // mapnik #include <mapnik/stroke.hpp> #include "mapnik_enumeration.hpp" using namespace mapnik; namespace { using namespace boost::python; list get_dashes_list(const stroke& stroke) { list l; if (stroke.has_dash()) { mapnik::dash_array const& dash = stroke.get_dash_array(); mapnik::dash_array::const_iterator iter = dash.begin(); mapnik::dash_array::const_iterator end = dash.end(); for (; iter != end; ++iter) { l.append(make_tuple(iter->first, iter->second)); } } return l; } } struct stroke_pickle_suite : boost::python::pickle_suite { static boost::python::tuple getinitargs(const stroke& s) { return boost::python::make_tuple(s.get_color(),s.get_width()); } static boost::python::tuple getstate(const stroke& s) { boost::python::list dashes = get_dashes_list(s); return boost::python::make_tuple(s.get_opacity(),dashes,s.get_line_cap(),s.get_line_join()); } static void setstate (stroke& s, boost::python::tuple state) { using namespace boost::python; if (len(state) != 4) { PyErr_SetObject(PyExc_ValueError, ("expected 4-item tuple in call to __setstate__; got %s" % state).ptr() ); throw_error_already_set(); } s.set_opacity(extract<float>(state[0])); if (state[1]) { list dashes = extract<list>(state[1]); for(boost::python::ssize_t i=0; i<len(dashes); i++) { double ds1 = extract<double>(dashes[i][0]); double ds2 = extract<double>(dashes[i][1]); s.add_dash(ds1,ds2); } } s.set_line_cap(extract<line_cap_e>(state[2])); s.set_line_join(extract<line_join_e>(state[3])); } }; void export_stroke () { using namespace boost::python; enumeration_<line_cap_e>("line_cap", "The possible values for a line cap used when drawing\n" "with a stroke.\n") .value("BUTT_CAP",BUTT_CAP) .value("SQUARE_CAP",SQUARE_CAP) .value("ROUND_CAP",ROUND_CAP) ; enumeration_<line_join_e>("line_join", "The possible values for the line joining mode\n" "when drawing with a stroke.\n") .value("MITER_JOIN",MITER_JOIN) .value("MITER_REVERT_JOIN",MITER_REVERT_JOIN) .value("ROUND_JOIN",ROUND_JOIN) .value("BEVEL_JOIN",BEVEL_JOIN) ; class_<stroke>("Stroke",init<>( "Creates a new default black stroke with the width of 1.\n")) .def(init<color,float>( (arg("color"),arg("width")), "Creates a new stroke object with a specified color and width.\n") ) .def_pickle(stroke_pickle_suite()) .add_property("color",make_function (&stroke::get_color,return_value_policy<copy_const_reference>()), &stroke::set_color, "Gets or sets the stroke color.\n" "Returns a new Color object on retrieval.\n") .add_property("width", &stroke::get_width, &stroke::set_width, "Gets or sets the stroke width in pixels.\n") .add_property("opacity", &stroke::get_opacity, &stroke::set_opacity, "Gets or sets the opacity of this stroke.\n" "The value is a float between 0 and 1.\n") .add_property("line_cap", &stroke::get_line_cap, &stroke::set_line_cap, "Gets or sets the line cap of this stroke.\n") .add_property("line_join", &stroke::get_line_join, &stroke::set_line_join, "Returns the line join mode of this stroke.\n") // todo consider providing a single get/set property .def("add_dash",&stroke::add_dash, (arg("length"),arg("gap")), "Adds a dash segment to the dash patterns of this stroke.\n") .def("get_dashes", get_dashes_list, "Returns the list of dash segments for this stroke.\n") ; } <commit_msg>+ reflect dash_offset as property in python<commit_after>/***************************************************************************** * * This file is part of Mapnik (c+mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko, Jean-Francois Doyon * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ //$Id$ // boost #include <boost/python.hpp> // mapnik #include <mapnik/stroke.hpp> #include "mapnik_enumeration.hpp" using namespace mapnik; namespace { using namespace boost::python; list get_dashes_list(const stroke& stroke) { list l; if (stroke.has_dash()) { mapnik::dash_array const& dash = stroke.get_dash_array(); mapnik::dash_array::const_iterator iter = dash.begin(); mapnik::dash_array::const_iterator end = dash.end(); for (; iter != end; ++iter) { l.append(make_tuple(iter->first, iter->second)); } } return l; } } struct stroke_pickle_suite : boost::python::pickle_suite { static boost::python::tuple getinitargs(const stroke& s) { return boost::python::make_tuple(s.get_color(),s.get_width()); } static boost::python::tuple getstate(const stroke& s) { boost::python::list dashes = get_dashes_list(s); return boost::python::make_tuple(s.get_opacity(),dashes,s.get_line_cap(),s.get_line_join()); } static void setstate (stroke& s, boost::python::tuple state) { using namespace boost::python; if (len(state) != 4) { PyErr_SetObject(PyExc_ValueError, ("expected 4-item tuple in call to __setstate__; got %s" % state).ptr() ); throw_error_already_set(); } s.set_opacity(extract<float>(state[0])); if (state[1]) { list dashes = extract<list>(state[1]); for(boost::python::ssize_t i=0; i<len(dashes); i++) { double ds1 = extract<double>(dashes[i][0]); double ds2 = extract<double>(dashes[i][1]); s.add_dash(ds1,ds2); } } s.set_line_cap(extract<line_cap_e>(state[2])); s.set_line_join(extract<line_join_e>(state[3])); } }; void export_stroke () { using namespace boost::python; enumeration_<line_cap_e>("line_cap", "The possible values for a line cap used when drawing\n" "with a stroke.\n") .value("BUTT_CAP",BUTT_CAP) .value("SQUARE_CAP",SQUARE_CAP) .value("ROUND_CAP",ROUND_CAP) ; enumeration_<line_join_e>("line_join", "The possible values for the line joining mode\n" "when drawing with a stroke.\n") .value("MITER_JOIN",MITER_JOIN) .value("MITER_REVERT_JOIN",MITER_REVERT_JOIN) .value("ROUND_JOIN",ROUND_JOIN) .value("BEVEL_JOIN",BEVEL_JOIN) ; class_<stroke>("Stroke",init<>( "Creates a new default black stroke with the width of 1.\n")) .def(init<color,float>( (arg("color"),arg("width")), "Creates a new stroke object with a specified color and width.\n") ) .def_pickle(stroke_pickle_suite()) .add_property("color",make_function (&stroke::get_color,return_value_policy<copy_const_reference>()), &stroke::set_color, "Gets or sets the stroke color.\n" "Returns a new Color object on retrieval.\n") .add_property("width", &stroke::get_width, &stroke::set_width, "Gets or sets the stroke width in pixels.\n") .add_property("opacity", &stroke::get_opacity, &stroke::set_opacity, "Gets or sets the opacity of this stroke.\n" "The value is a float between 0 and 1.\n") .add_property("line_cap", &stroke::get_line_cap, &stroke::set_line_cap, "Gets or sets the line cap of this stroke.\n") .add_property("line_join", &stroke::get_line_join, &stroke::set_line_join, "Returns the line join mode of this stroke.\n") // todo consider providing a single get/set property .def("add_dash",&stroke::add_dash, (arg("length"),arg("gap")), "Adds a dash segment to the dash patterns of this stroke.\n") .def("get_dashes", get_dashes_list, "Returns the list of dash segments for this stroke.\n") .add_property("dash_offset", &stroke::dash_offset, &stroke::set_dash_offset, "Gets or sets dash offset of this stroke.\n") ; } <|endoftext|>
<commit_before>#ifndef BLUETOE_BITS_HPP #define BLUETOE_BITS_HPP #include <cstdint> #include <bluetoe/codes.hpp> namespace bluetoe { namespace details { inline std::uint16_t read_handle( const std::uint8_t* h ) { return *h + ( *( h + 1 ) << 8 ); } inline std::uint16_t read_16bit_uuid( const std::uint8_t* h ) { return read_handle( h ); } inline std::uint16_t read_16bit( const std::uint8_t* h ) { return read_handle( h ); } inline std::uint8_t* write_handle( std::uint8_t* out, std::uint16_t handle ) { out[ 0 ] = handle & 0xff; out[ 1 ] = handle >> 8; return out + 2; } inline std::uint8_t* write_16bit_uuid( std::uint8_t* out, std::uint16_t uuid ) { return write_handle( out, uuid ); } inline std::uint8_t* write_16bit( std::uint8_t* out, std::uint16_t bits16 ) { return write_handle( out, bits16 ); } inline std::uint8_t* write_32bit( std::uint8_t* out, std::uint32_t bits32 ) { return write_16bit( write_16bit( out, bits32 & 0xffff ), bits32 >> 16 ); } inline std::uint8_t* write_opcode( std::uint8_t* out, details::att_opcodes opcode ) { *out = bits( opcode ); return out + 1; } inline std::uint8_t* write_byte( std::uint8_t* out, std::uint8_t byte ) { *out = byte; return out + 1; } } } #endif <commit_msg>read_32bit<commit_after>#ifndef BLUETOE_BITS_HPP #define BLUETOE_BITS_HPP #include <cstdint> #include <bluetoe/codes.hpp> namespace bluetoe { namespace details { inline std::uint16_t read_handle( const std::uint8_t* h ) { return *h + ( *( h + 1 ) << 8 ); } inline std::uint16_t read_16bit_uuid( const std::uint8_t* h ) { return read_handle( h ); } inline std::uint16_t read_16bit( const std::uint8_t* h ) { return read_handle( h ); } inline std::uint32_t read_32bit( const std::uint8_t* p ) { return static_cast< std::uint32_t >( read_16bit( p ) ) | ( static_cast< std::uint32_t >( read_16bit( p + 2 ) ) << 16 ); } inline std::uint8_t* write_handle( std::uint8_t* out, std::uint16_t handle ) { out[ 0 ] = handle & 0xff; out[ 1 ] = handle >> 8; return out + 2; } inline std::uint8_t* write_16bit_uuid( std::uint8_t* out, std::uint16_t uuid ) { return write_handle( out, uuid ); } inline std::uint8_t* write_16bit( std::uint8_t* out, std::uint16_t bits16 ) { return write_handle( out, bits16 ); } inline std::uint8_t* write_32bit( std::uint8_t* out, std::uint32_t bits32 ) { return write_16bit( write_16bit( out, bits32 & 0xffff ), bits32 >> 16 ); } inline std::uint8_t* write_opcode( std::uint8_t* out, details::att_opcodes opcode ) { *out = bits( opcode ); return out + 1; } inline std::uint8_t* write_byte( std::uint8_t* out, std::uint8_t byte ) { *out = byte; return out + 1; } } } #endif <|endoftext|>
<commit_before>/* * Copyright (c) 2016 Luke San Antonio * All rights reserved. * * This file provides the implementation for the engine's C interface, * specifically tailored for LuaJIT's FFI facilities. * * General engine stuff */ #include "redcrane.hpp" #include "../common/version.h" #include "../assets/load_dir.h" #include "../gfx/gl/driver.h" using namespace redc; namespace { void redc_lua_log(Log_Severity s, const char *msg) { redc::log(s, "(Mod) %", msg); } } extern "C" { // See redcrane.lua void redc_log_d(const char* str) { redc_lua_log(Log_Severity::Debug, str); } void redc_log_i(const char* str) { redc_lua_log(Log_Severity::Info, str); } void redc_log_w(const char* str) { redc_lua_log(Log_Severity::Warning, str); } void redc_log_e(const char* str) { redc_lua_log(Log_Severity::Error, str); } void* redc_init_engine(Redc_Config cfg) { // Switch into the current working directory requested by the mod if(!exists(boost::filesystem::path(cfg.cwd))) { log_e("Failed to enter requested '%' directory", cfg.cwd); return nullptr; } auto eng = new Engine{cfg, assets::share_path(), true, nullptr}; log_i("Initialized the Red Crane Engine alpha version %.%.% (Mod: %)", REDC_ENGINE_VERSION_MAJOR, REDC_ENGINE_VERSION_MINOR, REDC_ENGINE_VERSION_PATCH, cfg.mod_name); return eng; } void redc_init_client(void* eng) { auto rce = (Engine*) eng; auto sdl_init_raii_lock = redc::init_sdl(rce->config.mod_name, {1000,1000}, false, false); auto sdl_window = sdl_init_raii_lock.window; rce->client = std::make_unique<Client>(std::move(sdl_init_raii_lock)); SDL_SetRelativeMouseMode(SDL_TRUE); int x, y; SDL_GetWindowSize(sdl_window, &x, &y); rce->client->driver = std::make_unique<gfx::gl::Driver>(Vec<int>{x,y}); rce->client->mesh_cache = std::make_unique<gfx::Mesh_Cache>(rce->share_path / "obj", rce->share_path / "obj_cache"); // Load default shader, etc. auto df_shade = rce->client->driver->make_shader_repr(); // TODO: Load shaders like we load mesh. Right now is bad auto basic_shade_path = rce->share_path / "shader" / "basic"; df_shade->load_vertex_part((basic_shade_path / "vs.glsl").native()); df_shade->load_fragment_part((basic_shade_path / "fs.glsl").native()); df_shade->set_model_name("model"); df_shade->set_view_name("view"); df_shade->set_projection_name("proj"); // Make it the default rce->client->driver->use_shader(*df_shade); // Make sure we don't delete it later by linking its lifetime with that of // the engines. rce->client->shaders.push_back(std::move(df_shade)); } void redc_uninit_engine(void* eng) { auto rce = (Engine*) eng; delete rce; } bool redc_running(void *eng) { auto rce = (Engine*) eng; return rce->running; } const char* redc_get_asset_path(void* eng) { // Will this ever change mid-execution? auto rce = (Engine*) eng; return rce->share_path.native().c_str(); } void redc_window_swap(void* eng) { auto engine = (Engine*) eng; if(engine->client) { SDL_GL_SwapWindow(engine->client->sdl_raii.window); } } void redc_gc(void* eng) { auto rce = (Engine*) eng; auto is_null = [](auto const& peer) { return peer.get() == nullptr; }; // Go through the vector of peer pointers and removed deallocated ones. using std::begin; using std::end; if(rce->client) { auto& client = *rce->client; auto mesh_end = std::remove_if(begin(client.meshs), end(client.meshs), is_null); client.meshs.erase(mesh_end, end(client.meshs)); auto textures_end = std::remove_if(begin(client.textures), end(client.textures), is_null); client.textures.erase(textures_end, end(client.textures)); auto shaders_end = std::remove_if(begin(client.shaders), end(client.shaders), is_null); client.shaders.erase(shaders_end, end(client.shaders)); } } } <commit_msg>Set color clear color to white on engine init<commit_after>/* * Copyright (c) 2016 Luke San Antonio * All rights reserved. * * This file provides the implementation for the engine's C interface, * specifically tailored for LuaJIT's FFI facilities. * * General engine stuff */ #include "redcrane.hpp" #include "../common/version.h" #include "../assets/load_dir.h" #include "../gfx/gl/driver.h" using namespace redc; namespace { void redc_lua_log(Log_Severity s, const char *msg) { redc::log(s, "(Mod) %", msg); } } extern "C" { // See redcrane.lua void redc_log_d(const char* str) { redc_lua_log(Log_Severity::Debug, str); } void redc_log_i(const char* str) { redc_lua_log(Log_Severity::Info, str); } void redc_log_w(const char* str) { redc_lua_log(Log_Severity::Warning, str); } void redc_log_e(const char* str) { redc_lua_log(Log_Severity::Error, str); } void* redc_init_engine(Redc_Config cfg) { // Switch into the current working directory requested by the mod if(!exists(boost::filesystem::path(cfg.cwd))) { log_e("Failed to enter requested '%' directory", cfg.cwd); return nullptr; } auto eng = new Engine{cfg, assets::share_path(), true, nullptr}; log_i("Initialized the Red Crane Engine alpha version %.%.% (Mod: %)", REDC_ENGINE_VERSION_MAJOR, REDC_ENGINE_VERSION_MINOR, REDC_ENGINE_VERSION_PATCH, cfg.mod_name); return eng; } void redc_init_client(void* eng) { auto rce = (Engine*) eng; auto sdl_init_raii_lock = redc::init_sdl(rce->config.mod_name, {1000,1000}, false, false); auto sdl_window = sdl_init_raii_lock.window; rce->client = std::make_unique<Client>(std::move(sdl_init_raii_lock)); SDL_SetRelativeMouseMode(SDL_TRUE); int x, y; SDL_GetWindowSize(sdl_window, &x, &y); rce->client->driver = std::make_unique<gfx::gl::Driver>(Vec<int>{x,y}); rce->client->driver->set_clear_color(colors::white); rce->client->mesh_cache = std::make_unique<gfx::Mesh_Cache>(rce->share_path / "obj", rce->share_path / "obj_cache"); // Load default shader, etc. auto df_shade = rce->client->driver->make_shader_repr(); // TODO: Load shaders like we load mesh. Right now is bad auto basic_shade_path = rce->share_path / "shader" / "basic"; df_shade->load_vertex_part((basic_shade_path / "vs.glsl").native()); df_shade->load_fragment_part((basic_shade_path / "fs.glsl").native()); df_shade->set_model_name("model"); df_shade->set_view_name("view"); df_shade->set_projection_name("proj"); // Make it the default rce->client->driver->use_shader(*df_shade); // Make sure we don't delete it later by linking its lifetime with that of // the engines. rce->client->shaders.push_back(std::move(df_shade)); } void redc_uninit_engine(void* eng) { auto rce = (Engine*) eng; delete rce; } bool redc_running(void *eng) { auto rce = (Engine*) eng; return rce->running; } const char* redc_get_asset_path(void* eng) { // Will this ever change mid-execution? auto rce = (Engine*) eng; return rce->share_path.native().c_str(); } void redc_window_swap(void* eng) { auto engine = (Engine*) eng; if(engine->client) { SDL_GL_SwapWindow(engine->client->sdl_raii.window); } } void redc_gc(void* eng) { auto rce = (Engine*) eng; auto is_null = [](auto const& peer) { return peer.get() == nullptr; }; // Go through the vector of peer pointers and removed deallocated ones. using std::begin; using std::end; if(rce->client) { auto& client = *rce->client; auto mesh_end = std::remove_if(begin(client.meshs), end(client.meshs), is_null); client.meshs.erase(mesh_end, end(client.meshs)); auto textures_end = std::remove_if(begin(client.textures), end(client.textures), is_null); client.textures.erase(textures_end, end(client.textures)); auto shaders_end = std::remove_if(begin(client.shaders), end(client.shaders), is_null); client.shaders.erase(shaders_end, end(client.shaders)); } } } <|endoftext|>