<commit_before>#include <iostream>
#include <vw/Image.h>
#include <vw/FileIO.h>

#include <vw/Cartography/GeoReference.h>
#include <vw/Cartography/GeoTransform.h>
#include <vw/Cartography/FileIO.h>
#include <vw/Cartography/Datum.h>
#include <vw/Image/ImageMath.h>
#include <vw/Image/Algorithms.h>
#include <vw/Math/Matrix.h>
#include <vw/Math/Vector.h>
#include <vw/Math/LinearAlgebra.h>
#include <boost/program_options.hpp>

namespace po = boost::program_options;

using namespace vw;
using namespace vw::math;
using namespace vw::cartography;
using namespace std;

//Global variables
double pi=4*atan(1.0);
std::string input_file_name, output_prefix = "", algorithm;
double radius=1737400.0;
bool output_gradient=true;
bool output_aspect=true;
bool output_pretty=true;
bool use_horn=true; //arbitrary default

// Erases a file suffix if one exists and returns the base string
static std::string prefix_from_filename(std::string const& filename) {
  std::string result=filename;
  int index = result.rfind(".");
  if (index != -1)
    result.erase(index, result.size());
  return result;
}

template <class ImageT>
Vector3 pixel_to_cart (Vector2 pos, ImageView<ImageT> img, GeoReference GR) {

	Vector2 loc_longlat2=GR.point_to_lonlat(GR.pixel_to_point(pos));
	Vector3 loc_longlat3(loc_longlat2(0),loc_longlat2(1),img((int)pos(0),(int)pos(1))+radius);
	Vector3 loc_cartesian=GR.datum().geodetic_to_cartesian(loc_longlat3);
	return loc_cartesian;
}

template <class ImageT>
double pixel_cartesian_dist(Vector2 pt1, Vector2 pt2, ImageView<ImageT> img, GeoReference GR) {

	Vector3 loc1=pixel_to_cart(pt1, img, GR);
	Vector3 loc2=pixel_to_cart(pt2, img, GR);
	unsigned int i;
	double res=0;
	//cartesian distance. sqrt(dx^2+dy^2+dz^2).
	for(i=0;i<3;i++)
		res+= pow(loc1[i]-loc2[i],2);
	res=pow(res,0.5);
	return res;
}

template <class ImageT>
Vector3 naive_horn (int x, int y, ImageView<ImageT> img, GeoReference GR) {

	double pi=(4.0*atan(1.0));//ok, this should be somewhere else

	Vector2 Nc(x,y-1);
	Vector2 Wc(x-1,y);
	Vector2 Sc(x,y+1);
	Vector2 Ec(x+1,y);

	double N=img(x,y-1);
	double NW=img(x-1,y-1);
	double W=img(x-1,y);
	double SW=img(x-1,y+1);
	double S=img(x,y+1);
	double SE=img(x+1,y+1);
	double E=img(x+1,y);
	double NE=img(x+1,y-1);

	//calculate an east-west gradient and a north-south gradient
	//p: west to east
	double p=( (NE+2*E+SE)-(NW+2*W+SW) )/(4*pixel_cartesian_dist(Wc,Ec, img, GR) );

	//q: south to north
	double q=( (NW+2*N+NE)-(SW+2*S+SE) )/(4*pixel_cartesian_dist(Nc,Sc, img, GR) );

	//total gradient:
	double gradient=pow(p*p+q*q, 0.5);

	//aspect: q/p=tan(angle)
	double aspect=atan(q/p);

	aspect=aspect-pi/2;
	if(p<0) aspect=pi+aspect;
	else aspect=pi-aspect;

	if(p==0) return Vector3(0,0,0);

	return Vector3(aspect,gradient,1);
}

template <class ImageT>
Vector3 interpolate_plane (int x, int y, ImageView<ImageT> img, GeoReference GR) {

	Matrix<double> A(9,4);
	int i=0;
	int j=0;

	int ct=0;

	Vector3 center_normal=pixel_to_cart(Vector2(x,y),img,GR);

	for(i=-1;i<=1;i++) {
		for(j=-1;j<=1;j++) {
			Vector3 tmp=pixel_to_cart(Vector2(x+i,y+j),img,GR);
			A(ct,0)=tmp(0);
			A(ct,1)=tmp(1);
			A(ct,2)=tmp(2);
			A(ct,3)=1;
			ct++;
		}
	}

	Matrix<double> U;
	Matrix<double> VT;
	Vector<double> s;

	svd(A, U, s, VT);
	Vector<double> plane_normal(3);
	plane_normal(0)=VT(3,0);
	plane_normal(1)=VT(3,1);
	plane_normal(2)=VT(3,2);

	//normalize
	center_normal=normalize(center_normal);
	plane_normal=normalize(plane_normal);

	if(dot_prod(plane_normal,center_normal) <0) plane_normal=plane_normal*-1;

	double dotprod=dot_prod(plane_normal,center_normal);

	//gradient angle is absval
	double gradient_angle=acos(dotprod);
	if(gradient_angle>pi/2)
		gradient_angle=pi-gradient_angle;

	//calculating aspect...
	Vector3 surface_normal_on_sphere_tangent_plane=normalize(plane_normal-dot_prod(plane_normal,center_normal)*center_normal);
	//get projection of (0,0,1) onto sphere tangent plane.
	Vector3 north(0,0,1);
	Vector3 north_projected=normalize(north-dot_prod(north,center_normal)*center_normal);
	//find the angle between those two
	double dotprod2=dot_prod(surface_normal_on_sphere_tangent_plane, north_projected);

	//figure out which angle it is.
	double aspect=acos(dotprod2);

	if( dot_prod((cross_prod(north_projected,surface_normal_on_sphere_tangent_plane)),center_normal) < 0)
		aspect=pi+aspect;
	else
		aspect=pi-aspect;

	return Vector3(aspect,abs(gradient_angle),1);
}

template <class imageT>
void do_slopemap (po::variables_map const& vm) { //not sure what the arguments are

	GeoReference GR;
	read_georeference( GR, input_file_name );

	ImageView<imageT> img;
	read_image( img, input_file_name );

	int x;
	int y;

	ImageView<double> gradient_angle;
	ImageView<double> aspect;
	ImageView<PixelHSV<double> > pretty;

	if(output_gradient) gradient_angle.set_size(img.cols(),img.rows());
	if(output_aspect) aspect.set_size(img.cols(),img.rows());
	if(output_pretty) pretty.set_size(img.cols(),img.rows());

	for(x=1;x<img.cols()-1;x++) {

		for(y=1;y<img.rows()-1;y++) {
			//does the calculations for both gradient and aspect but outputs one or the other or both
			Vector3 res;
			if(use_horn) res=naive_horn(x,y,img,GR);
			else res=interpolate_plane(x,y,img,GR);

			if(output_aspect)   aspect(x,y) = res(0);
			if(output_gradient) gradient_angle(x,y) = res(1);
			if(output_pretty)   pretty(x,y) = PixelHSV<double>(res(0),res(1)+0.1*abs(pi-res(0))/pi,res(1)+0.2*abs(pi-res(0)));
			//pretty things arbitrary
		}
	}

	ImageView<PixelRGB<uint8> > pretty2;

	if(output_pretty) {
		select_channel(pretty,0)=normalize(select_channel(pretty,0));
		select_channel(pretty,1)=normalize(select_channel(pretty,1),0,0.25,0.3,1);
		select_channel(pretty,2)=normalize(select_channel(pretty,2),0.5,1);

		pretty2=pixel_cast_rescale<PixelRGB<uint8> >( copy(pretty) );
	}

	//save everything to file
	if(output_gradient) write_georeferenced_image( output_prefix + "_gradient.tif" , gradient_angle, GR);
	if(output_aspect)   write_georeferenced_image( output_prefix + "_aspect.tif"   , aspect, GR);
	if(output_pretty)   write_image( output_prefix + "_pretty.tif"   , pretty2);
}

int main( int argc, char *argv[] ) {

  set_debug_level(InfoMessage);

  po::options_description desc("Description: Outputs gradient and/or aspect at each point of an input DEM with altitude values\n\nUsage: slopemap [options] <input file> \n\nOptions");
  desc.add_options()
    ("help", "Display this help messsage")
    ("input-file", po::value<std::string>(&input_file_name), "Explicitly specify the input file")
    ("output-prefix,o", po::value<std::string>(&output_prefix), "Specify the output prefix") //should add more description...
    ("radius", po::value<double>(&radius), "Set radius in meters as specified. [default: 1737400 meters (moon radius)]")
    ("no-aspect", "Do not output aspect")
    ("no-gradient", "Do not output gradient")
    ("algorithm", po::value<std::string>(&algorithm)->default_value("horn"), "Choose an algorithm to calculate slope/aspect from [horn, planefit]") //could use better names
    ("no-pretty", "Do not output colored image.");

  po::positional_options_description p;
  p.add("input-file", 1);

  po::variables_map vm;
  po::store( po::command_line_parser( argc, argv ).options(desc).positional(p).run(), vm );
  po::notify( vm );

  if( vm.count("help") ) {
    std::cout << desc << std::endl;
    return 1;
  }

  if( vm.count("input-file") != 1 ) {
    std::cout << "Error: Must specify exactly one input file!\n" << std::endl;
    std::cout << desc << std::endl;
    return 1;
  }

  if( output_prefix == "" ) { output_prefix=prefix_from_filename(input_file_name);
  }

  if( vm.count("verbose") ) {
    set_debug_level(VerboseDebugMessage);
  }

//checking strings
boost::to_lower(algorithm);
if( !(  algorithm == "horn" ||
	algorithm == "planefit" ||
	algorithm == "" ) ) { //it's okay if it isn't set?
	vw_out(0) << "Unknown algorithm: " << algorithm << ". Options are : [ horn, planefit ]\n";
	exit(0);
}
else {
if(algorithm=="horn")
	use_horn=true;
else
	use_horn=false;
}

if(vm.count("no-aspect")) output_aspect=false;
if(vm.count("no-gradient")) output_gradient=false;
if(!output_aspect && !output_gradient && !output_pretty) {
	vw_out(0) << "No output specified. Select at least one of [gradient, output, pretty].\n" << endl;
}

if(vm.count("no-pretty")) output_pretty=false;

  try {
    // Get the right pixel/channel type.
    DiskImageResource *rsrc = DiskImageResource::open(input_file_name);
    ChannelTypeEnum channel_type = rsrc->channel_type();
    PixelFormatEnum pixel_format = rsrc->pixel_format();
    delete rsrc;

    switch(pixel_format) {
    case VW_PIXEL_GRAY:
    case VW_PIXEL_GRAYA:
    case VW_PIXEL_RGB:
    case VW_PIXEL_RGBA:
      switch(channel_type) {
      case VW_CHANNEL_UINT8:  do_slopemap<PixelGray<uint8>   >(vm); break;
      case VW_CHANNEL_INT16:  do_slopemap<PixelGray<int16>   >(vm); break;
      case VW_CHANNEL_UINT16: do_slopemap<PixelGray<uint16>  >(vm); break;
      case VW_CHANNEL_FLOAT32:do_slopemap<PixelGray<float32> >(vm); break;
      case VW_CHANNEL_FLOAT64:do_slopemap<PixelGray<float64> >(vm); break;
      default:                do_slopemap<PixelGray<float32> >(vm); break;
      }
      break;
    default:
      std::cout << "Error: Unsupported pixel format.\n";
      exit(0);
    }
  } catch( Exception& e ) {
    std::cout << "Error: " << e.what() << std::endl;
  }
  return 0;

}
<commit_msg>fixed a few more things<commit_after>#include <iostream>
#include <vw/Image.h>
#include <vw/FileIO.h>

