<commit_before>#include <stdlib.h>
#include <stdio.h>
#include <boost/version.hpp>

#include <fstream>
#include <stdint.h>
#include "task_manager_lib/TaskServerInterface.h"
#include <ros/ros.h>
#include <ros/package.h>

using namespace boost::posix_time;
using namespace std;
using namespace task_manager_lib;

std::string TaskServerInterface::package_name = "task_manager_turtlesim";

TaskServerInterface::TaskServerInterface(task_manager_lib::TaskScheduler &ts_ref)
{
	saveBasicMissionSrv = ts_ref.getNodeHandle().advertiseService("save_basic_mission", &TaskServerInterface::saveBasicMission,this);
	saveComplexMissionSrv = ts_ref.getNodeHandle().advertiseService("save_complex_mission", &TaskServerInterface::saveComplexMission,this);
	executeComplexMissionsSrv= ts_ref.getNodeHandle().advertiseService("execute_complex_mission", &TaskServerInterface::executeComplexMission,this);
	stopComplexMissionsSrv= ts_ref.getNodeHandle().advertiseService("abord_complex_mission", &TaskServerInterface::stopComplexMission,this);
	listMissionsSrv=ts_ref.getNodeHandle().advertiseService("list_mission", &TaskServerInterface::listMissions,this);
}

//callback

bool TaskServerInterface::saveBasicMission(task_manager_lib::SaveBasicMission::Request  &req, task_manager_lib::SaveBasicMission::Response &res )
{
	createBasicMissionFile(req.basic_mission,res.filename);
	return true;
}

bool TaskServerInterface::saveComplexMission(task_manager_lib::SaveComplexMission::Request  &req, task_manager_lib::SaveComplexMission::Response &res )
{
	createComplexMissionFile(req.complex_mission,res.filename);
	return true;
}

bool TaskServerInterface::executeComplexMission(task_manager_lib::ExeComplexMission::Request  &req, task_manager_lib::ExeComplexMission::Response &res )
{
	launchComplexMission(req.mission_name, res.pid);
	return true;
}

bool TaskServerInterface::stopComplexMission(task_manager_lib::StopComplexMission::Request  &req, task_manager_lib::StopComplexMission::Response &res )
{
	abordComplexMission(req.pid);
	return true;
}

bool TaskServerInterface::listMissions(task_manager_lib::ListMissions::Request  &req, task_manager_lib::ListMissions::Response &res )
{
	parseMissionDirectory(res.basic_missions,res.complex_missions);
	return true;
}

void TaskServerInterface::createBasicMissionFile(std::vector<task_manager_msgs::TaskDescriptionLight> &basic_mission, std::string &filename) const
{
	std::vector<task_manager_msgs::TaskDescriptionLight> tasklist=basic_mission;

	try
	{
		stringstream path(ros::package::getPath(TaskServerInterface::package_name));
		stringstream msg;
		if (path.str().length() >0)
		{
			boost::filesystem::path mission_path(path.str()+"/missions");
			if (boost::filesystem::exists(mission_path))
			{
				time_facet *facet = new time_facet("%d-%b-%Y-%H_%M_%S");

				stringstream pathName;
				pathName.imbue(locale(pathName.getloc(), facet));
				pathName<<mission_path.string()<<"/mission_"<<second_clock::local_time() << ".mission";

				boost::filesystem::path output_boost_path(pathName.str());

				ofstream outputFile (pathName.str().c_str()) ;
				//write mission file
				//Mission task
				for (unsigned int i = 0;i<tasklist.size();i++)
				{
					outputFile<<"---"<<"\n";
					outputFile<<tasklist[i].name<<"\n";

					if (tasklist[i].parameters.size()==0)
					{
						outputFile<<"empty"<<"\n";
					}
					else
					{
						for (unsigned int j = 0;j<tasklist[i].parameters.size();j++)
						{
							outputFile<<tasklist[i].parameters[j].name;
							outputFile<<";";
							outputFile<<tasklist[i].parameters[j].value;
							outputFile<<"|";
						}
						outputFile<<"\n";
					}

					outputFile.close();

				}
#if (BOOST_VERSION > 104200)
                filename=output_boost_path.filename().string();
#else
                filename=output_boost_path.filename();
#endif
			}
			else
			{
				#if (BOOST_VERSION > 104200)
					PRINTF(1,"%s does not exist\n",mission_path.c_str());
				#else
					PRINTF(1,"%s does not exist\n",mission_path.string().c_str());
				#endif
			}

		}
		else
		{
			PRINTF(1,"%s does not exist\n",path.str().c_str());
		}

	}
	catch (char * str)
	{
		PRINTF(1,"%s",str);
		filename="Error creating Basic Mission file";
	}
}

void TaskServerInterface::createComplexMissionFile(std::string &complex_mission, std::string &filename)
{
	std::string tasklist=complex_mission;
	stringstream msg;
	try
	{
		std::stringstream path(ros::package::getPath(TaskServerInterface::package_name));
		if (path.str().length() >0)
		{
			boost::filesystem::path mission_path(path.str()+"/missions");
			if (boost::filesystem::exists(mission_path))
			{
				time_facet *facet = new time_facet("%d-%b-%Y-%H_%M_%S");

				std::stringstream pathName;
				pathName.imbue(locale(pathName.getloc(), facet));
				pathName<<mission_path.string()<<"/mission_"<<second_clock::local_time() << ".py";

				boost::filesystem::path output_boost_path(pathName.str());

				if (boost::filesystem::exists(output_boost_path))
				{
					//replace
				}
				else
				{
					//write mission file
					try
					{
						ofstream outputFile (pathName.str().c_str()) ;
						outputFile<<tasklist<<endl;
						outputFile.close();
						std::stringstream command_line;
						command_line<<"chmod 775 "<<pathName.str();
						int result=system(command_line.str().c_str());
						if (result!=0)
						{
							PRINTF(1,"Error %d setting execution permission to %s",result,command_line.str().c_str());
						}
					}
					catch(char * str)
					{
						PRINTF(1,"%s",str);
					}
				}
#if BOOST_VERSION > 104200
				filename=output_boost_path.filename().string();
#else
				filename=output_boost_path.filename();
#endif
				//update list of complex filename
				task_manager_msgs::ComplexMission current_mission;
				current_mission.name=filename;
				current_mission.complex_mission=tasklist;
				ComplexMissions.push_back(current_mission);

			}
			else
			{
				#if (BOOST_VERSION > 104200)
					PRINTF(1,"%s does not exist\n",mission_path.c_str());
				#else
					PRINTF(1,"%s does not exist\n",mission_path.string().c_str());
				#endif
			}
		}
		else
		{
			PRINTF(1," %s does not exist\n",path.str().c_str());
		}

	}
	catch (char * str)
	{
		PRINTF(1,"%s",str);
		filename="error creating file";
	}

}

void TaskServerInterface::parseBasicMissionFile(boost::filesystem::path &mission_file_path, std::vector<task_manager_msgs::BasicMission>& basic_missions)
{
	if (boost::filesystem::exists(mission_file_path))
	{
		stringstream pathName(mission_file_path.string());
		ifstream MisssionFile(pathName.str().c_str());
		std::string line;

		task_manager_msgs::BasicMission mission_elem;
		std::vector<task_manager_msgs::TaskDescriptionLight> tasks;

		if (MisssionFile.is_open())
		{
			task_manager_msgs::TaskDescriptionLight current_task;
			std::vector<task_manager_msgs::TaskParameter> parameters;

			unsigned int current_line(0), task_line(0);
			while ( getline(MisssionFile,line))
			{
				current_line ++;
				if (line=="---")
				{
					task_line=current_line;
					current_task=task_manager_msgs::TaskDescriptionLight();
					parameters.clear();

				}
				else
				{
					if (current_line>0)
					{
						if (current_line==task_line+1)//name
						{
							current_task.name=line;
						}
						else if (current_line==task_line+2)//params
						{
							if (line!="empty")
							{
								std::vector<std::string> params;
								split(line,'|',params);
								for (unsigned int j=0;j<params.size();j++)
								{
									std::vector<std::string> name_value;
									split(params[j],';',name_value);
									task_manager_msgs::TaskParameter current_param;
									current_param.name=name_value[0];
									current_param.value=name_value[1];
									parameters.push_back(current_param);
								}
								current_task.parameters=parameters;
								tasks.push_back(current_task);

							}
						}
						else
						{
							//error
						}
					}
				}

			}
		}
#if BOOST_VERSION > 104200
		mission_elem.name=mission_file_path.filename().string();
#else
		mission_elem.name=mission_file_path.filename();
#endif
		mission_elem.basic_mission=tasks;
		//store in taskserverinterface BasicMissions
		BasicMissions.push_back(mission_elem);
		//response
		basic_missions.push_back(mission_elem);
	}
}

void TaskServerInterface::parseComplexMissionFile(boost::filesystem::path &mission_file_path, std::vector<task_manager_msgs::ComplexMission>& complex_missions)
{
	if (boost::filesystem::exists(mission_file_path))
	{
		stringstream pathName(mission_file_path.string());
		ifstream MisssionFile(pathName.str().c_str());
		std::string line;
		task_manager_msgs::ComplexMission mission_elem;
		stringstream current_complex_mission;

		if (MisssionFile.is_open())
		{
			while ( getline(MisssionFile,line))
			{
				current_complex_mission<<line<<endl;
			}
		}
#if BOOST_VERSION > 104200
		mission_elem.name=mission_file_path.filename().string();
#else
		mission_elem.name=mission_file_path.filename();
#endif
		mission_elem.complex_mission= current_complex_mission.str();
		//store
		ComplexMissions.push_back(mission_elem);
		//in response
		complex_missions.push_back(mission_elem);

	}
}

void TaskServerInterface::parseMissionDirectory(std::vector<task_manager_msgs::BasicMission>& basic_missions,std::vector<task_manager_msgs::ComplexMission>& complex_missions )
{
	try
	{
	//todo for all package
	std::stringstream path(ros::package::getPath(TaskServerInterface::package_name));

		if (path.str().length() >0)
		{
			boost::filesystem::path mission_path(path.str()+"/missions");
			if (boost::filesystem::exists(mission_path))
			{
				boost::filesystem::directory_iterator end;

				for( boost::filesystem::directory_iterator iter(mission_path) ; iter != end ;iter++ )
				{
					if ( !boost::filesystem::is_directory( *iter ) )
					{
#if BOOST_VERSION > 104200
						boost::filesystem::path current_path(boost::filesystem::absolute(iter-> path()));
#else
							//char * cwd = get_current_dir_name();
							//boost::filesystem::path current_path(std::string(cwd) + iter-> path().string());
							//free(cwd);
							boost::filesystem::path current_path(iter-> path().string());
#endif

						if (current_path.extension() ==".py")
						{
							parseComplexMissionFile(current_path,complex_missions);
						}
						else if (current_path.extension() ==".mission")
						{
							parseBasicMissionFile(current_path,basic_missions);
						}
					}
				}

			}
			else
			{
				PRINTF(1,"Can't find missions directory in %s \n",path.str().c_str());
			}
		}
	}
	catch(char * str)
	{
		PRINTF(1,"%s",str);
	}
}

