<commit_before>//
// Copyright (c) 2015 CNRS
//
// This file is part of Pinocchio
// Pinocchio is free software: you can redistribute it
// and/or modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation, either version
// 3 of the License, or (at your option) any later version.
//
// Pinocchio is distributed in the hope that it will be
// useful, but WITHOUT ANY WARRANTY; without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Lesser Public License for more details. You should have
// received a copy of the GNU Lesser General Public License along with
// Pinocchio If not, see
// <http://www.gnu.org/licenses/>.

#ifndef __se3_python_inertia_hpp__
#define __se3_python_inertia_hpp__

#include <eigenpy/exception.hpp>
#include <eigenpy/eigenpy.hpp>
#include "pinocchio/spatial/inertia.hpp"

namespace eigenpy
{
  template<>
  struct UnalignedEquivalent<se3::Inertia>
  {
    typedef se3::InertiaTpl<double,Eigen::DontAlign> type;
  };

} // namespace eigenpy

namespace se3
{
  namespace python
  {
    namespace bp = boost::python;

    template<typename Inertia>
    struct InertiaPythonVisitor
      : public boost::python::def_visitor< InertiaPythonVisitor<Inertia> >
    {
      typedef typename eigenpy::UnalignedEquivalent<Inertia>::type Inertia_fx;
      typedef typename Inertia::Matrix3 Matrix3;
      typedef typename Inertia::Matrix6 Matrix6;
      typedef typename Inertia::Vector6 Vector6;
      typedef typename Inertia::Vector3 Vector3;

      typedef typename Inertia_fx::Matrix3 Matrix3_fx;
      typedef typename Inertia_fx::Matrix6 Matrix6_fx;
      typedef typename Inertia_fx::Vector6 Vector6_fx;
      typedef typename Inertia_fx::Vector3 Vector3_fx;
      typedef typename Inertia_fx::Motion  Motion_fx ;
    public:

      static PyObject* convert(Inertia const& m)
      {
	Inertia_fx m_fx = m;
	return bp::incref(bp::object(m_fx).ptr());
      }

      template<class PyClass>
      void visit(PyClass& cl) const
      {
	cl
	  .def("__init__",
	       bp::make_constructor(&InertiaPythonVisitor::makeFromMCI,
	   			    bp::default_call_policies(),
	   			    (bp::arg("mass"),bp::arg("lever"),bp::arg("inertia"))),
	       "Initialize from mass, lever and 3d inertia.")

	  .add_property("mass",&Inertia_fx::mass)
	  .add_property("lever",&InertiaPythonVisitor::lever)
	  .add_property("inertia",&InertiaPythonVisitor::inertia)

	  .def("matrix",&Inertia_fx::matrix)
	  .def("se3Action",&Inertia_fx::se3Action)
	  .def("se3ActionInverse",&Inertia_fx::se3ActionInverse)

	  .def("__str__",&InertiaPythonVisitor::toString)
	  .def( bp::self + bp::self)
	  .def( bp::self * bp::other<Motion_fx>() )
	  .add_property("np",&Inertia_fx::matrix)

	  .def("Identity",&Inertia_fx::Identity)
	  .staticmethod("Identity")
	  .def("Zero",&Inertia_fx::Zero)
	  .staticmethod("Zero")
	  .def("Random",&Inertia_fx::Random)
	  .staticmethod("Random")
	  ;
	  }

      static Inertia_fx* makeFromMCI(const double & mass,
				     const Vector3_fx & lever,
				     const Matrix3_fx & inertia)
      {
	if(! inertia.isApprox(inertia.transpose()) )
	   throw eigenpy::Exception("The 3d inertia should be symmetric.");
	if( (Eigen::Vector3d::UnitX().transpose()*inertia*Eigen::Vector3d::UnitX()<0)
	    || (Eigen::Vector3d::UnitY().transpose()*inertia*Eigen::Vector3d::UnitY()<0)
	    || (Eigen::Vector3d::UnitZ().transpose()*inertia*Eigen::Vector3d::UnitZ()<0) )
	  throw eigenpy::Exception("The 3d inertia should be positive.");
	return new Inertia_fx(mass,lever,inertia);
      }
      static Matrix3_fx inertia(const Inertia_fx& Y) { return Y.inertia().matrix(); }
      static Vector3_fx lever(const Inertia_fx& Y) { return Y.lever(); }
      static std::string toString(const Inertia_fx& m)
      {	  std::ostringstream s; s << m; return s.str();       }

      static void expose()
      {
	bp::class_<Inertia_fx>("Inertia",
			     "Inertia matrix, in L(se3,se3*) == R^6x6.\n\n"
			     "Supported operations ...",
			     bp::init<>())
	  .def(InertiaPythonVisitor<Inertia>())
	;

	bp::to_python_converter< Inertia,InertiaPythonVisitor<Inertia> >();
    }

    };

  }} // namespace se3::python

#endif // ifndef __se3_python_se3_hpp__

<commit_msg>[Python] Expose new setter methods for inertia class<commit_after>//
// Copyright (c) 2015 CNRS
//
// This file is part of Pinocchio
// Pinocchio is free software: you can redistribute it
// and/or modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation, either version
// 3 of the License, or (at your option) any later version.
//
// Pinocchio is distributed in the hope that it will be
// useful, but WITHOUT ANY WARRANTY; without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Lesser Public License for more details. You should have
// received a copy of the GNU Lesser General Public License along with
// Pinocchio If not, see
// <http://www.gnu.org/licenses/>.

#ifndef __se3_python_inertia_hpp__
#define __se3_python_inertia_hpp__

#include <eigenpy/exception.hpp>
#include <eigenpy/eigenpy.hpp>
#include "pinocchio/spatial/inertia.hpp"

namespace eigenpy
{
  template<>
  struct UnalignedEquivalent<se3::Inertia>
  {
    typedef se3::InertiaTpl<double,Eigen::DontAlign> type;
  };

} // namespace eigenpy

namespace se3
{
  namespace python
  {
    namespace bp = boost::python;

    template<typename Inertia>
    struct InertiaPythonVisitor
      : public boost::python::def_visitor< InertiaPythonVisitor<Inertia> >
    {
      typedef typename eigenpy::UnalignedEquivalent<Inertia>::type Inertia_fx;
      typedef typename Inertia::Matrix3 Matrix3;
      typedef typename Inertia::Matrix6 Matrix6;
      typedef typename Inertia::Vector6 Vector6;
      typedef typename Inertia::Vector3 Vector3;

      typedef typename Inertia_fx::Matrix3 Matrix3_fx;
      typedef typename Inertia_fx::Matrix6 Matrix6_fx;
      typedef typename Inertia_fx::Vector6 Vector6_fx;
      typedef typename Inertia_fx::Vector3 Vector3_fx;
      typedef typename Inertia_fx::Motion  Motion_fx ;

      typedef typename Inertia_fx::Scalar_t Scalar_t;

    public:

      static PyObject* convert(Inertia const& m)
      {
	Inertia_fx m_fx = m;
	return bp::incref(bp::object(m_fx).ptr());
      }

      template<class PyClass>
      void visit(PyClass& cl) const
      {
	cl
	  .def("__init__",
	       bp::make_constructor(&InertiaPythonVisitor::makeFromMCI,
	   			    bp::default_call_policies(),
	   			    (bp::arg("mass"),bp::arg("lever"),bp::arg("inertia"))),
	       "Initialize from mass, lever and 3d inertia.")

      .add_property("mass", &InertiaPythonVisitor::getMass, &InertiaPythonVisitor::setMass)
	  .add_property("lever", &InertiaPythonVisitor::getLever, &InertiaPythonVisitor::setLever)
	  .add_property("inertia", &InertiaPythonVisitor::getInertia, &InertiaPythonVisitor::setInertia)

	  .def("matrix",&Inertia_fx::matrix)
	  .def("se3Action",&Inertia_fx::se3Action)
	  .def("se3ActionInverse",&Inertia_fx::se3ActionInverse)

	  .def("__str__",&InertiaPythonVisitor::toString)
	  .def( bp::self + bp::self)
	  .def( bp::self * bp::other<Motion_fx>() )
	  .add_property("np",&Inertia_fx::matrix)

	  .def("Identity",&Inertia_fx::Identity)
	  .staticmethod("Identity")
	  .def("Zero",&Inertia_fx::Zero)
	  .staticmethod("Zero")
	  .def("Random",&Inertia_fx::Random)
	  .staticmethod("Random")
	  ;
	  }

      static Scalar_t getMass( const Inertia_fx & self ) { return self.mass(); }
      static void setMass( Inertia_fx & self, Scalar_t mass ) { self.mass() = mass; }

      static Vector3_fx getLever( const Inertia_fx & self ) { return self.lever(); }
      static void setLever( Inertia_fx & self, const Vector3_fx & lever ) { self.lever() = lever; }

      static Matrix3_fx getInertia( const Inertia_fx & self ) { return self.inertia().matrix(); }
      static void setInertia( Inertia_fx & self, const Vector6_fx & minimal_inertia ) { self.inertia().data() = minimal_inertia; }

      static Inertia_fx* makeFromMCI(const double & mass,
				     const Vector3_fx & lever,
				     const Matrix3_fx & inertia)
      {
	if(! inertia.isApprox(inertia.transpose()) )
	   throw eigenpy::Exception("The 3d inertia should be symmetric.");
	if( (Eigen::Vector3d::UnitX().transpose()*inertia*Eigen::Vector3d::UnitX()<0)
	    || (Eigen::Vector3d::UnitY().transpose()*inertia*Eigen::Vector3d::UnitY()<0)
	    || (Eigen::Vector3d::UnitZ().transpose()*inertia*Eigen::Vector3d::UnitZ()<0) )
	  throw eigenpy::Exception("The 3d inertia should be positive.");
	return new Inertia_fx(mass,lever,inertia);
      }
      static std::string toString(const Inertia_fx& m)
      {	  std::ostringstream s; s << m; return s.str();       }

      static void expose()
      {
	bp::class_<Inertia_fx>("Inertia",
			     "Inertia matrix, in L(se3,se3*) == R^6x6.\n\n"
			     "Supported operations ...",
			     bp::init<>())
	  .def(InertiaPythonVisitor<Inertia>())
	;

	bp::to_python_converter< Inertia,InertiaPythonVisitor<Inertia> >();
    }

    }; // struct InertiaPythonVisitor

  }} // namespace se3::python

#endif // ifndef __se3_python_se3_hpp__

<|endoftext|>


<commit_before>#include "factory.h"
#include "except.h"
#ifdef USE_OPENCV
#include "opencv_video_source.h"
#include "opencv_video_target.h"
#endif // USE_OPENCV
#ifdef USE_I420
#ifdef USE_EPIPHANSDK
#include "epiphansdk_video_source.h"
#endif
#endif
#ifdef USE_FFMPEG
#include "ffmpeg_video_target.h"
#endif
#include <boost/python.hpp>
#include <boost/python/exception_translator.hpp>

using namespace boost::python;

class IVideoSourceWrapper : IVideoSource, wrapper<IVideoSource>
{
    bool get_frame_dimensions(int & width, int & height)
    {
        return this->get_override("get_frame_dimensions")(width, height);
    }

    bool get_frame(VideoFrame_BGRA & frame)
    {
        return this->get_override("get_frame")(frame);
    }

#ifdef USE_I420
    bool get_frame(gg::VideoFrame_I420 & frame)
    {
        return this->get_override("get_frame")(frame);
    }
#endif

    double get_frame_rate()
    {
        return this->get_override("get_frame_rate")();
    }

    void set_sub_frame(int x, int y, int width, int height)
    {
        this->get_override("set_sub_frame")(x, y, width, height);
    }

    void get_full_frame()
    {
        this->get_override("get_full_frame")();
    }
};

class IVideoTargetWrapper : gg::IVideoTarget, wrapper<gg::IVideoTarget>
{
    void init(const std::string filepath, const float framerate)
    {
        this->get_override("init")(filepath, framerate);
    }

    void append(const VideoFrame_BGRA & frame)
    {
        this->get_override("append")(frame);
    }

    void finalise()
    {
        this->get_override("finalise")();
    }
};

void translate_VideoSourceError(gg::VideoSourceError const & e)
{
    std::string msg;
    msg.append("VideoSourceError: ").append(e.what());
    PyErr_SetString(PyExc_RuntimeError, msg.c_str());
}

void translate_DeviceNotFound(gg::DeviceNotFound const & e)
{
    std::string msg;
    msg.append("DeviceNotFound: ").append(e.what());
    PyErr_SetString(PyExc_IOError, msg.c_str());
}