#include <vw/Cartography/GeoReference.h>
#include <vw/Cartography/GeoTransform.h>
#include <vw/Cartography/FileIO.h>
#include <vw/Cartography/Datum.h>
#include <vw/Image/ImageMath.h>
#include <vw/Image/Algorithms.h>
#include <vw/Math/Matrix.h>
#include <vw/Math/Vector.h>
#include <vw/Math/LinearAlgebra.h>
#include <boost/program_options.hpp>

namespace po = boost::program_options;

using namespace vw;
using namespace vw::math;
using namespace vw::cartography;
using namespace std;

//Global variables
double pi=4*atan(1.0);
std::string input_file_name, output_prefix = "", algorithm;
double radius=1737400.0;
bool output_gradient=true;
bool output_aspect=true;
bool output_pretty=true;
bool use_horn=true; //arbitrary default

// Erases a file suffix if one exists and returns the base string
static std::string prefix_from_filename(std::string const& filename) {
  std::string result=filename;
  int index = result.rfind(".");
  if (index != -1)
    result.erase(index, result.size());
  return result;
}

template <class ImageT>
Vector3 pixel_to_cart (Vector2 pos, ImageView<ImageT> img, GeoReference GR) {

	Vector2 loc_longlat2=GR.point_to_lonlat(GR.pixel_to_point(pos));
	Vector3 loc_longlat3(loc_longlat2(0),loc_longlat2(1),img((int)pos(0),(int)pos(1))+radius);
	Vector3 loc_cartesian=GR.datum().geodetic_to_cartesian(loc_longlat3);
	return loc_cartesian;
}

template <class ImageT>
double pixel_cartesian_dist(Vector2 pt1, Vector2 pt2, ImageView<ImageT> img, GeoReference GR) {

	Vector3 loc1=pixel_to_cart(pt1, img, GR);
	Vector3 loc2=pixel_to_cart(pt2, img, GR);
	unsigned int i;
	double res=0;
	//cartesian distance. sqrt(dx^2+dy^2+dz^2).
	for(i=0;i<3;i++)
		res+= pow(loc1[i]-loc2[i],2);
	res=pow(res,0.5);
	return res;
}

template <class ImageT>
Vector3 naive_horn (int x, int y, ImageView<ImageT> img, GeoReference GR) {

	double pi=(4.0*atan(1.0));//ok, this should be somewhere else

	Vector2 Nc(x,y-1);
	Vector2 Wc(x-1,y);
	Vector2 Sc(x,y+1);
	Vector2 Ec(x+1,y);

	double N=img(x,y-1);
	double NW=img(x-1,y-1);
	double W=img(x-1,y);
	double SW=img(x-1,y+1);
	double S=img(x,y+1);
	double SE=img(x+1,y+1);
	double E=img(x+1,y);
	double NE=img(x+1,y-1);

	//calculate an east-west gradient and a north-south gradient
	//p: west to east
	double p=( (NE+2*E+SE)-(NW+2*W+SW) )/(4*pixel_cartesian_dist(Wc,Ec, img, GR) );

	//q: south to north
	double q=( (NW+2*N+NE)-(SW+2*S+SE) )/(4*pixel_cartesian_dist(Nc,Sc, img, GR) );

	//total gradient:
	double gradient=pow(p*p+q*q, 0.5);

	//aspect: q/p=tan(angle)
	double aspect=atan(q/p);

	if(p<0) aspect=aspect+pi;

	aspect=2*pi-aspect+pi/2;
	if(aspect<0) aspect=2*pi+aspect;
	if(aspect>=2*pi) aspect=aspect-2*pi*(int)(aspect/2/pi);

	if(p==0) return Vector3(0,0,0);

	return Vector3(aspect,gradient,1);
}

template <class ImageT>
Vector3 interpolate_plane (int x, int y, ImageView<ImageT> img, GeoReference GR) {

	Matrix<double> A(9,4);
	int i=0;
	int j=0;

	int ct=0;

	Vector3 center_normal=pixel_to_cart(Vector2(x,y),img,GR);

	for(i=-1;i<=1;i++) {
		for(j=-1;j<=1;j++) {
			Vector3 tmp=pixel_to_cart(Vector2(x+i,y+j),img,GR);
			A(ct,0)=tmp(0);
			A(ct,1)=tmp(1);
			A(ct,2)=tmp(2);
			A(ct,3)=1;
			ct++;
		}
	}

	Matrix<double> U;
	Matrix<double> VT;
	Vector<double> s;

	svd(A, U, s, VT);
	Vector<double> plane_normal(3);
	plane_normal(0)=VT(3,0);
	plane_normal(1)=VT(3,1);
	plane_normal(2)=VT(3,2);

	//normalize
	center_normal=normalize(center_normal);
	plane_normal=normalize(plane_normal);

	if(dot_prod(plane_normal,center_normal) <0) plane_normal=plane_normal*-1;

	double dotprod=dot_prod(plane_normal,center_normal);

	//gradient angle is absval
	double gradient_angle=acos(dotprod);
	if(gradient_angle>pi/2)
		gradient_angle=pi-gradient_angle;

	//calculating aspect...
	Vector3 surface_normal_on_sphere_tangent_plane=normalize(plane_normal-dot_prod(plane_normal,center_normal)*center_normal);
	//get projection of (0,0,1) onto sphere tangent plane.
	Vector3 north(0,0,1);
	Vector3 north_projected=normalize(north-dot_prod(north,center_normal)*center_normal);
	//find the angle between those two
	double dotprod2=dot_prod(surface_normal_on_sphere_tangent_plane, north_projected);

	//figure out which angle it is.
	double aspect=acos(dotprod2);

	if( dot_prod((cross_prod(north_projected,surface_normal_on_sphere_tangent_plane)),center_normal) < 0)
		aspect=pi+aspect;
	else
		aspect=pi-aspect;

	return Vector3(aspect,abs(gradient_angle),1);
}

template <class imageT>
void do_slopemap (po::variables_map const& vm) { //not sure what the arguments are

	GeoReference GR;
	read_georeference( GR, input_file_name );

	ImageView<imageT> img;
	read_image( img, input_file_name );

	int x;
	int y;

	ImageView<double> gradient_angle;
	ImageView<double> aspect;
	ImageView<PixelHSV<double> > pretty;

	if(output_gradient) gradient_angle.set_size(img.cols(),img.rows());
	if(output_aspect) aspect.set_size(img.cols(),img.rows());
	if(output_pretty) pretty.set_size(img.cols(),img.rows());

	for(x=1;x<img.cols()-1;x++) {

		for(y=1;y<img.rows()-1;y++) {
			//does the calculations for both gradient and aspect but outputs one or the other or both
			Vector3 res;
			if(use_horn) res=naive_horn(x,y,img,GR);
			else res=interpolate_plane(x,y,img,GR);

			if(output_aspect)   aspect(x,y) = res(0);
			if(output_gradient) gradient_angle(x,y) = res(1);
			if(output_pretty)   pretty(x,y) = PixelHSV<double>(res(0),res(1)+0.1*abs(pi-res(0))/pi,res(1)+0.2*abs(pi-res(0)));
			//pretty things arbitrary
		}
	}

	ImageView<PixelRGB<uint8> > pretty2;

	if(output_pretty) {
		select_channel(pretty,0)=normalize(select_channel(pretty,0));
		select_channel(pretty,1)=normalize(select_channel(pretty,1),0,0.25,0.3,1);
		select_channel(pretty,2)=normalize(select_channel(pretty,2),0.5,1);

		pretty2=pixel_cast_rescale<PixelRGB<uint8> >( copy(pretty) );
	}

	//save everything to file
	if(output_gradient) write_georeferenced_image( output_prefix + "_gradient.tif" , gradient_angle, GR);
	if(output_aspect)   write_georeferenced_image( output_prefix + "_aspect.tif"   , aspect, GR);
	if(output_pretty)   write_image( output_prefix + "_pretty.tif"   , pretty2);
}

int main( int argc, char *argv[] ) {

  set_debug_level(InfoMessage);

  po::options_description desc("Description: Outputs gradient and/or aspect at each point of an input DEM with altitude values\n\nUsage: slopemap [options] <input file> \n\nOptions");
  desc.add_options()
    ("help", "Display this help messsage")
    ("input-file", po::value<std::string>(&input_file_name), "Explicitly specify the input file")
    ("output-prefix,o", po::value<std::string>(&output_prefix), "Specify the output prefix") //should add more description...
    ("radius", po::value<double>(&radius), "Set radius in meters as specified. [default: 1737400 meters (moon radius)]")
    ("no-aspect", "Do not output aspect")
    ("no-gradient", "Do not output gradient")
    ("algorithm", po::value<std::string>(&algorithm)->default_value("horn"), "Choose an algorithm to calculate slope/aspect from [horn, planefit]") //could use better names
    ("no-pretty", "Do not output colored image.");

  po::positional_options_description p;
  p.add("input-file", 1);

  po::variables_map vm;
  po::store( po::command_line_parser( argc, argv ).options(desc).positional(p).run(), vm );
  po::notify( vm );

  if( vm.count("help") ) {
    std::cout << desc << std::endl;
    return 1;
  }

  if( vm.count("input-file") != 1 ) {
    std::cout << "Error: Must specify exactly one input file!\n" << std::endl;
    std::cout << desc << std::endl;
    return 1;
  }

  if( output_prefix == "" ) { output_prefix=prefix_from_filename(input_file_name);
  }

  if( vm.count("verbose") ) {
    set_debug_level(VerboseDebugMessage);
  }

//checking strings
boost::to_lower(algorithm);
if( !(  algorithm == "horn" ||
	algorithm == "planefit" ||
	algorithm == "" ) ) { //it's okay if it isn't set?
	vw_out(0) << "Unknown algorithm: " << algorithm << ". Options are : [ horn, planefit ]\n";
	exit(0);
}
else {
if(algorithm=="horn")
	use_horn=true;
else
	use_horn=false;
}

if(vm.count("no-aspect")) output_aspect=false;
if(vm.count("no-gradient")) output_gradient=false;
if(!output_aspect && !output_gradient && !output_pretty) {
	vw_out(0) << "No output specified. Select at least one of [gradient, output, pretty].\n" << endl;
}

if(vm.count("no-pretty")) output_pretty=false;

  try {
    // Get the right pixel/channel type.
    DiskImageResource *rsrc = DiskImageResource::open(input_file_name);
    ChannelTypeEnum channel_type = rsrc->channel_type();
    PixelFormatEnum pixel_format = rsrc->pixel_format();
    delete rsrc;

    switch(pixel_format) {
    case VW_PIXEL_GRAY:
    case VW_PIXEL_GRAYA:
    case VW_PIXEL_RGB:
    case VW_PIXEL_RGBA:
      switch(channel_type) {
      case VW_CHANNEL_UINT8:  do_slopemap<PixelGray<uint8>   >(vm); break;
      case VW_CHANNEL_INT16:  do_slopemap<PixelGray<int16>   >(vm); break;
      case VW_CHANNEL_UINT16: do_slopemap<PixelGray<uint16>  >(vm); break;
      case VW_CHANNEL_FLOAT32:do_slopemap<PixelGray<float32> >(vm); break;
      case VW_CHANNEL_FLOAT64:do_slopemap<PixelGray<float64> >(vm); break;
      default:                do_slopemap<PixelGray<float32> >(vm); break;
      }
      break;
    default:
      std::cout << "Error: Unsupported pixel format.\n";
      exit(0);
    }
  } catch( Exception& e ) {
    std::cout << "Error: " << e.what() << std::endl;
  }
  return 0;

}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: bridge_connection.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: jbu $ $Date: 2001-06-22 16:39:16 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#include <osl/interlck.h>