void TaskServerInterface::launchComplexMission(std::string & mission_name, int &pid) const
{

	int id(-1);
	for (unsigned int i=0;i<ComplexMissions.size();i++)
	{
		if (ComplexMissions[i].name==mission_name)
		{
			id=i;
		}
	}

	std::string full_name=saveBasicMissionSrv.getService();
	size_t pos=full_name.find("save_basic_mission");
	std::string node_name=full_name.substr(0,pos-1);

	stringstream parameter;
	parameter<<" _server:="<<node_name;

	stringstream rosrun_path;
	rosrun_path<<getenv("ROS_ROOT")<<"/bin/rosrun";

	//WARNING adding fork in service
	stringstream msg;
	if (id>-1)
	{
		int current_pid = fork();

		if (current_pid ==-1)
		{
			PRINTF(1,"Fork failed");
		}
		else if (current_pid ==0)//in child
		{
			execl (rosrun_path.str().c_str(),"rosrun", package_name.c_str(), mission_name.c_str(),parameter.str().c_str(),(char *) 0);
			//msg<<"Error running the following command :"<<"rosrun "<<package_name.c_str()<<" "<<mission_name.c_str()<<" "<<parameter.str().c_str()<<"\n";
			PRINTF(1,"Error running the following command : 'rosrun %s %s %s' \n",package_name.c_str(),mission_name.c_str(),parameter.str().c_str());
		}
		else //in parent
		{
			pid=current_pid;
		}
	}
	else
	{
		PRINTF(1,"Complex Mission %s not found\n",mission_name.c_str());
	}
}

void TaskServerInterface::abordComplexMission(int &pid)
{
	kill( pid, SIGKILL );
}

void TaskServerInterface::split(const std::string &s, char delim, std::vector<std::string> &elems) {
    std::stringstream ss(s);
    std::string item;
    while(std::getline(ss, item, delim)) {
        elems.push_back(item);
    }
}

<commit_msg>Execute complex mission using bash to avoid rosrun path issue<commit_after>#include <stdlib.h>
#include <stdio.h>
#include <boost/version.hpp>

#include <fstream>
#include <stdint.h>
#include "task_manager_lib/TaskServerInterface.h"
#include <ros/ros.h>
#include <ros/package.h>

using namespace boost::posix_time;
using namespace std;
using namespace task_manager_lib;

std::string TaskServerInterface::package_name = "task_manager_turtlesim";

TaskServerInterface::TaskServerInterface(task_manager_lib::TaskScheduler &ts_ref)
{
	saveBasicMissionSrv = ts_ref.getNodeHandle().advertiseService("save_basic_mission", &TaskServerInterface::saveBasicMission,this);
	saveComplexMissionSrv = ts_ref.getNodeHandle().advertiseService("save_complex_mission", &TaskServerInterface::saveComplexMission,this);
	executeComplexMissionsSrv= ts_ref.getNodeHandle().advertiseService("execute_complex_mission", &TaskServerInterface::executeComplexMission,this);
	stopComplexMissionsSrv= ts_ref.getNodeHandle().advertiseService("abord_complex_mission", &TaskServerInterface::stopComplexMission,this);
	listMissionsSrv=ts_ref.getNodeHandle().advertiseService("list_mission", &TaskServerInterface::listMissions,this);
}

//callback

bool TaskServerInterface::saveBasicMission(task_manager_lib::SaveBasicMission::Request  &req, task_manager_lib::SaveBasicMission::Response &res )
{
	createBasicMissionFile(req.basic_mission,res.filename);
	return true;
}

bool TaskServerInterface::saveComplexMission(task_manager_lib::SaveComplexMission::Request  &req, task_manager_lib::SaveComplexMission::Response &res )
{
	createComplexMissionFile(req.complex_mission,res.filename);
	return true;
}

bool TaskServerInterface::executeComplexMission(task_manager_lib::ExeComplexMission::Request  &req, task_manager_lib::ExeComplexMission::Response &res )
{
	launchComplexMission(req.mission_name, res.pid);
	return true;
}

bool TaskServerInterface::stopComplexMission(task_manager_lib::StopComplexMission::Request  &req, task_manager_lib::StopComplexMission::Response &res )
{
	abordComplexMission(req.pid);
	return true;
}

bool TaskServerInterface::listMissions(task_manager_lib::ListMissions::Request  &req, task_manager_lib::ListMissions::Response &res )
{
	parseMissionDirectory(res.basic_missions,res.complex_missions);
	return true;
}

void TaskServerInterface::createBasicMissionFile(std::vector<task_manager_msgs::TaskDescriptionLight> &basic_mission, std::string &filename) const
{
	std::vector<task_manager_msgs::TaskDescriptionLight> tasklist=basic_mission;

	try
	{
		stringstream path(ros::package::getPath(TaskServerInterface::package_name));
		stringstream msg;
		if (path.str().length() >0)
		{
			boost::filesystem::path mission_path(path.str()+"/missions");
			if (boost::filesystem::exists(mission_path))
			{
				time_facet *facet = new time_facet("%d-%b-%Y-%H_%M_%S");

				stringstream pathName;
				pathName.imbue(locale(pathName.getloc(), facet));
				pathName<<mission_path.string()<<"/mission_"<<second_clock::local_time() << ".mission";

				boost::filesystem::path output_boost_path(pathName.str());

				ofstream outputFile (pathName.str().c_str()) ;
				//write mission file
				//Mission task
				for (unsigned int i = 0;i<tasklist.size();i++)
				{
					outputFile<<"---"<<"\n";
					outputFile<<tasklist[i].name<<"\n";

					if (tasklist[i].parameters.size()==0)
					{
						outputFile<<"empty"<<"\n";
					}
					else
					{
						for (unsigned int j = 0;j<tasklist[i].parameters.size();j++)
						{
							outputFile<<tasklist[i].parameters[j].name;
							outputFile<<";";
							outputFile<<tasklist[i].parameters[j].value;
							outputFile<<"|";
						}
						outputFile<<"\n";
					}

					outputFile.close();

				}
#if (BOOST_VERSION > 104200)
                filename=output_boost_path.filename().string();
#else
                filename=output_boost_path.filename();
#endif
			}
			else
			{
				#if (BOOST_VERSION > 104200)
					PRINTF(1,"%s does not exist\n",mission_path.c_str());
				#else
					PRINTF(1,"%s does not exist\n",mission_path.string().c_str());
				#endif
			}

		}
		else
		{
			PRINTF(1,"%s does not exist\n",path.str().c_str());
		}

	}
	catch (char * str)
	{
		PRINTF(1,"%s",str);
		filename="Error creating Basic Mission file";
	}
}

void TaskServerInterface::createComplexMissionFile(std::string &complex_mission, std::string &filename)
{
	std::string tasklist=complex_mission;
	stringstream msg;
	try
	{
		std::stringstream path(ros::package::getPath(TaskServerInterface::package_name));
		if (path.str().length() >0)
		{
			boost::filesystem::path mission_path(path.str()+"/missions");
			if (boost::filesystem::exists(mission_path))
			{
				time_facet *facet = new time_facet("%d-%b-%Y-%H_%M_%S");

				std::stringstream pathName;
				pathName.imbue(locale(pathName.getloc(), facet));
				pathName<<mission_path.string()<<"/mission_"<<second_clock::local_time() << ".py";

				boost::filesystem::path output_boost_path(pathName.str());

				if (boost::filesystem::exists(output_boost_path))
				{
					//replace
				}
				else
				{
					//write mission file
					try
					{
						ofstream outputFile (pathName.str().c_str()) ;
						outputFile<<tasklist<<endl;
						outputFile.close();
						std::stringstream command_line;
						command_line<<"chmod 775 "<<pathName.str();
						int result=system(command_line.str().c_str());
						if (result!=0)
						{
							PRINTF(1,"Error %d setting execution permission to %s",result,command_line.str().c_str());
						}
					}
					catch(char * str)
					{
						PRINTF(1,"%s",str);
					}
				}
#if BOOST_VERSION > 104200
				filename=output_boost_path.filename().string();
#else
				filename=output_boost_path.filename();
#endif
				//update list of complex filename
				task_manager_msgs::ComplexMission current_mission;
				current_mission.name=filename;
				current_mission.complex_mission=tasklist;
				ComplexMissions.push_back(current_mission);

			}
			else
			{
				#if (BOOST_VERSION > 104200)
					PRINTF(1,"%s does not exist\n",mission_path.c_str());
				#else
					PRINTF(1,"%s does not exist\n",mission_path.string().c_str());
				#endif
			}
		}
		else
		{
			PRINTF(1," %s does not exist\n",path.str().c_str());
		}

	}
	catch (char * str)
	{
		PRINTF(1,"%s",str);
		filename="error creating file";
	}

}

void TaskServerInterface::parseBasicMissionFile(boost::filesystem::path &mission_file_path, std::vector<task_manager_msgs::BasicMission>& basic_missions)
{
	if (boost::filesystem::exists(mission_file_path))
	{
		stringstream pathName(mission_file_path.string());
		ifstream MisssionFile(pathName.str().c_str());
		std::string line;

		task_manager_msgs::BasicMission mission_elem;
		std::vector<task_manager_msgs::TaskDescriptionLight> tasks;

		if (MisssionFile.is_open())
		{
			task_manager_msgs::TaskDescriptionLight current_task;
			std::vector<task_manager_msgs::TaskParameter> parameters;

			unsigned int current_line(0), task_line(0);
			while ( getline(MisssionFile,line))
			{
				current_line ++;
				if (line=="---")
				{
					task_line=current_line;
					current_task=task_manager_msgs::TaskDescriptionLight();
					parameters.clear();

				}
				else
				{
					if (current_line>0)
					{
						if (current_line==task_line+1)//name
						{
							current_task.name=line;
						}
						else if (current_line==task_line+2)//params
						{
							if (line!="empty")
							{
								std::vector<std::string> params;
								split(line,'|',params);
								for (unsigned int j=0;j<params.size();j++)
								{
									std::vector<std::string> name_value;
									split(params[j],';',name_value);
									task_manager_msgs::TaskParameter current_param;
									current_param.name=name_value[0];
									current_param.value=name_value[1];
									parameters.push_back(current_param);
								}
								current_task.parameters=parameters;
								tasks.push_back(current_task);

							}
						}
						else
						{
							//error
						}
					}
				}

			}
		}
#if BOOST_VERSION > 104200
		mission_elem.name=mission_file_path.filename().string();
#else
		mission_elem.name=mission_file_path.filename();
#endif
		mission_elem.basic_mission=tasks;
		//store in taskserverinterface BasicMissions
		BasicMissions.push_back(mission_elem);
		//response
		basic_missions.push_back(mission_elem);
	}
}

void TaskServerInterface::parseComplexMissionFile(boost::filesystem::path &mission_file_path, std::vector<task_manager_msgs::ComplexMission>& complex_missions)
{
	if (boost::filesystem::exists(mission_file_path))
	{
		stringstream pathName(mission_file_path.string());
		ifstream MisssionFile(pathName.str().c_str());
		std::string line;
		task_manager_msgs::ComplexMission mission_elem;
		stringstream current_complex_mission;

		if (MisssionFile.is_open())
		{
			while ( getline(MisssionFile,line))
			{
				current_complex_mission<<line<<endl;
			}
		}
#if BOOST_VERSION > 104200
		mission_elem.name=mission_file_path.filename().string();
#else
		mission_elem.name=mission_file_path.filename();
#endif
		mission_elem.complex_mission= current_complex_mission.str();
		//store
		ComplexMissions.push_back(mission_elem);
		//in response
		complex_missions.push_back(mission_elem);

	}
}