void translate_DeviceOffline(gg::DeviceOffline const & e)
{
    std::string msg;
    msg.append("DeviceOffline: ").append(e.what());
    PyErr_SetString(PyExc_IOError, msg.c_str());
}

void translate_VideoTargetError(gg::VideoTargetError const & e)
{
    std::string msg;
    msg.append("VideoTargetError: ").append(e.what());
    PyErr_SetString(PyExc_RuntimeError, msg.c_str());
}

BOOST_PYTHON_MODULE(pygiftgrab)
{
    register_exception_translator<gg::VideoSourceError>(&translate_VideoSourceError);
    register_exception_translator<gg::DeviceNotFound>(&translate_DeviceNotFound);
    register_exception_translator<gg::DeviceOffline>(&translate_DeviceOffline);
    register_exception_translator<gg::VideoTargetError>(&translate_VideoTargetError);

    enum_<gg::Device>("Device")
        .value("DVI2PCIeDuo_SDI", gg::Device::DVI2PCIeDuo_SDI)
        .value("DVI2PCIeDuo_DVI", gg::Device::DVI2PCIeDuo_DVI)
    ;

    enum_<gg::Storage>("Storage")
        .value("File_HEVC", gg::Storage::File_HEVC)
        .value("File_XviD", gg::Storage::File_XviD)
        .value("File_VP9", gg::Storage::File_VP9)
    ;

    class_<VideoFrame_BGRA>("VideoFrame_BGRA", init<bool>())
        .def(init<const size_t, const size_t>())
        .def("rows", &VideoFrame_BGRA::rows)
        .def("cols", &VideoFrame_BGRA::cols)
    ;

    class_<IVideoSource, boost::noncopyable>("IVideoSource", no_init)
    ;

#ifdef USE_OPENCV
    bool (VideoSourceOpenCV::*opencv_get_frame_bgra)(VideoFrame_BGRA &) = &VideoSourceOpenCV::get_frame;
    class_<VideoSourceOpenCV, bases<IVideoSource>, boost::noncopyable>(
                "VideoSourceOpenCV", init<int>())
        .def(init<char *>())
        .def("get_frame", opencv_get_frame_bgra)
        .def("get_frame_dimensions", &VideoSourceOpenCV::get_frame_dimensions)
        .def("get_frame_rate", &VideoSourceOpenCV::get_frame_rate)
        .def("set_sub_frame", &VideoSourceOpenCV::set_sub_frame)
        .def("get_full_frame", &VideoSourceOpenCV::get_full_frame)
    ;
#endif // USE_OPENCV

#ifdef USE_I420
    class_<gg::VideoFrame_I420>("VideoFrame_I420", init<bool>())
        .def(init<const size_t, const size_t>())
        .def("rows", &gg::VideoFrame_I420::rows)
        .def("cols", &gg::VideoFrame_I420::cols)
    ;
#ifdef USE_EPIPHANSDK
    bool (gg::VideoSourceEpiphanSDK::*epiphansdk_get_frame_i420)(gg::VideoFrame_I420 &) = &gg::VideoSourceEpiphanSDK::get_frame;
    class_<gg::VideoSourceEpiphanSDK, bases<IVideoSource>, boost::noncopyable>(
                "VideoSourceEpiphanSDK", init<const std::string, const V2U_INT32>())
        .def("get_frame", epiphansdk_get_frame_i420)
        .def("get_frame_dimensions", &gg::VideoSourceEpiphanSDK::get_frame_dimensions)
        .def("get_frame_rate", &gg::VideoSourceEpiphanSDK::get_frame_rate)
        .def("set_sub_frame", &gg::VideoSourceEpiphanSDK::set_sub_frame)
        .def("get_full_frame", &gg::VideoSourceEpiphanSDK::get_full_frame)
    ;
#endif
#endif

    class_<gg::IVideoTarget, boost::noncopyable>("IVideoTarget", no_init)
    ;

#ifdef USE_FFMPEG
    void (gg::VideoTargetFFmpeg::*ffmpeg_append_bgra)(const VideoFrame_BGRA &) = &gg::VideoTargetFFmpeg::append;
#ifdef USE_I420
    void (gg::VideoTargetFFmpeg::*ffmpeg_append_i420)(const gg::VideoFrame_I420 &) = &gg::VideoTargetFFmpeg::append;
#endif

    class_<gg::VideoTargetFFmpeg, bases<gg::IVideoTarget>, boost::noncopyable>(
                "VideoTargetFFmpeg", init<std::string>())
        .def("init", &gg::VideoTargetFFmpeg::init)
        .def("append", ffmpeg_append_bgra)
#ifdef USE_I420
        .def("append", ffmpeg_append_i420)
#endif
        .def("finalise", &gg::VideoTargetFFmpeg::finalise)
    ;
#endif

#ifdef USE_OPENCV
    class_<gg::VideoTargetOpenCV, bases<gg::IVideoTarget>, boost::noncopyable>(
                "VideoTargetOpenCV", init<std::string>())
        .def("init", &gg::VideoTargetOpenCV::init)
        .def("append", &gg::VideoTargetOpenCV::append)
        .def("finalise", &gg::VideoTargetOpenCV::finalise)
    ;
#endif // USE_OPENCV

    class_<gg::Factory>("Factory", no_init)
        .def("connect", &gg::Factory::connect,
             /* because client should never delete returned
              * object on its own, but should rather call
              * disconnect when done
              */
             return_value_policy<reference_existing_object>())
        .staticmethod("connect")
        .def("disconnect", &gg::Factory::disconnect)
        .staticmethod("disconnect")
        .def("writer", &gg::Factory::writer,
             // because ownership is passed to client
             return_value_policy<manage_new_object>())
        .staticmethod("writer")
    ;
}
<commit_msg>Issue #83: VLC video source exported in Python wrapper<commit_after>#include "factory.h"
#include "except.h"
#ifdef USE_OPENCV
#include "opencv_video_source.h"
#include "opencv_video_target.h"
#endif // USE_OPENCV
#ifdef USE_I420
#ifdef USE_EPIPHANSDK
#include "epiphansdk_video_source.h"
#endif
#ifdef USE_LIBVLC
#include "vlc_video_source.h"
#endif
#endif
#ifdef USE_FFMPEG
#include "ffmpeg_video_target.h"
#endif
#include <boost/python.hpp>
#include <boost/python/exception_translator.hpp>

using namespace boost::python;

class IVideoSourceWrapper : IVideoSource, wrapper<IVideoSource>
{
    bool get_frame_dimensions(int & width, int & height)
    {
        return this->get_override("get_frame_dimensions")(width, height);
    }

    bool get_frame(VideoFrame_BGRA & frame)
    {
        return this->get_override("get_frame")(frame);
    }

#ifdef USE_I420
    bool get_frame(gg::VideoFrame_I420 & frame)
    {
        return this->get_override("get_frame")(frame);
    }
#endif

    double get_frame_rate()
    {
        return this->get_override("get_frame_rate")();
    }

    void set_sub_frame(int x, int y, int width, int height)
    {
        this->get_override("set_sub_frame")(x, y, width, height);
    }

    void get_full_frame()
    {
        this->get_override("get_full_frame")();
    }
};

class IVideoTargetWrapper : gg::IVideoTarget, wrapper<gg::IVideoTarget>
{
    void init(const std::string filepath, const float framerate)
    {
        this->get_override("init")(filepath, framerate);
    }

    void append(const VideoFrame_BGRA & frame)
    {
        this->get_override("append")(frame);
    }

    void finalise()
    {
        this->get_override("finalise")();
    }
};

void translate_VideoSourceError(gg::VideoSourceError const & e)
{
    std::string msg;
    msg.append("VideoSourceError: ").append(e.what());
    PyErr_SetString(PyExc_RuntimeError, msg.c_str());
}

void translate_DeviceNotFound(gg::DeviceNotFound const & e)
{
    std::string msg;
    msg.append("DeviceNotFound: ").append(e.what());
    PyErr_SetString(PyExc_IOError, msg.c_str());
}

void translate_DeviceOffline(gg::DeviceOffline const & e)
{
    std::string msg;
    msg.append("DeviceOffline: ").append(e.what());
    PyErr_SetString(PyExc_IOError, msg.c_str());
}

void translate_VideoTargetError(gg::VideoTargetError const & e)
{
    std::string msg;
    msg.append("VideoTargetError: ").append(e.what());
    PyErr_SetString(PyExc_RuntimeError, msg.c_str());
}

BOOST_PYTHON_MODULE(pygiftgrab)
{
    register_exception_translator<gg::VideoSourceError>(&translate_VideoSourceError);
    register_exception_translator<gg::DeviceNotFound>(&translate_DeviceNotFound);
    register_exception_translator<gg::DeviceOffline>(&translate_DeviceOffline);
    register_exception_translator<gg::VideoTargetError>(&translate_VideoTargetError);

    enum_<gg::Device>("Device")
        .value("DVI2PCIeDuo_SDI", gg::Device::DVI2PCIeDuo_SDI)
        .value("DVI2PCIeDuo_DVI", gg::Device::DVI2PCIeDuo_DVI)
    ;

    enum_<gg::Storage>("Storage")
        .value("File_HEVC", gg::Storage::File_HEVC)
        .value("File_XviD", gg::Storage::File_XviD)
        .value("File_VP9", gg::Storage::File_VP9)
    ;

    class_<VideoFrame_BGRA>("VideoFrame_BGRA", init<bool>())
        .def(init<const size_t, const size_t>())
        .def("rows", &VideoFrame_BGRA::rows)
        .def("cols", &VideoFrame_BGRA::cols)
    ;

    class_<IVideoSource, boost::noncopyable>("IVideoSource", no_init)
    ;

#ifdef USE_OPENCV
    bool (VideoSourceOpenCV::*opencv_get_frame_bgra)(VideoFrame_BGRA &) = &VideoSourceOpenCV::get_frame;
    class_<VideoSourceOpenCV, bases<IVideoSource>, boost::noncopyable>(
                "VideoSourceOpenCV", init<int>())
        .def(init<char *>())
        .def("get_frame", opencv_get_frame_bgra)
        .def("get_frame_dimensions", &VideoSourceOpenCV::get_frame_dimensions)
        .def("get_frame_rate", &VideoSourceOpenCV::get_frame_rate)
        .def("set_sub_frame", &VideoSourceOpenCV::set_sub_frame)
        .def("get_full_frame", &VideoSourceOpenCV::get_full_frame)
    ;
#endif // USE_OPENCV

#ifdef USE_I420
    class_<gg::VideoFrame_I420>("VideoFrame_I420", init<bool>())
        .def(init<const size_t, const size_t>())
        .def("rows", &gg::VideoFrame_I420::rows)
        .def("cols", &gg::VideoFrame_I420::cols)
    ;
#ifdef USE_EPIPHANSDK
    bool (gg::VideoSourceEpiphanSDK::*epiphansdk_get_frame_i420)(gg::VideoFrame_I420 &) = &gg::VideoSourceEpiphanSDK::get_frame;
    class_<gg::VideoSourceEpiphanSDK, bases<IVideoSource>, boost::noncopyable>(
                "VideoSourceEpiphanSDK", init<const std::string, const V2U_INT32>())
        .def("get_frame", epiphansdk_get_frame_i420)
        .def("get_frame_dimensions", &gg::VideoSourceEpiphanSDK::get_frame_dimensions)
        .def("get_frame_rate", &gg::VideoSourceEpiphanSDK::get_frame_rate)
        .def("set_sub_frame", &gg::VideoSourceEpiphanSDK::set_sub_frame)
        .def("get_full_frame", &gg::VideoSourceEpiphanSDK::get_full_frame)
    ;
#endif

#ifdef USE_LIBVLC
    bool (gg::VideoSourceVLC::*vlc_get_frame_i420)(gg::VideoFrame_I420 &) = &gg::VideoSourceVLC::get_frame;
    class_<gg::VideoSourceVLC, bases<IVideoSource>, boost::noncopyable>(
                "VideoSourceVLC", init<const std::string>())
        .def("get_frame", vlc_get_frame_i420)
        .def("get_frame_dimensions", &gg::VideoSourceVLC::get_frame_dimensions)
        .def("get_frame_rate", &gg::VideoSourceVLC::get_frame_rate)
        .def("set_sub_frame", &gg::VideoSourceVLC::set_sub_frame)
        .def("get_full_frame", &gg::VideoSourceVLC::get_full_frame)
    ;
#endif
#endif

    class_<gg::IVideoTarget, boost::noncopyable>("IVideoTarget", no_init)
    ;

#ifdef USE_FFMPEG
    void (gg::VideoTargetFFmpeg::*ffmpeg_append_bgra)(const VideoFrame_BGRA &) = &gg::VideoTargetFFmpeg::append;
#ifdef USE_I420
    void (gg::VideoTargetFFmpeg::*ffmpeg_append_i420)(const gg::VideoFrame_I420 &) = &gg::VideoTargetFFmpeg::append;
#endif

    class_<gg::VideoTargetFFmpeg, bases<gg::IVideoTarget>, boost::noncopyable>(
                "VideoTargetFFmpeg", init<std::string>())
        .def("init", &gg::VideoTargetFFmpeg::init)
        .def("append", ffmpeg_append_bgra)
#ifdef USE_I420
        .def("append", ffmpeg_append_i420)
#endif
        .def("finalise", &gg::VideoTargetFFmpeg::finalise)
    ;
#endif

#ifdef USE_OPENCV
    class_<gg::VideoTargetOpenCV, bases<gg::IVideoTarget>, boost::noncopyable>(
                "VideoTargetOpenCV", init<std::string>())
        .def("init", &gg::VideoTargetOpenCV::init)
        .def("append", &gg::VideoTargetOpenCV::append)
        .def("finalise", &gg::VideoTargetOpenCV::finalise)
    ;
#endif // USE_OPENCV

    class_<gg::Factory>("Factory", no_init)
        .def("connect", &gg::Factory::connect,
             /* because client should never delete returned
              * object on its own, but should rather call
              * disconnect when done
              */
             return_value_policy<reference_existing_object>())
        .staticmethod("connect")
        .def("disconnect", &gg::Factory::disconnect)
        .staticmethod("disconnect")
        .def("writer", &gg::Factory::writer,
             // because ownership is passed to client
             return_value_policy<manage_new_object>())
        .staticmethod("writer")
    ;
}
<|endoftext|>