#include <bridges/remote/connection.h>

#include <com/sun/star/connection/XConnection.hpp>

namespace remotebridges_bridge
{

    class OConnectionWrapper :
        public remote_Connection
    {
    public:
        OConnectionWrapper( const ::com::sun::star::uno::Reference <
                            ::com::sun::star::connection::XConnection > & );
        ~OConnectionWrapper();

        static void      SAL_CALL thisAcquire( remote_Connection *);
        static void      SAL_CALL thisRelease( remote_Connection *);
        static sal_Int32 SAL_CALL thisRead( remote_Connection * , sal_Int8 *pDest , sal_Int32 nSize );
        static sal_Int32 SAL_CALL thisWrite( remote_Connection * ,
                                             const sal_Int8 *pSource ,
                                             sal_Int32 nSize );
        static void      SAL_CALL thisFlush( remote_Connection * );
        static void      SAL_CALL thisClose( remote_Connection * );

        ::com::sun::star::uno::Reference < ::com::sun::star::connection::XConnection > m_r;
        oslInterlockedCount m_nRef;
    };
}

<commit_msg>INTEGRATION: CWS ooo19126 (1.2.124); FILE MERGED 2005/09/05 13:56:24 rt 1.2.124.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: bridge_connection.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 05:21:42 $
 *
 *  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
 *
 ************************************************************************/
#include <osl/interlck.h>

#include <bridges/remote/connection.h>

#include <com/sun/star/connection/XConnection.hpp>

namespace remotebridges_bridge
{

    class OConnectionWrapper :
        public remote_Connection
    {
    public:
        OConnectionWrapper( const ::com::sun::star::uno::Reference <
                            ::com::sun::star::connection::XConnection > & );
        ~OConnectionWrapper();

        static void      SAL_CALL thisAcquire( remote_Connection *);
        static void      SAL_CALL thisRelease( remote_Connection *);
        static sal_Int32 SAL_CALL thisRead( remote_Connection * , sal_Int8 *pDest , sal_Int32 nSize );
        static sal_Int32 SAL_CALL thisWrite( remote_Connection * ,
                                             const sal_Int8 *pSource ,
                                             sal_Int32 nSize );
        static void      SAL_CALL thisFlush( remote_Connection * );
        static void      SAL_CALL thisClose( remote_Connection * );

        ::com::sun::star::uno::Reference < ::com::sun::star::connection::XConnection > m_r;
        oslInterlockedCount m_nRef;
    };
}

<|endoftext|>


<commit_before>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (testabilitydriver@nokia.com)
**
** This file is part of Testability Driver Qt Agent
**
** If you have questions regarding the use of this file, please contact
** Nokia at testabilitydriver@nokia.com .
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/

#include <QApplication>
#include <QGraphicsItem>
#include <QGraphicsWidget>
#include <QGraphicsProxyWidget>
#include <QWidget>
#include <QGraphicsView>
#include <QQuickItem>
#include <QQuickView>
#include <QLocale>

#include "tasuitraverser.h"
#include "taslogger.h"
#include "testabilityutils.h"
#include "tastraverserloader.h"
#include "tasdeviceutils.h"

#if defined(TAS_MAEMO) && defined(HAVE_QAPP)
#include <MApplication>
#include <MLocale>
#endif

TasUiTraverser::TasUiTraverser(QHash<QString, TasTraverseInterface*> traversers)
{
    mTraversers = traversers;
}

TasUiTraverser::~TasUiTraverser()
{
    mTraversers.clear();
    mPluginBlackList.clear();
    mPluginWhiteList.clear();
}

void TasUiTraverser::setFilterLists(TasCommand* command)
{
    mPluginBlackList.clear();
    mPluginWhiteList.clear();

    if(!command) return;

    if(!command->apiParameter("pluginBlackList").isEmpty()){
        mPluginBlackList = command->apiParameter("pluginBlackList").split(",");
    }

    if(!command->apiParameter("pluginWhiteList").isEmpty()){
        mPluginWhiteList = command->apiParameter("pluginWhiteList").split(",");
    }

}

bool TasUiTraverser::filterPlugin(const QString& pluginName)
{
    bool filter = true;

    if(mPluginWhiteList.isEmpty() && mPluginBlackList.isEmpty()){
        filter = false;
    }
    //black list is valued higher than white list
    else if(mPluginWhiteList.contains(pluginName) && !mPluginBlackList.contains(pluginName)){
        filter = false;
    }
    else if(mPluginWhiteList.isEmpty() && !mPluginBlackList.contains(pluginName)){
        filter = false;
    }
    return filter;
}

void TasUiTraverser::initializeTraverse(TasCommand* command)
{
    setFilterLists(command);
    //let traversers know that a new traverse operation is starting
    QHashIterator<QString, TasTraverseInterface*> traversers(mTraversers);
    while (traversers.hasNext()) {
        traversers.next();
        traversers.value()->beginTraverse(command);
    }
}

void TasUiTraverser::finalizeTraverse()
{
    //let traversers know that a new traverse operation is starting
    QHashIterator<QString, TasTraverseInterface*> traversers(mTraversers);
    while (traversers.hasNext()) {
        traversers.next();
        traversers.value()->endTraverse();
    }
}

TasObject& TasUiTraverser::addModelRoot(TasDataModel& model, TasCommand* command)
{
    TasObjectContainer& container = model.addNewObjectContainer("qt", "sut");
    container.setId(qVersion());
    QString appName = getApplicationName();
    TasObject& application = container.addNewObject(QString::number(qApp->applicationPid()), appName, "application");
    if(appName == PENINPUT_SERVER){
        application.setType(VKB_IDENTIFIER);
    }
    addApplicationDetails(application, command);
    return application;
}

TasDataModel* TasUiTraverser::getUiState(TasCommand* command)
{
    initializeTraverse(command);

    TasDataModel* model = new TasDataModel();
    TasObject& application = addModelRoot(*model, command);

    QWidgetList widgetList = qApp->topLevelWidgets();
    if (!widgetList.empty()){
        QListIterator<QWidget*> iter(qApp->topLevelWidgets());
        while(iter.hasNext()){
            QWidget *widget = iter.next();
            //only print widgets if they are visible
            if (!widget->graphicsProxyWidget() &&  (TestabilityUtils::isCustomTraverse() || widget->isVisible())){
                //widgets that have a parent will not be traversed unless the parent is the app
                //this is done to avoid objects being traversed more than once
                if(!widget->parent() || widget->parent() == qApp){
                    traverseObject(application.addObject(), widget, command);
                }
            }
        }
    }

    foreach (QWindow* w, qApp->topLevelWindows()) {
        traverseObject(application.addObject(), w, command);
    }

    finalizeTraverse();

    return model;
}

void TasUiTraverser::traverseObject(TasObject& objectInfo, QObject* object, TasCommand* command, bool traverseChildren)
{
    QHashIterator<QString, TasTraverseInterface*> i(mTraversers);
    while (i.hasNext()) {
        i.next();
        if(!filterPlugin(i.key())){
            i.value()->traverseObject(&objectInfo, object, command);
        }
    }
    if(traverseChildren){
        printActions(objectInfo, object);
    }
    if (traverseChildren) {

        QQuickView* quickView = qobject_cast<QQuickView*>(object);
        if (quickView) {
            QQuickItem* root = quickView->rootObject();
            if (root) {
                traverseObject(objectInfo.addObject(), root, command);
            }
        }

        QQuickItem* quickItem = qobject_cast<QQuickItem*>(object);
        if (quickItem) {
            foreach(QQuickItem* child, quickItem->childItems()) {
                traverseObject(objectInfo.addObject(), child, command);
            }
        }

        //check decendants
        //1. is graphicsview
        QGraphicsView* gView = qobject_cast<QGraphicsView*>(object);
        if(gView){
            traverseGraphicsViewItems(objectInfo, gView, command);
        }
        //2. is QGraphicsObject
        QGraphicsObject* graphicsObject = qobject_cast<QGraphicsObject*>(object);
        if(graphicsObject){
            traverseGraphicsItemList(objectInfo, graphicsObject,command);
        }
        //3. Widget children
        else{
            QObjectList children = object->children();
            if (!children.isEmpty()) {
                for (int i = 0; i < children.size(); ++i){
                    QObject *obj = children.at(i);
                    //only include widgets
                    if (obj->isWidgetType() && obj->parent() == object){
                        QWidget *widget = qobject_cast<QWidget*>(obj);
                        // TODO This (and other similar hacks) needs to be moved to plugins once OSS changes are done
                        if (TestabilityUtils::isCustomTraverse() || widget->isVisible() ) /*&& !wasTraversed(widget)*/{
                            traverseObject(objectInfo.addObject(), widget, command);
                        }
                    }
                }
            }
        }
    }
}

void TasUiTraverser::traverseGraphicsItem(TasObject& objectInfo, QGraphicsItem* graphicsItem, TasCommand* command, bool traverseChildren)
{
    QGraphicsObject* object = graphicsItem->toGraphicsObject();
    if (object) {
        traverseObject(objectInfo, object, command);
        // Traverse the actual widget under the proxy, if available
        QGraphicsProxyWidget* proxy = qobject_cast<QGraphicsProxyWidget*>(object);
        if (proxy) {
            traverseObject(objectInfo.addObject(), proxy->widget(), command, traverseChildren);
        }
    }
    else{
        objectInfo.setType("QGraphicsItem");
        QHashIterator<QString, TasTraverseInterface*> i(mTraversers);
        while (i.hasNext()) {
            i.next();
            if(!filterPlugin(i.key())){
                i.value()->traverseGraphicsItem(&objectInfo, graphicsItem, command);
            }
        }
        if(traverseChildren){
            traverseGraphicsItemList(objectInfo, graphicsItem, command);
        }
    }
}