void TaskServerInterface::parseMissionDirectory(std::vector<task_manager_msgs::BasicMission>& basic_missions,std::vector<task_manager_msgs::ComplexMission>& complex_missions )
{
	try
	{
	//todo for all package
	std::stringstream path(ros::package::getPath(TaskServerInterface::package_name));

		if (path.str().length() >0)
		{
			boost::filesystem::path mission_path(path.str()+"/missions");
			if (boost::filesystem::exists(mission_path))
			{
				boost::filesystem::directory_iterator end;

				for( boost::filesystem::directory_iterator iter(mission_path) ; iter != end ;iter++ )
				{
					if ( !boost::filesystem::is_directory( *iter ) )
					{
#if BOOST_VERSION > 104200
						boost::filesystem::path current_path(boost::filesystem::absolute(iter-> path()));
#else
							//char * cwd = get_current_dir_name();
							//boost::filesystem::path current_path(std::string(cwd) + iter-> path().string());
							//free(cwd);
							boost::filesystem::path current_path(iter-> path().string());
#endif

						if (current_path.extension() ==".py")
						{
							parseComplexMissionFile(current_path,complex_missions);
						}
						else if (current_path.extension() ==".mission")
						{
							parseBasicMissionFile(current_path,basic_missions);
						}
					}
				}

			}
			else
			{
				PRINTF(1,"Can't find missions directory in %s \n",path.str().c_str());
			}
		}
	}
	catch(char * str)
	{
		PRINTF(1,"%s",str);
	}
}

void TaskServerInterface::launchComplexMission(std::string & mission_name, int &pid) const
{

	int id(-1);
	for (unsigned int i=0;i<ComplexMissions.size();i++)
	{
		if (ComplexMissions[i].name==mission_name)
		{
			id=i;
		}
	}

	std::string full_name=saveBasicMissionSrv.getService();
	size_t pos=full_name.find("save_basic_mission");
	std::string node_name=full_name.substr(0,pos-1);

	stringstream parameter;
	parameter<<"_server:="<<node_name;

	stringstream command_line;
	command_line<<"rosrun "<<package_name<<" "<<mission_name<<" "<<parameter.str();

	//WARNING adding fork in service
	stringstream msg;
	if (id>-1)
	{
		int current_pid = fork();

		if (current_pid ==-1)
		{
			PRINTF(1,"Fork failed");
		}
		else if (current_pid ==0)//in child
		{

			execl ("/bin/bash","bash","-i","-c",command_line.str().c_str(),(char *) 0);
			//msg<<"Error running the following command :"<<"rosrun "<<package_name.c_str()<<" "<<mission_name.c_str()<<" "<<parameter.str().c_str()<<"\n";
			PRINTF(1,"Error running the following command : 'bash -i -c  %s ' \n",command_line.str().c_str());
		}
		else //in parent
		{
			pid=current_pid;
		}
	}
	else
	{
		PRINTF(1,"Complex Mission %s not found\n",mission_name.c_str());
	}
}

void TaskServerInterface::abordComplexMission(int &pid)
{
	kill( pid, SIGKILL );
}

void TaskServerInterface::split(const std::string &s, char delim, std::vector<std::string> &elems) {
    std::stringstream ss(s);
    std::string item;
    while(std::getline(ss, item, delim)) {
        elems.push_back(item);
    }
}

<|endoftext|>


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

#include "chrome/browser/meta_table_helper.h"

#include "base/logging.h"
#include "base/string_util.h"
#include "chrome/common/sqlite_utils.h"

// Key used in our meta table for version numbers.
static const char kVersionKey[] = "version";
static const char kCompatibleVersionKey[] = "last_compatible_version";

// static
void MetaTableHelper::PrimeCache(const std::string& db_name, sqlite3* db) {
  // A statement must be open for the preload command to work. If the meta
  // table doesn't exist, it probably means this is a new database and there
  // is nothing to preload (so it's OK we do nothing).
  SQLStatement dummy;
  if (!DoesSqliteTableExist(db, db_name.c_str(), "meta"))
    return;
  std::string sql("SELECT * from ");
  appendMetaTableName(db_name, &sql);
  if (dummy.prepare(db, sql.c_str()) != SQLITE_OK)
    return;
  if (dummy.step() != SQLITE_ROW)
    return;

  sqlite3Preload(db);
}

MetaTableHelper::MetaTableHelper() : db_(NULL) {
}

MetaTableHelper::~MetaTableHelper() {
}

bool MetaTableHelper::Init(const std::string& db_name,
                           int version,
                           int compatible_version,
                           sqlite3* db) {
  DCHECK(!db_ && db);
  db_ = db;
  db_name_ = db_name;
  if (!DoesSqliteTableExist(db_, db_name.c_str(), "meta")) {
    // Build the sql.
    std::string sql("CREATE TABLE ");
    appendMetaTableName(db_name, &sql);
    sql.append("(key LONGVARCHAR NOT NULL UNIQUE PRIMARY KEY,"
               "value LONGVARCHAR)");

    if (sqlite3_exec(db_, sql.c_str(), NULL, NULL, NULL) != SQLITE_OK)
      return false;

    // Note: there is no index over the meta table. We currently only have a
    // couple of keys, so it doesn't matter. If we start storing more stuff in
    // there, we should create an index.
    SetVersionNumber(version);
    SetCompatibleVersionNumber(compatible_version);
  }
  return true;
}

bool MetaTableHelper::SetValue(const std::string& key,
                               const std::wstring& value) {
  SQLStatement s;
  if (!PrepareSetStatement(&s, key))
    return false;
  s.bind_wstring(1, value);
  return s.step() == SQLITE_DONE;
}

bool MetaTableHelper::GetValue(const std::string& key,
                               std::wstring* value) {
  DCHECK(value);
  SQLStatement s;
  if (!PrepareGetStatement(&s, key))
    return false;

  s.column_wstring(0, value);
  return true;
}

bool MetaTableHelper::SetValue(const std::string& key,
                               int value) {
  SQLStatement s;
  if (!PrepareSetStatement(&s, key))
    return false;
  s.bind_int(1, value);
  return s.step() == SQLITE_DONE;
}

bool MetaTableHelper::GetValue(const std::string& key,
                               int* value) {
  DCHECK(value);
  SQLStatement s;
  if (!PrepareGetStatement(&s, key))
    return false;

  *value = s.column_int(0);
  return true;
}

bool MetaTableHelper::SetValue(const std::string& key,
                               int64 value) {
  SQLStatement s;
  if (!PrepareSetStatement(&s, key))
    return false;
  s.bind_int64(1, value);
  return s.step() == SQLITE_DONE;
}

bool MetaTableHelper::GetValue(const std::string& key,
                               int64* value) {
  DCHECK(value);
  SQLStatement s;
  if (!PrepareGetStatement(&s, key))
    return false;

  *value = s.column_int64(0);
  return true;
}

void MetaTableHelper::SetVersionNumber(int version) {
  SetValue(kVersionKey, version);
}

int MetaTableHelper::GetVersionNumber() {
  int version;
  if (!GetValue(kVersionKey, &version))
    return 0;
  return version;
}

void MetaTableHelper::SetCompatibleVersionNumber(int version) {
  SetValue(kCompatibleVersionKey, version);
}

int MetaTableHelper::GetCompatibleVersionNumber() {
  int version;
  if (!GetValue(kCompatibleVersionKey, &version))
    return 0;
  return version;
}

// static
void MetaTableHelper::appendMetaTableName(const std::string& db_name,
                                          std::string* sql) {
  if (!db_name.empty()) {
    sql->append(db_name);
    sql->push_back('.');
  }
  sql->append("meta");
}

bool MetaTableHelper::PrepareSetStatement(SQLStatement* statement,
                                          const std::string& key) {
  DCHECK(db_ && statement);
  std::string sql("INSERT OR REPLACE INTO ");
  appendMetaTableName(db_name_, &sql);
  sql.append("(key,value) VALUES(?,?)");
  if (statement->prepare(db_, sql.c_str()) != SQLITE_OK) {
    NOTREACHED() << sqlite3_errmsg(db_);
    return false;
  }
  statement->bind_text(0, key.c_str());
  return true;
}

bool MetaTableHelper::PrepareGetStatement(SQLStatement* statement,
                                          const std::string& key) {
  DCHECK(db_ && statement);
  std::string sql("SELECT value FROM ");
  appendMetaTableName(db_name_, &sql);
  sql.append(" WHERE key = ?");
  if (statement->prepare(db_, sql.c_str()) != SQLITE_OK) {
    NOTREACHED() << sqlite3_errmsg(db_);
    return false;
  }
  statement->bind_string(0, key);
  if (statement->step() != SQLITE_ROW)
    return false;
  return true;
}
<commit_msg>Fix gcc warning about possible unused variable experienced with Apple gcc 4.2 in an -O3 experiment. Review URL: http://codereview.chromium.org/173124<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/meta_table_helper.h"

#include "base/logging.h"
#include "base/string_util.h"
#include "chrome/common/sqlite_utils.h"

// Key used in our meta table for version numbers.
static const char kVersionKey[] = "version";
static const char kCompatibleVersionKey[] = "last_compatible_version";

// static
void MetaTableHelper::PrimeCache(const std::string& db_name, sqlite3* db) {
  // A statement must be open for the preload command to work. If the meta
  // table doesn't exist, it probably means this is a new database and there
  // is nothing to preload (so it's OK we do nothing).
  SQLStatement dummy;
  if (!DoesSqliteTableExist(db, db_name.c_str(), "meta"))
    return;
  std::string sql("SELECT * from ");
  appendMetaTableName(db_name, &sql);
  if (dummy.prepare(db, sql.c_str()) != SQLITE_OK)
    return;
  if (dummy.step() != SQLITE_ROW)
    return;

  sqlite3Preload(db);
}

MetaTableHelper::MetaTableHelper() : db_(NULL) {
}

MetaTableHelper::~MetaTableHelper() {
}

bool MetaTableHelper::Init(const std::string& db_name,
                           int version,
                           int compatible_version,
                           sqlite3* db) {
  DCHECK(!db_ && db);
  db_ = db;
  db_name_ = db_name;
  if (!DoesSqliteTableExist(db_, db_name.c_str(), "meta")) {
    // Build the sql.
    std::string sql("CREATE TABLE ");
    appendMetaTableName(db_name, &sql);
    sql.append("(key LONGVARCHAR NOT NULL UNIQUE PRIMARY KEY,"
               "value LONGVARCHAR)");

    if (sqlite3_exec(db_, sql.c_str(), NULL, NULL, NULL) != SQLITE_OK)
      return false;

    // Note: there is no index over the meta table. We currently only have a
    // couple of keys, so it doesn't matter. If we start storing more stuff in
    // there, we should create an index.
    SetVersionNumber(version);
    SetCompatibleVersionNumber(compatible_version);
  }
  return true;
}

bool MetaTableHelper::SetValue(const std::string& key,
                               const std::wstring& value) {
  SQLStatement s;
  if (!PrepareSetStatement(&s, key))
    return false;
  s.bind_wstring(1, value);
  return s.step() == SQLITE_DONE;
}