<commit_before>// @(#)root/tree:$Id$
// Author: Rene Brun   07/04/2001

/*************************************************************************
 * Copyright (C) 1995-2001, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

//////////////////////////////////////////////////////////////////////////
//                                                                      //
// TFriendElement                                                       //
//                                                                      //
// A TFriendElement TF describes a TTree object TF in a file.           //
// When a TFriendElement TF is added to the the list of friends of an   //
// existing TTree T, any variable from TF can be referenced in a query  //
// to T.                                                                //
//                                                                      //
// To add a TFriendElement to an existing TTree T, do:                  //
//       T.AddFriend("friendTreename","friendTreeFile");                //
//                                                                      //
//  See TTree::AddFriend for more information.                          //
//                                                                      //
//////////////////////////////////////////////////////////////////////////

#include "TTree.h"
#include "TFriendElement.h"
#include "TFile.h"
#include "TROOT.h"

R__EXTERN TTree *gTree;

ClassImp(TFriendElement)

//______________________________________________________________________________
TFriendElement::TFriendElement() : TNamed()
{
//*-*-*-*-*-*Default constructor for a friend element*-*-*-*-*-*-*-*-*-*-*-*-*
//*-*        =======================================

   fFile       = 0;
   fTree       = 0;
   fOwnFile    = kFALSE;
   fParentTree = gTree;
}

//______________________________________________________________________________
TFriendElement::TFriendElement(TTree *tree, const char *treename, const char *filename)
    :TNamed(treename,filename)
{
//*-*-*-*-*-*-*-*-*-*-*-*-*Create a friend element*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
//*-*                      ======================
//
// If treename is of the form "a=b", an alias called "a" is created for
// treename = "b" by default the alias name is the name of the tree.

   fFile       = 0;
   fTree       = 0;
   fOwnFile    = kTRUE;
   fParentTree = tree;
   fTreeName   = treename;
   if (strchr(treename,'=')) {
      char *temp = Compress(treename);
      char *equal = strchr(temp,'=');
      if (!equal) return;;
      *equal=0;
      fTreeName = equal+1;
      SetName(temp);
      delete [] temp;
   }

   Connect();
}

//______________________________________________________________________________
TFriendElement::TFriendElement(TTree *tree, const char *treename, TFile *file)
    :TNamed(treename,file?file->GetName():"")
{
//*-*-*-*-*-*-*-*-*-*-*-*-*Create a friend element*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
//*-*                      ======================
//
// If treename is of the form "a=b", an alias called "a" is created for
// treename = "b" by default the alias name is the name of the tree.
// The passed TFile is managed by the user (i.e. user must delete the TFile).

   fFile       = file;
   fTree       = 0;
   fOwnFile    = kFALSE;
   fParentTree = tree;
   fTreeName   = treename;
   if (fParentTree && fParentTree->GetDirectory()
       && fParentTree->GetDirectory()->GetFile() == fFile) {
      // The friend and the TTree are in the same file, let's not record
      // the filename.
      SetTitle("");
   }
   if (strchr(treename,'=')) {
      char *temp = Compress(treename);
      char *equal = strchr(temp,'=');
      *equal=0;
      fTreeName = equal+1;
      SetName(temp);
      delete [] temp;
   }

   Connect();
}

//______________________________________________________________________________
TFriendElement::TFriendElement(TTree *tree, TTree* friendtree, const char *alias)
   : TNamed(friendtree?friendtree->GetName():"",
            friendtree
            ? (   friendtree->GetDirectory()
                  ? (    friendtree->GetDirectory()->GetFile()
                         ? friendtree->GetDirectory()->GetFile()->GetName()
                         :  "")
                  : "")
            :  "")
{
   // Create a friend element.

   fTree       = friendtree;
   fTreeName   = "";
   fFile       = 0;
   fOwnFile    = kFALSE;
   fParentTree = tree;
   if (fTree) {
      fTreeName   = fTree->GetName();
      if (fTree->GetDirectory()) fFile = fTree->GetDirectory()->GetFile();
      if (fParentTree && fParentTree->GetDirectory()
          && fParentTree->GetDirectory()->GetFile() == fFile) {
         // The friend and the TTree are in the same file, let's not record
         // the filename.
         SetTitle("");
      }
   }
   if (alias && strlen(alias)) {
      char *temp = Compress(alias);
      SetName(temp);
      delete [] temp;
   }

   // No need to Connect.
}

//______________________________________________________________________________
TFriendElement::TFriendElement(const TFriendElement& tfe) :
   TNamed(tfe),
   fParentTree(tfe.fParentTree),
   fTree(tfe.fTree),
   fFile(tfe.fFile),
   fTreeName(tfe.fTreeName),
   fOwnFile(tfe.fOwnFile)
{
   // Copy constructor
}

//______________________________________________________________________________
TFriendElement& TFriendElement::operator=(const TFriendElement& tfe)
{
   // Equal operator
   if(this!=&tfe) {
      TNamed::operator=(tfe);
      fParentTree=tfe.fParentTree;
      fTree=tfe.fTree;
      fFile=tfe.fFile;
      fTreeName=tfe.fTreeName;
      fOwnFile=tfe.fOwnFile;
   } return *this;
}

//______________________________________________________________________________
TFriendElement::~TFriendElement()
{
   // Destructor.  Disconnect from the owning tree if needed.

   DisConnect();
}

//_______________________________________________________________________
TTree *TFriendElement::Connect()
{
   // Connect file and return TTree.

   GetFile();
   return GetTree();
}

//_______________________________________________________________________
TTree *TFriendElement::DisConnect()
{
   // DisConnect file and TTree.

   if (fOwnFile) delete fFile;
   fFile = 0;
   fTree = 0;
   return 0;
}

//_______________________________________________________________________
TFile *TFriendElement::GetFile()
{
   // Return pointer to TFile containing this friend TTree.

   if (fFile || IsZombie()) return fFile;

   if (strlen(GetTitle())) {
      TDirectory::TContext ctxt(gDirectory, 0);
      fFile = TFile::Open(GetTitle());
      fOwnFile = kTRUE;
   } else {
      TDirectory *dir = fParentTree->GetDirectory();
      if (dir) {
         fFile = dir->GetFile();
         fOwnFile = kFALSE;
      }
   }
   if (fFile && fFile->IsZombie()) {
      MakeZombie();
      delete fFile;
      fFile = 0;
   }
   return fFile;
}

//_______________________________________________________________________
TTree *TFriendElement::GetTree()
{
   // Return pointer to friend TTree.

   if (fTree) return fTree;

   if (GetFile()) {
      fFile->GetObject(GetTreeName(),fTree);
      if (fTree) return fTree;
   }

   // This could be a memory tree or chain
   fTree = dynamic_cast<TTree*>( gROOT->FindObject(GetTreeName()) );

   return fTree;
}

//_______________________________________________________________________
void TFriendElement::ls(Option_t *) const
{
   // List this friend element.

   printf(" Friend Tree: %s in file: %s\n",GetName(),GetTitle());
}
<commit_msg>Fix another null_return. coverity<commit_after>// @(#)root/tree:$Id$
// Author: Rene Brun   07/04/2001

/*************************************************************************
 * Copyright (C) 1995-2001, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

//////////////////////////////////////////////////////////////////////////
//                                                                      //
// TFriendElement                                                       //
//                                                                      //
// A TFriendElement TF describes a TTree object TF in a file.           //
// When a TFriendElement TF is added to the the list of friends of an   //
// existing TTree T, any variable from TF can be referenced in a query  //
// to T.                                                                //
//                                                                      //
// To add a TFriendElement to an existing TTree T, do:                  //
//       T.AddFriend("friendTreename","friendTreeFile");                //
//                                                                      //
//  See TTree::AddFriend for more information.                          //
//                                                                      //
//////////////////////////////////////////////////////////////////////////

#include "TTree.h"
#include "TFriendElement.h"
#include "TFile.h"
#include "TROOT.h"

R__EXTERN TTree *gTree;

ClassImp(TFriendElement)

//______________________________________________________________________________
TFriendElement::TFriendElement() : TNamed()
{
//*-*-*-*-*-*Default constructor for a friend element*-*-*-*-*-*-*-*-*-*-*-*-*
//*-*        =======================================

   fFile       = 0;
   fTree       = 0;
   fOwnFile    = kFALSE;
   fParentTree = gTree;
}

//______________________________________________________________________________
TFriendElement::TFriendElement(TTree *tree, const char *treename, const char *filename)
    :TNamed(treename,filename)
{
//*-*-*-*-*-*-*-*-*-*-*-*-*Create a friend element*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
//*-*                      ======================
//
// If treename is of the form "a=b", an alias called "a" is created for
// treename = "b" by default the alias name is the name of the tree.

   fFile       = 0;
   fTree       = 0;
   fOwnFile    = kTRUE;
   fParentTree = tree;
   fTreeName   = treename;
   if (strchr(treename,'=')) {
      char *temp = Compress(treename);
      char *equal = strchr(temp,'=');
      if (!equal) return;;
      *equal=0;
      fTreeName = equal+1;
      SetName(temp);
      delete [] temp;
   }

   Connect();
}

//______________________________________________________________________________
TFriendElement::TFriendElement(TTree *tree, const char *treename, TFile *file)
    :TNamed(treename,file?file->GetName():"")
{
//*-*-*-*-*-*-*-*-*-*-*-*-*Create a friend element*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
//*-*                      ======================
//
// If treename is of the form "a=b", an alias called "a" is created for
// treename = "b" by default the alias name is the name of the tree.
// The passed TFile is managed by the user (i.e. user must delete the TFile).

   fFile       = file;
   fTree       = 0;
   fOwnFile    = kFALSE;
   fParentTree = tree;
   fTreeName   = treename;
   if (fParentTree && fParentTree->GetDirectory()
       && fParentTree->GetDirectory()->GetFile() == fFile) {
      // The friend and the TTree are in the same file, let's not record
      // the filename.
      SetTitle("");
   }
   if (strchr(treename,'=')) {
      char *temp = Compress(treename);
      char *equal = strchr(temp,'=');
      if (!equal) return;;
      *equal=0;
      fTreeName = equal+1;
      SetName(temp);
      delete [] temp;
   }

   Connect();
}

//______________________________________________________________________________
TFriendElement::TFriendElement(TTree *tree, TTree* friendtree, const char *alias)
   : TNamed(friendtree?friendtree->GetName():"",
            friendtree
            ? (   friendtree->GetDirectory()
                  ? (    friendtree->GetDirectory()->GetFile()
                         ? friendtree->GetDirectory()->GetFile()->GetName()
                         :  "")
                  : "")
            :  "")
{
   // Create a friend element.

   fTree       = friendtree;
   fTreeName   = "";
   fFile       = 0;
   fOwnFile    = kFALSE;
   fParentTree = tree;
   if (fTree) {
      fTreeName   = fTree->GetName();
      if (fTree->GetDirectory()) fFile = fTree->GetDirectory()->GetFile();
      if (fParentTree && fParentTree->GetDirectory()
          && fParentTree->GetDirectory()->GetFile() == fFile) {
         // The friend and the TTree are in the same file, let's not record
         // the filename.
         SetTitle("");
      }
   }
   if (alias && strlen(alias)) {
      char *temp = Compress(alias);
      SetName(temp);
      delete [] temp;
   }

   // No need to Connect.
}

//______________________________________________________________________________
TFriendElement::TFriendElement(const TFriendElement& tfe) :
   TNamed(tfe),
   fParentTree(tfe.fParentTree),
   fTree(tfe.fTree),
   fFile(tfe.fFile),
   fTreeName(tfe.fTreeName),
   fOwnFile(tfe.fOwnFile)
{
   // Copy constructor
}

//______________________________________________________________________________
TFriendElement& TFriendElement::operator=(const TFriendElement& tfe)
{
   // Equal operator
   if(this!=&tfe) {
      TNamed::operator=(tfe);
      fParentTree=tfe.fParentTree;
      fTree=tfe.fTree;
      fFile=tfe.fFile;
      fTreeName=tfe.fTreeName;
      fOwnFile=tfe.fOwnFile;
   } return *this;
}

//______________________________________________________________________________
TFriendElement::~TFriendElement()
{
   // Destructor.  Disconnect from the owning tree if needed.

   DisConnect();
}

//_______________________________________________________________________
TTree *TFriendElement::Connect()
{
   // Connect file and return TTree.

   GetFile();
   return GetTree();
}

//_______________________________________________________________________
TTree *TFriendElement::DisConnect()
{
   // DisConnect file and TTree.

   if (fOwnFile) delete fFile;
   fFile = 0;
   fTree = 0;
   return 0;
}

//_______________________________________________________________________
TFile *TFriendElement::GetFile()
{
   // Return pointer to TFile containing this friend TTree.

   if (fFile || IsZombie()) return fFile;

   if (strlen(GetTitle())) {
      TDirectory::TContext ctxt(gDirectory, 0);
      fFile = TFile::Open(GetTitle());
      fOwnFile = kTRUE;
   } else {
      TDirectory *dir = fParentTree->GetDirectory();
      if (dir) {
         fFile = dir->GetFile();
         fOwnFile = kFALSE;
      }
   }
   if (fFile && fFile->IsZombie()) {
      MakeZombie();
      delete fFile;
      fFile = 0;
   }
   return fFile;
}

//_______________________________________________________________________
TTree *TFriendElement::GetTree()
{
   // Return pointer to friend TTree.

   if (fTree) return fTree;

   if (GetFile()) {
      fFile->GetObject(GetTreeName(),fTree);
      if (fTree) return fTree;
   }

   // This could be a memory tree or chain
   fTree = dynamic_cast<TTree*>( gROOT->FindObject(GetTreeName()) );

   return fTree;
}

//_______________________________________________________________________
void TFriendElement::ls(Option_t *) const
{
   // List this friend element.

   printf(" Friend Tree: %s in file: %s\n",GetName(),GetTitle());
}
<|endoftext|>


<commit_before>/******************************************************************************\
* File:          appl.cpp
* Purpose:       Implementation of classes for syncodbcquery
* Author:        Anton van Wezenbeek
* RCS-ID:        $Id$
*
* Copyright (c) 2008-2009, Anton van Wezenbeek
* All rights are reserved. Reproduction in whole or part is prohibited
* without the written consent of the copyright owner.
\******************************************************************************/