void TasUiTraverser::traverseGraphicsItemList(TasObject& parent, QGraphicsItem* graphicsItem, TasCommand* command)
{
    foreach (QGraphicsItem* item, graphicsItem->childItems()){
        if(graphicsItem == item->parentItem()){
            // TODO This needs to be moved to plugins once OSS changes are done
            if(TestabilityUtils::isCustomTraverse()|| item->isVisible() ) {
                traverseGraphicsItem(parent.addObject(), item, command);
            }
        }
    }
}

void TasUiTraverser::traverseGraphicsViewItems(TasObject& parent, QGraphicsView* view, TasCommand* command)
{
    foreach(QGraphicsItem* item, view->items()){
        if(item->parentItem() == 0){
            // TODO This needs to be moved to plugins once OSS changes are done
            if(TestabilityUtils::isCustomTraverse() || item->isVisible()) {
                traverseGraphicsItem(parent.addObject(), item, command);
            }
        }
    }
}

void TasUiTraverser::addApplicationDetails(TasObject& application, TasCommand* command)
{
    traverseObject(application, qApp, command, false);
    application.setEnv("qt");
    //set these again cause properties overwrite them
    application.setName(getApplicationName());
    application.setId(QString::number(qApp->applicationPid()));
#ifdef Q_OS_SYMBIAN
    quintptr uid = CEikonEnv::Static()->EikAppUi()->Application()->AppDllUid().iUid;
    application.addAttribute("applicationUid", QString::number(uid));

    CWsScreenDevice* sws = new ( ELeave ) CWsScreenDevice( CEikonEnv::Static()->WsSession() );
    CleanupStack::PushL( sws );
    if( sws->Construct() == KErrNone)
    {
        TPixelsAndRotation sizeAndRotation;
        sws->GetDefaultScreenSizeAndRotation( sizeAndRotation );
        qApp->setProperty(APP_ROTATION, QVariant(sizeAndRotation.iRotation));
        application.addAttribute(APP_ROTATION, sizeAndRotation.iRotation);
    }
    CleanupStack::PopAndDestroy( sws );
#endif

    application.addAttribute("arguments", qApp->arguments().join(" ").toLatin1().data());
    application.addAttribute("exepath", qApp->applicationFilePath().toLatin1().data());
    application.addAttribute("FullName", qApp->applicationFilePath().toLatin1().data());
    application.addAttribute("dirpath", qApp->applicationDirPath().toLatin1().data());
    application.addAttribute("processId", QString::number(qApp->applicationPid()).toLatin1().data());
    application.addAttribute("version", qApp->applicationVersion().toLatin1().data());
    application.addAttribute("objectType", TYPE_APPLICATION_VIEW);
    application.addAttribute("objectId", TasCoreUtils::objectId(qApp));

    int mem = TasDeviceUtils::currentProcessHeapSize();
    if(mem != -1){
        application.addAttribute("memUsage", mem);
    }
#if defined(TAS_MAEMO) && defined(HAVE_QAPP)
    MApplication* app = MApplication::instance();
    if (app){
        MLocale defaultMLocale;
        application.addAttribute("localeName", defaultMLocale.name());
        application.addAttribute("localeCountry", defaultMLocale.country());
        application.addAttribute("localeLanguage", defaultMLocale.language());
    }
    else{
        QLocale defaultLocale;
        application.addAttribute("localeName", defaultLocale.name());
        application.addAttribute("localeCountry", defaultLocale.countryToString(defaultLocale.country()));
        application.addAttribute("localeLanguage", defaultLocale.languageToString(defaultLocale.language()));
    }
#else
    QLocale defaultLocale;
    application.addAttribute("localeName", defaultLocale.name());
    application.addAttribute("localeCountry", defaultLocale.countryToString(defaultLocale.country()));
    application.addAttribute("localeLanguage", defaultLocale.languageToString(defaultLocale.language()));
#endif
}

/*!

  Prints all of the actions that a widget has under the widget.
  Makes it possible to easily map the correct action to the
  correct widget and also command the correct widget.
  Returns true if an action was added.

 */

void TasUiTraverser::printActions(TasObject& objectInfo, QObject* object)
{
    QWidget* widget = qobject_cast<QWidget*>(object);
    if(widget){
        addActions(objectInfo, widget->actions());
    }
    else{
        QGraphicsWidget* gWidget = qobject_cast<QGraphicsWidget*>(object);
        if(gWidget){
            addActions(objectInfo, gWidget->actions());
        }
    }
}

void TasUiTraverser::addActions(TasObject& parentObject, QList<QAction*> actions)
{
    if(actions.size() > 0){
        for(int i = 0 ; i < actions.size(); i++){
            QObject* action = actions.at(i);
            traverseObject(parentObject.addObject(), action, 0);
        }
    }
}

<commit_msg>Added support for QQuickWindow based items, such as QML Window and QML ApplicationWindow.<commit_after>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (testabilitydriver@nokia.com)
**
** This file is part of Testability Driver Qt Agent
**
** If you have questions regarding the use of this file, please contact
** Nokia at testabilitydriver@nokia.com .
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/

#include <QApplication>
#include <QGraphicsItem>
#include <QGraphicsWidget>
#include <QGraphicsProxyWidget>
#include <QWidget>
#include <QGraphicsView>
#include <QQuickItem>
#include <QQuickView>
#include <QLocale>

#include "tasuitraverser.h"
#include "taslogger.h"
#include "testabilityutils.h"
#include "tastraverserloader.h"
#include "tasdeviceutils.h"

#if defined(TAS_MAEMO) && defined(HAVE_QAPP)
#include <MApplication>
#include <MLocale>
#endif

TasUiTraverser::TasUiTraverser(QHash<QString, TasTraverseInterface*> traversers)
{
    mTraversers = traversers;
}

TasUiTraverser::~TasUiTraverser()
{
    mTraversers.clear();
    mPluginBlackList.clear();
    mPluginWhiteList.clear();
}

void TasUiTraverser::setFilterLists(TasCommand* command)
{
    mPluginBlackList.clear();
    mPluginWhiteList.clear();

    if(!command) return;

    if(!command->apiParameter("pluginBlackList").isEmpty()){
        mPluginBlackList = command->apiParameter("pluginBlackList").split(",");
    }

    if(!command->apiParameter("pluginWhiteList").isEmpty()){
        mPluginWhiteList = command->apiParameter("pluginWhiteList").split(",");
    }

}

bool TasUiTraverser::filterPlugin(const QString& pluginName)
{
    bool filter = true;

    if(mPluginWhiteList.isEmpty() && mPluginBlackList.isEmpty()){
        filter = false;
    }
    //black list is valued higher than white list
    else if(mPluginWhiteList.contains(pluginName) && !mPluginBlackList.contains(pluginName)){
        filter = false;
    }
    else if(mPluginWhiteList.isEmpty() && !mPluginBlackList.contains(pluginName)){
        filter = false;
    }
    return filter;
}

void TasUiTraverser::initializeTraverse(TasCommand* command)
{
    setFilterLists(command);
    //let traversers know that a new traverse operation is starting
    QHashIterator<QString, TasTraverseInterface*> traversers(mTraversers);
    while (traversers.hasNext()) {
        traversers.next();
        traversers.value()->beginTraverse(command);
    }
}

void TasUiTraverser::finalizeTraverse()
{
    //let traversers know that a new traverse operation is starting
    QHashIterator<QString, TasTraverseInterface*> traversers(mTraversers);
    while (traversers.hasNext()) {
        traversers.next();
        traversers.value()->endTraverse();
    }
}

TasObject& TasUiTraverser::addModelRoot(TasDataModel& model, TasCommand* command)
{
    TasObjectContainer& container = model.addNewObjectContainer("qt", "sut");
    container.setId(qVersion());
    QString appName = getApplicationName();
    TasObject& application = container.addNewObject(QString::number(qApp->applicationPid()), appName, "application");
    if(appName == PENINPUT_SERVER){
        application.setType(VKB_IDENTIFIER);
    }
    addApplicationDetails(application, command);
    return application;
}

TasDataModel* TasUiTraverser::getUiState(TasCommand* command)
{
    initializeTraverse(command);

    TasDataModel* model = new TasDataModel();
    TasObject& application = addModelRoot(*model, command);

    QWidgetList widgetList = qApp->topLevelWidgets();
    if (!widgetList.empty()){
        QListIterator<QWidget*> iter(qApp->topLevelWidgets());
        while(iter.hasNext()){
            QWidget *widget = iter.next();
            //only print widgets if they are visible
            if (!widget->graphicsProxyWidget() &&  (TestabilityUtils::isCustomTraverse() || widget->isVisible())){
                //widgets that have a parent will not be traversed unless the parent is the app
                //this is done to avoid objects being traversed more than once
                if(!widget->parent() || widget->parent() == qApp){
                    traverseObject(application.addObject(), widget, command);
                }
            }
        }
    }

    foreach (QWindow* w, qApp->topLevelWindows()) {
        traverseObject(application.addObject(), w, command);
    }

    finalizeTraverse();

    return model;
}

void TasUiTraverser::traverseObject(TasObject& objectInfo, QObject* object, TasCommand* command, bool traverseChildren)
{
    QHashIterator<QString, TasTraverseInterface*> i(mTraversers);
    while (i.hasNext()) {
        i.next();
        if(!filterPlugin(i.key())){
            i.value()->traverseObject(&objectInfo, object, command);
        }
    }
    if(traverseChildren){
        printActions(objectInfo, object);
    }
    if (traverseChildren) {

        QQuickView* quickView = qobject_cast<QQuickView*>(object);
        if (quickView) {
            QQuickItem* root = quickView->rootObject();
            if (root) {
                traverseObject(objectInfo.addObject(), root, command);
            }
        }

        QQuickItem* quickItem = qobject_cast<QQuickItem*>(object);
        if (quickItem) {
            foreach(QQuickItem* child, quickItem->childItems()) {
                traverseObject(objectInfo.addObject(), child, command);
            }
        }

        // support for QML Window.
        QQuickWindow* quickWindow = qobject_cast<QQuickWindow*>(object);
        if (quickWindow) {
            QQuickItem* root = quickWindow->contentItem();
            if (root) {
                traverseObject(objectInfo.addObject(), root, command);
            }
        }

        //check decendants
        //1. is graphicsview
        QGraphicsView* gView = qobject_cast<QGraphicsView*>(object);
        if(gView){
            traverseGraphicsViewItems(objectInfo, gView, command);
        }
        //2. is QGraphicsObject
        QGraphicsObject* graphicsObject = qobject_cast<QGraphicsObject*>(object);
        if(graphicsObject){
            traverseGraphicsItemList(objectInfo, graphicsObject,command);
        }
        //3. Widget children
        else{
            QObjectList children = object->children();
            if (!children.isEmpty()) {
                for (int i = 0; i < children.size(); ++i){
                    QObject *obj = children.at(i);
                    //only include widgets
                    if (obj->isWidgetType() && obj->parent() == object){
                        QWidget *widget = qobject_cast<QWidget*>(obj);
                        // TODO This (and other similar hacks) needs to be moved to plugins once OSS changes are done
                        if (TestabilityUtils::isCustomTraverse() || widget->isVisible() ) /*&& !wasTraversed(widget)*/{
                            traverseObject(objectInfo.addObject(), widget, command);
                        }
                    }
                }
            }
        }
    }
}