bool MetaTableHelper::GetValue(const std::string& key,
                               std::wstring* value) {
  DCHECK(value);
  SQLStatement s;
  if (!PrepareGetStatement(&s, key))
    return false;

  s.column_wstring(0, value);
  return true;
}

bool MetaTableHelper::SetValue(const std::string& key,
                               int value) {
  SQLStatement s;
  if (!PrepareSetStatement(&s, key))
    return false;
  s.bind_int(1, value);
  return s.step() == SQLITE_DONE;
}

bool MetaTableHelper::GetValue(const std::string& key,
                               int* value) {
  DCHECK(value);
  SQLStatement s;
  if (!PrepareGetStatement(&s, key))
    return false;

  *value = s.column_int(0);
  return true;
}

bool MetaTableHelper::SetValue(const std::string& key,
                               int64 value) {
  SQLStatement s;
  if (!PrepareSetStatement(&s, key))
    return false;
  s.bind_int64(1, value);
  return s.step() == SQLITE_DONE;
}

bool MetaTableHelper::GetValue(const std::string& key,
                               int64* value) {
  DCHECK(value);
  SQLStatement s;
  if (!PrepareGetStatement(&s, key))
    return false;

  *value = s.column_int64(0);
  return true;
}

void MetaTableHelper::SetVersionNumber(int version) {
  SetValue(kVersionKey, version);
}

int MetaTableHelper::GetVersionNumber() {
  int version = 0;
  if (!GetValue(kVersionKey, &version))
    return 0;
  return version;
}

void MetaTableHelper::SetCompatibleVersionNumber(int version) {
  SetValue(kCompatibleVersionKey, version);
}

int MetaTableHelper::GetCompatibleVersionNumber() {
  int version = 0;
  if (!GetValue(kCompatibleVersionKey, &version))
    return 0;
  return version;
}

// static
void MetaTableHelper::appendMetaTableName(const std::string& db_name,
                                          std::string* sql) {
  if (!db_name.empty()) {
    sql->append(db_name);
    sql->push_back('.');
  }
  sql->append("meta");
}

bool MetaTableHelper::PrepareSetStatement(SQLStatement* statement,
                                          const std::string& key) {
  DCHECK(db_ && statement);
  std::string sql("INSERT OR REPLACE INTO ");
  appendMetaTableName(db_name_, &sql);
  sql.append("(key,value) VALUES(?,?)");
  if (statement->prepare(db_, sql.c_str()) != SQLITE_OK) {
    NOTREACHED() << sqlite3_errmsg(db_);
    return false;
  }
  statement->bind_text(0, key.c_str());
  return true;
}

bool MetaTableHelper::PrepareGetStatement(SQLStatement* statement,
                                          const std::string& key) {
  DCHECK(db_ && statement);
  std::string sql("SELECT value FROM ");
  appendMetaTableName(db_name_, &sql);
  sql.append(" WHERE key = ?");
  if (statement->prepare(db_, sql.c_str()) != SQLITE_OK) {
    NOTREACHED() << sqlite3_errmsg(db_);
    return false;
  }
  statement->bind_string(0, key);
  if (statement->step() != SQLITE_ROW)
    return false;
  return true;
}
<|endoftext|>


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

#include "base/file_util.h"
#include "base/path_service.h"
#include "base/platform_thread.h"
#include "base/string_util.h"
#include "base/test_file_util.h"
#include "base/time.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/ui/ui_test.h"
#include "net/base/net_util.h"

using base::TimeDelta;
using base::TimeTicks;

namespace {

class StartupTest : public UITest {
 public:
  StartupTest() {
    show_window_ = true;
    pages_ = "about:blank";
  }
  void SetUp() {}
  void TearDown() {}

  void RunStartupTest(const char* graph, const char* trace,
      bool test_cold, bool important, int profile_type) {
    profile_type_ = profile_type;

    // Sets the profile data for the run.  For now, this is only used for
    // the non-default themes test.
    if (profile_type != UITest::DEFAULT_THEME) {
      set_template_user_data(UITest::ComputeTypicalUserDataSource(
          profile_type).ToWStringHack());
    }

    const int kNumCyclesMax = 20;
    int numCycles = kNumCyclesMax;
// It's ok for unit test code to use getenv(), isn't it?
#if defined(OS_WIN)
#pragma warning( disable : 4996 )
#endif
    const char* numCyclesEnv = getenv("STARTUP_TESTS_NUMCYCLES");
    if (numCyclesEnv && StringToInt(numCyclesEnv, &numCycles))
      LOG(INFO) << "STARTUP_TESTS_NUMCYCLES set in environment, "
                << "so setting numCycles to " << numCycles;

    TimeDelta timings[kNumCyclesMax];
    for (int i = 0; i < numCycles; ++i) {
      if (test_cold) {
        FilePath dir_app;
        ASSERT_TRUE(PathService::Get(chrome::DIR_APP, &dir_app));

        FilePath chrome_exe(dir_app.Append(
            FilePath::FromWStringHack(chrome::kBrowserProcessExecutablePath)));
        ASSERT_TRUE(EvictFileFromSystemCacheWrapper(chrome_exe));
#if defined(OS_WIN)
        // chrome.dll is windows specific.
        FilePath chrome_dll(dir_app.Append(FILE_PATH_LITERAL("chrome.dll")));
        ASSERT_TRUE(EvictFileFromSystemCacheWrapper(chrome_dll));
#endif

#if defined(OS_WIN)
        // TODO(port): Re-enable once gears is working on mac/linux.
        FilePath gears_dll;
        ASSERT_TRUE(PathService::Get(chrome::FILE_GEARS_PLUGIN, &gears_dll));
        ASSERT_TRUE(EvictFileFromSystemCacheWrapper(gears_dll));
#else
        NOTIMPLEMENTED() << "gears not enabled yet";
#endif
      }
      UITest::SetUp();
      TimeTicks end_time = TimeTicks::Now();
      timings[i] = end_time - browser_launch_time_;
      // TODO(beng): Can't shut down so quickly. Figure out why, and fix. If we
      // do, we crash.
      PlatformThread::Sleep(50);
      UITest::TearDown();

      if (i == 0) {
        // Re-use the profile data after first run so that the noise from
        // creating databases doesn't impact all the runs.
        clear_profile_ = false;
        // Destroy template_user_data_ for complex/gtk themes so we don't try
        // to rewrite each time through.
        if (profile_type != UITest::DEFAULT_THEME)
          set_template_user_data(L"");
      }
    }

    std::string times;
    for (int i = 0; i < numCycles; ++i)
      StringAppendF(&times, "%.2f,", timings[i].InMillisecondsF());
    PrintResultList(graph, "", trace, times, "ms", important);
  }

 protected:
  std::string pages_;
};

class StartupReferenceTest : public StartupTest {
 public:
  // override the browser directory that is used by UITest::SetUp to cause it
  // to use the reference build instead.
  void SetUp() {
    FilePath dir;
    PathService::Get(chrome::DIR_TEST_TOOLS, &dir);
    dir = dir.AppendASCII("reference_build");
#if defined(OS_WIN)
    dir = dir.AppendASCII("chrome");
#elif defined(OS_LINUX)
    dir = dir.AppendASCII("chrome_linux");
#elif defined(OS_MACOSX)
    dir = dir.AppendASCII("chrome_mac");
#endif
    browser_directory_ = dir;
  }
};

class StartupFileTest : public StartupTest {
 public:
  // Load a file on startup rather than about:blank.  This tests a longer
  // startup path, including resource loading and the loading of gears.dll.
  void SetUp() {
    FilePath file_url;
    ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &file_url));
    file_url = file_url.AppendASCII("empty.html");
    ASSERT_TRUE(file_util::PathExists(file_url));
    launch_arguments_.AppendLooseValue(file_url.ToWStringHack());

    pages_ = WideToUTF8(file_url.ToWStringHack());
  }
};

TEST_F(StartupTest, Perf) {
  RunStartupTest("warm", "t", false /* not cold */, true /* important */,
                 UITest::DEFAULT_THEME);
}

// TODO(port): We need a mac reference build checked in for this.
TEST_F(StartupReferenceTest, Perf) {
  RunStartupTest("warm", "t_ref", false /* not cold */,
                 true /* important */, UITest::DEFAULT_THEME);
}

// TODO(mpcomplete): Should we have reference timings for all these?

TEST_F(StartupTest, PerfCold) {
  RunStartupTest("cold", "t", true /* cold */, false /* not important */,
                 UITest::DEFAULT_THEME);
}

#if defined(OS_WIN)
// TODO(port): Enable gears tests on linux/mac once gears is working.
TEST_F(StartupFileTest, PerfGears) {
  RunStartupTest("warm", "gears", false /* not cold */,
                 false /* not important */, UITest::DEFAULT_THEME);
}

TEST_F(StartupFileTest, PerfColdGears) {
  RunStartupTest("cold", "gears", true /* cold */,
                 false /* not important */, UITest::DEFAULT_THEME);
}
#endif

TEST_F(StartupTest, PerfColdComplexTheme) {
  RunStartupTest("warm", "t-theme", false /* warm */,
                 false /* not important */, UITest::COMPLEX_THEME);
}

#if defined(OS_LINUX)
TEST_F(StartupTest, PerfColdGtkTheme) {
  RunStartupTest("warm", "gtk-theme", false /* warm */,
                 false /* not important */, UITest::NATIVE_THEME);
}
#endif

}  // namespace
<commit_msg>Enable startup tests for custom frame.  I meant to do this with the last change, but missed it.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/file_util.h"
#include "base/path_service.h"
#include "base/platform_thread.h"
#include "base/string_util.h"
#include "base/test_file_util.h"
#include "base/time.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/ui/ui_test.h"
#include "net/base/net_util.h"

using base::TimeDelta;
using base::TimeTicks;

namespace {

class StartupTest : public UITest {
 public:
  StartupTest() {
    show_window_ = true;
    pages_ = "about:blank";
  }
  void SetUp() {}
  void TearDown() {}