#include <wx/aboutdlg.h>
#include <wx/tokenzr.h>
#include <wx/extension/grid.h>
#include <wx/extension/shell.h>
#include <wx/extension/version.h>
#include <wx/extension/report/defs.h>
#include <wx/extension/report/stc.h>
#include "appl.h"

#ifndef __WXMSW__
#include "appl.xpm"
#endif

IMPLEMENT_APP(MyApp)

bool MyApp::OnInit()
{
  SetAppName("syncodbcquery");

  if (!wxExApp::OnInit())
  {
    return false;
  }

  MyFrame *frame = new MyFrame("syncodbcquery");
  frame->Show(true);

  SetTopWindow(frame);

  return true;
}

BEGIN_EVENT_TABLE(MyFrame, wxExFrameWithHistory)
  EVT_CLOSE(MyFrame::OnClose)
  EVT_MENU(wxID_EXECUTE, MyFrame::OnCommand)
  EVT_MENU(wxID_PREFERENCES, MyFrame::OnCommand)
  EVT_MENU(ID_SHELL_COMMAND, MyFrame::OnCommand)
  EVT_MENU(ID_SHELL_COMMAND_STOP, MyFrame::OnCommand)
  EVT_MENU_RANGE(wxID_LOWEST, wxID_HIGHEST, MyFrame::OnCommand)
  EVT_MENU_RANGE(ID_FIRST, ID_LAST, MyFrame::OnCommand)
  EVT_UPDATE_UI(wxID_SAVE, MyFrame::OnUpdateUI)
  EVT_UPDATE_UI(wxID_SAVEAS, MyFrame::OnUpdateUI)
  EVT_UPDATE_UI(wxID_STOP, MyFrame::OnUpdateUI)
  EVT_UPDATE_UI(ID_DATABASE_CLOSE, MyFrame::OnUpdateUI)
  EVT_UPDATE_UI(ID_DATABASE_OPEN, MyFrame::OnUpdateUI)
  EVT_UPDATE_UI(wxID_EXECUTE, MyFrame::OnUpdateUI)
  EVT_UPDATE_UI(ID_RECENTFILE_MENU, MyFrame::OnUpdateUI)
  EVT_UPDATE_UI(ID_VIEW_QUERY, MyFrame::OnUpdateUI)
  EVT_UPDATE_UI(ID_VIEW_RESULTS, MyFrame::OnUpdateUI)
  EVT_UPDATE_UI(ID_VIEW_STATISTICS, MyFrame::OnUpdateUI)
END_EVENT_TABLE()

MyFrame::MyFrame(const wxString& title)
  : wxExFrameWithHistory(NULL, wxID_ANY, title)
  , m_Running(false)
  , m_Stopped(false)
{
  SetIcon(wxICON(appl));

  wxExMenu* menuFile = new wxExMenu;
  menuFile->Append(wxID_OPEN);
  UseFileHistory(ID_RECENTFILE_MENU, menuFile);
  menuFile->AppendSeparator();
  menuFile->Append(wxID_SAVE);
  menuFile->Append(wxID_SAVEAS);
  menuFile->AppendSeparator();
  menuFile->Append(wxID_EXIT);

  wxExMenu* menuDatabase = new wxExMenu;
  menuDatabase->Append(ID_DATABASE_OPEN, wxExEllipsed(_("&Open")));
  menuDatabase->Append(ID_DATABASE_CLOSE, _("&Close"));

  wxExMenu* menuQuery = new wxExMenu;
  menuQuery->Append(wxID_EXECUTE);
  menuQuery->Append(wxID_STOP);

  wxMenu* menuOptions = new wxMenu();
  menuOptions->Append(wxID_PREFERENCES);

  wxMenu* menuView = new wxMenu();
  menuView->AppendCheckItem(ID_VIEW_STATUSBAR, _("&Statusbar"));
  menuView->AppendCheckItem(ID_VIEW_TOOLBAR, _("&Toolbar"));
  menuView->AppendSeparator();
  menuView->AppendCheckItem(ID_VIEW_QUERY, _("Query"));
  menuView->AppendCheckItem(ID_VIEW_RESULTS, _("Results"));
  menuView->AppendCheckItem(ID_VIEW_STATISTICS, _("Statistics"));

  wxMenu* menuHelp = new wxMenu();
  menuHelp->Append(wxID_ABOUT);

  wxMenuBar *menubar = new wxMenuBar;
  menubar->Append(menuFile, _("&File"));
  menubar->Append(menuView, _("&View"));
  menubar->Append(menuDatabase, _("&Database"));
  menubar->Append(menuQuery, _("&Query"));
  menubar->Append(menuOptions, _("&Options"));
  menubar->Append(menuHelp, _("&Help"));
  SetMenuBar(menubar);

  m_Query = new wxExSTCWithFrame(this);
  m_Query->SetLexer("sql");

  m_Results = new wxExGrid(this);
  m_Results->CreateGrid(0, 0);
  m_Results->EnableEditing(false); // this is a read-only grid

  m_Shell = new wxExSTCShell(this, ">", ";", true, 50);
  m_Shell->SetFocus();

  GetManager().AddPane(m_Shell,
    wxAuiPaneInfo().
      Name("CONSOLE").
      CenterPane());

  GetManager().AddPane(m_Results,
    wxAuiPaneInfo().
      Name("RESULTS").
      Caption(_("Results")).
      CloseButton(true).
      MaximizeButton(true));

  GetManager().AddPane(m_Query,
    wxAuiPaneInfo().
      Name("QUERY").
      Caption(_("Query")).
      CloseButton(true).
      MaximizeButton(true));

  GetManager().AddPane(m_Statistics.Show(this),
    wxAuiPaneInfo().Left().
      MaximizeButton(true).
      Caption(_("Statistics")).
      Name("STATISTICS"));

  GetManager().LoadPerspective(wxExApp::GetConfig("Perspective"));
  GetManager().GetPane("QUERY").Show(false);

  GetManager().Update();

  std::vector<wxExPane> panes;
  panes.push_back(wxExPane("PaneText", -3));
  panes.push_back(wxExPane("PaneLines", 100, _("Lines in window")));
  SetupStatusBar(panes);

  CreateToolBar();

  m_ToolBar->AddTool(wxID_NEW);
  m_ToolBar->AddTool(wxID_OPEN);
  m_ToolBar->AddTool(wxID_SAVE);

#ifdef __WXGTK__
  m_ToolBar->AddTool(wxID_EXECUTE);
#endif

  m_ToolBar->Realize();
}

void MyFrame::ConfigDialogApplied(wxWindowID dialogid)
{
  if (dialogid == wxID_PREFERENCES)
  {
    m_Query->ConfigGet();
    m_Shell->ConfigGet();
  }
  else
  {
    wxFAIL;
  }
}

void MyFrame::OnClose(wxCloseEvent& event)
{
  if (!m_Query->Continue())
  {
    return;
  }

  wxExApp::SetConfig("Perspective", GetManager().SavePerspective());

  event.Skip();
}

void MyFrame::OnCommand(wxCommandEvent& event)
{
  switch (event.GetId())
  {
  case wxID_ABOUT:
    {
    wxAboutDialogInfo info;
    info.SetIcon(GetIcon());
    info.SetDescription(_("This program offers a general ODBC query."));
    info.SetVersion("v1.0");
    info.SetCopyright("(c) 2008-2009, Anton van Wezenbeek");
    info.AddDeveloper(wxVERSION_STRING);
    info.AddDeveloper(wxEX_VERSION_STRING);
    info.AddDeveloper(wxExOTL::Version());
    wxAboutBox(info);
    }
    break;

  case wxID_EXECUTE:
    m_Stopped = false;
    RunQueries(m_Query->GetText());
    break;

  case wxID_EXIT:
    Close(true);
    break;

  case wxID_NEW:
    if (m_Query->FileNew())
    {
      m_Query->SetLexer("sql");
      m_Query->SetFocus();
      GetManager().GetPane("QUERY").Show();
      GetManager().Update();
    }
    break;

  case wxID_OPEN:
    DialogFileOpen(wxFD_OPEN | wxFD_CHANGE_DIR, "sql files (*.sql) | *.sql", true);
    break;

  case wxID_PREFERENCES:
    wxExSTC::ConfigDialog(this,
      _("Editor Options"),
      wxExSTC::STC_CONFIG_MODELESS |
      wxExSTC::STC_CONFIG_SIMPLE |
      wxExSTC::STC_CONFIG_WITH_APPLY,
      event.GetId());
    break;

  case wxID_SAVE:
    m_Query->FileSave();
    break;

  case wxID_SAVEAS:
    m_Query->FileSaveAs();
    break;

  case wxID_STOP:
    m_Running = false;
    m_Stopped = true;
    break;

  case ID_DATABASE_CLOSE:
    m_otl.GetConnect().logoff();
    m_Shell->SetPrompt(">");
    break;

  case ID_DATABASE_OPEN:
    m_otl.Logon(this, wxExApp::GetConfig());
    m_Shell->SetPrompt((m_otl.IsConnected() ? wxExApp::GetConfig(_("Datasource")): "") + ">");
    break;

  case ID_SHELL_COMMAND:
    if (m_otl.IsConnected())
    {
      try
      {
        const wxString query = event.GetString().substr(
          0,
          event.GetString().length() - 1);

        m_Stopped = false;
        RunQuery(query, true);
      }
      catch (otl_exception& p)
      {
        if (m_Results->IsShown())
        {
          m_Results->EndBatch();
        }

        m_Shell->AppendText(_("\nerror: ") + wxExQuoted(p.msg));
      }
    }
    else
    {
      m_Shell->AppendText(_("\nnot connected"));
    }

    m_Shell->Prompt();
    break;

  case ID_SHELL_COMMAND_STOP:
    m_Stopped = true;
    m_Shell->Prompt(_("cancelled"));
    break;

  case ID_VIEW_QUERY: TogglePane("QUERY"); break;
  case ID_VIEW_RESULTS: TogglePane("RESULTS"); break;
  case ID_VIEW_STATISTICS: TogglePane("STATISTICS"); break;

  default:
    wxFAIL;
  }
}