void TasUiTraverser::traverseGraphicsItem(TasObject& objectInfo, QGraphicsItem* graphicsItem, TasCommand* command, bool traverseChildren)
{
    QGraphicsObject* object = graphicsItem->toGraphicsObject();
    if (object) {
        traverseObject(objectInfo, object, command);
        // Traverse the actual widget under the proxy, if available
        QGraphicsProxyWidget* proxy = qobject_cast<QGraphicsProxyWidget*>(object);
        if (proxy) {
            traverseObject(objectInfo.addObject(), proxy->widget(), command, traverseChildren);
        }
    }
    else{
        objectInfo.setType("QGraphicsItem");
        QHashIterator<QString, TasTraverseInterface*> i(mTraversers);
        while (i.hasNext()) {
            i.next();
            if(!filterPlugin(i.key())){
                i.value()->traverseGraphicsItem(&objectInfo, graphicsItem, command);
            }
        }
        if(traverseChildren){
            traverseGraphicsItemList(objectInfo, graphicsItem, command);
        }
    }
}

void TasUiTraverser::traverseGraphicsItemList(TasObject& parent, QGraphicsItem* graphicsItem, TasCommand* command)
{
    foreach (QGraphicsItem* item, graphicsItem->childItems()){
        if(graphicsItem == item->parentItem()){
            // TODO This needs to be moved to plugins once OSS changes are done
            if(TestabilityUtils::isCustomTraverse()|| item->isVisible() ) {
                traverseGraphicsItem(parent.addObject(), item, command);
            }
        }
    }
}

void TasUiTraverser::traverseGraphicsViewItems(TasObject& parent, QGraphicsView* view, TasCommand* command)
{
    foreach(QGraphicsItem* item, view->items()){
        if(item->parentItem() == 0){
            // TODO This needs to be moved to plugins once OSS changes are done
            if(TestabilityUtils::isCustomTraverse() || item->isVisible()) {
                traverseGraphicsItem(parent.addObject(), item, command);
            }
        }
    }
}

void TasUiTraverser::addApplicationDetails(TasObject& application, TasCommand* command)
{
    traverseObject(application, qApp, command, false);
    application.setEnv("qt");
    //set these again cause properties overwrite them
    application.setName(getApplicationName());
    application.setId(QString::number(qApp->applicationPid()));
#ifdef Q_OS_SYMBIAN
    quintptr uid = CEikonEnv::Static()->EikAppUi()->Application()->AppDllUid().iUid;
    application.addAttribute("applicationUid", QString::number(uid));

    CWsScreenDevice* sws = new ( ELeave ) CWsScreenDevice( CEikonEnv::Static()->WsSession() );
    CleanupStack::PushL( sws );
    if( sws->Construct() == KErrNone)
    {
        TPixelsAndRotation sizeAndRotation;
        sws->GetDefaultScreenSizeAndRotation( sizeAndRotation );
        qApp->setProperty(APP_ROTATION, QVariant(sizeAndRotation.iRotation));
        application.addAttribute(APP_ROTATION, sizeAndRotation.iRotation);
    }
    CleanupStack::PopAndDestroy( sws );
#endif

    application.addAttribute("arguments", qApp->arguments().join(" ").toLatin1().data());
    application.addAttribute("exepath", qApp->applicationFilePath().toLatin1().data());
    application.addAttribute("FullName", qApp->applicationFilePath().toLatin1().data());
    application.addAttribute("dirpath", qApp->applicationDirPath().toLatin1().data());
    application.addAttribute("processId", QString::number(qApp->applicationPid()).toLatin1().data());
    application.addAttribute("version", qApp->applicationVersion().toLatin1().data());
    application.addAttribute("objectType", TYPE_APPLICATION_VIEW);
    application.addAttribute("objectId", TasCoreUtils::objectId(qApp));

    int mem = TasDeviceUtils::currentProcessHeapSize();
    if(mem != -1){
        application.addAttribute("memUsage", mem);
    }
#if defined(TAS_MAEMO) && defined(HAVE_QAPP)
    MApplication* app = MApplication::instance();
    if (app){
        MLocale defaultMLocale;
        application.addAttribute("localeName", defaultMLocale.name());
        application.addAttribute("localeCountry", defaultMLocale.country());
        application.addAttribute("localeLanguage", defaultMLocale.language());
    }
    else{
        QLocale defaultLocale;
        application.addAttribute("localeName", defaultLocale.name());
        application.addAttribute("localeCountry", defaultLocale.countryToString(defaultLocale.country()));
        application.addAttribute("localeLanguage", defaultLocale.languageToString(defaultLocale.language()));
    }
#else
    QLocale defaultLocale;
    application.addAttribute("localeName", defaultLocale.name());
    application.addAttribute("localeCountry", defaultLocale.countryToString(defaultLocale.country()));
    application.addAttribute("localeLanguage", defaultLocale.languageToString(defaultLocale.language()));
#endif
}

/*!

  Prints all of the actions that a widget has under the widget.
  Makes it possible to easily map the correct action to the
  correct widget and also command the correct widget.
  Returns true if an action was added.

 */

void TasUiTraverser::printActions(TasObject& objectInfo, QObject* object)
{
    QWidget* widget = qobject_cast<QWidget*>(object);
    if(widget){
        addActions(objectInfo, widget->actions());
    }
    else{
        QGraphicsWidget* gWidget = qobject_cast<QGraphicsWidget*>(object);
        if(gWidget){
            addActions(objectInfo, gWidget->actions());
        }
    }
}

void TasUiTraverser::addActions(TasObject& parentObject, QList<QAction*> actions)
{
    if(actions.size() > 0){
        for(int i = 0 ; i < actions.size(); i++){
            QObject* action = actions.at(i);
            traverseObject(parentObject.addObject(), action, 0);
        }
    }
}

<|endoftext|>


<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "xwalk/runtime/browser/android/xwalk_dev_tools_server.h"

#include <sys/types.h>
#include <unistd.h>
#include <vector>

#include "base/android/jni_string.h"
#include "base/basictypes.h"
#include "base/bind.h"
#include "base/callback.h"
#include "base/compiler_specific.h"
#include "base/logging.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "content/public/browser/android/devtools_auth.h"
#include "content/public/browser/devtools_agent_host.h"
#include "content/public/browser/devtools_http_handler.h"
#include "content/public/browser/devtools_http_handler_delegate.h"
#include "content/public/browser/devtools_manager_delegate.h"
#include "content/public/browser/devtools_target.h"
#include "content/public/browser/favicon_status.h"
#include "content/public/browser/navigation_entry.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_delegate.h"
#include "content/public/common/user_agent.h"
#include "grit/xwalk_resources.h"
#include "jni/XWalkDevToolsServer_jni.h"
#include "net/socket/unix_domain_listen_socket_posix.h"
#include "ui/base/resource/resource_bundle.h"

using content::DevToolsAgentHost;
using content::RenderViewHost;
using content::WebContents;

namespace {

// FIXME(girish): The frontend URL needs to be served from the domain below
// for remote debugging to work in chrome (see chrome's devtools_ui.cc).
// Currently, the chrome version is hardcoded because of this dependancy.
const char kFrontEndURL[] =
    "http://chrome-devtools-frontend.appspot.com/serve_rev/%s/devtools.html";
const char kTargetTypePage[] = "page";
const char kTargetTypeServiceWorker[] = "service_worker";
const char kTargetTypeOther[] = "other";

bool AuthorizeSocketAccessWithDebugPermission(
     const net::UnixDomainServerSocket::Credentials& credentials) {
  JNIEnv* env = base::android::AttachCurrentThread();
  return xwalk::Java_XWalkDevToolsServer_checkDebugPermission(
      env, base::android::GetApplicationContext(),
      credentials.process_id, credentials.user_id) ||
      content::CanUserConnectToDevTools(credentials);
}

class Target : public content::DevToolsTarget {
 public:
  explicit Target(scoped_refptr<content::DevToolsAgentHost> agent_host);

  virtual std::string GetId() const OVERRIDE { return agent_host_->GetId(); }
  virtual std::string GetType() const OVERRIDE {
      switch (agent_host_->GetType()) {
        case content::DevToolsAgentHost::TYPE_WEB_CONTENTS:
           return kTargetTypePage;
         case content::DevToolsAgentHost::TYPE_SERVICE_WORKER:
           return kTargetTypeServiceWorker;
         default:
           break;
       }
       return kTargetTypeOther;
     }
  virtual std::string GetTitle() const OVERRIDE {
    return agent_host_->GetTitle();
  }

  // TODO(hmin): Get the description about web contents view.
  virtual std::string GetDescription() const OVERRIDE { return std::string(); }
  virtual GURL GetURL() const OVERRIDE { return url_; }
  virtual GURL GetFaviconURL() const OVERRIDE { return GURL(); }
  virtual base::TimeTicks GetLastActivityTime() const OVERRIDE {
    return last_activity_time_;
  }
  virtual std::string GetParentId() const OVERRIDE { return std::string(); }
  virtual bool IsAttached() const OVERRIDE {
    return agent_host_->IsAttached();
  }
  virtual scoped_refptr<DevToolsAgentHost> GetAgentHost() const OVERRIDE {
    return agent_host_;
  }

  virtual bool Activate() const OVERRIDE {
    WebContents* web_contents = agent_host_->GetWebContents();
    if (!web_contents)
      return false;
    web_contents->GetDelegate()->ActivateContents(web_contents);
    return true;
  }

  virtual bool Close() const OVERRIDE { return false; }