  void RunStartupTest(const char* graph, const char* trace,
      bool test_cold, bool important, int profile_type) {
    profile_type_ = profile_type;

    // Sets the profile data for the run.  For now, this is only used for
    // the non-default themes test.
    if (profile_type != UITest::DEFAULT_THEME) {
      set_template_user_data(UITest::ComputeTypicalUserDataSource(
          profile_type).ToWStringHack());
    }

    const int kNumCyclesMax = 20;
    int numCycles = kNumCyclesMax;
// It's ok for unit test code to use getenv(), isn't it?
#if defined(OS_WIN)
#pragma warning( disable : 4996 )
#endif
    const char* numCyclesEnv = getenv("STARTUP_TESTS_NUMCYCLES");
    if (numCyclesEnv && StringToInt(numCyclesEnv, &numCycles))
      LOG(INFO) << "STARTUP_TESTS_NUMCYCLES set in environment, "
                << "so setting numCycles to " << numCycles;

    TimeDelta timings[kNumCyclesMax];
    for (int i = 0; i < numCycles; ++i) {
      if (test_cold) {
        FilePath dir_app;
        ASSERT_TRUE(PathService::Get(chrome::DIR_APP, &dir_app));

        FilePath chrome_exe(dir_app.Append(
            FilePath::FromWStringHack(chrome::kBrowserProcessExecutablePath)));
        ASSERT_TRUE(EvictFileFromSystemCacheWrapper(chrome_exe));
#if defined(OS_WIN)
        // chrome.dll is windows specific.
        FilePath chrome_dll(dir_app.Append(FILE_PATH_LITERAL("chrome.dll")));
        ASSERT_TRUE(EvictFileFromSystemCacheWrapper(chrome_dll));
#endif

#if defined(OS_WIN)
        // TODO(port): Re-enable once gears is working on mac/linux.
        FilePath gears_dll;
        ASSERT_TRUE(PathService::Get(chrome::FILE_GEARS_PLUGIN, &gears_dll));
        ASSERT_TRUE(EvictFileFromSystemCacheWrapper(gears_dll));
#else
        NOTIMPLEMENTED() << "gears not enabled yet";
#endif
      }
      UITest::SetUp();
      TimeTicks end_time = TimeTicks::Now();
      timings[i] = end_time - browser_launch_time_;
      // TODO(beng): Can't shut down so quickly. Figure out why, and fix. If we
      // do, we crash.
      PlatformThread::Sleep(50);
      UITest::TearDown();

      if (i == 0) {
        // Re-use the profile data after first run so that the noise from
        // creating databases doesn't impact all the runs.
        clear_profile_ = false;
        // Destroy template_user_data_ for complex/gtk themes so we don't try
        // to rewrite each time through.
        if (profile_type != UITest::DEFAULT_THEME)
          set_template_user_data(L"");
      }
    }

    std::string times;
    for (int i = 0; i < numCycles; ++i)
      StringAppendF(&times, "%.2f,", timings[i].InMillisecondsF());
    PrintResultList(graph, "", trace, times, "ms", important);
  }

 protected:
  std::string pages_;
};

class StartupReferenceTest : public StartupTest {
 public:
  // override the browser directory that is used by UITest::SetUp to cause it
  // to use the reference build instead.
  void SetUp() {
    FilePath dir;
    PathService::Get(chrome::DIR_TEST_TOOLS, &dir);
    dir = dir.AppendASCII("reference_build");
#if defined(OS_WIN)
    dir = dir.AppendASCII("chrome");
#elif defined(OS_LINUX)
    dir = dir.AppendASCII("chrome_linux");
#elif defined(OS_MACOSX)
    dir = dir.AppendASCII("chrome_mac");
#endif
    browser_directory_ = dir;
  }
};

class StartupFileTest : public StartupTest {
 public:
  // Load a file on startup rather than about:blank.  This tests a longer
  // startup path, including resource loading and the loading of gears.dll.
  void SetUp() {
    FilePath file_url;
    ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &file_url));
    file_url = file_url.AppendASCII("empty.html");
    ASSERT_TRUE(file_util::PathExists(file_url));
    launch_arguments_.AppendLooseValue(file_url.ToWStringHack());

    pages_ = WideToUTF8(file_url.ToWStringHack());
  }
};

TEST_F(StartupTest, Perf) {
  RunStartupTest("warm", "t", false /* not cold */, true /* important */,
                 UITest::DEFAULT_THEME);
}

// TODO(port): We need a mac reference build checked in for this.
TEST_F(StartupReferenceTest, Perf) {
  RunStartupTest("warm", "t_ref", false /* not cold */,
                 true /* important */, UITest::DEFAULT_THEME);
}

// TODO(mpcomplete): Should we have reference timings for all these?

TEST_F(StartupTest, PerfCold) {
  RunStartupTest("cold", "t", true /* cold */, false /* not important */,
                 UITest::DEFAULT_THEME);
}

#if defined(OS_WIN)
// TODO(port): Enable gears tests on linux/mac once gears is working.
TEST_F(StartupFileTest, PerfGears) {
  RunStartupTest("warm", "gears", false /* not cold */,
                 false /* not important */, UITest::DEFAULT_THEME);
}

TEST_F(StartupFileTest, PerfColdGears) {
  RunStartupTest("cold", "gears", true /* cold */,
                 false /* not important */, UITest::DEFAULT_THEME);
}
#endif

TEST_F(StartupTest, PerfColdComplexTheme) {
  RunStartupTest("warm", "t-theme", false /* warm */,
                 false /* not important */, UITest::COMPLEX_THEME);
}

#if defined(OS_LINUX)
TEST_F(StartupTest, PerfColdGtkTheme) {
  RunStartupTest("warm", "gtk-theme", false /* warm */,
                 false /* not important */, UITest::NATIVE_THEME);
}

TEST_F(StartupTest, PrefColdNativeFrame) {
  RunStartupTest("warm", "custom-frame", false /* warm */,
                 false /* not important */, UITest::CUSTOM_FRAME);
}

TEST_F(StartupTest, PerfColdNativeFrameGtkTheme) {
  RunStartupTest("warm", "custom-frame-gtk-theme", false /* warm */,
                 false /* not important */, UITest::CUSTOM_FRAME_NATIVE_THEME);
}
#endif

}  // namespace
<|endoftext|>


<commit_before>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: lex.hxx,v $
 * $Revision: 1.4 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef _LEX_HXX
#define _LEX_HXX

#include <hash.hxx>
#include <tools/gen.hxx>
#include <tools/stream.hxx>

/******************** enum ***********************************************/
enum SVTOKEN_ENUM { SVTOKEN_EMPTY,      SVTOKEN_COMMENT,
                    SVTOKEN_INTEGER,    SVTOKEN_STRING,
                    SVTOKEN_BOOL,       SVTOKEN_IDENTIFIER,
                    SVTOKEN_CHAR,       SVTOKEN_RTTIBASE,
                    SVTOKEN_EOF,        SVTOKEN_HASHID };

/******************** class SvToken **************************************/
class BigInt;
class SvToken
{
friend class SvTokenStream;
    ULONG                   nLine, nColumn;
    SVTOKEN_ENUM            nType;
    ByteString                  aString;
    union
    {
        ULONG               nLong;
        BOOL                bBool;
        char                cChar;
//      SvRttiBase *        pComplexObj;
        SvStringHashEntry * pHash;
    };
public:
            SvToken();
            SvToken( const SvToken & rObj );
            SvToken( ULONG n );
            SvToken( SVTOKEN_ENUM nTypeP, BOOL b );
            SvToken( char c );
            SvToken( SVTOKEN_ENUM nTypeP, const ByteString & rStr );
//            SvToken( SvRttiBase * pComplexObj );
            SvToken( SVTOKEN_ENUM nTypeP );

    SvToken & operator = ( const SvToken & rObj );

    ByteString          GetTokenAsString() const;
    ByteString          Print() const;
    SVTOKEN_ENUM    GetType() const { return nType; }

    void        SetLine( ULONG nLineP )     { nLine = nLineP;       }
    ULONG       GetLine() const             { return nLine;         }

    void        SetColumn( ULONG nColumnP ) { nColumn = nColumnP;   }
    ULONG       GetColumn() const           { return nColumn;       }

    BOOL        IsEmpty() const     { return nType == SVTOKEN_EMPTY; }
    BOOL        IsComment() const   { return nType == SVTOKEN_COMMENT; }
    BOOL        IsInteger() const   { return nType == SVTOKEN_INTEGER; }
    BOOL        IsString() const    { return nType == SVTOKEN_STRING; }
    BOOL        IsBool() const      { return nType == SVTOKEN_BOOL; }
    BOOL        IsIdentifierHash() const
                { return nType == SVTOKEN_HASHID; }
    BOOL        IsIdentifier() const
                {
                    return nType == SVTOKEN_IDENTIFIER
                            || nType == SVTOKEN_HASHID;
                }
    BOOL        IsChar() const      { return nType == SVTOKEN_CHAR; }
    BOOL        IsRttiBase() const  { return nType == SVTOKEN_RTTIBASE; }
    BOOL        IsEof() const       { return nType == SVTOKEN_EOF; }

    const ByteString & GetString() const
                {
                    return IsIdentifierHash()
                        ? pHash->GetName()
                        : aString;
                }
    ULONG       GetNumber() const       { return nLong;         }
    BOOL        GetBool() const         { return bBool;         }
    char        GetChar() const         { return cChar;         }
//    SvRttiBase *GetObject() const       { return pComplexObj;   }

    void        SetHash( SvStringHashEntry * pHashP )
                { pHash = pHashP; nType = SVTOKEN_HASHID; }
    BOOL        HasHash() const
                { return nType == SVTOKEN_HASHID; }
    SvStringHashEntry * GetHash() const { return pHash; }
    BOOL        Is( SvStringHashEntry * pEntry ) const
                { return IsIdentifierHash() && pHash == pEntry; }
};

inline SvToken::SvToken()
    : nType( SVTOKEN_EMPTY ) {}

inline SvToken::SvToken( ULONG n )
    : nType( SVTOKEN_INTEGER ), nLong( n ) {}

inline SvToken::SvToken( SVTOKEN_ENUM nTypeP, BOOL b )
    : nType( nTypeP ), bBool( b ) {}

inline SvToken::SvToken( char c )
    : nType( SVTOKEN_CHAR ), cChar( c ) {}

inline SvToken::SvToken( SVTOKEN_ENUM nTypeP, const ByteString & rStr )
    : nType( nTypeP ), aString( rStr ) {}

/*
inline SvToken::SvToken( SvRttiBase * pObj )
    : nType( SVTOKEN_RTTIBASE ), pComplexObj( pObj )
        { pObj->AddRef(); }
*/

inline SvToken::SvToken( SVTOKEN_ENUM nTypeP )
: nType( nTypeP ) {}

DECLARE_LIST( SvTokenList, SvToken * )

/******************** class SvTokenStream ********************************/
class SvTokenStream
{
    ULONG       nLine, nColumn;
    int         nBufPos;
    int         c;          // naechstes Zeichen
    CharSet     nCharSet;
    char *      pCharTab;   // Zeiger auf die Konverierungstabelle
    USHORT      nTabSize;   // Tabulator Laenge
    ByteString      aStrTrue;
    ByteString      aStrFalse;
    ULONG       nMaxPos;

    SvFileStream *  pInStream;
    SvStream &      rInStream;
    String          aFileName;
    SvTokenList     aTokList;
    SvToken *       pCurToken;

    void        InitCtor();

    ByteString          aBufStr;
    int             GetNextChar();
    int             GetFastNextChar()
                    {
                        return aBufStr.GetChar((USHORT)nBufPos++);
                    }

    void            FillTokenList();
    ULONG           GetNumber();
    BOOL            MakeToken( SvToken & );
    BOOL            IsEof() const { return rInStream.IsEof(); }
    void            SetMax()
                    {
                        ULONG n = Tell();
                        if( n > nMaxPos )
                            nMaxPos = n;
                    }
    void            CalcColumn()
                    {
                        // wenn Zeilenende berechnung sparen
                        if( 0 != c )
                        {
                            USHORT n = 0;
                            nColumn = 0;
                            while( n < nBufPos )
                                nColumn += aBufStr.GetChar(n++) == '\t' ? nTabSize : 1;
                        }
                    }
public:
                    SvTokenStream( const String & rFileName );
                    SvTokenStream( SvStream & rInStream, const String & rFileName );
                    ~SvTokenStream();

    static BOOL     GetHexValue( const ByteString & rStr, BigInt * pValue );
    const String &  GetFileName() const { return aFileName; }
    SvStream &      GetStream() { return rInStream; }

    void            SetCharSet( CharSet nSet );
    CharSet         GetCharSet() const { return nCharSet; }