void MyFrame::OnUpdateUI(wxUpdateUIEvent& event)
{
  switch (event.GetId())
  {
  case wxID_EXECUTE:
    // If we have a query, you can hide it, but still run it.
    event.Enable(m_Query->GetLength() > 0 && m_otl.IsConnected());
    break;

  case wxID_SAVE:
    event.Enable(m_Query->GetModify());
    break;

  case wxID_SAVEAS:
    event.Enable(m_Query->GetLength() > 0);
    break;

  case wxID_STOP:
    event.Enable(m_Running);
    break;

  case ID_DATABASE_CLOSE:
    event.Enable(m_otl.IsConnected());
    break;

  case ID_DATABASE_OPEN:
    event.Enable(!m_otl.IsConnected());
    break;

  case ID_RECENTFILE_MENU:
    event.Enable(!GetRecentFile().empty());
    break;

  case ID_VIEW_QUERY:
    event.Check(GetManager().GetPane("QUERY").IsShown());
    break;

  case ID_VIEW_RESULTS:
    event.Check(GetManager().GetPane("RESULTS").IsShown());
    break;

  case ID_VIEW_STATISTICS:
    event.Check(GetManager().GetPane("STATISTICS").IsShown());
    break;

  default:
    wxFAIL;
  }
}

bool MyFrame::OpenFile(
  const wxExFileName& filename,
  int line_number,
  const wxString& match,
  long flags)
{
  GetManager().GetPane("QUERY").Show(true);
  GetManager().Update();

  // Take care that DialogFileOpen always results in opening in the query.
  // Otherwise if results are focused, the file is opened in the results.
  return m_Query->Open(filename, line_number, match, flags);
}

void MyFrame::RunQuery(const wxString& query, bool empty_results)
{
  wxStopWatch sw;

  const wxString query_lower = query.Lower();

  // Query functions supported by ODBC
  // $SQLTables, $SQLColumns, etc.
  // $SQLTables $1:'%'
  // allow you to get database schema.
  if (query_lower.StartsWith("select") ||
      query_lower.StartsWith("describe") ||
      query_lower.StartsWith("show") ||
      query_lower.StartsWith("explain") ||
      query_lower.StartsWith("$sql"))
  {
    long rpc;

    if (m_Results->IsShown())
    {
      rpc = m_otl.Query(query, m_Results, m_Stopped, empty_results);
    }
    else
    {
      rpc = m_otl.Query(query, m_Shell, m_Stopped);
    }

    sw.Pause();

    UpdateStatistics(sw, rpc);
  }
  else
  {
    const long rpc = m_otl.Query(query);

    sw.Pause();

    UpdateStatistics(sw, rpc);
  }

  m_Shell->DocumentEnd();
}

void MyFrame::RunQueries(const wxString& text)
{
  if (m_Results->IsShown())
  {
    m_Results->ClearGrid();
  }

  // Skip sql comments.
  wxString output = text;
  wxRegEx("--.*$", wxRE_NEWLINE).ReplaceAll(&output, "");

  // Queries are seperated by ; character.
  wxStringTokenizer tkz(output, ";");
  int no_queries = 0;

  wxStopWatch sw;
  m_Running = true;

  // Run all queries.
  while (tkz.HasMoreTokens() && !m_Stopped)
  {
    wxString query = tkz.GetNextToken();
    query.Trim(true);
    query.Trim(false);

    if (!query.empty())
    {
      try
      {
        RunQuery(query, no_queries == 0);
        no_queries++;
        wxTheApp->Yield();
      }
      catch (otl_exception& p)
      {
        m_Statistics.Inc(_("Number of query errors"));
        m_Shell->AppendText(
          _("\nerror: ") +  wxExQuoted(p.msg) +
          _(" in: ") + wxExQuoted(query));
      }
    }
  }

  m_Shell->Prompt(wxString::Format(_("\n%d queries (%.3f seconds)"),
    no_queries,
    (float)sw.Time() / (float)1000));

  m_Running = false;
}

void MyFrame::UpdateStatistics(const wxStopWatch& sw, long rpc)
{
  m_Shell->AppendText(wxString::Format(_("\n%d rows processed (%.3f seconds)"),
    rpc,
    (float)sw.Time() / (float)1000));

  m_Statistics.Set(_("Rows processed"), rpc);
  m_Statistics.Set(_("Query runtime"), sw.Time());

  m_Statistics.Inc(_("Total number of queries run"));
  m_Statistics.Inc(_("Total query runtime"), sw.Time());
  m_Statistics.Inc(_("Total rows processed"), rpc);
}
<commit_msg>removed redundant event table entries<commit_after>/******************************************************************************\
* File:          appl.cpp
* Purpose:       Implementation of classes for syncodbcquery
* Author:        Anton van Wezenbeek
* RCS-ID:        $Id$
*
* Copyright (c) 2008-2009, Anton van Wezenbeek
* All rights are reserved. Reproduction in whole or part is prohibited
* without the written consent of the copyright owner.
\******************************************************************************/

#include <wx/aboutdlg.h>
#include <wx/tokenzr.h>
#include <wx/extension/grid.h>
#include <wx/extension/shell.h>
#include <wx/extension/version.h>
#include <wx/extension/report/defs.h>
#include <wx/extension/report/stc.h>
#include "appl.h"

#ifndef __WXMSW__
#include "appl.xpm"
#endif

IMPLEMENT_APP(MyApp)

bool MyApp::OnInit()
{
  SetAppName("syncodbcquery");

  if (!wxExApp::OnInit())
  {
    return false;
  }

  MyFrame *frame = new MyFrame("syncodbcquery");
  frame->Show(true);

  SetTopWindow(frame);

  return true;
}

BEGIN_EVENT_TABLE(MyFrame, wxExFrameWithHistory)
  EVT_CLOSE(MyFrame::OnClose)
  EVT_MENU(ID_SHELL_COMMAND, MyFrame::OnCommand)
  EVT_MENU(ID_SHELL_COMMAND_STOP, MyFrame::OnCommand)
  EVT_MENU_RANGE(wxID_LOWEST, wxID_HIGHEST, MyFrame::OnCommand)
  EVT_MENU_RANGE(ID_FIRST, ID_LAST, MyFrame::OnCommand)
  EVT_UPDATE_UI(wxID_SAVE, MyFrame::OnUpdateUI)
  EVT_UPDATE_UI(wxID_SAVEAS, MyFrame::OnUpdateUI)
  EVT_UPDATE_UI(wxID_STOP, MyFrame::OnUpdateUI)
  EVT_UPDATE_UI(ID_DATABASE_CLOSE, MyFrame::OnUpdateUI)
  EVT_UPDATE_UI(ID_DATABASE_OPEN, MyFrame::OnUpdateUI)
  EVT_UPDATE_UI(wxID_EXECUTE, MyFrame::OnUpdateUI)
  EVT_UPDATE_UI(ID_RECENTFILE_MENU, MyFrame::OnUpdateUI)
  EVT_UPDATE_UI(ID_VIEW_QUERY, MyFrame::OnUpdateUI)
  EVT_UPDATE_UI(ID_VIEW_RESULTS, MyFrame::OnUpdateUI)
  EVT_UPDATE_UI(ID_VIEW_STATISTICS, MyFrame::OnUpdateUI)
END_EVENT_TABLE()

MyFrame::MyFrame(const wxString& title)
  : wxExFrameWithHistory(NULL, wxID_ANY, title)
  , m_Running(false)
  , m_Stopped(false)
{
  SetIcon(wxICON(appl));

  wxExMenu* menuFile = new wxExMenu;
  menuFile->Append(wxID_OPEN);
  UseFileHistory(ID_RECENTFILE_MENU, menuFile);
  menuFile->AppendSeparator();
  menuFile->Append(wxID_SAVE);
  menuFile->Append(wxID_SAVEAS);
  menuFile->AppendSeparator();
  menuFile->Append(wxID_EXIT);

  wxExMenu* menuDatabase = new wxExMenu;
  menuDatabase->Append(ID_DATABASE_OPEN, wxExEllipsed(_("&Open")));
  menuDatabase->Append(ID_DATABASE_CLOSE, _("&Close"));

  wxExMenu* menuQuery = new wxExMenu;
  menuQuery->Append(wxID_EXECUTE);
  menuQuery->Append(wxID_STOP);

  wxMenu* menuOptions = new wxMenu();
  menuOptions->Append(wxID_PREFERENCES);

  wxMenu* menuView = new wxMenu();
  menuView->AppendCheckItem(ID_VIEW_STATUSBAR, _("&Statusbar"));
  menuView->AppendCheckItem(ID_VIEW_TOOLBAR, _("&Toolbar"));
  menuView->AppendSeparator();
  menuView->AppendCheckItem(ID_VIEW_QUERY, _("Query"));
  menuView->AppendCheckItem(ID_VIEW_RESULTS, _("Results"));
  menuView->AppendCheckItem(ID_VIEW_STATISTICS, _("Statistics"));

  wxMenu* menuHelp = new wxMenu();
  menuHelp->Append(wxID_ABOUT);

  wxMenuBar *menubar = new wxMenuBar;
  menubar->Append(menuFile, _("&File"));
  menubar->Append(menuView, _("&View"));
  menubar->Append(menuDatabase, _("&Database"));
  menubar->Append(menuQuery, _("&Query"));
  menubar->Append(menuOptions, _("&Options"));
  menubar->Append(menuHelp, _("&Help"));
  SetMenuBar(menubar);

  m_Query = new wxExSTCWithFrame(this);
  m_Query->SetLexer("sql");

  m_Results = new wxExGrid(this);
  m_Results->CreateGrid(0, 0);
  m_Results->EnableEditing(false); // this is a read-only grid

  m_Shell = new wxExSTCShell(this, ">", ";", true, 50);
  m_Shell->SetFocus();

  GetManager().AddPane(m_Shell,
    wxAuiPaneInfo().
      Name("CONSOLE").
      CenterPane());

  GetManager().AddPane(m_Results,
    wxAuiPaneInfo().
      Name("RESULTS").
      Caption(_("Results")).
      CloseButton(true).
      MaximizeButton(true));

  GetManager().AddPane(m_Query,
    wxAuiPaneInfo().
      Name("QUERY").
      Caption(_("Query")).
      CloseButton(true).
      MaximizeButton(true));

  GetManager().AddPane(m_Statistics.Show(this),
    wxAuiPaneInfo().Left().
      MaximizeButton(true).
      Caption(_("Statistics")).
      Name("STATISTICS"));

  GetManager().LoadPerspective(wxExApp::GetConfig("Perspective"));
  GetManager().GetPane("QUERY").Show(false);

  GetManager().Update();

  std::vector<wxExPane> panes;
  panes.push_back(wxExPane("PaneText", -3));
  panes.push_back(wxExPane("PaneLines", 100, _("Lines in window")));
  SetupStatusBar(panes);

  CreateToolBar();

  m_ToolBar->AddTool(wxID_NEW);
  m_ToolBar->AddTool(wxID_OPEN);
  m_ToolBar->AddTool(wxID_SAVE);

#ifdef __WXGTK__
  m_ToolBar->AddTool(wxID_EXECUTE);
#endif

  m_ToolBar->Realize();
}

void MyFrame::ConfigDialogApplied(wxWindowID dialogid)
{
  if (dialogid == wxID_PREFERENCES)
  {
    m_Query->ConfigGet();
    m_Shell->ConfigGet();
  }
  else
  {
    wxFAIL;
  }
}

void MyFrame::OnClose(wxCloseEvent& event)
{
  if (!m_Query->Continue())
  {
    return;
  }

  wxExApp::SetConfig("Perspective", GetManager().SavePerspective());

  event.Skip();
}