 private:
  scoped_refptr<DevToolsAgentHost> agent_host_;
  std::string id_;
  std::string title_;
  GURL url_;
  GURL favicon_url_;
  base::TimeTicks last_activity_time_;
};

Target::Target(scoped_refptr<content::DevToolsAgentHost> agent_host)
    : agent_host_(agent_host) {
  if (content::WebContents* web_contents = agent_host_->GetWebContents()) {
    content::NavigationController& controller = web_contents->GetController();
    content::NavigationEntry* entry = controller.GetActiveEntry();
    if (entry != NULL && entry->GetURL().is_valid())
      favicon_url_ = entry->GetFavicon().url;
    last_activity_time_ = web_contents->GetLastActiveTime();
  }
}

// Delegate implementation for the devtools http handler on android. A new
// instance of this gets created each time devtools is enabled.
class XWalkDevToolsHttpHandlerDelegate
  : public content::DevToolsHttpHandlerDelegate {
 public:
  explicit XWalkDevToolsHttpHandlerDelegate(
    const net::UnixDomainServerSocket::AuthCallback& auth_callback)
    : auth_callback_(auth_callback) {
  }

  virtual std::string GetDiscoveryPageHTML() OVERRIDE {
    return ResourceBundle::GetSharedInstance().GetRawDataResource(
        IDR_DEVTOOLS_FRONTEND_PAGE_HTML).as_string();
  }

  virtual bool BundlesFrontendResources() OVERRIDE {
    return false;
  }

  virtual base::FilePath GetDebugFrontendDir() OVERRIDE {
    return base::FilePath();
  }

  virtual scoped_ptr<net::StreamListenSocket> CreateSocketForTethering(
      net::StreamListenSocket::Delegate* delegate,
      std::string* name) OVERRIDE {
    return scoped_ptr<net::StreamListenSocket>();
  }
 private:
  const net::UnixDomainServerSocket::AuthCallback auth_callback_;
  DISALLOW_COPY_AND_ASSIGN(XWalkDevToolsHttpHandlerDelegate);
};

class XWalkDevToolsDelegate
  : public content::DevToolsManagerDelegate {
 public:
  virtual std::string GetPageThumbnailData(const GURL& url) OVERRIDE {
    return std::string();
  }

  virtual scoped_ptr<content::DevToolsTarget> CreateNewTarget(
      const GURL&) OVERRIDE {
    return scoped_ptr<content::DevToolsTarget>();
  }
  virtual void EnumerateTargets(TargetCallback callback) OVERRIDE {
    TargetList targets;
    content::DevToolsAgentHost::List agents =
        content::DevToolsAgentHost::GetOrCreateAll();
    for (content::DevToolsAgentHost::List::iterator it = agents.begin();
         it != agents.end(); ++it) {
      targets.push_back(new Target(*it));
    }
    callback.Run(targets);
  }
};

// Factory for UnixDomainServerSocket.
class UnixDomainServerSocketFactory
    : public content::DevToolsHttpHandler::ServerSocketFactory {
 public:
  explicit UnixDomainServerSocketFactory(const std::string& socket_name)
      : content::DevToolsHttpHandler::ServerSocketFactory(socket_name, 0, 1) {}

 private:
  // content::DevToolsHttpHandler::ServerSocketFactory.
  virtual scoped_ptr<net::ServerSocket> Create() const OVERRIDE {
    return scoped_ptr<net::ServerSocket>(
        new net::UnixDomainServerSocket(
            base::Bind(&content::CanUserConnectToDevTools),
            true /* use_abstract_namespace */));
  }

  DISALLOW_COPY_AND_ASSIGN(UnixDomainServerSocketFactory);
};

}  // namespace

namespace xwalk {

XWalkDevToolsServer::XWalkDevToolsServer(const std::string& socket_name)
    : socket_name_(socket_name),
      protocol_handler_(NULL),
      allowed_uid_(0) {
}

XWalkDevToolsServer::~XWalkDevToolsServer() {
  Stop();
}

// Allow connection from uid specified using AllowConnectionFromUid to devtools
// server. This supports the XDK usage: debug bridge wrapper runs in a separate
// process and connects to the devtools server.
bool XWalkDevToolsServer::CanUserConnectToDevTools(
    const net::UnixDomainServerSocket::Credentials& credentials) {
  if (credentials.user_id == allowed_uid_)
    return true;
  return content::CanUserConnectToDevTools(credentials);
}

void XWalkDevToolsServer::Start(bool allow_debug_permission) {
  if (protocol_handler_)
    return;

  net::UnixDomainServerSocket::AuthCallback auth_callback =
      allow_debug_permission ?
          base::Bind(&AuthorizeSocketAccessWithDebugPermission) :
          base::Bind(&content::CanUserConnectToDevTools);

  scoped_ptr<content::DevToolsHttpHandler::ServerSocketFactory> factory(
      new UnixDomainServerSocketFactory(socket_name_));
  protocol_handler_ = content::DevToolsHttpHandler::Start(
      factory.Pass(),
      base::StringPrintf(kFrontEndURL, content::GetWebKitRevision().c_str()),
      new XWalkDevToolsHttpHandlerDelegate(auth_callback), base::FilePath());
}

void XWalkDevToolsServer::Stop() {
  if (!protocol_handler_)
    return;
  // Note that the call to Stop() below takes care of |protocol_handler_|
  // deletion.
  protocol_handler_->Stop();
  protocol_handler_ = NULL;
}

bool XWalkDevToolsServer::IsStarted() const {
  return protocol_handler_;
}

void XWalkDevToolsServer::AllowConnectionFromUid(uid_t uid) {
  allowed_uid_ = uid;
}

bool RegisterXWalkDevToolsServer(JNIEnv* env) {
  return RegisterNativesImpl(env);
}

static jlong InitRemoteDebugging(JNIEnv* env,
                                jobject obj,
                                jstring socketName) {
  XWalkDevToolsServer* server = new XWalkDevToolsServer(
      base::android::ConvertJavaStringToUTF8(env, socketName));
  return reinterpret_cast<intptr_t>(server);
}

static void DestroyRemoteDebugging(JNIEnv* env, jobject obj, jlong server) {
  delete reinterpret_cast<XWalkDevToolsServer*>(server);
}

static jboolean IsRemoteDebuggingEnabled(JNIEnv* env,
                                         jobject obj,
                                         jlong server) {
  return reinterpret_cast<XWalkDevToolsServer*>(server)->IsStarted();
}

static void SetRemoteDebuggingEnabled(JNIEnv* env,
                                      jobject obj,
                                      jlong server,
                                      jboolean enabled,
                                      jboolean allow_debug_permission) {
  XWalkDevToolsServer* devtools_server =
      reinterpret_cast<XWalkDevToolsServer*>(server);
  if (enabled) {
    devtools_server->Start(allow_debug_permission);
  } else {
    devtools_server->Stop();
  }
}

static void AllowConnectionFromUid(JNIEnv* env,
                                    jobject obj,
                                    jlong server,
                                    jint uid) {
  XWalkDevToolsServer* devtools_server =
      reinterpret_cast<XWalkDevToolsServer*>(server);
  devtools_server->AllowConnectionFromUid((uid_t) uid);
}

}  // namespace xwalk
<commit_msg>restored functionality of XDK agents (AppPreview and AppPreviewXWalk) broken since xwalk9. The fix consist in checking of uid passed thorough AllowConnectionFromUid and only if uid is not eq to the stored, call chromium corresponded function to check<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "xwalk/runtime/browser/android/xwalk_dev_tools_server.h"

#include <sys/types.h>
#include <unistd.h>
#include <vector>

#include "base/android/jni_string.h"
#include "base/basictypes.h"
#include "base/bind.h"
#include "base/callback.h"
#include "base/compiler_specific.h"
#include "base/logging.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "content/public/browser/android/devtools_auth.h"
#include "content/public/browser/devtools_agent_host.h"
#include "content/public/browser/devtools_http_handler.h"
#include "content/public/browser/devtools_http_handler_delegate.h"
#include "content/public/browser/devtools_manager_delegate.h"
#include "content/public/browser/devtools_target.h"
#include "content/public/browser/favicon_status.h"
#include "content/public/browser/navigation_entry.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_delegate.h"
#include "content/public/common/user_agent.h"
#include "grit/xwalk_resources.h"
#include "jni/XWalkDevToolsServer_jni.h"
#include "net/socket/unix_domain_listen_socket_posix.h"
#include "ui/base/resource/resource_bundle.h"

using content::DevToolsAgentHost;
using content::RenderViewHost;
using content::WebContents;

namespace {

// FIXME(girish): The frontend URL needs to be served from the domain below
// for remote debugging to work in chrome (see chrome's devtools_ui.cc).
// Currently, the chrome version is hardcoded because of this dependancy.
const char kFrontEndURL[] =
    "http://chrome-devtools-frontend.appspot.com/serve_rev/%s/devtools.html";
const char kTargetTypePage[] = "page";
const char kTargetTypeServiceWorker[] = "service_worker";
const char kTargetTypeOther[] = "other";

bool AuthorizeSocketAccessWithDebugPermission(
     const net::UnixDomainServerSocket::Credentials& credentials) {
  JNIEnv* env = base::android::AttachCurrentThread();
  return xwalk::Java_XWalkDevToolsServer_checkDebugPermission(
      env, base::android::GetApplicationContext(),
      credentials.process_id, credentials.user_id) ||
      content::CanUserConnectToDevTools(credentials);
}

class Target : public content::DevToolsTarget {
 public:
  explicit Target(scoped_refptr<content::DevToolsAgentHost> agent_host);

  virtual std::string GetId() const OVERRIDE { return agent_host_->GetId(); }
  virtual std::string GetType() const OVERRIDE {
      switch (agent_host_->GetType()) {
        case content::DevToolsAgentHost::TYPE_WEB_CONTENTS:
           return kTargetTypePage;
         case content::DevToolsAgentHost::TYPE_SERVICE_WORKER:
           return kTargetTypeServiceWorker;
         default:
           break;
       }
       return kTargetTypeOther;
     }
  virtual std::string GetTitle() const OVERRIDE {
    return agent_host_->GetTitle();
  }

  // TODO(hmin): Get the description about web contents view.
  virtual std::string GetDescription() const OVERRIDE { return std::string(); }
  virtual GURL GetURL() const OVERRIDE { return url_; }
  virtual GURL GetFaviconURL() const OVERRIDE { return GURL(); }
  virtual base::TimeTicks GetLastActivityTime() const OVERRIDE {
    return last_activity_time_;
  }
  virtual std::string GetParentId() const OVERRIDE { return std::string(); }
  virtual bool IsAttached() const OVERRIDE {
    return agent_host_->IsAttached();
  }
  virtual scoped_refptr<DevToolsAgentHost> GetAgentHost() const OVERRIDE {
    return agent_host_;
  }

  virtual bool Activate() const OVERRIDE {
    WebContents* web_contents = agent_host_->GetWebContents();
    if (!web_contents)
      return false;
    web_contents->GetDelegate()->ActivateContents(web_contents);
    return true;
  }

  virtual bool Close() const OVERRIDE { return false; }