    void            SetTabSize( USHORT nTabSizeP )
                    { nTabSize = nTabSizeP; }
    USHORT          GetTabSize() const { return nTabSize; }

    SvToken *       GetToken_PrevAll()
                    {
                        SvToken * pRetToken = pCurToken;
                        if( NULL == (pCurToken = aTokList.Prev()) )
                            // Current Zeiger nie Null
                            pCurToken = pRetToken;

                        return pRetToken;
                    }
    SvToken *       GetToken_NextAll()
                    {
                        SvToken * pRetToken = pCurToken;
                        if( NULL == (pCurToken = aTokList.Next()) )
                            // Current Zeiger nie Null
                            pCurToken = pRetToken;
                        SetMax();
                        return pRetToken;
                    }
    SvToken *       GetToken_Next()
                    {
                        // Kommentare werden initial entfernt
                        return GetToken_NextAll();
                    }
    SvToken *       GetToken() const { return pCurToken; }
    BOOL            Skip( char cStart, char cEnd, UINT32 * pBegin );
    BOOL            Read( char cChar )
                    {
                        if( pCurToken->IsChar()
                          && cChar == pCurToken->GetChar() )
                        {
                            GetToken_Next();
                            return TRUE;
                        }
                        else
                            return FALSE;
                    }
    void            ReadDelemiter()
                    {
                        if( pCurToken->IsChar()
                          && (';' == pCurToken->GetChar()
                                || ',' == pCurToken->GetChar()) )
                        {
                            GetToken_Next();
                        }
                    }

    UINT32          Tell() const
                    { return aTokList.GetCurPos(); }
    void            Seek( UINT32 nPos )
                    {
                        pCurToken = aTokList.Seek( nPos );
                        SetMax();
                    }
    void            SeekRel( INT32 nRelPos )
                    {
                        pCurToken = aTokList.Seek( Tell() + nRelPos );
                        SetMax();
                    }
    void            SeekEnd()
                    {
                        pCurToken = aTokList.Seek( nMaxPos );
                    }
};

#endif // _LEX_HXX

<commit_msg>INTEGRATION: CWS mba30patches01 (1.3.36); FILE MERGED 2008/04/23 09:44:58 mba 1.3.36.2: RESYNC: (1.3-1.4); FILE MERGED 2008/03/18 15:40:03 mba 1.3.36.1: #i86353#: remove unused code<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: lex.hxx,v $
 * $Revision: 1.5 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef _LEX_HXX
#define _LEX_HXX

#include <hash.hxx>
#include <tools/gen.hxx>
#include <tools/stream.hxx>

/******************** enum ***********************************************/
enum SVTOKEN_ENUM { SVTOKEN_EMPTY,      SVTOKEN_COMMENT,
                    SVTOKEN_INTEGER,    SVTOKEN_STRING,
                    SVTOKEN_BOOL,       SVTOKEN_IDENTIFIER,
                    SVTOKEN_CHAR,       SVTOKEN_RTTIBASE,
                    SVTOKEN_EOF,        SVTOKEN_HASHID };

/******************** class SvToken **************************************/
class BigInt;
class SvToken
{
friend class SvTokenStream;
    ULONG                   nLine, nColumn;
    SVTOKEN_ENUM            nType;
    ByteString                  aString;
    union
    {
        ULONG               nLong;
        BOOL                bBool;
        char                cChar;
//      SvRttiBase *        pComplexObj;
        SvStringHashEntry * pHash;
    };
public:
            SvToken();
            SvToken( const SvToken & rObj );
            SvToken( ULONG n );
            SvToken( SVTOKEN_ENUM nTypeP, BOOL b );
            SvToken( char c );
            SvToken( SVTOKEN_ENUM nTypeP, const ByteString & rStr );
//            SvToken( SvRttiBase * pComplexObj );
            SvToken( SVTOKEN_ENUM nTypeP );

    SvToken & operator = ( const SvToken & rObj );

    ByteString          GetTokenAsString() const;
    SVTOKEN_ENUM    GetType() const { return nType; }

    void        SetLine( ULONG nLineP )     { nLine = nLineP;       }
    ULONG       GetLine() const             { return nLine;         }

    void        SetColumn( ULONG nColumnP ) { nColumn = nColumnP;   }
    ULONG       GetColumn() const           { return nColumn;       }

    BOOL        IsEmpty() const     { return nType == SVTOKEN_EMPTY; }
    BOOL        IsComment() const   { return nType == SVTOKEN_COMMENT; }
    BOOL        IsInteger() const   { return nType == SVTOKEN_INTEGER; }
    BOOL        IsString() const    { return nType == SVTOKEN_STRING; }
    BOOL        IsBool() const      { return nType == SVTOKEN_BOOL; }
    BOOL        IsIdentifierHash() const
                { return nType == SVTOKEN_HASHID; }
    BOOL        IsIdentifier() const
                {
                    return nType == SVTOKEN_IDENTIFIER
                            || nType == SVTOKEN_HASHID;
                }
    BOOL        IsChar() const      { return nType == SVTOKEN_CHAR; }
    BOOL        IsRttiBase() const  { return nType == SVTOKEN_RTTIBASE; }
    BOOL        IsEof() const       { return nType == SVTOKEN_EOF; }

    const ByteString & GetString() const
                {
                    return IsIdentifierHash()
                        ? pHash->GetName()
                        : aString;
                }
    ULONG       GetNumber() const       { return nLong;         }
    BOOL        GetBool() const         { return bBool;         }
    char        GetChar() const         { return cChar;         }
//    SvRttiBase *GetObject() const       { return pComplexObj;   }

    void        SetHash( SvStringHashEntry * pHashP )
                { pHash = pHashP; nType = SVTOKEN_HASHID; }
    BOOL        HasHash() const
                { return nType == SVTOKEN_HASHID; }
    SvStringHashEntry * GetHash() const { return pHash; }
    BOOL        Is( SvStringHashEntry * pEntry ) const
                { return IsIdentifierHash() && pHash == pEntry; }
};

inline SvToken::SvToken()
    : nType( SVTOKEN_EMPTY ) {}

inline SvToken::SvToken( ULONG n )
    : nType( SVTOKEN_INTEGER ), nLong( n ) {}

inline SvToken::SvToken( SVTOKEN_ENUM nTypeP, BOOL b )
    : nType( nTypeP ), bBool( b ) {}

inline SvToken::SvToken( char c )
    : nType( SVTOKEN_CHAR ), cChar( c ) {}

inline SvToken::SvToken( SVTOKEN_ENUM nTypeP, const ByteString & rStr )
    : nType( nTypeP ), aString( rStr ) {}

/*
inline SvToken::SvToken( SvRttiBase * pObj )
    : nType( SVTOKEN_RTTIBASE ), pComplexObj( pObj )
        { pObj->AddRef(); }
*/

inline SvToken::SvToken( SVTOKEN_ENUM nTypeP )
: nType( nTypeP ) {}

DECLARE_LIST( SvTokenList, SvToken * )

/******************** class SvTokenStream ********************************/
class SvTokenStream
{
    ULONG       nLine, nColumn;
    int         nBufPos;
    int         c;          // naechstes Zeichen
    CharSet     nCharSet;
    char *      pCharTab;   // Zeiger auf die Konverierungstabelle
    USHORT      nTabSize;   // Tabulator Laenge
    ByteString      aStrTrue;
    ByteString      aStrFalse;
    ULONG       nMaxPos;

    SvFileStream *  pInStream;
    SvStream &      rInStream;
    String          aFileName;
    SvTokenList     aTokList;
    SvToken *       pCurToken;

    void        InitCtor();

    ByteString          aBufStr;
    int             GetNextChar();
    int             GetFastNextChar()
                    {
                        return aBufStr.GetChar((USHORT)nBufPos++);
                    }

    void            FillTokenList();
    ULONG           GetNumber();
    BOOL            MakeToken( SvToken & );
    BOOL            IsEof() const { return rInStream.IsEof(); }
    void            SetMax()
                    {
                        ULONG n = Tell();
                        if( n > nMaxPos )
                            nMaxPos = n;
                    }
    void            CalcColumn()
                    {
                        // wenn Zeilenende berechnung sparen
                        if( 0 != c )
                        {
                            USHORT n = 0;
                            nColumn = 0;
                            while( n < nBufPos )
                                nColumn += aBufStr.GetChar(n++) == '\t' ? nTabSize : 1;
                        }
                    }
public:
                    SvTokenStream( const String & rFileName );
                    SvTokenStream( SvStream & rInStream, const String & rFileName );
                    ~SvTokenStream();

    const String &  GetFileName() const { return aFileName; }
    SvStream &      GetStream() { return rInStream; }

    void            SetCharSet( CharSet nSet );
    CharSet         GetCharSet() const { return nCharSet; }

    void            SetTabSize( USHORT nTabSizeP )
                    { nTabSize = nTabSizeP; }
    USHORT          GetTabSize() const { return nTabSize; }

    SvToken *       GetToken_PrevAll()
                    {
                        SvToken * pRetToken = pCurToken;
                        if( NULL == (pCurToken = aTokList.Prev()) )
                            // Current Zeiger nie Null
                            pCurToken = pRetToken;

                        return pRetToken;
                    }
    SvToken *       GetToken_NextAll()
                    {
                        SvToken * pRetToken = pCurToken;
                        if( NULL == (pCurToken = aTokList.Next()) )
                            // Current Zeiger nie Null
                            pCurToken = pRetToken;
                        SetMax();
                        return pRetToken;
                    }
    SvToken *       GetToken_Next()
                    {
                        // Kommentare werden initial entfernt
                        return GetToken_NextAll();
                    }
    SvToken *       GetToken() const { return pCurToken; }
    BOOL            Read( char cChar )
                    {
                        if( pCurToken->IsChar()
                          && cChar == pCurToken->GetChar() )
                        {
                            GetToken_Next();
                            return TRUE;
                        }
                        else
                            return FALSE;
                    }
    void            ReadDelemiter()
                    {
                        if( pCurToken->IsChar()
                          && (';' == pCurToken->GetChar()
                                || ',' == pCurToken->GetChar()) )
                        {
                            GetToken_Next();
                        }
                    }

    UINT32          Tell() const
                    { return aTokList.GetCurPos(); }
    void            Seek( UINT32 nPos )
                    {
                        pCurToken = aTokList.Seek( nPos );
                        SetMax();
                    }
    void            SeekRel( INT32 nRelPos )
                    {
                        pCurToken = aTokList.Seek( Tell() + nRelPos );
                        SetMax();
                    }
    void            SeekEnd()
                    {
                        pCurToken = aTokList.Seek( nMaxPos );
                    }
};

#endif // _LEX_HXX

<|endoftext|>


<commit_before>// $Id$
// vim:tabstop=2

/***********************************************************************
Moses - factored phrase-based language decoder
Copyright (C) 2006 University of Edinburgh

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
***********************************************************************/

#include "util/check.hh"
#include <algorithm>
#include <sstream>
#include <string>
#include "memory.h"
#include "FactorCollection.h"
#include "Phrase.h"
#include "StaticData.h"  // GetMaxNumFactors

#include "util/string_piece.hh"
#include "util/tokenize_piece.hh"

using namespace std;