void MyFrame::OnCommand(wxCommandEvent& event)
{
  switch (event.GetId())
  {
  case wxID_ABOUT:
    {
    wxAboutDialogInfo info;
    info.SetIcon(GetIcon());
    info.SetDescription(_("This program offers a general ODBC query."));
    info.SetVersion("v1.0");
    info.SetCopyright("(c) 2008-2009, Anton van Wezenbeek");
    info.AddDeveloper(wxVERSION_STRING);
    info.AddDeveloper(wxEX_VERSION_STRING);
    info.AddDeveloper(wxExOTL::Version());
    wxAboutBox(info);
    }
    break;

  case wxID_EXECUTE:
    m_Stopped = false;
    RunQueries(m_Query->GetText());
    break;

  case wxID_EXIT:
    Close(true);
    break;

  case wxID_NEW:
    if (m_Query->FileNew())
    {
      m_Query->SetLexer("sql");
      m_Query->SetFocus();
      GetManager().GetPane("QUERY").Show();
      GetManager().Update();
    }
    break;

  case wxID_OPEN:
    DialogFileOpen(wxFD_OPEN | wxFD_CHANGE_DIR, "sql files (*.sql) | *.sql", true);
    break;

  case wxID_PREFERENCES:
    wxExSTC::ConfigDialog(this,
      _("Editor Options"),
      wxExSTC::STC_CONFIG_MODELESS |
      wxExSTC::STC_CONFIG_SIMPLE |
      wxExSTC::STC_CONFIG_WITH_APPLY,
      event.GetId());
    break;

  case wxID_SAVE:
    m_Query->FileSave();
    break;

  case wxID_SAVEAS:
    m_Query->FileSaveAs();
    break;

  case wxID_STOP:
    m_Running = false;
    m_Stopped = true;
    break;

  case ID_DATABASE_CLOSE:
    m_otl.GetConnect().logoff();
    m_Shell->SetPrompt(">");
    break;

  case ID_DATABASE_OPEN:
    m_otl.Logon(this, wxExApp::GetConfig());
    m_Shell->SetPrompt((m_otl.IsConnected() ? wxExApp::GetConfig(_("Datasource")): "") + ">");
    break;

  case ID_SHELL_COMMAND:
    if (m_otl.IsConnected())
    {
      try
      {
        const wxString query = event.GetString().substr(
          0,
          event.GetString().length() - 1);

        m_Stopped = false;
        RunQuery(query, true);
      }
      catch (otl_exception& p)
      {
        if (m_Results->IsShown())
        {
          m_Results->EndBatch();
        }

        m_Shell->AppendText(_("\nerror: ") + wxExQuoted(p.msg));
      }
    }
    else
    {
      m_Shell->AppendText(_("\nnot connected"));
    }

    m_Shell->Prompt();
    break;

  case ID_SHELL_COMMAND_STOP:
    m_Stopped = true;
    m_Shell->Prompt(_("cancelled"));
    break;

  case ID_VIEW_QUERY: TogglePane("QUERY"); break;
  case ID_VIEW_RESULTS: TogglePane("RESULTS"); break;
  case ID_VIEW_STATISTICS: TogglePane("STATISTICS"); break;

  default:
    wxFAIL;
  }
}

void MyFrame::OnUpdateUI(wxUpdateUIEvent& event)
{
  switch (event.GetId())
  {
  case wxID_EXECUTE:
    // If we have a query, you can hide it, but still run it.
    event.Enable(m_Query->GetLength() > 0 && m_otl.IsConnected());
    break;

  case wxID_SAVE:
    event.Enable(m_Query->GetModify());
    break;

  case wxID_SAVEAS:
    event.Enable(m_Query->GetLength() > 0);
    break;

  case wxID_STOP:
    event.Enable(m_Running);
    break;

  case ID_DATABASE_CLOSE:
    event.Enable(m_otl.IsConnected());
    break;

  case ID_DATABASE_OPEN:
    event.Enable(!m_otl.IsConnected());
    break;

  case ID_RECENTFILE_MENU:
    event.Enable(!GetRecentFile().empty());
    break;

  case ID_VIEW_QUERY:
    event.Check(GetManager().GetPane("QUERY").IsShown());
    break;

  case ID_VIEW_RESULTS:
    event.Check(GetManager().GetPane("RESULTS").IsShown());
    break;

  case ID_VIEW_STATISTICS:
    event.Check(GetManager().GetPane("STATISTICS").IsShown());
    break;

  default:
    wxFAIL;
  }
}

bool MyFrame::OpenFile(
  const wxExFileName& filename,
  int line_number,
  const wxString& match,
  long flags)
{
  GetManager().GetPane("QUERY").Show(true);
  GetManager().Update();

  // Take care that DialogFileOpen always results in opening in the query.
  // Otherwise if results are focused, the file is opened in the results.
  return m_Query->Open(filename, line_number, match, flags);
}

void MyFrame::RunQuery(const wxString& query, bool empty_results)
{
  wxStopWatch sw;

  const wxString query_lower = query.Lower();

  // Query functions supported by ODBC
  // $SQLTables, $SQLColumns, etc.
  // $SQLTables $1:'%'
  // allow you to get database schema.
  if (query_lower.StartsWith("select") ||
      query_lower.StartsWith("describe") ||
      query_lower.StartsWith("show") ||
      query_lower.StartsWith("explain") ||
      query_lower.StartsWith("$sql"))
  {
    long rpc;

    if (m_Results->IsShown())
    {
      rpc = m_otl.Query(query, m_Results, m_Stopped, empty_results);
    }
    else
    {
      rpc = m_otl.Query(query, m_Shell, m_Stopped);
    }

    sw.Pause();

    UpdateStatistics(sw, rpc);
  }
  else
  {
    const long rpc = m_otl.Query(query);

    sw.Pause();

    UpdateStatistics(sw, rpc);
  }

  m_Shell->DocumentEnd();
}

void MyFrame::RunQueries(const wxString& text)
{
  if (m_Results->IsShown())
  {
    m_Results->ClearGrid();
  }

  // Skip sql comments.
  wxString output = text;
  wxRegEx("--.*$", wxRE_NEWLINE).ReplaceAll(&output, "");

  // Queries are seperated by ; character.
  wxStringTokenizer tkz(output, ";");
  int no_queries = 0;

  wxStopWatch sw;
  m_Running = true;

  // Run all queries.
  while (tkz.HasMoreTokens() && !m_Stopped)
  {
    wxString query = tkz.GetNextToken();
    query.Trim(true);
    query.Trim(false);

    if (!query.empty())
    {
      try
      {
        RunQuery(query, no_queries == 0);
        no_queries++;
        wxTheApp->Yield();
      }
      catch (otl_exception& p)
      {
        m_Statistics.Inc(_("Number of query errors"));
        m_Shell->AppendText(
          _("\nerror: ") +  wxExQuoted(p.msg) +
          _(" in: ") + wxExQuoted(query));
      }
    }
  }

  m_Shell->Prompt(wxString::Format(_("\n%d queries (%.3f seconds)"),
    no_queries,
    (float)sw.Time() / (float)1000));

  m_Running = false;
}

void MyFrame::UpdateStatistics(const wxStopWatch& sw, long rpc)
{
  m_Shell->AppendText(wxString::Format(_("\n%d rows processed (%.3f seconds)"),
    rpc,
    (float)sw.Time() / (float)1000));

  m_Statistics.Set(_("Rows processed"), rpc);
  m_Statistics.Set(_("Query runtime"), sw.Time());

  m_Statistics.Inc(_("Total number of queries run"));
  m_Statistics.Inc(_("Total query runtime"), sw.Time());
  m_Statistics.Inc(_("Total rows processed"), rpc);
}
<|endoftext|>


<commit_before>/******************************************************************************\
* File:          appl.cpp
* Purpose:       Implementation of classes for syncodbcquery
* Author:        Anton van Wezenbeek
* RCS-ID:        $Id$
*
* Copyright (c) 2008-2009, Anton van Wezenbeek
* All rights are reserved. Reproduction in whole or part is prohibited
* without the written consent of the copyright owner.
\******************************************************************************/

#include <wx/aboutdlg.h>
#include <wx/tokenzr.h>
#include <wx/extension/grid.h>
#include <wx/extension/shell.h>
#include <wx/extension/version.h>
#include <wx/extension/report/defs.h>
#include <wx/extension/report/stc.h>
#include "appl.h"
#include "appl.xpm"

const wxString Quoted(const wxString& text)
{
  return "'" + text + "'";
}

IMPLEMENT_APP(MyApp)

bool MyApp::OnInit()
{
  SetAppName("syncodbcquery");

  if (!wxExApp::OnInit())
  {
    return false;
  }

  MyFrame *frame = new MyFrame("syncodbcquery");
  frame->Show(true);

  SetTopWindow(frame);

  return true;
}

BEGIN_EVENT_TABLE(MyFrame, wxExFrameWithHistory)
  EVT_CLOSE(MyFrame::OnClose)
  EVT_MENU(wxID_EXECUTE, MyFrame::OnCommand)
  EVT_MENU(wxID_PREFERENCES, MyFrame::OnCommand)
  EVT_MENU(ID_SHELL_COMMAND, MyFrame::OnCommand)
  EVT_MENU(ID_SHELL_COMMAND_STOP, MyFrame::OnCommand)
  EVT_MENU_RANGE(wxID_LOWEST, wxID_HIGHEST, MyFrame::OnCommand)
  EVT_MENU_RANGE(ID_FIRST, ID_LAST, MyFrame::OnCommand)
  EVT_UPDATE_UI(wxID_SAVE, MyFrame::OnUpdateUI)
  EVT_UPDATE_UI(wxID_SAVEAS, MyFrame::OnUpdateUI)
  EVT_UPDATE_UI(wxID_STOP, MyFrame::OnUpdateUI)
  EVT_UPDATE_UI(ID_DATABASE_CLOSE, MyFrame::OnUpdateUI)
  EVT_UPDATE_UI(ID_DATABASE_OPEN, MyFrame::OnUpdateUI)
  EVT_UPDATE_UI(wxID_EXECUTE, MyFrame::OnUpdateUI)
  EVT_UPDATE_UI(ID_RECENTFILE_MENU, MyFrame::OnUpdateUI)
  EVT_UPDATE_UI(ID_VIEW_QUERY, MyFrame::OnUpdateUI)
  EVT_UPDATE_UI(ID_VIEW_RESULTS, MyFrame::OnUpdateUI)
  EVT_UPDATE_UI(ID_VIEW_STATISTICS, MyFrame::OnUpdateUI)
END_EVENT_TABLE()