 private:
  scoped_refptr<DevToolsAgentHost> agent_host_;
  std::string id_;
  std::string title_;
  GURL url_;
  GURL favicon_url_;
  base::TimeTicks last_activity_time_;
};

Target::Target(scoped_refptr<content::DevToolsAgentHost> agent_host)
    : agent_host_(agent_host) {
  if (content::WebContents* web_contents = agent_host_->GetWebContents()) {
    content::NavigationController& controller = web_contents->GetController();
    content::NavigationEntry* entry = controller.GetActiveEntry();
    if (entry != NULL && entry->GetURL().is_valid())
      favicon_url_ = entry->GetFavicon().url;
    last_activity_time_ = web_contents->GetLastActiveTime();
  }
}

// Delegate implementation for the devtools http handler on android. A new
// instance of this gets created each time devtools is enabled.
class XWalkDevToolsHttpHandlerDelegate
  : public content::DevToolsHttpHandlerDelegate {
 public:
  explicit XWalkDevToolsHttpHandlerDelegate(
    const net::UnixDomainServerSocket::AuthCallback& auth_callback)
    : auth_callback_(auth_callback) {
  }

  virtual std::string GetDiscoveryPageHTML() OVERRIDE {
    return ResourceBundle::GetSharedInstance().GetRawDataResource(
        IDR_DEVTOOLS_FRONTEND_PAGE_HTML).as_string();
  }

  virtual bool BundlesFrontendResources() OVERRIDE {
    return false;
  }

  virtual base::FilePath GetDebugFrontendDir() OVERRIDE {
    return base::FilePath();
  }

  virtual scoped_ptr<net::StreamListenSocket> CreateSocketForTethering(
      net::StreamListenSocket::Delegate* delegate,
      std::string* name) OVERRIDE {
    return scoped_ptr<net::StreamListenSocket>();
  }
 private:
  const net::UnixDomainServerSocket::AuthCallback auth_callback_;
  DISALLOW_COPY_AND_ASSIGN(XWalkDevToolsHttpHandlerDelegate);
};

class XWalkDevToolsDelegate
  : public content::DevToolsManagerDelegate {
 public:
  virtual std::string GetPageThumbnailData(const GURL& url) OVERRIDE {
    return std::string();
  }

  virtual scoped_ptr<content::DevToolsTarget> CreateNewTarget(
      const GURL&) OVERRIDE {
    return scoped_ptr<content::DevToolsTarget>();
  }
  virtual void EnumerateTargets(TargetCallback callback) OVERRIDE {
    TargetList targets;
    content::DevToolsAgentHost::List agents =
        content::DevToolsAgentHost::GetOrCreateAll();
    for (content::DevToolsAgentHost::List::iterator it = agents.begin();
         it != agents.end(); ++it) {
      targets.push_back(new Target(*it));
    }
    callback.Run(targets);
  }
};

// Factory for UnixDomainServerSocket.
class UnixDomainServerSocketFactory
    : public content::DevToolsHttpHandler::ServerSocketFactory {
 public:
  explicit UnixDomainServerSocketFactory(const std::string& socket_name)
      : content::DevToolsHttpHandler::ServerSocketFactory(socket_name, 0, 1) {}

 private:
  // content::DevToolsHttpHandler::ServerSocketFactory.
  virtual scoped_ptr<net::ServerSocket> Create() const OVERRIDE {
    return scoped_ptr<net::ServerSocket>(
        new net::UnixDomainServerSocket(
            base::Bind(&content::CanUserConnectToDevTools),
            true /* use_abstract_namespace */));
  }

  DISALLOW_COPY_AND_ASSIGN(UnixDomainServerSocketFactory);
};

}  // namespace

namespace xwalk {

XWalkDevToolsServer::XWalkDevToolsServer(const std::string& socket_name)
    : socket_name_(socket_name),
      protocol_handler_(NULL),
      allowed_uid_(0) {
}

XWalkDevToolsServer::~XWalkDevToolsServer() {
  Stop();
}

// Allow connection from uid specified using AllowConnectionFromUid to devtools
// server. This supports the XDK usage: debug bridge wrapper runs in a separate
// process and connects to the devtools server.
bool XWalkDevToolsServer::CanUserConnectToDevTools(
    const net::UnixDomainServerSocket::Credentials& credentials) {
  if (credentials.user_id == allowed_uid_)
    return true;
  return content::CanUserConnectToDevTools(credentials);
}

void XWalkDevToolsServer::Start(bool allow_debug_permission) {
  if (protocol_handler_)
    return;

  net::UnixDomainServerSocket::AuthCallback auth_callback =
      allow_debug_permission ?
          base::Bind(&AuthorizeSocketAccessWithDebugPermission) :
          base::Bind(&XWalkDevToolsServer::CanUserConnectToDevTools,
              base::Unretained(this));

  scoped_ptr<content::DevToolsHttpHandler::ServerSocketFactory> factory(
      new UnixDomainServerSocketFactory(socket_name_));
  protocol_handler_ = content::DevToolsHttpHandler::Start(
      factory.Pass(),
      base::StringPrintf(kFrontEndURL, content::GetWebKitRevision().c_str()),
      new XWalkDevToolsHttpHandlerDelegate(auth_callback), base::FilePath());
}

void XWalkDevToolsServer::Stop() {
  if (!protocol_handler_)
    return;
  // Note that the call to Stop() below takes care of |protocol_handler_|
  // deletion.
  protocol_handler_->Stop();
  protocol_handler_ = NULL;
}

bool XWalkDevToolsServer::IsStarted() const {
  return protocol_handler_;
}

void XWalkDevToolsServer::AllowConnectionFromUid(uid_t uid) {
  allowed_uid_ = uid;
}

bool RegisterXWalkDevToolsServer(JNIEnv* env) {
  return RegisterNativesImpl(env);
}

static jlong InitRemoteDebugging(JNIEnv* env,
                                jobject obj,
                                jstring socketName) {
  XWalkDevToolsServer* server = new XWalkDevToolsServer(
      base::android::ConvertJavaStringToUTF8(env, socketName));
  return reinterpret_cast<intptr_t>(server);
}

static void DestroyRemoteDebugging(JNIEnv* env, jobject obj, jlong server) {
  delete reinterpret_cast<XWalkDevToolsServer*>(server);
}

static jboolean IsRemoteDebuggingEnabled(JNIEnv* env,
                                         jobject obj,
                                         jlong server) {
  return reinterpret_cast<XWalkDevToolsServer*>(server)->IsStarted();
}

static void SetRemoteDebuggingEnabled(JNIEnv* env,
                                      jobject obj,
                                      jlong server,
                                      jboolean enabled,
                                      jboolean allow_debug_permission) {
  XWalkDevToolsServer* devtools_server =
      reinterpret_cast<XWalkDevToolsServer*>(server);
  if (enabled) {
    devtools_server->Start(allow_debug_permission);
  } else {
    devtools_server->Stop();
  }
}

static void AllowConnectionFromUid(JNIEnv* env,
                                    jobject obj,
                                    jlong server,
                                    jint uid) {
  XWalkDevToolsServer* devtools_server =
      reinterpret_cast<XWalkDevToolsServer*>(server);
  devtools_server->AllowConnectionFromUid((uid_t) uid);
}

}  // namespace xwalk
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: TokenWriter.hxx,v $
 *
 *  $Revision: 1.20 $
 *
 *  last change: $Author: rt $ $Date: 2007-07-24 12:09:26 $
 *
 *  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_TOKENWRITER_HXX
#define DBAUI_TOKENWRITER_HXX

#ifndef DBAUI_DATABASEEXPORT_HXX
#include "DExport.hxx"
#endif
#ifndef _DBAUI_MODULE_DBU_HXX_
#include "moduledbu.hxx"
#endif
#ifndef _STREAM_HXX //autogen
#include <tools/stream.hxx>
#endif
#ifndef _COM_SUN_STAR_AWT_FONTDESCRIPTOR_HPP_
#include <com/sun/star/awt/FontDescriptor.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_
#include <com/sun/star/sdbc/XResultSet.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XRESULTSETUPDATE_HPP_
#include <com/sun/star/sdbc/XResultSetUpdate.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XROW_HPP_
#include <com/sun/star/sdbc/XRow.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XEVENTLISTENER_HPP_
#include <com/sun/star/lang/XEventListener.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XMODEL_HPP_
#include <com/sun/star/frame/XModel.hpp>
#endif
#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _COM_SUN_STAR_SDB_COMMANDTYPE_HPP_
#include <com/sun/star/sdb/CommandType.hpp>
#endif
#ifndef _SVX_DATACCESSDESCRIPTOR_HXX_
#include <svx/dataaccessdescriptor.hxx>
#endif
#ifndef _DBAUI_COMMON_TYPES_HXX_
#include "commontypes.hxx"
#endif
#include <memory>

namespace com { namespace sun { namespace star {
    namespace sdbc{
        class XRowUpdate;
    }
}}}

namespace dbaui
{
    // =========================================================================
    // ODatabaseImportExport Basisklasse f"ur Import/Export
    // =========================================================================
    class ODatabaseExport;
    typedef ::cppu::WeakImplHelper1< ::com::sun::star::lang::XEventListener> ODatabaseImportExport_BASE;
    class ODatabaseImportExport : public ODatabaseImportExport_BASE
    {
    private:
        void disposing();

    protected:
        typedef ::utl::SharedUNOComponent   <   ::com::sun::star::frame::XModel
                                            ,   ::utl::CloseableComponent
                                            >   SharedModel;

    protected:
        ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any>                    m_aSelection;
        SvStream*                                                                       m_pStream;
        ::com::sun::star::awt::FontDescriptor                                           m_aFont;
        ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >       m_xObject;      // table/query
        SharedConnection                                                                m_xConnection;  //
        ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet >          m_xResultSet;   //
        ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XRow >                m_xRow; //
        ::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;
        SharedModel                                                                     m_aKeepModelAlive;

        ::rtl::OUString m_sName;
        ::rtl::OUString m_sDataSourceName;
        sal_Int32       m_nCommandType;

#if defined UNX
        static const char __FAR_DATA sNewLine;
#else
        static const char __FAR_DATA sNewLine[];
#endif

        ODatabaseExport*    m_pReader;
        sal_Int32*          m_pRowMarker; // wenn gesetzt, dann nur diese Rows kopieren
        sal_Bool            m_bInInitialize;
        sal_Bool            m_bCheckOnly;

        // export data
        ODatabaseImportExport(  const ::svx::ODataAccessDescriptor& _aDataDescriptor,
                                const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rM,
                                const ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatter >& _rxNumberF,
                                const String& rExchange = String());

        // import data
        ODatabaseImportExport(  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);

        virtual ~ODatabaseImportExport();

        virtual void initialize();
    public:
        void setStream(SvStream* _pStream){  m_pStream = _pStream; }

        virtual BOOL Write()    = 0; // Export
        virtual BOOL Read()     = 0; // Import

        void initialize(const ::svx::ODataAccessDescriptor& _aDataDescriptor);

        virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source ) throw(::com::sun::star::uno::RuntimeException);

        void enableCheckOnly() { m_bCheckOnly = sal_True; }
        sal_Bool isCheckEnabled() const { return m_bCheckOnly; }