namespace Moses
{

Phrase::Phrase() {}

Phrase::Phrase(size_t reserveSize)
{
  m_words.reserve(reserveSize);
}

Phrase::Phrase(const vector< const Word* > &mergeWords)
{
  m_words.reserve(mergeWords.size());
  for (size_t currPos = 0 ; currPos < mergeWords.size() ; currPos++) {
    AddWord(*mergeWords[currPos]);
  }
}

Phrase::~Phrase()
{
}

void Phrase::MergeFactors(const Phrase &copy)
{
  CHECK(GetSize() == copy.GetSize());
  size_t size = GetSize();
  const size_t maxNumFactors = MAX_NUM_FACTORS;
  for (size_t currPos = 0 ; currPos < size ; currPos++) {
    for (unsigned int currFactor = 0 ; currFactor < maxNumFactors ; currFactor++) {
      FactorType factorType = static_cast<FactorType>(currFactor);
      const Factor *factor = copy.GetFactor(currPos, factorType);
      if (factor != NULL)
        SetFactor(currPos, factorType, factor);
    }
  }
}

void Phrase::MergeFactors(const Phrase &copy, FactorType factorType)
{
  CHECK(GetSize() == copy.GetSize());
  for (size_t currPos = 0 ; currPos < GetSize() ; currPos++)
    SetFactor(currPos, factorType, copy.GetFactor(currPos, factorType));
}

void Phrase::MergeFactors(const Phrase &copy, const std::vector<FactorType>& factorVec)
{
  CHECK(GetSize() == copy.GetSize());
  for (size_t currPos = 0 ; currPos < GetSize() ; currPos++)
    for (std::vector<FactorType>::const_iterator i = factorVec.begin();
         i != factorVec.end(); ++i) {
      SetFactor(currPos, *i, copy.GetFactor(currPos, *i));
    }
}

Phrase Phrase::GetSubString(const WordsRange &wordsRange) const
{
  Phrase retPhrase(wordsRange.GetNumWordsCovered());

  for (size_t currPos = wordsRange.GetStartPos() ; currPos <= wordsRange.GetEndPos() ; currPos++) {
    Word &word = retPhrase.AddWord();
    word = GetWord(currPos);
  }

  return retPhrase;
}

Phrase Phrase::GetSubString(const WordsRange &wordsRange, FactorType factorType) const
{
  Phrase retPhrase(wordsRange.GetNumWordsCovered());

  for (size_t currPos = wordsRange.GetStartPos() ; currPos <= wordsRange.GetEndPos() ; currPos++) {
    const Factor* f = GetFactor(currPos, factorType);
    Word &word = retPhrase.AddWord();
    word.SetFactor(factorType, f);
  }

  return retPhrase;
}

std::string Phrase::GetStringRep(const vector<FactorType> factorsToPrint) const
{
  stringstream strme;
  for (size_t pos = 0 ; pos < GetSize() ; pos++) {
    strme << GetWord(pos).GetString(factorsToPrint, (pos != GetSize()-1));
  }

  return strme.str();
}

Word &Phrase::AddWord()
{
  m_words.push_back(Word());
  return m_words.back();
}

void Phrase::Append(const Phrase &endPhrase)
{

  for (size_t i = 0; i < endPhrase.GetSize(); i++) {
    AddWord(endPhrase.GetWord(i));
  }
}

void Phrase::PrependWord(const Word &newWord)
{
  AddWord();

  // shift
  for (size_t pos = GetSize() - 1; pos >= 1; --pos) {
    const Word &word = m_words[pos - 1];
    m_words[pos] = word;
  }

  m_words[0] = newWord;
}

void Phrase::CreateFromString(FactorDirection direction
                              ,const std::vector<FactorType> &factorOrder
                              ,const StringPiece &phraseString
                              ,const StringPiece &factorDelimiter
                              ,Word **lhs)
{
  // parse
  vector<StringPiece> annotatedWordVector;
  for (util::TokenIter<util::AnyCharacter, true> it(phraseString, "\t "); it; ++it) {
    annotatedWordVector.push_back(*it);
  }

  if (annotatedWordVector.size() == 0) {
    if (lhs) {
      (*lhs) = NULL;
    }
    return;
  }

  // KOMMA|none ART|Def.Z NN|Neut.NotGen.Sg VVFIN|none
  //    to
  // "KOMMA|none" "ART|Def.Z" "NN|Neut.NotGen.Sg" "VVFIN|none"

  size_t numWords;
  const StringPiece &annotatedWord = annotatedWordVector.back();
  if (annotatedWord.size() >= 2
      && *annotatedWord.data() == '['
      && annotatedWord.data()[annotatedWord.size() - 1] == ']') {
    // hiero/syntax rule
    numWords = annotatedWordVector.size()-1;

    // lhs
    assert(lhs);
    (*lhs) = new Word(true);
    (*lhs)->CreateFromString(direction, factorOrder, annotatedWord.substr(1, annotatedWord.size() - 2), true);
    assert((*lhs)->IsNonTerminal());
  } else {
    numWords = annotatedWordVector.size();
    //CHECK(lhs == NULL);
    if (lhs) {
      (*lhs) = NULL;
    }
  }

  // parse each word
  m_words.reserve(numWords);

  for (size_t phrasePos = 0 ; phrasePos < numWords; phrasePos++) {
    StringPiece &annotatedWord = annotatedWordVector[phrasePos];
    bool isNonTerminal;
    if (annotatedWord.size() >= 2 && *annotatedWord.data() == '[' && annotatedWord.data()[annotatedWord.size() - 1] == ']') {
      // non-term
      isNonTerminal = true;

      size_t nextPos = annotatedWord.find('[', 1);
      CHECK(nextPos != string::npos);

      if (direction == Input)
        annotatedWord = annotatedWord.substr(1, nextPos - 2);
      else
        annotatedWord = annotatedWord.substr(nextPos + 1, annotatedWord.size() - nextPos - 2);
    } else {
      isNonTerminal = false;
    }

    Word &word = AddWord();
    word.CreateFromString(direction, factorOrder, annotatedWord, isNonTerminal);

  }
}

int Phrase::Compare(const Phrase &other) const
{
#ifdef min
#undef min
#endif
  size_t thisSize			= GetSize()
                        ,compareSize	= other.GetSize();
  if (thisSize != compareSize) {
    return (thisSize < compareSize) ? -1 : 1;
  }

  for (size_t pos = 0 ; pos < thisSize ; pos++) {
    const Word &thisWord	= GetWord(pos)
                            ,&otherWord	= other.GetWord(pos);
    int ret = Word::Compare(thisWord, otherWord);

    if (ret != 0)
      return ret;
  }

  return 0;
}

bool Phrase::Contains(const vector< vector<string> > &subPhraseVector
                      , const vector<FactorType> &inputFactor) const
{
  const size_t subSize = subPhraseVector.size()
                         ,thisSize= GetSize();
  if (subSize > thisSize)
    return false;

  // try to match word-for-word
  for (size_t currStartPos = 0 ; currStartPos < (thisSize - subSize + 1) ; currStartPos++) {
    bool match = true;

    for (size_t currFactorIndex = 0 ; currFactorIndex < inputFactor.size() ; currFactorIndex++) {
      FactorType factorType = inputFactor[currFactorIndex];
      for (size_t currSubPos = 0 ; currSubPos < subSize ; currSubPos++) {
        size_t currThisPos = currSubPos + currStartPos;
        const string &subStr	= subPhraseVector[currSubPos][currFactorIndex];
        StringPiece thisStr	= GetFactor(currThisPos, factorType)->GetString();
        if (subStr != thisStr) {
          match = false;
          break;
        }
      }
      if (!match)
        break;
    }

    if (match)
      return true;
  }
  return false;
}

bool Phrase::IsCompatible(const Phrase &inputPhrase) const
{
  if (inputPhrase.GetSize() != GetSize()) {
    return false;
  }

  const size_t size = GetSize();

  const size_t maxNumFactors = MAX_NUM_FACTORS;
  for (size_t currPos = 0 ; currPos < size ; currPos++) {
    for (unsigned int currFactor = 0 ; currFactor < maxNumFactors ; currFactor++) {
      FactorType factorType = static_cast<FactorType>(currFactor);
      const Factor *thisFactor 		= GetFactor(currPos, factorType)
                                    ,*inputFactor	= inputPhrase.GetFactor(currPos, factorType);
      if (thisFactor != NULL && inputFactor != NULL && thisFactor != inputFactor)
        return false;
    }
  }
  return true;

}

bool Phrase::IsCompatible(const Phrase &inputPhrase, FactorType factorType) const
{
  if (inputPhrase.GetSize() != GetSize())	{
    return false;
  }
  for (size_t currPos = 0 ; currPos < GetSize() ; currPos++) {
    if (GetFactor(currPos, factorType) != inputPhrase.GetFactor(currPos, factorType))
      return false;
  }
  return true;
}

bool Phrase::IsCompatible(const Phrase &inputPhrase, const std::vector<FactorType>& factorVec) const
{
  if (inputPhrase.GetSize() != GetSize())	{
    return false;
  }
  for (size_t currPos = 0 ; currPos < GetSize() ; currPos++) {
    for (std::vector<FactorType>::const_iterator i = factorVec.begin();
         i != factorVec.end(); ++i) {
      if (GetFactor(currPos, *i) != inputPhrase.GetFactor(currPos, *i))
        return false;
    }
  }
  return true;
}

size_t Phrase::GetNumTerminals() const
{
  size_t ret = 0;

  for (size_t pos = 0; pos < GetSize(); ++pos) {
    if (!GetWord(pos).IsNonTerminal())
      ret++;
  }
  return ret;
}

void Phrase::InitializeMemPool()
{
}

void Phrase::FinalizeMemPool()
{
}

void Phrase::OnlyTheseFactors(const FactorMask &factors)
{
  for (unsigned int currFactor = 0 ; currFactor < MAX_NUM_FACTORS ; currFactor++) {
    if (!factors[currFactor]) {
      for (size_t pos = 0; pos < GetSize(); ++pos) {
        SetFactor(pos, currFactor, NULL);
      }
    }
  }
}

void Phrase::InitStartEndWord()
{
  FactorCollection &factorCollection = FactorCollection::Instance();

  Word startWord(Input);
  const Factor *factor = factorCollection.AddFactor(Input, 0, BOS_); // TODO - non-factored
  startWord.SetFactor(0, factor);
  PrependWord(startWord);

  Word endWord(Input);
  factor = factorCollection.AddFactor(Input, 0, EOS_); // TODO - non-factored
  endWord.SetFactor(0, factor);
  AddWord(endWord);
}

bool Phrase::Contains(const Phrase &sought) const
{

}

TO_STRING_BODY(Phrase);

// friend
ostream& operator<<(ostream& out, const Phrase& phrase)
{
//	out << "(size " << phrase.GetSize() << ") ";
  for (size_t pos = 0 ; pos < phrase.GetSize() ; pos++) {
    const Word &word = phrase.GetWord(pos);
    out << word;
  }
  return out;
}

}

<commit_msg>Phrase::Contains(const Phrase& sought) throws exception, since it's not implemented yet. Added return value to make the compiler shut up.<commit_after>// $Id$
// vim:tabstop=2

/***********************************************************************
Moses - factored phrase-based language decoder
Copyright (C) 2006 University of Edinburgh

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
***********************************************************************/

#include "util/check.hh"
#include <algorithm>
#include <sstream>
#include <string>
#include "memory.h"
#include "FactorCollection.h"
#include "Phrase.h"
#include "StaticData.h"  // GetMaxNumFactors