MyFrame::MyFrame(const wxString& title)
  : wxExFrameWithHistory(NULL, wxID_ANY, title)
  , m_Running(false)
  , m_Stopped(false)
{
  SetIcon(appl_xpm);

  wxExMenu* menuFile = new wxExMenu;
  menuFile->Append(wxID_OPEN);
  UseFileHistory(ID_RECENTFILE_MENU, menuFile);
  menuFile->AppendSeparator();
  menuFile->Append(wxID_SAVE);
  menuFile->Append(wxID_SAVEAS);
  menuFile->AppendSeparator();
  menuFile->Append(wxID_EXIT);

  wxExMenu* menuDatabase = new wxExMenu;
  menuDatabase->Append(ID_DATABASE_OPEN, wxExEllipsed(_("&Open")));
  menuDatabase->Append(ID_DATABASE_CLOSE, _("&Close"));

  wxExMenu* menuQuery = new wxExMenu;
  menuQuery->Append(wxID_EXECUTE);
  menuQuery->Append(wxID_STOP);

  wxMenu* menuOptions = new wxMenu();
  menuOptions->Append(wxID_PREFERENCES);

  wxMenu* menuView = new wxMenu();
  menuView->AppendCheckItem(ID_VIEW_STATUSBAR, _("&Statusbar"));
  menuView->AppendCheckItem(ID_VIEW_TOOLBAR, _("&Toolbar"));
  menuView->AppendSeparator();
  menuView->AppendCheckItem(ID_VIEW_QUERY, _("Query"));
  menuView->AppendCheckItem(ID_VIEW_RESULTS, _("Results"));
  menuView->AppendCheckItem(ID_VIEW_STATISTICS, _("Statistics"));

  wxMenu* menuHelp = new wxMenu();
  menuHelp->Append(wxID_ABOUT);

  wxMenuBar *menubar = new wxMenuBar;
  menubar->Append(menuFile, _("&File"));
  menubar->Append(menuView, _("&View"));
  menubar->Append(menuDatabase, _("&Database"));
  menubar->Append(menuQuery, _("&Query"));
  menubar->Append(menuOptions, _("&Options"));
  menubar->Append(menuHelp, _("&Help"));
  SetMenuBar(menubar);

  m_Query = new wxExSTCWithFrame(this,
    wxExSTC::STC_MENU_SIMPLE | wxExSTC::STC_MENU_FIND |
    wxExSTC::STC_MENU_REPLACE | wxExSTC::STC_MENU_INSERT);
  m_Query->SetLexer("sql");

  m_Results = new wxExGrid(this);
  m_Results->CreateGrid(0, 0);
  m_Results->EnableEditing(false); // this is a read-only grid

  m_Shell = new wxExSTCShell(this, ">", ";", true, 50);
  m_Shell->SetFocus();
  m_Shell->DocumentEnd();
  m_Shell->SetLexer();

  GetManager().AddPane(m_Shell,
    wxAuiPaneInfo().
      Name("CONSOLE").
      CenterPane());

  GetManager().AddPane(m_Results,
    wxAuiPaneInfo().
      Name("RESULTS").
      Caption(_("Results")).
      CloseButton(true).
      MaximizeButton(true));

  GetManager().AddPane(m_Query,
    wxAuiPaneInfo().
      Name("QUERY").
      Caption(_("Query")).
      CloseButton(true).
      MaximizeButton(true));

  GetManager().AddPane(m_Statistics.Show(this),
    wxAuiPaneInfo().Left().
      MaximizeButton(true).
      Caption(_("Statistics")).
      Name("STATISTICS"));

  GetManager().LoadPerspective(wxExApp::GetConfig("Perspective"));
  GetManager().GetPane("QUERY").Show(false);

  GetManager().Update();

  std::vector<wxExPane> panes;
  panes.push_back(wxExPane("PaneText", -3));
  panes.push_back(wxExPane("PaneLines", 100, _("Lines in window")));
  SetupStatusBar(panes);

  CreateToolBar();

  m_ToolBar->AddTool(wxID_NEW);
  m_ToolBar->AddTool(wxID_OPEN);
  m_ToolBar->AddTool(wxID_SAVE);

#ifdef __WXGTK__
  m_ToolBar->AddTool(wxID_EXECUTE);
#endif

  m_ToolBar->Realize();

  otl_connect::otl_initialize();
}

void MyFrame::ConfigDialogApplied(wxWindowID WXUNUSED(dialogid))
{
  m_Query->ConfigGet();
  m_Shell->ConfigGet();
}

void MyFrame::OnClose(wxCloseEvent& event)
{
  if (!m_Query->Continue())
  {
    return;
  }

  wxExApp::SetConfig("Perspective", GetManager().SavePerspective());

  m_db.logoff();

  event.Skip();
}

void MyFrame::OnCommand(wxCommandEvent& event)
{
  switch (event.GetId())
  {
  case wxID_ABOUT:
    {
    wxAboutDialogInfo info;
    info.SetIcon(GetIcon());
    info.SetDescription(_("This program offers a general ODBC query."));
    info.SetVersion("v1.0");
    info.SetCopyright("(c) 2008-2009, Anton van Wezenbeek");
    info.AddDeveloper(wxVERSION_STRING);
    info.AddDeveloper(wxEX_VERSION_STRING);
    info.AddDeveloper(wxExOTLVersion());
    wxAboutBox(info);
    }
    break;

  case wxID_EXECUTE:
    m_Stopped = false;
    RunQueries(m_Query->GetText());
    break;

  case wxID_EXIT:
    Close(true);
    break;

  case wxID_NEW:
    if (m_Query->FileNew())
    {
      m_Query->SetLexer("sql");
      m_Query->SetFocus();
      GetManager().GetPane("QUERY").Show();
      GetManager().Update();
    }
    break;

  case wxID_OPEN:
    DialogFileOpen(wxFD_OPEN | wxFD_CHANGE_DIR, "sql files (*.sql) | *.sql", true);
    break;

  case wxID_PREFERENCES:
    wxExSTC::ConfigDialog(_("Editor Options"),
      wxExSTC::STC_CONFIG_SIMPLE | wxExSTC::STC_CONFIG_MODELESS);
    break;

  case wxID_SAVE:
    m_Query->FileSave();
    break;

  case wxID_SAVEAS:
    m_Query->FileSaveAs();
    break;

  case wxID_STOP:
    m_Running = false;
    m_Stopped = true;
    break;

  case ID_DATABASE_CLOSE:
    m_db.logoff();
    m_Shell->SetPrompt(">");
    break;

  case ID_DATABASE_OPEN:
    wxExOTLDialog(wxExApp::GetConfig(), &m_db);
    m_Shell->SetPrompt((m_db.connected ? wxExApp::GetConfig(_("Datasource")): "") + ">");
    break;

  case ID_SHELL_COMMAND:
    if (m_db.connected)
    {
      try
      {
        const wxString query = event.GetString().substr(
          0,
          event.GetString().length() - 1);

        m_Stopped = false;
        RunQuery(query, true);
      }
      catch (otl_exception& p)
      {
        if (m_Results->IsShown())
        {
          m_Results->EndBatch();
        }

        m_Shell->AppendText(_("\nerror: ") + Quoted(p.msg));
      }
    }
    else
    {
      m_Shell->AppendText(_("\nnot connected"));
    }

    m_Shell->Prompt();
    break;

  case ID_SHELL_COMMAND_STOP:
    m_Stopped = true;
    m_Shell->Prompt("Cancelled");
    break;

  case ID_VIEW_QUERY: TogglePane("QUERY"); break;
  case ID_VIEW_RESULTS: TogglePane("RESULTS"); break;
  case ID_VIEW_STATISTICS: TogglePane("STATISTICS"); break;

  default: event.Skip();
  }
}

void MyFrame::OnUpdateUI(wxUpdateUIEvent& event)
{
  switch (event.GetId())
  {
  case wxID_EXECUTE:
    // If we have a query, you can hide it, but still run it.
    event.Enable(m_Query->GetLength() > 0 && m_db.connected);
    break;

  case wxID_SAVE:
    event.Enable(m_Query->GetModify());
    break;

  case wxID_SAVEAS:
    event.Enable(m_Query->GetLength() > 0);
    break;

  case wxID_STOP:
    event.Enable(m_Running);
    break;

  case ID_DATABASE_CLOSE:
    event.Enable(m_db.connected > 0);
    break;

  case ID_DATABASE_OPEN:
    event.Enable(!m_db.connected);
    break;

  case ID_RECENTFILE_MENU:
    event.Enable(!GetRecentFile().empty());
    break;

  case ID_VIEW_QUERY:
    event.Check(GetManager().GetPane("QUERY").IsShown());
    break;

  case ID_VIEW_RESULTS:
    event.Check(GetManager().GetPane("RESULTS").IsShown());
    break;

  case ID_VIEW_STATISTICS:
    event.Check(GetManager().GetPane("STATISTICS").IsShown());
    break;

  default:
    wxFAIL;
  }
}

bool MyFrame::OpenFile(
  const wxExFileName& filename,
  int line_number,
  const wxString& match,
  long flags)
{
  GetManager().GetPane("QUERY").Show(true);
  GetManager().Update();

  // Take care that DialogFileOpen always results in opening in the query.
  // Otherwise if results are focused, the file is opened in the results.
  return m_Query->Open(filename, line_number, match, flags);
}

void MyFrame::RunQuery(const wxString& query, bool empty_results)
{
  wxStopWatch sw;

  const wxString query_lower = query.Lower();

  // Query functions supported by ODBC
  // $SQLTables, $SQLColumns, etc.
  // $SQLTables $1:'%'
  // allow you to get database schema.
  if (query_lower.StartsWith("select") ||
      query_lower.StartsWith("describe") ||
      query_lower.StartsWith("show") ||
      query_lower.StartsWith("explain") ||
      query_lower.StartsWith("$sql"))
  {
    long rpc;

    if (m_Results->IsShown())
    {
      rpc = wxExOTLQueryToGrid(&m_db, query, m_Results, m_Stopped, empty_results);
    }
    else
    {
      rpc = wxExOTLQueryToSTC(&m_db, query, m_Shell, m_Stopped);
    }

    sw.Pause();

    UpdateStatistics(sw, rpc);
  }
  else
  {
    const long rpc = otl_cursor::direct_exec(m_db, query.c_str());
    sw.Pause();

    UpdateStatistics(sw, rpc);
  }

  m_Shell->DocumentEnd();
}

void MyFrame::RunQueries(const wxString& text)
{
  if (m_Results->IsShown())
  {
    m_Results->ClearGrid();
  }

  // Skip sql comments.
  wxString output = text;
  wxRegEx("--.*$", wxRE_NEWLINE).ReplaceAll(&output, "");

  // Queries are seperated by ; character.
  wxStringTokenizer tkz(output, ";");
  int no_queries = 0;

  wxStopWatch sw;
  m_Running = true;

  // Run all queries.
  while (tkz.HasMoreTokens() && !m_Stopped)
  {
    wxString query = tkz.GetNextToken();
    query.Trim(true);
    query.Trim(false);

    if (!query.empty())
    {
      try
      {
        RunQuery(query, no_queries == 0);
        no_queries++;
        wxYield();
      }
      catch (otl_exception& p)
      {
        m_Statistics.Inc(_("Number of query errors"));
        m_Shell->AppendText(_("\nerror: ") +  Quoted(p.msg) + _(" in: ") + Quoted(query));
      }
    }
  }

  m_Shell->Prompt(wxString::Format(_("\n%d queries (%.3f seconds)"),
    no_queries,
    (float)sw.Time() / (float)1000));

  m_Running = false;
}

void MyFrame::UpdateStatistics(const wxStopWatch& sw, long rpc)
{
  m_Shell->AppendText(wxString::Format(_("\n%d rows processed (%.3f seconds)"),
    rpc,
    (float)sw.Time() / (float)1000));

  m_Statistics.Set(_("Rows processed"), rpc);
  m_Statistics.Set(_("Query runtime"), sw.Time());

  m_Statistics.Inc(_("Total number of queries run"));
  m_Statistics.Inc(_("Total query runtime"), sw.Time());
  m_Statistics.Inc(_("Total rows processed"), rpc);
}
<commit_msg>made canceled translatable<commit_after>/******************************************************************************\
* File:          appl.cpp
* Purpose:       Implementation of classes for syncodbcquery
* Author:        Anton van Wezenbeek
* RCS-ID:        $Id$
*
* Copyright (c) 2008-2009, Anton van Wezenbeek
* All rights are reserved. Reproduction in whole or part is prohibited
* without the written consent of the copyright owner.
\******************************************************************************/

#include <wx/aboutdlg.h>
#include <wx/tokenzr.h>
#include <wx/extension/grid.h>
#include <wx/extension/shell.h>
#include <wx/extension/version.h>
#include <wx/extension/report/defs.h>
#include <wx/extension/report/stc.h>
#include "appl.h"
#include "appl.xpm"

const wxString Quoted(const wxString& text)
{
  return "'" + text + "'";
}

IMPLEMENT_APP(MyApp)

bool MyApp::OnInit()
{
  SetAppName("syncodbcquery");

  if (!wxExApp::OnInit())
  {
    return false;
  }

  MyFrame *frame = new MyFrame("syncodbcquery");
  frame->Show(true);

  SetTopWindow(frame);

  return true;
}

BEGIN_EVENT_TABLE(MyFrame, wxExFrameWithHistory)
  EVT_CLOSE(MyFrame::OnClose)
  EVT_MENU(wxID_EXECUTE, MyFrame::OnCommand)
  EVT_MENU(wxID_PREFERENCES, MyFrame::OnCommand)
  EVT_MENU(ID_SHELL_COMMAND, MyFrame::OnCommand)
  EVT_MENU(ID_SHELL_COMMAND_STOP, MyFrame::OnCommand)
  EVT_MENU_RANGE(wxID_LOWEST, wxID_HIGHEST, MyFrame::OnCommand)
  EVT_MENU_RANGE(ID_FIRST, ID_LAST, MyFrame::OnCommand)
  EVT_UPDATE_UI(wxID_SAVE, MyFrame::OnUpdateUI)
  EVT_UPDATE_UI(wxID_SAVEAS, MyFrame::OnUpdateUI)
  EVT_UPDATE_UI(wxID_STOP, MyFrame::OnUpdateUI)
  EVT_UPDATE_UI(ID_DATABASE_CLOSE, MyFrame::OnUpdateUI)
  EVT_UPDATE_UI(ID_DATABASE_OPEN, MyFrame::OnUpdateUI)
  EVT_UPDATE_UI(wxID_EXECUTE, MyFrame::OnUpdateUI)
  EVT_UPDATE_UI(ID_RECENTFILE_MENU, MyFrame::OnUpdateUI)
  EVT_UPDATE_UI(ID_VIEW_QUERY, MyFrame::OnUpdateUI)
  EVT_UPDATE_UI(ID_VIEW_RESULTS, MyFrame::OnUpdateUI)
  EVT_UPDATE_UI(ID_VIEW_STATISTICS, MyFrame::OnUpdateUI)