    private:
        void impl_initFromDescriptor( const ::svx::ODataAccessDescriptor& _aDataDescriptor, bool _bPlusDefaultInit );
    };

    // =========================================================================
    // RTF Im- und Export
    // =========================================================================

    class ORTFImportExport : public ODatabaseImportExport
    {

    public:
        // export data
        ORTFImportExport(   const ::svx::ODataAccessDescriptor& _aDataDescriptor,
                            const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rM,
                            const ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatter >& _rxNumberF,
                            const String& rExchange = String())
                            : ODatabaseImportExport(_aDataDescriptor,_rM,_rxNumberF,rExchange) {};

        // import data
        ORTFImportExport(   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)
                        : ODatabaseImportExport(_rxConnection,_rxNumberF,_rM)
        {}

        virtual BOOL Write();
        virtual BOOL Read();
    };
    // =========================================================================
    // HTML Im- und Export
    // =========================================================================
    #define SBA_HTML_FONTSIZES 7
    const sal_Int16 nIndentMax = 23;
    class OHTMLImportExport : public ODatabaseImportExport
    {
        // default HtmlFontSz[1-7]
        static const sal_Int16  nDefaultFontSize[SBA_HTML_FONTSIZES];
        // HtmlFontSz[1-7] in s*3.ini [user]
        static sal_Int16        nFontSize[SBA_HTML_FONTSIZES];
        static const sal_Int16  nCellSpacing;
        static const char __FAR_DATA sIndentSource[];
        char                    sIndent[nIndentMax+1];
        sal_Int16               m_nIndent;
    #ifdef DBG_UTIL
        BOOL                    m_bCheckFont;
    #endif

        void WriteHeader();
        void WriteBody();
        void WriteTables();
        void WriteCell( sal_Int32 nFormat,sal_Int32 nWidthPixel,sal_Int32 nHeightPixel,const char* pChar,const String& rValue,const char* pHtmlTag);
        void IncIndent( sal_Int16 nVal );
        const char*         GetIndentStr() { return sIndent; }
        void FontOn();
        inline void FontOff();

    public:
        // export data
        OHTMLImportExport(  const ::svx::ODataAccessDescriptor& _aDataDescriptor,
                            const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rM,
                            const ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatter >& _rxNumberF,
                            const String& rExchange = String());
        // import data
        OHTMLImportExport(  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)
                        : ODatabaseImportExport(_rxConnection,_rxNumberF,_rM)
        {}

        virtual BOOL Write();
        virtual BOOL Read();

    };
    // =========================================================================
    // normal RowSet Im- und Export
    // =========================================================================

    class ORowSetImportExport : public ODatabaseImportExport
    {
        OModuleClient       m_aModuleClient;
        ::std::vector<sal_Int32>    m_aColumnMapping;
        ::std::vector<sal_Int32>    m_aColumnTypes;
        ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSetUpdate >    m_xTargetResultSetUpdate;   //
        ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XRowUpdate >          m_xTargetRowUpdate;         //
        ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSetMetaData >  m_xTargetResultSetMetaData; //
        Window*                     m_pParent;
        sal_Bool                    m_bAlreadyAsked;

        sal_Bool insertNewRow();
    protected:
        virtual void initialize();

    public:
        // export data
        ORowSetImportExport(Window* _pParent,
                            const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSetUpdate >& _xResultSetUpdate,
                            const ::svx::ODataAccessDescriptor& _aDataDescriptor,
                            const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rM,
                            const String& rExchange = String());

        // import data
        ORowSetImportExport(const SharedConnection& _rxConnection,
                            const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rM)
                        : ODatabaseImportExport(_rxConnection,NULL,_rM)
        {}

        virtual BOOL Write();
        virtual BOOL Read();

    private:
        using ODatabaseImportExport::initialize;
    };

}
#endif // DBAUI_TOKENWRITER_HXX

<commit_msg>INTEGRATION: CWS dba24a (1.19.16); FILE MERGED 2007/08/13 05:31:06 oj 1.19.16.2: RESYNC: (1.19-1.20); FILE MERGED 2007/07/23 11:59:03 fs 1.19.16.1: when pasting tables, use a meaningful default in the wizard, as indicated by the current selection Issue number:  #i18907# Submitted by:  dyf@openoffice.org Reviewed by:   frank.schoenheit@sun.com<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: TokenWriter.hxx,v $
 *
 *  $Revision: 1.21 $
 *
 *  last change: $Author: hr $ $Date: 2007-09-26 14:50:16 $
 *
 *  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_TOKENWRITER_HXX
#define DBAUI_TOKENWRITER_HXX

#ifndef DBAUI_DATABASEEXPORT_HXX
#include "DExport.hxx"
#endif
#ifndef _DBAUI_MODULE_DBU_HXX_
#include "moduledbu.hxx"
#endif
#ifndef _STREAM_HXX //autogen
#include <tools/stream.hxx>
#endif
#ifndef _COM_SUN_STAR_AWT_FONTDESCRIPTOR_HPP_
#include <com/sun/star/awt/FontDescriptor.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_
#include <com/sun/star/sdbc/XResultSet.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XRESULTSETUPDATE_HPP_
#include <com/sun/star/sdbc/XResultSetUpdate.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XROW_HPP_
#include <com/sun/star/sdbc/XRow.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XEVENTLISTENER_HPP_
#include <com/sun/star/lang/XEventListener.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XMODEL_HPP_
#include <com/sun/star/frame/XModel.hpp>
#endif
#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _COM_SUN_STAR_SDB_COMMANDTYPE_HPP_
#include <com/sun/star/sdb/CommandType.hpp>
#endif
#ifndef _SVX_DATACCESSDESCRIPTOR_HXX_
#include <svx/dataaccessdescriptor.hxx>
#endif
#ifndef _DBAUI_COMMON_TYPES_HXX_
#include "commontypes.hxx"
#endif
#include <memory>

namespace com { namespace sun { namespace star {
    namespace sdbc{
        class XRowUpdate;
    }
}}}

namespace dbaui
{
    // =========================================================================
    // ODatabaseImportExport Basisklasse f"ur Import/Export
    // =========================================================================
    class ODatabaseExport;
    typedef ::cppu::WeakImplHelper1< ::com::sun::star::lang::XEventListener> ODatabaseImportExport_BASE;
    class ODatabaseImportExport : public ODatabaseImportExport_BASE
    {
    private:
        void disposing();

    protected:
        typedef ::utl::SharedUNOComponent   <   ::com::sun::star::frame::XModel
                                            ,   ::utl::CloseableComponent
                                            >   SharedModel;

    protected:
        ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any>                    m_aSelection;
        SvStream*                                                                       m_pStream;
        ::com::sun::star::awt::FontDescriptor                                           m_aFont;
        ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >       m_xObject;      // table/query
        SharedConnection                                                                m_xConnection;  //
        ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet >          m_xResultSet;   //
        ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XRow >                m_xRow; //
        ::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;
        SharedModel                                                                     m_aKeepModelAlive;

        ::rtl::OUString m_sName;
        //dyf add 20070601
        //for transfor the tablename
        ::rtl::OUString m_sDefaultTableName;
        //dyf add end
        ::rtl::OUString m_sDataSourceName;
        sal_Int32       m_nCommandType;

#if defined UNX
        static const char __FAR_DATA sNewLine;
#else
        static const char __FAR_DATA sNewLine[];
#endif

        ODatabaseExport*    m_pReader;
        sal_Int32*          m_pRowMarker; // wenn gesetzt, dann nur diese Rows kopieren
        sal_Bool            m_bInInitialize;
        sal_Bool            m_bCheckOnly;

        // export data
        ODatabaseImportExport(  const ::svx::ODataAccessDescriptor& _aDataDescriptor,
                                const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rM,
                                const ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatter >& _rxNumberF,
                                const String& rExchange = String());

        // import data
        ODatabaseImportExport(  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);

        virtual ~ODatabaseImportExport();

        virtual void initialize();
    public:
        void setStream(SvStream* _pStream){  m_pStream = _pStream; }

        //dyf add 20070601
        //for set the tablename
        void setSTableName(const ::rtl::OUString &_sTableName){ m_sDefaultTableName = _sTableName; }
        //dyf add end

        virtual BOOL Write()    = 0; // Export
        virtual BOOL Read()     = 0; // Import

        void initialize(const ::svx::ODataAccessDescriptor& _aDataDescriptor);

        virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source ) throw(::com::sun::star::uno::RuntimeException);

        void enableCheckOnly() { m_bCheckOnly = sal_True; }
        sal_Bool isCheckEnabled() const { return m_bCheckOnly; }

    private:
        void impl_initFromDescriptor( const ::svx::ODataAccessDescriptor& _aDataDescriptor, bool _bPlusDefaultInit );
    };

    // =========================================================================
    // RTF Im- und Export
    // =========================================================================

    class ORTFImportExport : public ODatabaseImportExport
    {

    public:
        // export data
        ORTFImportExport(   const ::svx::ODataAccessDescriptor& _aDataDescriptor,
                            const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rM,
                            const ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatter >& _rxNumberF,
                            const String& rExchange = String())
                            : ODatabaseImportExport(_aDataDescriptor,_rM,_rxNumberF,rExchange) {};

        // import data
        ORTFImportExport(   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)
                        : ODatabaseImportExport(_rxConnection,_rxNumberF,_rM)
        {}

        virtual BOOL Write();
        virtual BOOL Read();
    };
    // =========================================================================
    // HTML Im- und Export
    // =========================================================================
    #define SBA_HTML_FONTSIZES 7
    const sal_Int16 nIndentMax = 23;
    class OHTMLImportExport : public ODatabaseImportExport
    {
        // default HtmlFontSz[1-7]
        static const sal_Int16  nDefaultFontSize[SBA_HTML_FONTSIZES];
        // HtmlFontSz[1-7] in s*3.ini [user]
        static sal_Int16        nFontSize[SBA_HTML_FONTSIZES];
        static const sal_Int16  nCellSpacing;
        static const char __FAR_DATA sIndentSource[];
        char                    sIndent[nIndentMax+1];
        sal_Int16               m_nIndent;
    #ifdef DBG_UTIL
        BOOL                    m_bCheckFont;
    #endif

        void WriteHeader();
        void WriteBody();
        void WriteTables();
        void WriteCell( sal_Int32 nFormat,sal_Int32 nWidthPixel,sal_Int32 nHeightPixel,const char* pChar,const String& rValue,const char* pHtmlTag);
        void IncIndent( sal_Int16 nVal );
        const char*         GetIndentStr() { return sIndent; }
        void FontOn();
        inline void FontOff();

    public:
        // export data
        OHTMLImportExport(  const ::svx::ODataAccessDescriptor& _aDataDescriptor,
                            const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rM,
                            const ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatter >& _rxNumberF,
                            const String& rExchange = String());
        // import data
        OHTMLImportExport(  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)
                        : ODatabaseImportExport(_rxConnection,_rxNumberF,_rM)
        {}

        virtual BOOL Write();
        virtual BOOL Read();

    };
    // =========================================================================
    // normal RowSet Im- und Export
    // =========================================================================

    class ORowSetImportExport : public ODatabaseImportExport
    {
        OModuleClient       m_aModuleClient;
        ::std::vector<sal_Int32>    m_aColumnMapping;
        ::std::vector<sal_Int32>    m_aColumnTypes;
        ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSetUpdate >    m_xTargetResultSetUpdate;   //
        ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XRowUpdate >          m_xTargetRowUpdate;         //
        ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSetMetaData >  m_xTargetResultSetMetaData; //
        Window*                     m_pParent;
        sal_Bool                    m_bAlreadyAsked;

        sal_Bool insertNewRow();
    protected:
        virtual void initialize();

    public:
        // export data
        ORowSetImportExport(Window* _pParent,
                            const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSetUpdate >& _xResultSetUpdate,
                            const ::svx::ODataAccessDescriptor& _aDataDescriptor,
                            const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rM,
                            const String& rExchange = String());

        // import data
        ORowSetImportExport(const SharedConnection& _rxConnection,
                            const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rM)
                        : ODatabaseImportExport(_rxConnection,NULL,_rM)
        {}

        virtual BOOL Write();
        virtual BOOL Read();

    private:
        using ODatabaseImportExport::initialize;
    };

}
#endif // DBAUI_TOKENWRITER_HXX

<|endoftext|>