#include "util/string_piece.hh"
#include "util/tokenize_piece.hh"

using namespace std;

namespace Moses
{

Phrase::Phrase() {}

Phrase::Phrase(size_t reserveSize)
{
  m_words.reserve(reserveSize);
}

Phrase::Phrase(const vector< const Word* > &mergeWords)
{
  m_words.reserve(mergeWords.size());
  for (size_t currPos = 0 ; currPos < mergeWords.size() ; currPos++) {
    AddWord(*mergeWords[currPos]);
  }
}

Phrase::~Phrase()
{
}

void Phrase::MergeFactors(const Phrase &copy)
{
  CHECK(GetSize() == copy.GetSize());
  size_t size = GetSize();
  const size_t maxNumFactors = MAX_NUM_FACTORS;
  for (size_t currPos = 0 ; currPos < size ; currPos++) {
    for (unsigned int currFactor = 0 ; currFactor < maxNumFactors ; currFactor++) {
      FactorType factorType = static_cast<FactorType>(currFactor);
      const Factor *factor = copy.GetFactor(currPos, factorType);
      if (factor != NULL)
        SetFactor(currPos, factorType, factor);
    }
  }
}

void Phrase::MergeFactors(const Phrase &copy, FactorType factorType)
{
  CHECK(GetSize() == copy.GetSize());
  for (size_t currPos = 0 ; currPos < GetSize() ; currPos++)
    SetFactor(currPos, factorType, copy.GetFactor(currPos, factorType));
}

void Phrase::MergeFactors(const Phrase &copy, const std::vector<FactorType>& factorVec)
{
  CHECK(GetSize() == copy.GetSize());
  for (size_t currPos = 0 ; currPos < GetSize() ; currPos++)
    for (std::vector<FactorType>::const_iterator i = factorVec.begin();
         i != factorVec.end(); ++i) {
      SetFactor(currPos, *i, copy.GetFactor(currPos, *i));
    }
}

Phrase Phrase::GetSubString(const WordsRange &wordsRange) const
{
  Phrase retPhrase(wordsRange.GetNumWordsCovered());

  for (size_t currPos = wordsRange.GetStartPos() ; currPos <= wordsRange.GetEndPos() ; currPos++) {
    Word &word = retPhrase.AddWord();
    word = GetWord(currPos);
  }

  return retPhrase;
}

Phrase Phrase::GetSubString(const WordsRange &wordsRange, FactorType factorType) const
{
  Phrase retPhrase(wordsRange.GetNumWordsCovered());

  for (size_t currPos = wordsRange.GetStartPos() ; currPos <= wordsRange.GetEndPos() ; currPos++) {
    const Factor* f = GetFactor(currPos, factorType);
    Word &word = retPhrase.AddWord();
    word.SetFactor(factorType, f);
  }

  return retPhrase;
}

std::string Phrase::GetStringRep(const vector<FactorType> factorsToPrint) const
{
  stringstream strme;
  for (size_t pos = 0 ; pos < GetSize() ; pos++) {
    strme << GetWord(pos).GetString(factorsToPrint, (pos != GetSize()-1));
  }

  return strme.str();
}

Word &Phrase::AddWord()
{
  m_words.push_back(Word());
  return m_words.back();
}

void Phrase::Append(const Phrase &endPhrase)
{

  for (size_t i = 0; i < endPhrase.GetSize(); i++) {
    AddWord(endPhrase.GetWord(i));
  }
}

void Phrase::PrependWord(const Word &newWord)
{
  AddWord();

  // shift
  for (size_t pos = GetSize() - 1; pos >= 1; --pos) {
    const Word &word = m_words[pos - 1];
    m_words[pos] = word;
  }

  m_words[0] = newWord;
}

void Phrase::CreateFromString(FactorDirection direction
                              ,const std::vector<FactorType> &factorOrder
                              ,const StringPiece &phraseString
                              ,const StringPiece &factorDelimiter
                              ,Word **lhs)
{
  // parse
  vector<StringPiece> annotatedWordVector;
  for (util::TokenIter<util::AnyCharacter, true> it(phraseString, "\t "); it; ++it) {
    annotatedWordVector.push_back(*it);
  }

  if (annotatedWordVector.size() == 0) {
    if (lhs) {
      (*lhs) = NULL;
    }
    return;
  }

  // KOMMA|none ART|Def.Z NN|Neut.NotGen.Sg VVFIN|none
  //    to
  // "KOMMA|none" "ART|Def.Z" "NN|Neut.NotGen.Sg" "VVFIN|none"

  size_t numWords;
  const StringPiece &annotatedWord = annotatedWordVector.back();
  if (annotatedWord.size() >= 2
      && *annotatedWord.data() == '['
      && annotatedWord.data()[annotatedWord.size() - 1] == ']') {
    // hiero/syntax rule
    numWords = annotatedWordVector.size()-1;

    // lhs
    assert(lhs);
    (*lhs) = new Word(true);
    (*lhs)->CreateFromString(direction, factorOrder, annotatedWord.substr(1, annotatedWord.size() - 2), true);
    assert((*lhs)->IsNonTerminal());
  } else {
    numWords = annotatedWordVector.size();
    //CHECK(lhs == NULL);
    if (lhs) {
      (*lhs) = NULL;
    }
  }

  // parse each word
  m_words.reserve(numWords);

  for (size_t phrasePos = 0 ; phrasePos < numWords; phrasePos++) {
    StringPiece &annotatedWord = annotatedWordVector[phrasePos];
    bool isNonTerminal;
    if (annotatedWord.size() >= 2 && *annotatedWord.data() == '[' && annotatedWord.data()[annotatedWord.size() - 1] == ']') {
      // non-term
      isNonTerminal = true;

      size_t nextPos = annotatedWord.find('[', 1);
      CHECK(nextPos != string::npos);

      if (direction == Input)
        annotatedWord = annotatedWord.substr(1, nextPos - 2);
      else
        annotatedWord = annotatedWord.substr(nextPos + 1, annotatedWord.size() - nextPos - 2);
    } else {
      isNonTerminal = false;
    }

    Word &word = AddWord();
    word.CreateFromString(direction, factorOrder, annotatedWord, isNonTerminal);

  }
}

int Phrase::Compare(const Phrase &other) const
{
#ifdef min
#undef min
#endif
  size_t thisSize			= GetSize()
                        ,compareSize	= other.GetSize();
  if (thisSize != compareSize) {
    return (thisSize < compareSize) ? -1 : 1;
  }

  for (size_t pos = 0 ; pos < thisSize ; pos++) {
    const Word &thisWord	= GetWord(pos)
                            ,&otherWord	= other.GetWord(pos);
    int ret = Word::Compare(thisWord, otherWord);

    if (ret != 0)
      return ret;
  }

  return 0;
}

bool Phrase::Contains(const vector< vector<string> > &subPhraseVector
                      , const vector<FactorType> &inputFactor) const
{
  const size_t subSize = subPhraseVector.size()
                         ,thisSize= GetSize();
  if (subSize > thisSize)
    return false;

  // try to match word-for-word
  for (size_t currStartPos = 0 ; currStartPos < (thisSize - subSize + 1) ; currStartPos++) {
    bool match = true;

    for (size_t currFactorIndex = 0 ; currFactorIndex < inputFactor.size() ; currFactorIndex++) {
      FactorType factorType = inputFactor[currFactorIndex];
      for (size_t currSubPos = 0 ; currSubPos < subSize ; currSubPos++) {
        size_t currThisPos = currSubPos + currStartPos;
        const string &subStr	= subPhraseVector[currSubPos][currFactorIndex];
        StringPiece thisStr	= GetFactor(currThisPos, factorType)->GetString();
        if (subStr != thisStr) {
          match = false;
          break;
        }
      }
      if (!match)
        break;
    }

    if (match)
      return true;
  }
  return false;
}

bool Phrase::IsCompatible(const Phrase &inputPhrase) const
{
  if (inputPhrase.GetSize() != GetSize()) {
    return false;
  }

  const size_t size = GetSize();

  const size_t maxNumFactors = MAX_NUM_FACTORS;
  for (size_t currPos = 0 ; currPos < size ; currPos++) {
    for (unsigned int currFactor = 0 ; currFactor < maxNumFactors ; currFactor++) {
      FactorType factorType = static_cast<FactorType>(currFactor);
      const Factor *thisFactor 		= GetFactor(currPos, factorType)
                                    ,*inputFactor	= inputPhrase.GetFactor(currPos, factorType);
      if (thisFactor != NULL && inputFactor != NULL && thisFactor != inputFactor)
        return false;
    }
  }
  return true;

}

bool Phrase::IsCompatible(const Phrase &inputPhrase, FactorType factorType) const
{
  if (inputPhrase.GetSize() != GetSize())	{
    return false;
  }
  for (size_t currPos = 0 ; currPos < GetSize() ; currPos++) {
    if (GetFactor(currPos, factorType) != inputPhrase.GetFactor(currPos, factorType))
      return false;
  }
  return true;
}

bool Phrase::IsCompatible(const Phrase &inputPhrase, const std::vector<FactorType>& factorVec) const
{
  if (inputPhrase.GetSize() != GetSize())	{
    return false;
  }
  for (size_t currPos = 0 ; currPos < GetSize() ; currPos++) {
    for (std::vector<FactorType>::const_iterator i = factorVec.begin();
         i != factorVec.end(); ++i) {
      if (GetFactor(currPos, *i) != inputPhrase.GetFactor(currPos, *i))
        return false;
    }
  }
  return true;
}

size_t Phrase::GetNumTerminals() const
{
  size_t ret = 0;

  for (size_t pos = 0; pos < GetSize(); ++pos) {
    if (!GetWord(pos).IsNonTerminal())
      ret++;
  }
  return ret;
}

void Phrase::InitializeMemPool()
{
}

void Phrase::FinalizeMemPool()
{
}

void Phrase::OnlyTheseFactors(const FactorMask &factors)
{
  for (unsigned int currFactor = 0 ; currFactor < MAX_NUM_FACTORS ; currFactor++) {
    if (!factors[currFactor]) {
      for (size_t pos = 0; pos < GetSize(); ++pos) {
        SetFactor(pos, currFactor, NULL);
      }
    }
  }
}

void Phrase::InitStartEndWord()
{
  FactorCollection &factorCollection = FactorCollection::Instance();

  Word startWord(Input);
  const Factor *factor = factorCollection.AddFactor(Input, 0, BOS_); // TODO - non-factored
  startWord.SetFactor(0, factor);
  PrependWord(startWord);

  Word endWord(Input);
  factor = factorCollection.AddFactor(Input, 0, EOS_); // TODO - non-factored
  endWord.SetFactor(0, factor);
  AddWord(endWord);
}

bool Phrase::Contains(const Phrase &sought) const
{
  throw "THIS FUNCTION IS NOT IMPLEMENTED YET!";
  return false;
}

TO_STRING_BODY(Phrase);

// friend
ostream& operator<<(ostream& out, const Phrase& phrase)
{
//	out << "(size " << phrase.GetSize() << ") ";
  for (size_t pos = 0 ; pos < phrase.GetSize() ; pos++) {
    const Word &word = phrase.GetWord(pos);
    out << word;
  }
  return out;
}

}

<|endoftext|>