END_EVENT_TABLE()

MyFrame::MyFrame(const wxString& title)
  : wxExFrameWithHistory(NULL, wxID_ANY, title)
  , m_Running(false)
  , m_Stopped(false)
{
  SetIcon(appl_xpm);

  wxExMenu* menuFile = new wxExMenu;
  menuFile->Append(wxID_OPEN);
  UseFileHistory(ID_RECENTFILE_MENU, menuFile);
  menuFile->AppendSeparator();
  menuFile->Append(wxID_SAVE);
  menuFile->Append(wxID_SAVEAS);
  menuFile->AppendSeparator();
  menuFile->Append(wxID_EXIT);

  wxExMenu* menuDatabase = new wxExMenu;
  menuDatabase->Append(ID_DATABASE_OPEN, wxExEllipsed(_("&Open")));
  menuDatabase->Append(ID_DATABASE_CLOSE, _("&Close"));

  wxExMenu* menuQuery = new wxExMenu;
  menuQuery->Append(wxID_EXECUTE);
  menuQuery->Append(wxID_STOP);

  wxMenu* menuOptions = new wxMenu();
  menuOptions->Append(wxID_PREFERENCES);

  wxMenu* menuView = new wxMenu();
  menuView->AppendCheckItem(ID_VIEW_STATUSBAR, _("&Statusbar"));
  menuView->AppendCheckItem(ID_VIEW_TOOLBAR, _("&Toolbar"));
  menuView->AppendSeparator();
  menuView->AppendCheckItem(ID_VIEW_QUERY, _("Query"));
  menuView->AppendCheckItem(ID_VIEW_RESULTS, _("Results"));
  menuView->AppendCheckItem(ID_VIEW_STATISTICS, _("Statistics"));

  wxMenu* menuHelp = new wxMenu();
  menuHelp->Append(wxID_ABOUT);

  wxMenuBar *menubar = new wxMenuBar;
  menubar->Append(menuFile, _("&File"));
  menubar->Append(menuView, _("&View"));
  menubar->Append(menuDatabase, _("&Database"));
  menubar->Append(menuQuery, _("&Query"));
  menubar->Append(menuOptions, _("&Options"));
  menubar->Append(menuHelp, _("&Help"));
  SetMenuBar(menubar);

  m_Query = new wxExSTCWithFrame(this,
    wxExSTC::STC_MENU_SIMPLE | wxExSTC::STC_MENU_FIND |
    wxExSTC::STC_MENU_REPLACE | wxExSTC::STC_MENU_INSERT);
  m_Query->SetLexer("sql");

  m_Results = new wxExGrid(this);
  m_Results->CreateGrid(0, 0);
  m_Results->EnableEditing(false); // this is a read-only grid

  m_Shell = new wxExSTCShell(this, ">", ";", true, 50);
  m_Shell->SetFocus();
  m_Shell->DocumentEnd();
  m_Shell->SetLexer();

  GetManager().AddPane(m_Shell,
    wxAuiPaneInfo().
      Name("CONSOLE").
      CenterPane());

  GetManager().AddPane(m_Results,
    wxAuiPaneInfo().
      Name("RESULTS").
      Caption(_("Results")).
      CloseButton(true).
      MaximizeButton(true));

  GetManager().AddPane(m_Query,
    wxAuiPaneInfo().
      Name("QUERY").
      Caption(_("Query")).
      CloseButton(true).
      MaximizeButton(true));

  GetManager().AddPane(m_Statistics.Show(this),
    wxAuiPaneInfo().Left().
      MaximizeButton(true).
      Caption(_("Statistics")).
      Name("STATISTICS"));

  GetManager().LoadPerspective(wxExApp::GetConfig("Perspective"));
  GetManager().GetPane("QUERY").Show(false);

  GetManager().Update();

  std::vector<wxExPane> panes;
  panes.push_back(wxExPane("PaneText", -3));
  panes.push_back(wxExPane("PaneLines", 100, _("Lines in window")));
  SetupStatusBar(panes);

  CreateToolBar();

  m_ToolBar->AddTool(wxID_NEW);
  m_ToolBar->AddTool(wxID_OPEN);
  m_ToolBar->AddTool(wxID_SAVE);

#ifdef __WXGTK__
  m_ToolBar->AddTool(wxID_EXECUTE);
#endif

  m_ToolBar->Realize();

  otl_connect::otl_initialize();
}

void MyFrame::ConfigDialogApplied(wxWindowID WXUNUSED(dialogid))
{
  m_Query->ConfigGet();
  m_Shell->ConfigGet();
}

void MyFrame::OnClose(wxCloseEvent& event)
{
  if (!m_Query->Continue())
  {
    return;
  }

  wxExApp::SetConfig("Perspective", GetManager().SavePerspective());

  m_db.logoff();

  event.Skip();
}

void MyFrame::OnCommand(wxCommandEvent& event)
{
  switch (event.GetId())
  {
  case wxID_ABOUT:
    {
    wxAboutDialogInfo info;
    info.SetIcon(GetIcon());
    info.SetDescription(_("This program offers a general ODBC query."));
    info.SetVersion("v1.0");
    info.SetCopyright("(c) 2008-2009, Anton van Wezenbeek");
    info.AddDeveloper(wxVERSION_STRING);
    info.AddDeveloper(wxEX_VERSION_STRING);
    info.AddDeveloper(wxExOTLVersion());
    wxAboutBox(info);
    }
    break;

  case wxID_EXECUTE:
    m_Stopped = false;
    RunQueries(m_Query->GetText());
    break;

  case wxID_EXIT:
    Close(true);
    break;

  case wxID_NEW:
    if (m_Query->FileNew())
    {
      m_Query->SetLexer("sql");
      m_Query->SetFocus();
      GetManager().GetPane("QUERY").Show();
      GetManager().Update();
    }
    break;

  case wxID_OPEN:
    DialogFileOpen(wxFD_OPEN | wxFD_CHANGE_DIR, "sql files (*.sql) | *.sql", true);
    break;

  case wxID_PREFERENCES:
    wxExSTC::ConfigDialog(_("Editor Options"),
      wxExSTC::STC_CONFIG_SIMPLE | wxExSTC::STC_CONFIG_MODELESS);
    break;

  case wxID_SAVE:
    m_Query->FileSave();
    break;

  case wxID_SAVEAS:
    m_Query->FileSaveAs();
    break;

  case wxID_STOP:
    m_Running = false;
    m_Stopped = true;
    break;

  case ID_DATABASE_CLOSE:
    m_db.logoff();
    m_Shell->SetPrompt(">");
    break;

  case ID_DATABASE_OPEN:
    wxExOTLDialog(wxExApp::GetConfig(), &m_db);
    m_Shell->SetPrompt((m_db.connected ? wxExApp::GetConfig(_("Datasource")): "") + ">");
    break;

  case ID_SHELL_COMMAND:
    if (m_db.connected)
    {
      try
      {
        const wxString query = event.GetString().substr(
          0,
          event.GetString().length() - 1);

        m_Stopped = false;
        RunQuery(query, true);
      }
      catch (otl_exception& p)
      {
        if (m_Results->IsShown())
        {
          m_Results->EndBatch();
        }

        m_Shell->AppendText(_("\nerror: ") + Quoted(p.msg));
      }
    }
    else
    {
      m_Shell->AppendText(_("\nnot connected"));
    }

    m_Shell->Prompt();
    break;

  case ID_SHELL_COMMAND_STOP:
    m_Stopped = true;
    m_Shell->Prompt(_("cancelled"));
    break;

  case ID_VIEW_QUERY: TogglePane("QUERY"); break;
  case ID_VIEW_RESULTS: TogglePane("RESULTS"); break;
  case ID_VIEW_STATISTICS: TogglePane("STATISTICS"); break;

  default: event.Skip();
  }
}

void MyFrame::OnUpdateUI(wxUpdateUIEvent& event)
{
  switch (event.GetId())
  {
  case wxID_EXECUTE:
    // If we have a query, you can hide it, but still run it.
    event.Enable(m_Query->GetLength() > 0 && m_db.connected);
    break;

  case wxID_SAVE:
    event.Enable(m_Query->GetModify());
    break;

  case wxID_SAVEAS:
    event.Enable(m_Query->GetLength() > 0);
    break;

  case wxID_STOP:
    event.Enable(m_Running);
    break;

  case ID_DATABASE_CLOSE:
    event.Enable(m_db.connected > 0);
    break;

  case ID_DATABASE_OPEN:
    event.Enable(!m_db.connected);
    break;

  case ID_RECENTFILE_MENU:
    event.Enable(!GetRecentFile().empty());
    break;

  case ID_VIEW_QUERY:
    event.Check(GetManager().GetPane("QUERY").IsShown());
    break;

  case ID_VIEW_RESULTS:
    event.Check(GetManager().GetPane("RESULTS").IsShown());
    break;

  case ID_VIEW_STATISTICS:
    event.Check(GetManager().GetPane("STATISTICS").IsShown());
    break;

  default:
    wxFAIL;
  }
}

bool MyFrame::OpenFile(
  const wxExFileName& filename,
  int line_number,
  const wxString& match,
  long flags)
{
  GetManager().GetPane("QUERY").Show(true);
  GetManager().Update();

  // Take care that DialogFileOpen always results in opening in the query.
  // Otherwise if results are focused, the file is opened in the results.
  return m_Query->Open(filename, line_number, match, flags);
}

void MyFrame::RunQuery(const wxString& query, bool empty_results)
{
  wxStopWatch sw;

  const wxString query_lower = query.Lower();

  // Query functions supported by ODBC
  // $SQLTables, $SQLColumns, etc.
  // $SQLTables $1:'%'
  // allow you to get database schema.
  if (query_lower.StartsWith("select") ||
      query_lower.StartsWith("describe") ||
      query_lower.StartsWith("show") ||
      query_lower.StartsWith("explain") ||
      query_lower.StartsWith("$sql"))
  {
    long rpc;

    if (m_Results->IsShown())
    {
      rpc = wxExOTLQueryToGrid(&m_db, query, m_Results, m_Stopped, empty_results);
    }
    else
    {
      rpc = wxExOTLQueryToSTC(&m_db, query, m_Shell, m_Stopped);
    }

    sw.Pause();

    UpdateStatistics(sw, rpc);
  }
  else
  {
    const long rpc = otl_cursor::direct_exec(m_db, query.c_str());
    sw.Pause();

    UpdateStatistics(sw, rpc);
  }

  m_Shell->DocumentEnd();
}

void MyFrame::RunQueries(const wxString& text)
{
  if (m_Results->IsShown())
  {
    m_Results->ClearGrid();
  }

  // Skip sql comments.
  wxString output = text;
  wxRegEx("--.*$", wxRE_NEWLINE).ReplaceAll(&output, "");

  // Queries are seperated by ; character.
  wxStringTokenizer tkz(output, ";");
  int no_queries = 0;

  wxStopWatch sw;
  m_Running = true;

  // Run all queries.
  while (tkz.HasMoreTokens() && !m_Stopped)
  {
    wxString query = tkz.GetNextToken();
    query.Trim(true);
    query.Trim(false);

    if (!query.empty())
    {
      try
      {
        RunQuery(query, no_queries == 0);
        no_queries++;
        wxYield();
      }
      catch (otl_exception& p)
      {
        m_Statistics.Inc(_("Number of query errors"));
        m_Shell->AppendText(_("\nerror: ") +  Quoted(p.msg) + _(" in: ") + Quoted(query));
      }
    }
  }

  m_Shell->Prompt(wxString::Format(_("\n%d queries (%.3f seconds)"),
    no_queries,
    (float)sw.Time() / (float)1000));

  m_Running = false;
}

void MyFrame::UpdateStatistics(const wxStopWatch& sw, long rpc)
{
  m_Shell->AppendText(wxString::Format(_("\n%d rows processed (%.3f seconds)"),
    rpc,
    (float)sw.Time() / (float)1000));

  m_Statistics.Set(_("Rows processed"), rpc);
  m_Statistics.Set(_("Query runtime"), sw.Time());

  m_Statistics.Inc(_("Total number of queries run"));
  m_Statistics.Inc(_("Total query runtime"), sw.Time());
  m_Statistics.Inc(_("Total rows processed"), rpc);
}
<|endoftext|>