<commit_before>#include <iostream>
#include <string>
#include <vector>

using namespace std;
vector <string> Census;

void Census2017(){
  // Census.push_back("Name @ GitHub link");
  Census.push_back("Allen Comp Sci @ https://github.com/AllenCompSci");
  Census.push_back("Mr. Hudson @ https://github.com/theshrewedshrew");
  Census.push_back("BEST Team 58 @ https://github.com/BESTTeam58");
  Census.push_back("TexasSnow @ https://github.com/TexasSnow");
  Census.push_back("hotdogshabab @ https://github.com/hotdogshabab");
  Census.push_back("alansunglee @ https://github.com/alansunglee");
  Census.push_back("Rahultheman12 @ https://github.com/Rahultheman12");
  Census.push_back("spicyboi @ https://github.com/spicyboi");
  Census.push_back("John Nguyen @ https://github.com/jawnlovesfreestuff");
  Census.push_back("CodeTimesTen @ https://github.com/CodeTimesTen");
  Census.push_back("YourFriendlyNeighborhoodSpiderman @ https://github.com/YourFriendlyNeighborhoodSpiderman");
  Census.push_back("Devin Petersen @ https://github.com/DevinPetersen");
  Census.push_back("Cameron Mathis @ https://github.com/Phylux");
  Census.push_back("Samuel Woon @ https://github.com/samuel-w");
  Census.push_back("JustinV10 @ https://github.com/JustinV10");
  Census.push_back("Kyleaustin36 @ https://github.com/kyleaustin36");
  Census.push_back("Maaz Kamal @ https://github.com/Maze-Camel");
  Census.push_back("bingood4ever @ https://github.com/bingood4ever");
  Census.push_back("Gainz101 @ https://github.com/Gainz101");
  Census.push_back("zachdogg @ https://github.com/Zachdogg1");

}
void printCensus(){
  for(int i = 0; i < (int)Census.size(); i++){
    cout << "Hello World from "Your name" + Census[i] << "\n";

  }
}
//test
void main(){
  Census2017();
  printCensus();
}
<commit_msg>Update HelloWorld.cpp<commit_after>#include <iostream>
#include <string>
#include <vector>

using namespace std;
vector <string> Census;

void Census2017(){
  // Census.push_back("Name @ GitHub link");
  Census.push_back("Allen Comp Sci @ https://github.com/AllenCompSci");
  Census.push_back("Mr. Hudson @ https://github.com/theshrewedshrew");
  Census.push_back("BEST Team 58 @ https://github.com/BESTTeam58");
  Census.push_back("TexasSnow @ https://github.com/TexasSnow");
  Census.push_back("hotdogshabab @ https://github.com/hotdogshabab");
  Census.push_back("alansunglee @ https://github.com/alansunglee");
  Census.push_back("Rahultheman12 @ https://github.com/Rahultheman12");
  Census.push_back("spicyboi @ https://github.com/spicyboi");
  Census.push_back("John Nguyen @ https://github.com/jawnlovesfreestuff");
  Census.push_back("CodeTimesTen @ https://github.com/CodeTimesTen");
  Census.push_back("YourFriendlyNeighborhoodSpiderman @ https://github.com/YourFriendlyNeighborhoodSpiderman");
  Census.push_back("Devin Petersen @ https://github.com/DevinPetersen");
  Census.push_back("Cameron Mathis @ https://github.com/Phylux");
  Census.push_back("Samuel Woon @ https://github.com/samuel-w");
  Census.push_back("JustinV10 @ https://github.com/JustinV10");
  Census.push_back("Kyleaustin36 @ https://github.com/kyleaustin36");
  Census.push_back("Maaz Kamal @ https://github.com/Maze-Camel");
  Census.push_back("bingood4ever @ https://github.com/bingood4ever");
  Census.push_back("Gainz101 @ https://github.com/Gainz101");
  Census.push_back("zachdogg @ https://github.com/Zachdogg1");
  Census.push_back("PJHudson618 @ https://github.com/PJHudson618");

}
void printCensus(){
  for(int i = 0; i < (int)Census.size(); i++){
    cout << "Hello World from "Your name" + Census[i] << "\n";

  }
}
//test
void main(){
  Census2017();
  printCensus();
}
<|endoftext|>


<commit_before>/*
Copyright (C) 2019 The Falco Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

#include <google/protobuf/util/time_util.h>

#include "falco_outputs.h"

#include "config_falco.h"

#include "formats.h"
#include "logger.h"
#include "falco_output_queue.h"

using namespace std;
using namespace falco::output;

const static struct luaL_reg ll_falco_outputs [] =
{
	{"handle_http", &falco_outputs::handle_http},
	{"handle_grpc", &falco_outputs::handle_grpc},
	{NULL,NULL}
};

falco_outputs::falco_outputs(falco_engine *engine)
	: m_falco_engine(engine),
	  m_initialized(false),
	  m_buffered(true),
	  m_json_output(false),
	  m_time_format_iso_8601(false)
{

}

falco_outputs::~falco_outputs()
{
	// Note: The assert()s in this destructor were previously places where
	//       exceptions were thrown.  C++11 doesn't allow destructors to
	//       emit exceptions; if they're thrown, they'll trigger a call
	//       to 'terminate()'.  To maintain similar behavior, the exceptions
	//       were replace with calls to 'assert()'
	if(m_initialized)
	{
		lua_getglobal(m_ls, m_lua_output_cleanup.c_str());
		if(!lua_isfunction(m_ls, -1))
		{
			falco_logger::log(LOG_ERR, std::string("No function ") + m_lua_output_cleanup + " found. ");
			assert(nullptr == "Missing lua cleanup function in ~falco_outputs");
		}

		if(lua_pcall(m_ls, 0, 0, 0) != 0)
		{
			const char* lerr = lua_tostring(m_ls, -1);
			falco_logger::log(LOG_ERR, std::string("lua_pcall failed, err: ") + lerr);
			assert(nullptr == "lua_pcall failed in ~falco_outputs");
		}
	}
}

void falco_outputs::init(bool json_output,
			 bool json_include_output_property,
			 uint32_t rate, uint32_t max_burst, bool buffered,
			 bool time_format_iso_8601)
{
	// The engine must have been given an inspector by now.
	if(! m_inspector)
	{
		throw falco_exception("No inspector provided");
	}

	m_json_output = json_output;

	falco_common::init(m_lua_main_filename.c_str(), FALCO_SOURCE_LUA_DIR);

	// Note that falco_formats is added to both the lua state used
	// by the falco engine as well as the separate lua state used
	// by falco outputs.
	falco_formats::init(m_inspector, m_falco_engine, m_ls, json_output, json_include_output_property);

	falco_logger::init(m_ls);

	luaL_openlib(m_ls, "c_outputs", ll_falco_outputs, 0);

	m_notifications_tb.init(rate, max_burst);

	m_buffered = buffered;
	m_time_format_iso_8601 = time_format_iso_8601;

	m_initialized = true;
}

void falco_outputs::add_output(output_config oc)
{
	uint8_t nargs = 3;
	lua_getglobal(m_ls, m_lua_add_output.c_str());

	if(!lua_isfunction(m_ls, -1))
	{
		throw falco_exception("No function " + m_lua_add_output + " found. ");
	}
	lua_pushstring(m_ls, oc.name.c_str());
	lua_pushnumber(m_ls, (m_buffered ? 1 : 0));
	lua_pushnumber(m_ls, (m_time_format_iso_8601 ? 1 : 0));

	// If we have options, build up a lua table containing them
	if (oc.options.size())
	{
		nargs = 4;
		lua_createtable(m_ls, 0, oc.options.size());

		for (auto it = oc.options.cbegin(); it != oc.options.cend(); ++it)
		{
			lua_pushstring(m_ls, (*it).second.c_str());
			lua_setfield(m_ls, -2, (*it).first.c_str());
		}
	}

	if(lua_pcall(m_ls, nargs, 0, 0) != 0)
	{
		const char* lerr = lua_tostring(m_ls, -1);
		throw falco_exception(string(lerr));
	}

}

void falco_outputs::handle_event(gen_event *ev, string &rule, string &source,
				 falco_common::priority_type priority, string &format)
{
	if(!m_notifications_tb.claim())
	{
		falco_logger::log(LOG_DEBUG, "Skipping rate-limited notification for rule " + rule + "\n");
		return;
	}

	std::lock_guard<std::mutex> guard(m_ls_semaphore);
	lua_getglobal(m_ls, m_lua_output_event.c_str());
	char hostname[256];
	char* env_hostname = getenv("FALCO_GRPC_HOSTNAME");
	if(env_hostname == NULL){
		int err = gethostname(hostname, sizeof(hostname));
		if(err != 0){
			string err = "Failed to get hostname";
			throw falco_exception(err);
		}
	}else{
		strcpy(hostname, env_hostname);
	}
	if(lua_isfunction(m_ls, -1))
	{
		lua_pushlightuserdata(m_ls, ev);
		lua_pushstring(m_ls, rule.c_str());
		lua_pushstring(m_ls, source.c_str());
		lua_pushstring(m_ls, falco_common::priority_names[priority].c_str());
		lua_pushnumber(m_ls, priority);
		lua_pushstring(m_ls, format.c_str());
		lua_pushstring(m_ls, hostname);

		if(lua_pcall(m_ls, 7, 0, 0) != 0)
		{
			const char* lerr = lua_tostring(m_ls, -1);
			string err = "Error invoking function output: " + string(lerr);
			throw falco_exception(err);
		}
	}
	else
	{
		throw falco_exception("No function " + m_lua_output_event + " found in lua compiler module");
	}
}

void falco_outputs::handle_msg(uint64_t now,
			       falco_common::priority_type priority,
			       std::string &msg,
			       std::string &rule,
			       std::map<std::string,std::string> &output_fields)
{
	std::string full_msg;

	if(m_json_output)
	{
		nlohmann::json jmsg;

		// Convert the time-as-nanoseconds to a more json-friendly ISO8601.
		time_t evttime = now/1000000000;
		char time_sec[20]; // sizeof "YYYY-MM-DDTHH:MM:SS"
		char time_ns[12]; // sizeof ".sssssssssZ"
		string iso8601evttime;

		strftime(time_sec, sizeof(time_sec), "%FT%T", gmtime(&evttime));
		snprintf(time_ns, sizeof(time_ns), ".%09luZ", now % 1000000000);
		iso8601evttime = time_sec;
		iso8601evttime += time_ns;

		jmsg["output"] = msg;
		jmsg["priority"] = "Critical";
		jmsg["rule"] = rule;
		jmsg["time"] = iso8601evttime;
		jmsg["output_fields"] = output_fields;

		full_msg = jmsg.dump();
	}
	else
	{
		std::string timestr;
		bool first = true;

		sinsp_utils::ts_to_string(now, &timestr, false, true);
		full_msg = timestr + ": " + falco_common::priority_names[LOG_CRIT] + " " + msg + " (";
		for(auto &pair : output_fields)
		{
			if(first)
			{
				first = false;
			}
			else
			{
				full_msg += " ";
			}
			full_msg += pair.first + "=" + pair.second;
		}
		full_msg += ")";
	}

	std::lock_guard<std::mutex> guard(m_ls_semaphore);
	lua_getglobal(m_ls, m_lua_output_msg.c_str());
	if(lua_isfunction(m_ls, -1))
	{
		lua_pushstring(m_ls, full_msg.c_str());
		lua_pushstring(m_ls, falco_common::priority_names[priority].c_str());
		lua_pushnumber(m_ls, priority);

		if(lua_pcall(m_ls, 3, 0, 0) != 0)
		{
			const char* lerr = lua_tostring(m_ls, -1);
			string err = "Error invoking function output: " + string(lerr);
			throw falco_exception(err);
		}
	}
	else
	{
		throw falco_exception("No function " + m_lua_output_msg + " found in lua compiler module");
	}

}

void falco_outputs::reopen_outputs()
{
	lua_getglobal(m_ls, m_lua_output_reopen.c_str());
	if(!lua_isfunction(m_ls, -1))
	{
		throw falco_exception("No function " + m_lua_output_reopen + " found. ");
	}

	if(lua_pcall(m_ls, 0, 0, 0) != 0)
	{
		const char* lerr = lua_tostring(m_ls, -1);
		throw falco_exception(string(lerr));
	}
}

int falco_outputs::handle_http(lua_State *ls)
{
	CURL *curl = NULL;
	CURLcode res = CURLE_FAILED_INIT;
	struct curl_slist *slist1;
	slist1 = NULL;

	if(!lua_isstring(ls, -1) ||
	   !lua_isstring(ls, -2))
	{
		lua_pushstring(ls, "Invalid arguments passed to handle_http()");
		lua_error(ls);
	}

	string url = (char *) lua_tostring(ls, 1);
	string msg = (char *) lua_tostring(ls, 2);

	curl = curl_easy_init();
	if(curl)
	{
		slist1 = curl_slist_append(slist1, "Content-Type: application/json");
		curl_easy_setopt(curl, CURLOPT_HTTPHEADER, slist1);
		curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
		curl_easy_setopt(curl, CURLOPT_POSTFIELDS, msg.c_str());
		curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, -1L);

		res = curl_easy_perform(curl);

		if(res != CURLE_OK) {
			falco_logger::log(LOG_ERR,"libcurl error: " + string(curl_easy_strerror(res)));
		}
		curl_easy_cleanup(curl);
		curl = NULL;
		curl_slist_free_all(slist1);
		slist1 = NULL;
	}
	return 1;
}

int falco_outputs::handle_grpc(lua_State *ls)
{
	// check parameters
	if(!lua_islightuserdata(ls, -8) ||
	   !lua_isstring(ls, -7) ||
	   !lua_isstring(ls, -6) ||
	   !lua_isstring(ls, -5) ||
	   !lua_isstring(ls, -4) ||
	   !lua_istable(ls, -3) ||
	   !lua_isstring(ls, -2) ||
	   !lua_istable(ls, -1))
	{
		lua_pushstring(ls, "Invalid arguments passed to handle_grpc()");
		lua_error(ls);
	}

	response grpc_res = response();

	// time
	gen_event* evt = (gen_event*)lua_topointer(ls, 1);
	auto& timestamp = *grpc_res.mutable_time();
	timestamp = google::protobuf::util::TimeUtil::NanosecondsToTimestamp(evt->get_ts());

	// rule
	grpc_res.set_rule((char *)lua_tostring(ls, 2));

	// source
	falco::schema::source s = falco::schema::source::SYSCALL;
	string sstr = (char *)lua_tostring(ls, 3);
	if(!falco::schema::source_Parse(sstr, &s))
	{
		lua_pushstring(ls, "Unknown source passed to to handle_grpc()");
		lua_error(ls);
	}
	grpc_res.set_source(s);

	// priority
	falco::schema::priority p = falco::schema::priority::EMERGENCY;
	string pstr = (char *)lua_tostring(ls, 4);
	if(!falco::schema::priority_Parse(pstr, &p))
	{
		lua_pushstring(ls, "Unknown priority passed to to handle_grpc()");
		lua_error(ls);
	}
	grpc_res.set_priority(p);

	// output
	grpc_res.set_output((char *)lua_tostring(ls, 5));

	// output fields
	auto& fields = *grpc_res.mutable_output_fields();

	lua_pushnil(ls); // so that lua_next removes it from stack and puts (k, v) on it
	while (lua_next(ls, 6) != 0) {
		fields[lua_tostring(ls, -2)] = lua_tostring(ls, -1);
		lua_pop(ls, 1); // remove value, keep key for lua_next
	}
	lua_pop(ls, 1); // pop table

	// hostname
	grpc_res.set_hostname((char* )lua_tostring(ls, 7));

	falco::output::queue::get().push(grpc_res);

	return 1;
}
<commit_msg>chore: use std::string to have safer copies<commit_after>/*
Copyright (C) 2019 The Falco Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

#include <google/protobuf/util/time_util.h>

#include "falco_outputs.h"

#include "config_falco.h"

#include "formats.h"
#include "logger.h"
#include "falco_output_queue.h"

using namespace std;
using namespace falco::output;

const static struct luaL_reg ll_falco_outputs [] =
{
	{"handle_http", &falco_outputs::handle_http},
	{"handle_grpc", &falco_outputs::handle_grpc},
	{NULL,NULL}
};

falco_outputs::falco_outputs(falco_engine *engine)
	: m_falco_engine(engine),
	  m_initialized(false),
	  m_buffered(true),
	  m_json_output(false),
	  m_time_format_iso_8601(false)
{

}

falco_outputs::~falco_outputs()
{
	// Note: The assert()s in this destructor were previously places where
	//       exceptions were thrown.  C++11 doesn't allow destructors to
	//       emit exceptions; if they're thrown, they'll trigger a call
	//       to 'terminate()'.  To maintain similar behavior, the exceptions
	//       were replace with calls to 'assert()'
	if(m_initialized)
	{
		lua_getglobal(m_ls, m_lua_output_cleanup.c_str());
		if(!lua_isfunction(m_ls, -1))
		{
			falco_logger::log(LOG_ERR, std::string("No function ") + m_lua_output_cleanup + " found. ");
			assert(nullptr == "Missing lua cleanup function in ~falco_outputs");
		}

		if(lua_pcall(m_ls, 0, 0, 0) != 0)
		{
			const char* lerr = lua_tostring(m_ls, -1);
			falco_logger::log(LOG_ERR, std::string("lua_pcall failed, err: ") + lerr);
			assert(nullptr == "lua_pcall failed in ~falco_outputs");
		}
	}
}

void falco_outputs::init(bool json_output,
			 bool json_include_output_property,
			 uint32_t rate, uint32_t max_burst, bool buffered,
			 bool time_format_iso_8601)
{
	// The engine must have been given an inspector by now.
	if(! m_inspector)
	{
		throw falco_exception("No inspector provided");
	}

	m_json_output = json_output;

	falco_common::init(m_lua_main_filename.c_str(), FALCO_SOURCE_LUA_DIR);

	// Note that falco_formats is added to both the lua state used
	// by the falco engine as well as the separate lua state used
	// by falco outputs.
	falco_formats::init(m_inspector, m_falco_engine, m_ls, json_output, json_include_output_property);

	falco_logger::init(m_ls);

	luaL_openlib(m_ls, "c_outputs", ll_falco_outputs, 0);

	m_notifications_tb.init(rate, max_burst);

	m_buffered = buffered;
	m_time_format_iso_8601 = time_format_iso_8601;

	m_initialized = true;
}

void falco_outputs::add_output(output_config oc)
{
	uint8_t nargs = 3;
	lua_getglobal(m_ls, m_lua_add_output.c_str());

	if(!lua_isfunction(m_ls, -1))
	{
		throw falco_exception("No function " + m_lua_add_output + " found. ");
	}
	lua_pushstring(m_ls, oc.name.c_str());
	lua_pushnumber(m_ls, (m_buffered ? 1 : 0));
	lua_pushnumber(m_ls, (m_time_format_iso_8601 ? 1 : 0));

	// If we have options, build up a lua table containing them
	if (oc.options.size())
	{
		nargs = 4;
		lua_createtable(m_ls, 0, oc.options.size());

		for (auto it = oc.options.cbegin(); it != oc.options.cend(); ++it)
		{
			lua_pushstring(m_ls, (*it).second.c_str());
			lua_setfield(m_ls, -2, (*it).first.c_str());
		}
	}

	if(lua_pcall(m_ls, nargs, 0, 0) != 0)
	{
		const char* lerr = lua_tostring(m_ls, -1);
		throw falco_exception(string(lerr));
	}

}

void falco_outputs::handle_event(gen_event *ev, string &rule, string &source,
				 falco_common::priority_type priority, string &format)
{
	if(!m_notifications_tb.claim())
	{
		falco_logger::log(LOG_DEBUG, "Skipping rate-limited notification for rule " + rule + "\n");
		return;
	}

	std::lock_guard<std::mutex> guard(m_ls_semaphore);
	lua_getglobal(m_ls, m_lua_output_event.c_str());
	std::string hostname;
	char* env_hostname = getenv("FALCO_GRPC_HOSTNAME");
	if(env_hostname == NULL){
		char c_hostname[256];
		int err = gethostname(c_hostname, 256);
		if(err != 0){
			string err = "Failed to get hostname";
			throw falco_exception(err);
		}
		hostname = c_hostname;
	}else{
		hostname = env_hostname;
	}
	if(lua_isfunction(m_ls, -1))
	{
		lua_pushlightuserdata(m_ls, ev);
		lua_pushstring(m_ls, rule.c_str());
		lua_pushstring(m_ls, source.c_str());
		lua_pushstring(m_ls, falco_common::priority_names[priority].c_str());
		lua_pushnumber(m_ls, priority);
		lua_pushstring(m_ls, format.c_str());
		lua_pushstring(m_ls, hostname.c_str());

		if(lua_pcall(m_ls, 7, 0, 0) != 0)
		{
			const char* lerr = lua_tostring(m_ls, -1);
			string err = "Error invoking function output: " + string(lerr);
			throw falco_exception(err);
		}
	}
	else
	{
		throw falco_exception("No function " + m_lua_output_event + " found in lua compiler module");
	}
}

void falco_outputs::handle_msg(uint64_t now,
			       falco_common::priority_type priority,
			       std::string &msg,
			       std::string &rule,
			       std::map<std::string,std::string> &output_fields)
{
	std::string full_msg;

	if(m_json_output)
	{
		nlohmann::json jmsg;

		// Convert the time-as-nanoseconds to a more json-friendly ISO8601.
		time_t evttime = now/1000000000;
		char time_sec[20]; // sizeof "YYYY-MM-DDTHH:MM:SS"
		char time_ns[12]; // sizeof ".sssssssssZ"
		string iso8601evttime;

		strftime(time_sec, sizeof(time_sec), "%FT%T", gmtime(&evttime));
		snprintf(time_ns, sizeof(time_ns), ".%09luZ", now % 1000000000);
		iso8601evttime = time_sec;
		iso8601evttime += time_ns;

		jmsg["output"] = msg;
		jmsg["priority"] = "Critical";
		jmsg["rule"] = rule;
		jmsg["time"] = iso8601evttime;
		jmsg["output_fields"] = output_fields;

		full_msg = jmsg.dump();
	}
	else
	{
		std::string timestr;
		bool first = true;

		sinsp_utils::ts_to_string(now, &timestr, false, true);
		full_msg = timestr + ": " + falco_common::priority_names[LOG_CRIT] + " " + msg + " (";
		for(auto &pair : output_fields)
		{
			if(first)
			{
				first = false;
			}
			else
			{
				full_msg += " ";
			}
			full_msg += pair.first + "=" + pair.second;
		}
		full_msg += ")";
	}

	std::lock_guard<std::mutex> guard(m_ls_semaphore);
	lua_getglobal(m_ls, m_lua_output_msg.c_str());
	if(lua_isfunction(m_ls, -1))
	{
		lua_pushstring(m_ls, full_msg.c_str());
		lua_pushstring(m_ls, falco_common::priority_names[priority].c_str());
		lua_pushnumber(m_ls, priority);

		if(lua_pcall(m_ls, 3, 0, 0) != 0)
		{
			const char* lerr = lua_tostring(m_ls, -1);
			string err = "Error invoking function output: " + string(lerr);
			throw falco_exception(err);
		}
	}
	else
	{
		throw falco_exception("No function " + m_lua_output_msg + " found in lua compiler module");
	}

}

void falco_outputs::reopen_outputs()
{
	lua_getglobal(m_ls, m_lua_output_reopen.c_str());
	if(!lua_isfunction(m_ls, -1))
	{
		throw falco_exception("No function " + m_lua_output_reopen + " found. ");
	}

	if(lua_pcall(m_ls, 0, 0, 0) != 0)
	{
		const char* lerr = lua_tostring(m_ls, -1);
		throw falco_exception(string(lerr));
	}
}

int falco_outputs::handle_http(lua_State *ls)
{
	CURL *curl = NULL;
	CURLcode res = CURLE_FAILED_INIT;
	struct curl_slist *slist1;
	slist1 = NULL;

	if(!lua_isstring(ls, -1) ||
	   !lua_isstring(ls, -2))
	{
		lua_pushstring(ls, "Invalid arguments passed to handle_http()");
		lua_error(ls);
	}

	string url = (char *) lua_tostring(ls, 1);
	string msg = (char *) lua_tostring(ls, 2);

	curl = curl_easy_init();
	if(curl)
	{
		slist1 = curl_slist_append(slist1, "Content-Type: application/json");
		curl_easy_setopt(curl, CURLOPT_HTTPHEADER, slist1);
		curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
		curl_easy_setopt(curl, CURLOPT_POSTFIELDS, msg.c_str());
		curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, -1L);

		res = curl_easy_perform(curl);

		if(res != CURLE_OK) {
			falco_logger::log(LOG_ERR,"libcurl error: " + string(curl_easy_strerror(res)));
		}
		curl_easy_cleanup(curl);
		curl = NULL;
		curl_slist_free_all(slist1);
		slist1 = NULL;
	}
	return 1;
}

int falco_outputs::handle_grpc(lua_State *ls)
{
	// check parameters
	if(!lua_islightuserdata(ls, -8) ||
	   !lua_isstring(ls, -7) ||
	   !lua_isstring(ls, -6) ||
	   !lua_isstring(ls, -5) ||
	   !lua_isstring(ls, -4) ||
	   !lua_istable(ls, -3) ||
	   !lua_isstring(ls, -2) ||
	   !lua_istable(ls, -1))
	{
		lua_pushstring(ls, "Invalid arguments passed to handle_grpc()");
		lua_error(ls);
	}

	response grpc_res = response();

	// time
	gen_event* evt = (gen_event*)lua_topointer(ls, 1);
	auto& timestamp = *grpc_res.mutable_time();
	timestamp = google::protobuf::util::TimeUtil::NanosecondsToTimestamp(evt->get_ts());

	// rule
	grpc_res.set_rule((char *)lua_tostring(ls, 2));

	// source
	falco::schema::source s = falco::schema::source::SYSCALL;
	string sstr = (char *)lua_tostring(ls, 3);
	if(!falco::schema::source_Parse(sstr, &s))
	{
		lua_pushstring(ls, "Unknown source passed to to handle_grpc()");
		lua_error(ls);
	}
	grpc_res.set_source(s);

	// priority
	falco::schema::priority p = falco::schema::priority::EMERGENCY;
	string pstr = (char *)lua_tostring(ls, 4);
	if(!falco::schema::priority_Parse(pstr, &p))
	{
		lua_pushstring(ls, "Unknown priority passed to to handle_grpc()");
		lua_error(ls);
	}
	grpc_res.set_priority(p);

	// output
	grpc_res.set_output((char *)lua_tostring(ls, 5));

	// output fields
	auto& fields = *grpc_res.mutable_output_fields();

	lua_pushnil(ls); // so that lua_next removes it from stack and puts (k, v) on it
	while (lua_next(ls, 6) != 0) {
		fields[lua_tostring(ls, -2)] = lua_tostring(ls, -1);
		lua_pop(ls, 1); // remove value, keep key for lua_next
	}
	lua_pop(ls, 1); // pop table

	// hostname
	grpc_res.set_hostname((char* )lua_tostring(ls, 7));

	falco::output::queue::get().push(grpc_res);

	return 1;
}
<|endoftext|>


<commit_before>/*
***************************************
*   Asylum3D @ 2014-12-24
***************************************
*/

#include "../../asylum.hpp"

/*****************************************************************************/
/*                                Attribute                                  */
/*****************************************************************************/

/* Asylum Namespace */
namespace asy {

/*******************************/
/* Wavefront Attribute (Fixed) */
/*******************************/
class crh3d9_attr_wf_fixed : public IAttrib
{
protected:
    D3DMATERIAL9        m_mtl;
    crh3d9_texr*        m_map_kd;
    LPDIRECT3DDEVICE9   m_device;

public:
    /* ======================================== */
    crh3d9_attr_wf_fixed (const crh3d9_main* main)
    {
        m_device = main->get_main()->dev;
    }

    /* ========================== */
    virtual ~crh3d9_attr_wf_fixed ()
    {
    }

public:
    /* ===================================================================== */
    bool init_ff (const sWAVEFRONT_M* mtl, const map_acs<crh3d9_texr>* texpool)
    {
        if (mtl->map_kd != NULL) {
            m_map_kd = texpool->get(mtl->map_kd);
            if (m_map_kd == NULL)
                return (false);
        }
        else {
            m_map_kd = NULL;
        }
        m_mtl.Diffuse.r = mtl->kd.x;
        m_mtl.Diffuse.g = mtl->kd.y;
        m_mtl.Diffuse.b = mtl->kd.z;
        m_mtl.Diffuse.a = mtl->d;
        if (m_mtl.Diffuse.a < 0.0f)
            m_mtl.Diffuse.a = 0.0f;
        else
        if (m_mtl.Diffuse.a > 1.0f)
            m_mtl.Diffuse.a = 1.0f;
        m_mtl.Ambient.r = mtl->ka.x;
        m_mtl.Ambient.g = mtl->ka.y;
        m_mtl.Ambient.b = mtl->ka.z;
        m_mtl.Ambient.a = 0.0f;
        m_mtl.Specular.r = mtl->ks.x;
        m_mtl.Specular.g = mtl->ks.y;
        m_mtl.Specular.b = mtl->ks.z;
        m_mtl.Specular.a = 0.0f;
        m_mtl.Emissive.r = 0.0f;
        m_mtl.Emissive.g = 0.0f;
        m_mtl.Emissive.b = 0.0f;
        m_mtl.Emissive.a = 0.0f;
        m_mtl.Power = mtl->ns;
        m_type = ATTR_TYPE_NORMAL;
        if (m_mtl.Diffuse.a < 1.0f)
            m_type |= ATTR_TYPE_TRANS;
        if (m_map_kd != NULL)
            m_type |= ATTR_TYPE_TEXTURE;
        if (m_mtl.Specular.r <= 0.0f && m_mtl.Specular.g <= 0.0f &&
            m_mtl.Specular.b <= 0.0f && m_mtl.Specular.a <= 0.0f)
            m_type |= ATTR_TYPE_SPECULAR;
        return (true);
    }

    /* ================ */
    virtual void commit ()
    {
        if (m_map_kd != NULL)
            m_map_kd->apply(0);
        else
            m_device->SetTexture(0, NULL);
        m_device->SetMaterial(&m_mtl);
    }
};

}   /* namespace */

/* ==================================================================== */
CR_API asy::IAttrib* create_crh3d9_attr_wf_fixed (const sWAVEFRONT_M* mtl,
    const asy::map_acs<asy::crh3d9_texr>* texpool, const asy::crh3d9_main* main)
{
    asy::crh3d9_attr_wf_fixed*  attr;

    attr = new asy::crh3d9_attr_wf_fixed (main);
    if (attr != NULL) {
        if (!attr->init(mtl, texpool)) {
            delete attr;
            attr = NULL;
        }
    }
    return ((asy::IAttrib*)attr);
}

/*****************************************************************************/
/*                                   Mesh                                    */
/*****************************************************************************/

/* Asylum Namespace */
namespace asy {

/**********************************/
/* Wavefront Mesh (Single Stream) */
/**********************************/
class crh3d9_mesh_wf_ss : public IMesh
{
private:
    sD3D9_MESH*         m_mesh;
    sD3D9_MAIN*         m_main;
    const sD3D9_CALL*   m_call;
    LPDIRECT3DDEVICE9   m_devs;

public:
    /* ===================================== */
    crh3d9_mesh_wf_ss (const crh3d9_main* main)
    {
        m_mesh = NULL;
        m_main = main->get_main();
        m_call = main->get_call();
        m_devs = m_main->dev;
    }

    /* ======================= */
    virtual ~crh3d9_mesh_wf_ss ()
    {
        if (m_mesh != NULL)
            m_call->release_mesh(m_mesh);
    }

public:
    /* =========================================== */
    bool init2_ss (const sWAVEFRONT* obj, leng_t idx)
    {
        leng_t  nv, ni, bpv;

        nv = wfront_gen_mesh2(NULL, NULL, NULL, 0, 0, 0, NULL, &ni, obj, idx);
        if (nv == 0)
            return (false);
        bpv = sizeof(vec3d_t);

        void_t* vb;
        void_t* ib;

        if (obj->p_f[0].idx[2] != 0)
            bpv += sizeof(vec3d_t);
        if (obj->p_f[0].idx[1] != 0)
            bpv += sizeof(vec2d_t);
        vb = mem_calloc(nv, bpv);
        if (vb == NULL)
            return (false);
        if (nv > 65536)
            ib = mem_calloc(ni, sizeof(int32u));
        else
            ib = mem_calloc(ni, sizeof(int16u));
        if (ib == NULL) {
            mem_free(vb);
            return (false);
        }

        uint_t      fvf;
        vec3d_t*    xyz;
        vec3d_t*    nrm;
        vec2d_t*    uvw;

        fvf = D3DFVF_XYZ;
        xyz = (vec3d_t*)vb;
        if (obj->p_f[0].idx[2] != 0) {
            fvf |= D3DFVF_NORMAL;
            nrm = xyz + 1;
            uvw = (vec2d_t*)(nrm + 1);
        }
        else {
            nrm = NULL;
            uvw = (vec2d_t*)(xyz + 1);
        }
        if (obj->p_f[0].idx[1] != 0)
            fvf |= D3DFVF_TEX1;
        else
            uvw = NULL;
        wfront_gen_mesh2(xyz, nrm, uvw, bpv, 0, 0, ib, NULL, obj, idx);
        m_mesh = m_call->create_mesh_vib(m_main, nv, bpv, ni, D3DPOOL_MANAGED, D3DUSAGE_WRITEONLY,
                                         D3DPOOL_MANAGED, D3DUSAGE_WRITEONLY, fvf, vb, ib);
        mem_free(ib);
        if (m_mesh == NULL) {
            mem_free(vb);
            return (false);
        }
        bound_get_aabb(&m_aabb, (vec3d_t*)vb, nv, bpv);
        bound_get_ball(&m_ball, (vec3d_t*)vb, nv, bpv);
        mem_free(vb);
        return (true);
    }

    /* ================ */
    virtual void commit ()
    {
        m_devs->SetStreamSource(0, m_mesh->vbuf, 0, m_mesh->nbpv);
        m_devs->SetIndices(m_mesh->ibuf);
        m_devs->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, 0, m_mesh->vnum, 0, m_mesh->ntri);
    }
};

}   /* namespace */

/* ========================================================================= */
CR_API asy::IMesh* create_crh3d9_mesh_wf_ss (const sWAVEFRONT* obj, leng_t idx,
                                             const asy::crh3d9_main* main)
{
    asy::crh3d9_mesh_wf_ss* mesh;

    mesh = new asy::crh3d9_mesh_wf_ss (main);
    if (mesh != NULL) {
        if (!mesh->init2_ss(obj, idx)) {
            delete mesh;
            mesh = NULL;
        }
    }
    return ((asy::IMesh*)mesh);
}
<commit_msg>Asylum: 修正编译错误<commit_after>/*
***************************************
*   Asylum3D @ 2014-12-24
***************************************
*/

#include "../../asylum.hpp"

/*****************************************************************************/
/*                                Attribute                                  */
/*****************************************************************************/

/* Asylum Namespace */
namespace asy {

/*******************************/
/* Wavefront Attribute (Fixed) */
/*******************************/
class crh3d9_attr_wf_fixed : public IAttrib
{
protected:
    D3DMATERIAL9        m_mtl;
    crh3d9_texr*        m_map_kd;
    LPDIRECT3DDEVICE9   m_device;

public:
    /* ======================================== */
    crh3d9_attr_wf_fixed (const crh3d9_main* main)
    {
        m_device = main->get_main()->dev;
    }

    /* ========================== */
    virtual ~crh3d9_attr_wf_fixed ()
    {
    }

public:
    /* ===================================================================== */
    bool init_ff (const sWAVEFRONT_M* mtl, const map_acs<crh3d9_texr>* texpool)
    {
        if (mtl->map_kd != NULL) {
            m_map_kd = texpool->get(mtl->map_kd);
            if (m_map_kd == NULL)
                return (false);
        }
        else {
            m_map_kd = NULL;
        }
        m_mtl.Diffuse.r = mtl->kd.x;
        m_mtl.Diffuse.g = mtl->kd.y;
        m_mtl.Diffuse.b = mtl->kd.z;
        m_mtl.Diffuse.a = mtl->d;
        if (m_mtl.Diffuse.a < 0.0f)
            m_mtl.Diffuse.a = 0.0f;
        else
        if (m_mtl.Diffuse.a > 1.0f)
            m_mtl.Diffuse.a = 1.0f;
        m_mtl.Ambient.r = mtl->ka.x;
        m_mtl.Ambient.g = mtl->ka.y;
        m_mtl.Ambient.b = mtl->ka.z;
        m_mtl.Ambient.a = 0.0f;
        m_mtl.Specular.r = mtl->ks.x;
        m_mtl.Specular.g = mtl->ks.y;
        m_mtl.Specular.b = mtl->ks.z;
        m_mtl.Specular.a = 0.0f;
        m_mtl.Emissive.r = 0.0f;
        m_mtl.Emissive.g = 0.0f;
        m_mtl.Emissive.b = 0.0f;
        m_mtl.Emissive.a = 0.0f;
        m_mtl.Power = mtl->ns;
        m_type = ATTR_TYPE_NORMAL;
        if (m_mtl.Diffuse.a < 1.0f)
            m_type |= ATTR_TYPE_TRANS;
        if (m_map_kd != NULL)
            m_type |= ATTR_TYPE_TEXTURE;
        if (m_mtl.Specular.r <= 0.0f && m_mtl.Specular.g <= 0.0f &&
            m_mtl.Specular.b <= 0.0f && m_mtl.Specular.a <= 0.0f)
            m_type |= ATTR_TYPE_SPECULAR;
        return (true);
    }

    /* ================ */
    virtual void commit ()
    {
        if (m_map_kd != NULL)
            m_map_kd->apply(0);
        else
            m_device->SetTexture(0, NULL);
        m_device->SetMaterial(&m_mtl);
    }
};

}   /* namespace */

/* ==================================================================== */
CR_API asy::IAttrib* create_crh3d9_attr_wf_fixed (const sWAVEFRONT_M* mtl,
    const asy::map_acs<asy::crh3d9_texr>* texpool, const asy::crh3d9_main* main)
{
    asy::crh3d9_attr_wf_fixed*  attr;

    attr = new asy::crh3d9_attr_wf_fixed (main);
    if (attr != NULL) {
        if (!attr->init_ff(mtl, texpool)) {
            delete attr;
            attr = NULL;
        }
    }
    return ((asy::IAttrib*)attr);
}

/*****************************************************************************/
/*                                   Mesh                                    */
/*****************************************************************************/

/* Asylum Namespace */
namespace asy {

/**********************************/
/* Wavefront Mesh (Single Stream) */
/**********************************/
class crh3d9_mesh_wf_ss : public IMesh
{
private:
    sD3D9_MESH*         m_mesh;
    sD3D9_MAIN*         m_main;
    const sD3D9_CALL*   m_call;
    LPDIRECT3DDEVICE9   m_devs;

public:
    /* ===================================== */
    crh3d9_mesh_wf_ss (const crh3d9_main* main)
    {
        m_mesh = NULL;
        m_main = main->get_main();
        m_call = main->get_call();
        m_devs = m_main->dev;
    }

    /* ======================= */
    virtual ~crh3d9_mesh_wf_ss ()
    {
        if (m_mesh != NULL)
            m_call->release_mesh(m_mesh);
    }

public:
    /* =========================================== */
    bool init2_ss (const sWAVEFRONT* obj, leng_t idx)
    {
        leng_t  nv, ni, bpv;

        nv = wfront_gen_mesh2(NULL, NULL, NULL, 0, 0, 0, NULL, &ni, obj, idx);
        if (nv == 0)
            return (false);
        bpv = sizeof(vec3d_t);

        void_t* vb;
        void_t* ib;

        if (obj->p_f[0].idx[2] != 0)
            bpv += sizeof(vec3d_t);
        if (obj->p_f[0].idx[1] != 0)
            bpv += sizeof(vec2d_t);
        vb = mem_calloc(nv, bpv);
        if (vb == NULL)
            return (false);
        if (nv > 65536)
            ib = mem_calloc(ni, sizeof(int32u));
        else
            ib = mem_calloc(ni, sizeof(int16u));
        if (ib == NULL) {
            mem_free(vb);
            return (false);
        }

        uint_t      fvf;
        vec3d_t*    xyz;
        vec3d_t*    nrm;
        vec2d_t*    uvw;

        fvf = D3DFVF_XYZ;
        xyz = (vec3d_t*)vb;
        if (obj->p_f[0].idx[2] != 0) {
            fvf |= D3DFVF_NORMAL;
            nrm = xyz + 1;
            uvw = (vec2d_t*)(nrm + 1);
        }
        else {
            nrm = NULL;
            uvw = (vec2d_t*)(xyz + 1);
        }
        if (obj->p_f[0].idx[1] != 0)
            fvf |= D3DFVF_TEX1;
        else
            uvw = NULL;
        wfront_gen_mesh2(xyz, nrm, uvw, bpv, 0, 0, ib, NULL, obj, idx);
        m_mesh = m_call->create_mesh_vib(m_main, nv, bpv, ni, D3DPOOL_MANAGED, D3DUSAGE_WRITEONLY,
                                         D3DPOOL_MANAGED, D3DUSAGE_WRITEONLY, fvf, vb, ib);
        mem_free(ib);
        if (m_mesh == NULL) {
            mem_free(vb);
            return (false);
        }
        bound_get_aabb(&m_aabb, (vec3d_t*)vb, nv, bpv);
        bound_get_ball(&m_ball, (vec3d_t*)vb, nv, bpv);
        mem_free(vb);
        return (true);
    }

    /* ================ */
    virtual void commit ()
    {
        m_devs->SetStreamSource(0, m_mesh->vbuf, 0, m_mesh->nbpv);
        m_devs->SetIndices(m_mesh->ibuf);
        m_devs->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, 0, m_mesh->vnum, 0, m_mesh->ntri);
    }
};

}   /* namespace */

/* ========================================================================= */
CR_API asy::IMesh* create_crh3d9_mesh_wf_ss (const sWAVEFRONT* obj, leng_t idx,
                                             const asy::crh3d9_main* main)
{
    asy::crh3d9_mesh_wf_ss* mesh;

    mesh = new asy::crh3d9_mesh_wf_ss (main);
    if (mesh != NULL) {
        if (!mesh->init2_ss(obj, idx)) {
            delete mesh;
            mesh = NULL;
        }
    }
    return ((asy::IMesh*)mesh);
}
<|endoftext|>


<commit_before>/****************************************************************************
 *
 *   Copyright (c) 2018 PX4 Development Team. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 * 3. Neither the name PX4 nor the names of its contributors may be
 *    used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 ****************************************************************************/

/**
 * @file CollisionPrevention.cpp
 * CollisionPrevention controller.
 *
 */

#include <CollisionPrevention/CollisionPrevention.hpp>
using namespace matrix;
using namespace time_literals;

CollisionPrevention::CollisionPrevention(ModuleParams *parent) :
	ModuleParams(parent)
{

}

CollisionPrevention::~CollisionPrevention()
{
	//unadvertise publishers
	if (_mavlink_log_pub != nullptr) {
		orb_unadvertise(_mavlink_log_pub);
	}
}

bool CollisionPrevention::initializeSubscriptions(SubscriptionArray &subscription_array)
{
	if (!subscription_array.get(ORB_ID(obstacle_distance), _sub_obstacle_distance)) {
		return false;
	}

	return true;
}

void CollisionPrevention::calculate_constrained_setpoint(Vector2f &setpoint, const float max_acc)
{
	const obstacle_distance_s &obstacle_distance = _sub_obstacle_distance->get();

	//The maximum velocity formula contains a square root, therefore the whole calculation is done with squared norms.
	//that way the root does not have to be calculated for every range bin but once at the end.
	float setpoint_length = setpoint.norm();
	Vector2f setpoint_sqrd = setpoint * setpoint_length;

	//Limit the deviation of the adapted setpoint from the originally given joystick input (slightly less than 90 degrees)
	float max_slide_angle_rad = 1.2f;

	if (hrt_elapsed_time(&obstacle_distance.timestamp) < RANGE_STREAM_TIMEOUT_US && setpoint_length > 0.001f) {

		int distances_array_size = sizeof(obstacle_distance.distances) / sizeof(obstacle_distance.distances[0]);

		for (int i = 0; i < distances_array_size; i++) {

			//determine if distance bin is valid and contains a valid distance measurement
			if (obstacle_distance.distances[i] < obstacle_distance.max_distance &&
			    obstacle_distance.distances[i] > obstacle_distance.min_distance && i * obstacle_distance.increment < 360) {
				float distance = obstacle_distance.distances[i] / 100.0f; //convert to meters
				float angle = math::radians((float)i * obstacle_distance.increment);

				//max admissible velocity in current bin direction: v = sqrt(2 * a * d), where d is the distance to standstill
				//a is the constant acceleration and v the current velocity. We use a = a_max/2 to stay well within the limits
				float vel_max_sqrd = math::max(0.f, max_acc * (distance - _param_mpc_col_prev_d.get()));

				//split current setpoint into parallel and orthogonal components with respect to the current bin direction
				Vector2f bin_direction = {cos(angle), sin(angle)};
				Vector2f orth_direction = {-bin_direction(1), bin_direction(0)};
				float sp_parallel = setpoint_sqrd.dot(bin_direction);
				float sp_orth = setpoint_sqrd.dot(orth_direction);

				//limit the setpoint to respect vel_max by subtracting from the parallel component
				if (sp_parallel > vel_max_sqrd) {
					Vector2f setpoint_temp = setpoint_sqrd - (sp_parallel - vel_max_sqrd) * bin_direction;
					float setpoint_temp_length = setpoint_temp.norm();

					//limit sliding angle
					float angle_diff_temp_orig = acos(setpoint_temp.dot(setpoint) / (setpoint_temp_length * setpoint_length));
					float angle_diff_temp_bin = acos(setpoint_temp.dot(bin_direction) / setpoint_temp_length);

					if (angle_diff_temp_orig > max_slide_angle_rad && setpoint_temp_length > 0.001f) {
						float angle_temp_bin_cropped = angle_diff_temp_bin - (angle_diff_temp_orig - max_slide_angle_rad);
						float orth_len = vel_max_sqrd * tan(angle_temp_bin_cropped);

						if (sp_orth > 0) {
							setpoint_temp = vel_max_sqrd * bin_direction + orth_len * orth_direction;

						} else {
							setpoint_temp = vel_max_sqrd * bin_direction - orth_len * orth_direction;
						}
					}

					setpoint_sqrd = setpoint_temp;
				}
			}
		}

		//take the squared root
		if (setpoint_sqrd.norm() > 0.001f) {
			setpoint = setpoint_sqrd / std::sqrt(setpoint_sqrd.norm());

		} else {
			setpoint.zero();
		}

	} else if (_last_message + MESSAGE_THROTTLE_US < hrt_absolute_time()) {
		mavlink_log_critical(&_mavlink_log_pub, "No range data received");
		_last_message = hrt_absolute_time();
	}
}

void CollisionPrevention::modifySetpoint(Vector2f &original_setpoint, const float max_speed,
		const float max_acc)
{
	//calculate movement constraints based on range data
	Vector2f new_setpoint = original_setpoint;
	calculate_constrained_setpoint(new_setpoint, max_acc);

	//warn user if collision prevention starts to interfere
	bool currently_interfering = (new_setpoint(0) < original_setpoint(0) - 0.05f * max_speed
				      || new_setpoint(0) > original_setpoint(0) + 0.05f * max_speed
				      || new_setpoint(1) < original_setpoint(1) - 0.05f * max_speed
				      || new_setpoint(1) > original_setpoint(1) + 0.05f * max_speed);

	if (currently_interfering && (currently_interfering != _interfering)) {
		mavlink_log_critical(&_mavlink_log_pub, "Collision Warning");
	}

	_interfering = currently_interfering;
	original_setpoint = new_setpoint;
}
<commit_msg>fix wrong if clause<commit_after>/****************************************************************************
 *
 *   Copyright (c) 2018 PX4 Development Team. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 * 3. Neither the name PX4 nor the names of its contributors may be
 *    used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 ****************************************************************************/

/**
 * @file CollisionPrevention.cpp
 * CollisionPrevention controller.
 *
 */

#include <CollisionPrevention/CollisionPrevention.hpp>
using namespace matrix;
using namespace time_literals;

CollisionPrevention::CollisionPrevention(ModuleParams *parent) :
	ModuleParams(parent)
{

}

CollisionPrevention::~CollisionPrevention()
{
	//unadvertise publishers
	if (_mavlink_log_pub != nullptr) {
		orb_unadvertise(_mavlink_log_pub);
	}
}

bool CollisionPrevention::initializeSubscriptions(SubscriptionArray &subscription_array)
{
	if (!subscription_array.get(ORB_ID(obstacle_distance), _sub_obstacle_distance)) {
		return false;
	}

	return true;
}

void CollisionPrevention::calculate_constrained_setpoint(Vector2f &setpoint, const float max_acc)
{
	const obstacle_distance_s &obstacle_distance = _sub_obstacle_distance->get();

	//The maximum velocity formula contains a square root, therefore the whole calculation is done with squared norms.
	//that way the root does not have to be calculated for every range bin but once at the end.
	float setpoint_length = setpoint.norm();
	Vector2f setpoint_sqrd = setpoint * setpoint_length;

	//Limit the deviation of the adapted setpoint from the originally given joystick input (slightly less than 90 degrees)
	float max_slide_angle_rad = 1.2f;

	if (hrt_elapsed_time(&obstacle_distance.timestamp) < RANGE_STREAM_TIMEOUT_US) {
		if (setpoint_length > 0.001f) {

			int distances_array_size = sizeof(obstacle_distance.distances) / sizeof(obstacle_distance.distances[0]);

			for (int i = 0; i < distances_array_size; i++) {

				//determine if distance bin is valid and contains a valid distance measurement
				if (obstacle_distance.distances[i] < obstacle_distance.max_distance &&
				    obstacle_distance.distances[i] > obstacle_distance.min_distance && i * obstacle_distance.increment < 360) {
					float distance = obstacle_distance.distances[i] / 100.0f; //convert to meters
					float angle = math::radians((float)i * obstacle_distance.increment);

					//max admissible velocity in current bin direction: v = sqrt(2 * a * d), where d is the distance to standstill
					//a is the constant acceleration and v the current velocity. We use a = a_max/2 to stay well within the limits
					float vel_max_sqrd = math::max(0.f, max_acc * (distance - _param_mpc_col_prev_d.get()));

					//split current setpoint into parallel and orthogonal components with respect to the current bin direction
					Vector2f bin_direction = {cos(angle), sin(angle)};
					Vector2f orth_direction = {-bin_direction(1), bin_direction(0)};
					float sp_parallel = setpoint_sqrd.dot(bin_direction);
					float sp_orth = setpoint_sqrd.dot(orth_direction);

					//limit the setpoint to respect vel_max by subtracting from the parallel component
					if (sp_parallel > vel_max_sqrd) {
						Vector2f setpoint_temp = setpoint_sqrd - (sp_parallel - vel_max_sqrd) * bin_direction;
						float setpoint_temp_length = setpoint_temp.norm();

						//limit sliding angle
						float angle_diff_temp_orig = acos(setpoint_temp.dot(setpoint) / (setpoint_temp_length * setpoint_length));
						float angle_diff_temp_bin = acos(setpoint_temp.dot(bin_direction) / setpoint_temp_length);

						if (angle_diff_temp_orig > max_slide_angle_rad && setpoint_temp_length > 0.001f) {
							float angle_temp_bin_cropped = angle_diff_temp_bin - (angle_diff_temp_orig - max_slide_angle_rad);
							float orth_len = vel_max_sqrd * tan(angle_temp_bin_cropped);

							if (sp_orth > 0) {
								setpoint_temp = vel_max_sqrd * bin_direction + orth_len * orth_direction;

							} else {
								setpoint_temp = vel_max_sqrd * bin_direction - orth_len * orth_direction;
							}
						}

						setpoint_sqrd = setpoint_temp;
					}
				}
			}

			//take the squared root
			if (setpoint_sqrd.norm() > 0.001f) {
				setpoint = setpoint_sqrd / std::sqrt(setpoint_sqrd.norm());

			} else {
				setpoint.zero();
			}
		}

	} else if (_last_message + MESSAGE_THROTTLE_US < hrt_absolute_time()) {
		mavlink_log_critical(&_mavlink_log_pub, "No range data received");
		_last_message = hrt_absolute_time();
	}
}

void CollisionPrevention::modifySetpoint(Vector2f &original_setpoint, const float max_speed,
		const float max_acc)
{
	//calculate movement constraints based on range data
	Vector2f new_setpoint = original_setpoint;
	calculate_constrained_setpoint(new_setpoint, max_acc);

	//warn user if collision prevention starts to interfere
	bool currently_interfering = (new_setpoint(0) < original_setpoint(0) - 0.05f * max_speed
				      || new_setpoint(0) > original_setpoint(0) + 0.05f * max_speed
				      || new_setpoint(1) < original_setpoint(1) - 0.05f * max_speed
				      || new_setpoint(1) > original_setpoint(1) + 0.05f * max_speed);

	if (currently_interfering && (currently_interfering != _interfering)) {
		mavlink_log_critical(&_mavlink_log_pub, "Collision Warning");
	}

	_interfering = currently_interfering;
	original_setpoint = new_setpoint;
}
<|endoftext|>


<commit_before>/*
* SEGS dbtool v0.2 dated 2017-11-04
* A database creation and management tool.
*/
#include <iostream>
#include <QtCore/QFileInfo>
#include <QtCore/QFile>
#include <QtCore/QDir>
#include <QtCore/QDebug>
#include <QtCore/QCoreApplication>
#include <QtCore/QCommandLineParser>
#include <QtSql/QtSql>
#include <QtSql/QSqlDatabase>
#include <QtSql/QSqlError>
#include <QtSql/QSqlQuery>

QString segs = "segs";
QString segs_game = "segs_game";

QTextStream& qout()
{
    static QTextStream ts( stdout );
    return ts;
}

bool fileExists(QString path)
{
    QFileInfo check_file("./" + path);
    return check_file.exists() && check_file.isFile();
}

void Pause(void)
{
    qInfo() << endl << "Press ENTER to continue...";
    std::cin.ignore(100000, '\n');  // Ignore characters until an ENTER (newline) is received.
    return;
}

void errorHandler(QtMsgType type, const char *msg)
{
    switch (type) {
        case QtDebugMsg:
            fprintf(stderr, "%s\n", msg);
            break;
        case QtWarningMsg:
            fprintf(stderr, "\033[1;33mWarning\033[0m: %s\n", msg);
            break;
        case QtCriticalMsg:
            fprintf(stderr, "\033[31mCritical\033[0m: %s\n", msg);
            break;
        case QtFatalMsg:
            fprintf(stderr, "\033[31mFatal\033[0m: %s\n", msg);
            abort();
    }
}

int main(int argc, char **argv)
{
    qInstallMsgHandler(errorHandler);
    QCoreApplication app(argc,argv);
    QCoreApplication::setApplicationName("segs-dbtool");
    QCoreApplication::setApplicationVersion("0.2");

    QCommandLineParser parser;
    parser.setApplicationDescription("SEGS database management utility");
    parser.addHelpOption();
    parser.addVersionOption();

    qDebug() << parser.applicationDescription() << " v" << QCoreApplication::applicationVersion() << endl;

    parser.addPositionalArgument("file", QCoreApplication::translate("main", "Database Script file to import."));

    // A boolean option with multiple names (-f, --force)
    QCommandLineOption forceOption(QStringList() << "f" << "force",
        QCoreApplication::translate("main", "Overwrite existing database files. THIS CANNOT BE UNDONE."));
    parser.addOption(forceOption);

    parser.process(app);

    const QStringList args = parser.positionalArguments();

    bool forced = parser.isSet(forceOption);
    bool nofile = args.isEmpty();

    // Check if dbtool is being run from server directory
    qInfo() << "Checking current directory for authserver...";
    if(!fileExists("./authserver")) {
        qDebug() << "SEGS dbtool must be run from the SEGS root folder (where authserver resides)";
        Pause();
        return 0;
    }
    qInfo() << "OK";

    // Check if database already exists
    qInfo() << "Checking for existing databases...";
    if((fileExists(segs) || fileExists(segs_game)) && !forced) {
        if(fileExists(segs))
            qWarning() << "WARNING! Database " << segs << " already exists.";
        if(fileExists(segs_game))
            qWarning() << "WARNING! Database " << segs_game << " already exists.";
        qDebug() << "Run dbtool with -f option to overwrite existing databases. THIS CANNOT BE UNDONE.";
        Pause();
        return 0;
    }

    qInfo() << "Creating database files...";
    QStringList db_files;
    if(nofile)
        db_files << "./default_dbs/segs" << "./default_dbs/segs_game";
    else
        db_files << args;

    // Let's itterate over db_files and create database files
    for (int i = 0; i < db_files.size(); ++i)
    {
        QFile db_template(db_file.at(i));
        int last_slash = db_template.at(i).lastIndexOf('/',-1);
        QFile db_path("./" + db_template.at(i).midRef(last_slash+1,-1)); // filename only: ./segs

        // Otherwise, import contents of db_template into db_path
        QSqlDatabase db = QSqlDatabase::addDatabase( "QSQLITE" );
        db.setDatabaseName( db_path );

        if( !db.open() )
        {
            qDebug() << db.lastError();
            qFatal() << "Failed to connect to database. Please check error messages for details.";
            Pause();
            return 0;
        }
        qDebug() << "Created new database!";

        QSqlQuery qry;
        if(db_template.open(QFile::ReadOnly))
            qry.exec(db_template.readAll());

        // Close our db
        db.close();
        qInfo() << "COMPLETED importing " << db_template << "!";
    }

    Pause();
    return 0;
}
<commit_msg>Removed qout function. Clarified some output<commit_after>/*
* SEGS dbtool v0.2 dated 2017-11-04
* A database creation and management tool.
*/
#include <iostream>
#include <QtCore/QFileInfo>
#include <QtCore/QFile>
#include <QtCore/QDir>
#include <QtCore/QDebug>
#include <QtCore/QCoreApplication>
#include <QtCore/QCommandLineParser>
#include <QtSql/QtSql>
#include <QtSql/QSqlDatabase>
#include <QtSql/QSqlError>
#include <QtSql/QSqlQuery>

QString segs = "segs";
QString segs_game = "segs_game";

bool fileExists(QString path)
{
    QFileInfo check_file("./" + path);
    return check_file.exists() && check_file.isFile();
}

void Pause(void)
{
    qInfo() << endl << "Press ENTER to continue...";
    std::cin.ignore(100000, '\n');  // Ignore characters until an ENTER (newline) is received.
    return;
}

void errorHandler(QtMsgType type, const char *msg)
{
    switch (type) {
        case QtDebugMsg:
            fprintf(stderr, "%s\n", msg);
            break;
        case QtWarningMsg:
            fprintf(stderr, "\033[1;33mWarning\033[0m: %s\n", msg);
            break;
        case QtCriticalMsg:
            fprintf(stderr, "\033[31mCritical\033[0m: %s\n", msg);
            break;
        case QtFatalMsg:
            fprintf(stderr, "\033[31mFatal\033[0m: %s\n", msg);
            abort();
    }
}

int main(int argc, char **argv)
{
    qInstallMsgHandler(errorHandler);
    QCoreApplication app(argc,argv);
    QCoreApplication::setApplicationName("segs-dbtool");
    QCoreApplication::setApplicationVersion("0.2");

    QCommandLineParser parser;
    parser.setApplicationDescription("SEGS database management utility");
    parser.addHelpOption();
    parser.addVersionOption();

    qDebug() << parser.applicationDescription() << " v" << QCoreApplication::applicationVersion() << endl;

    parser.addPositionalArgument("file", QCoreApplication::translate("main", "Database Script file to import."));

    // A boolean option with multiple names (-f, --force)
    QCommandLineOption forceOption(QStringList() << "f" << "force",
        QCoreApplication::translate("main", "Overwrite existing database files. THIS CANNOT BE UNDONE."));
    parser.addOption(forceOption);

    parser.process(app);

    const QStringList args = parser.positionalArguments();

    bool forced = parser.isSet(forceOption);
    bool nofile = args.isEmpty();

    // Check if dbtool is being run from server directory
    qInfo() << "Checking current directory for authserver...";
    if(!fileExists("./authserver")) {
        qDebug() << "SEGS dbtool must be run from the SEGS root folder (where authserver resides)";
        Pause();
        return 0;
    }
    qDebug() << "Authserver Found!";

    // Check if database already exists
    qInfo() << "Checking for existing databases...";
    if((fileExists(segs) || fileExists(segs_game)) && !forced) {
        if(fileExists(segs))
            qWarning() << "WARNING! Database " << segs << " already exists.";
        if(fileExists(segs_game))
            qWarning() << "WARNING! Database " << segs_game << " already exists.";
        qDebug() << "Run dbtool with -f option to overwrite existing databases. THIS CANNOT BE UNDONE.";
        Pause();
        return 0;
    }

    qInfo() << "Creating database files...";
    QStringList db_files;
    if(nofile)
        db_files << "./default_dbs/segs" << "./default_dbs/segs_game";
    else
        db_files << args;

    // Let's itterate over db_files and create database files
    for (int i = 0; i < db_files.size(); ++i)
    {
        QFile db_template(db_file.at(i));
        int last_slash = db_template.at(i).lastIndexOf('/',-1);
        QFile db_path("./" + db_template.at(i).midRef(last_slash+1,-1)); // filename only: ./segs

        // Otherwise, import contents of db_template into db_path
        QSqlDatabase db = QSqlDatabase::addDatabase( "QSQLITE" );
        db.setDatabaseName( db_path );

        if( !db.open() )
        {
            qDebug() << db.lastError();
            qFatal() << "Failed to connect to database. Please check error messages for details.";
            Pause();
            return 0;
        }
        qDebug() << "Created new database!";

        QSqlQuery qry;
        if(db_template.open(QFile::ReadOnly))
            qry.exec(db_template.readAll());

        // Close our db
        db.close();
        qInfo() << "COMPLETED importing " << db_template << "!";
    }

    Pause();
    return 0;
}
<|endoftext|>


<commit_before>/* medViewContainerCustom.cpp ---
 *
 * Author: Julien Wintz
 * Copyright (C) 2008 - Julien Wintz, Inria.
 * Created: Wed Mar 17 11:01:46 2010 (+0100)
 * Version: $Id$
 * Last-Updated: Mon Dec 20 11:26:53 2010 (+0100)
 *           By: Julien Wintz
 *     Update #: 69
 */

/* Commentary:
 *
 */

/* Change log:
 *
 */

#include "medViewContainer_p.h"
#include "medViewContainerCustom.h"
#include "medViewPool.h"

#include <dtkCore/dtkAbstractData.h>
#include <dtkCore/dtkAbstractView.h>
#include <dtkCore/dtkAbstractViewFactory.h>

#include <medCore/medAbstractView.h>
#include <medCore/medViewManager.h>

class medViewContainerCustomPrivate
{
public:
    QList<medViewContainerCustom*> children;
    int rowMax;
    int columnMax;
    int preset;
};

medViewContainerCustom::medViewContainerCustom (QWidget *parent) : medViewContainer(parent), d2 (new medViewContainerCustomPrivate)
{
    d2->rowMax    = 5;
    d2->columnMax = 5;
    d2->preset = medViewContainerCustom::A;
}

medViewContainerCustom::~medViewContainerCustom()
{
    delete d2;
    d2 = NULL;
}

void medViewContainerCustom::split(int rows, int cols)
{
    if (d->view)
        return;

    this->clear();

    for(int i = 0 ; i < rows ; i++) {
        d->layout->setRowStretch(i, 0);
        for(int j = 0 ; j < cols ; j++) {
            medViewContainerCustom *container = new medViewContainerCustom(this);
	    connect (container, SIGNAL(viewAdded(dtkAbstractView*)),   this, SIGNAL (viewAdded(dtkAbstractView*)));
	    connect (container, SIGNAL(viewRemoved(dtkAbstractView*)), this, SIGNAL (viewRemoved(dtkAbstractView*)));
            d2->children.append (container);
            d->layout->addWidget(container, i, j);
            d->layout->setColumnStretch(j, 0);
        }
    }

    // in split, the preset is no valid anymore
    d2->preset = 0;

    this->setCurrent(NULL);
}

void medViewContainerCustom::setPreset(int preset)
{
    if (d2->preset == preset)
        return;

    d2->preset = preset;

    this->clear();

    medViewContainerCustom *custom1;
    medViewContainerCustom *custom2;
    medViewContainerCustom *custom3;
    medViewContainerCustom *custom4;

    switch(preset) {
    case B:
        custom1 = new medViewContainerCustom(this);
	custom2 = new medViewContainerCustom(this);
	connect (custom1, SIGNAL(viewAdded(dtkAbstractView*)), this, SIGNAL (viewAdded(dtkAbstractView*)));
	connect (custom2, SIGNAL(viewAdded(dtkAbstractView*)), this, SIGNAL (viewAdded(dtkAbstractView*)));
	connect (custom1, SIGNAL(viewRemoved(dtkAbstractView*)), this, SIGNAL (viewRemoved(dtkAbstractView*)));
	connect (custom2, SIGNAL(viewRemoved(dtkAbstractView*)), this, SIGNAL (viewRemoved(dtkAbstractView*)));
	d2->children.append (custom1);
	d2->children.append (custom2);
        d->layout->addWidget(custom1, 0, 0);
        d->layout->addWidget(custom2, 1, 0);
	d->layout->setRowStretch(0, 0);
	d->layout->setRowStretch(1, 0);
        break;
    case C:
        custom1 = new medViewContainerCustom(this);
        custom1->split(2, 1);
        custom2 = new medViewContainerCustom(this);
	connect (custom1, SIGNAL(viewAdded(dtkAbstractView*)), this, SIGNAL (viewAdded(dtkAbstractView*)));
	connect (custom2, SIGNAL(viewAdded(dtkAbstractView*)), this, SIGNAL (viewAdded(dtkAbstractView*)));
	connect (custom1, SIGNAL(viewRemoved(dtkAbstractView*)), this, SIGNAL (viewRemoved(dtkAbstractView*)));
	connect (custom2, SIGNAL(viewRemoved(dtkAbstractView*)), this, SIGNAL (viewRemoved(dtkAbstractView*)));
	d2->children.append (custom1);
	d2->children.append (custom2);
        d->layout->addWidget(custom1, 0, 0);
        d->layout->addWidget(custom2, 0, 1);
        d->layout->setColumnStretch(0, 1);
        d->layout->setColumnStretch(1, 2);
        break;
    case D:
        custom1 = new medViewContainerCustom(this);
        custom1->split(3, 1);
        custom2 = new medViewContainerCustom(this);
	connect (custom1, SIGNAL(viewAdded(dtkAbstractView*)), this, SIGNAL (viewAdded(dtkAbstractView*)));
	connect (custom2, SIGNAL(viewAdded(dtkAbstractView*)), this, SIGNAL (viewAdded(dtkAbstractView*)));
	connect (custom1, SIGNAL(viewRemoved(dtkAbstractView*)), this, SIGNAL (viewRemoved(dtkAbstractView*)));
	connect (custom2, SIGNAL(viewRemoved(dtkAbstractView*)), this, SIGNAL (viewRemoved(dtkAbstractView*)));
	d2->children.append (custom1);
	d2->children.append (custom2);
        d->layout->addWidget(custom1, 0, 0);
        d->layout->addWidget(custom2, 0, 1);
        d->layout->setColumnStretch(0, 1);
        d->layout->setColumnStretch(1, 2);
        break;
    case E:
        custom1 = new medViewContainerCustom(this);
	custom2 = new medViewContainerCustom(this);
	custom3 = new medViewContainerCustom(this);
	custom4 = new medViewContainerCustom(this);

	connect (custom1, SIGNAL(viewAdded(dtkAbstractView*)), this, SIGNAL (viewAdded(dtkAbstractView*)));
	connect (custom2, SIGNAL(viewAdded(dtkAbstractView*)), this, SIGNAL (viewAdded(dtkAbstractView*)));
	connect (custom3, SIGNAL(viewAdded(dtkAbstractView*)), this, SIGNAL (viewAdded(dtkAbstractView*)));
	connect (custom4, SIGNAL(viewAdded(dtkAbstractView*)), this, SIGNAL (viewAdded(dtkAbstractView*)));
	connect (custom1, SIGNAL(viewRemoved(dtkAbstractView*)), this, SIGNAL (viewRemoved(dtkAbstractView*)));
	connect (custom2, SIGNAL(viewRemoved(dtkAbstractView*)), this, SIGNAL (viewRemoved(dtkAbstractView*)));
	connect (custom3, SIGNAL(viewRemoved(dtkAbstractView*)), this, SIGNAL (viewRemoved(dtkAbstractView*)));
	connect (custom4, SIGNAL(viewRemoved(dtkAbstractView*)), this, SIGNAL (viewRemoved(dtkAbstractView*)));

	custom1->setViewProperty ("Orientation", "Axial");
	custom2->setViewProperty ("Orientation", "Sagittal");
	custom3->setViewProperty ("Orientation", "Coronal");
	custom4->setViewProperty ("Orientation", "3D");

	d2->children.append (custom1);
	d2->children.append (custom2);
	d2->children.append (custom3);
	d2->children.append (custom4);

	d->layout->addWidget(custom1, 0, 0);
	d->layout->addWidget(custom2, 0, 1);
	d->layout->addWidget(custom3, 1, 0);
	d->layout->addWidget(custom4, 1, 1);
	d->layout->setColumnStretch(0, 0);
	d->layout->setColumnStretch(1, 0);
	d->layout->setRowStretch(0, 0);
	d->layout->setRowStretch(1, 0);
        break;

    case A:
	default:
        custom1 = new medViewContainerCustom(this);
        custom2 = new medViewContainerCustom(this);
	connect (custom1, SIGNAL(viewAdded(dtkAbstractView*)), this, SIGNAL (viewAdded(dtkAbstractView*)));
	connect (custom2, SIGNAL(viewAdded(dtkAbstractView*)), this, SIGNAL (viewAdded(dtkAbstractView*)));
	connect (custom1, SIGNAL(viewRemoved(dtkAbstractView*)), this, SIGNAL (viewRemoved(dtkAbstractView*)));
	connect (custom2, SIGNAL(viewRemoved(dtkAbstractView*)), this, SIGNAL (viewRemoved(dtkAbstractView*)));
	d2->children.append (custom1);
	d2->children.append (custom2);
        d->layout->addWidget(custom1, 0, 0);
        d->layout->addWidget(custom2, 0, 1);
	d->layout->setColumnStretch(0, 0);
	d->layout->setColumnStretch(1, 0);
        break;

    };

    this->setCurrent(NULL);
}

void medViewContainerCustom::setView(dtkAbstractView *view)
{
    if (d2->children.count()==0) {
      if (view!=d->view) {
	if (d->layout->count())
	  d->layout->removeItem(d->layout->itemAt(0));

	if (d->view)
	  this->onViewClosing();

	/*
	  dtkAbstractView *cloneView = dtkAbstractViewFactory::instance()->create (view->description());
	  cloneView->setData ( static_cast<dtkAbstractData*>(view->data()) );
	  cloneView->reset();
	*/

	medViewContainer::setView (view);

	d->layout->setContentsMargins(1, 1, 1, 1);
	d->layout->addWidget(view->widget(), 0, 0);

	d->view = view;
	// d->view->reset();

	this->synchronize_2 (view);

	connect (view, SIGNAL (closing()),        this, SLOT (onViewClosing()));
	connect (view, SIGNAL (fullScreen(bool)), this, SLOT (onViewFullScreen(bool)));

	emit viewAdded (view);
      }
    }
    /*
    else {
      foreach (medViewContainerCustom *container, d2->children)
	container->setView (view);
    }
    */
}

dtkAbstractView *medViewContainerCustom::view (void) const
{
    return d->view;
}

QList<dtkAbstractView *> medViewContainerCustom::views (void) const
{
    QList<dtkAbstractView *> views;
    if (d2->children.count()==0) {
        if (d->view)
	  views << d->view;
    }
    else {
      foreach (medViewContainerCustom *container, d2->children)
	  views << container->views();
    }
    return views;
}

void medViewContainerCustom::synchronize_2 (dtkAbstractView *view)
{
    if (medViewContainerCustom *parent = dynamic_cast<medViewContainerCustom*>(this->parent())) {
        parent->synchronize_2(view);
    }
    else { // top level medViewContainerCustom
        if (medAbstractView *medView = dynamic_cast<medAbstractView*> (view) )
            d->pool->appendView (medView);
	connect (view, SIGNAL (becomeDaddy(bool)), this, SLOT (repaint()));
    }
}

void medViewContainerCustom::desynchronize_2 (dtkAbstractView *view)
{
    if (medViewContainerCustom *parent = dynamic_cast<medViewContainerCustom*>(this->parent())) {
        parent->desynchronize_2(view);
    }
    else { // top level medViewContainerCustom
        if (medAbstractView *medView = dynamic_cast<medAbstractView*> (view) )
            d->pool->removeView (medView);
	disconnect (view, SIGNAL (becomeDaddy(bool)), this, SLOT (repaint()));
    }
}

void medViewContainerCustom::onViewClosing (void)
{
    if (d->view) {
        this->onViewFullScreen2 (false, d->view); // in case view is full screen
        d->layout->removeWidget (d->view->widget());
        this->desynchronize_2 (d->view);
        disconnect (d->view, SIGNAL (closing()), this, SLOT (onViewClosing()));
	disconnect (d->view, SIGNAL (fullScreen(bool)), this, SLOT (onViewFullScreen(bool)));

	emit viewRemoved (d->view);

        d->view->close();

        d->view = NULL;
    }
}

void medViewContainerCustom::onViewFullScreen (bool value)
{
    if (medViewContainerCustom *parent = dynamic_cast<medViewContainerCustom*>(this->parent())) {
        parent->onViewFullScreen2 (value, dynamic_cast<dtkAbstractView *>(this->sender()) );
    }
    else { // top level medViewContainerCustom
        this->fullScreen (value, dynamic_cast<dtkAbstractView *>(this->sender()));
    }
}

void medViewContainerCustom::onViewFullScreen2 (bool value, dtkAbstractView *view)
{
    if (medViewContainerCustom *parent = dynamic_cast<medViewContainerCustom*>(this->parent())) {
        parent->onViewFullScreen2 (value, view );
    }
    else { // top level medViewContainerCustom
        this->fullScreen (value, view);
    }
}

void medViewContainerCustom::fullScreen (bool value, dtkAbstractView *view)
{
  if (d2->children.count()==0) { // no children = end widget
      if (!d->view ||(d->view && d->view!=view)) {
	  if (value)
	    this->hide();
	  else
	    this->show();
      }
  }
  else {
      foreach (medViewContainerCustom *custom, d2->children)
	  custom->fullScreen (value, view);
  }
}

void medViewContainerCustom::dragEnterEvent(QDragEnterEvent *event)
{
    this->setAttribute(Qt::WA_UpdatesDisabled, true);

    medViewContainer::dragEnterEvent(event);
}

void medViewContainerCustom::dragMoveEvent(QDragMoveEvent *event)
{
    medViewContainer::dragMoveEvent(event);
}

void medViewContainerCustom::dragLeaveEvent(QDragLeaveEvent *event)
{
    this->setAttribute(Qt::WA_UpdatesDisabled, false);

    medViewContainer::dragLeaveEvent(event);
}

void medViewContainerCustom::dropEvent(QDropEvent *event)
{
    this->setCurrent(this);

    this->setAttribute(Qt::WA_UpdatesDisabled, false);

    medViewContainer::dropEvent(event);
}

void medViewContainerCustom::focusInEvent(QFocusEvent *event)
{
    medViewContainer::focusInEvent(event);
}

void medViewContainerCustom::focusOutEvent(QFocusEvent *event)
{
    medViewContainer::focusOutEvent(event);
}

void medViewContainerCustom::clear (void)
{
    if (d->view)
        this->onViewClosing();

    foreach (medViewContainerCustom *custom, d2->children) {
        custom->clear();
	d->layout->removeWidget (custom);
	custom->deleteLater(); // safer than delete custom
    }
    d2->children.clear();

    for(int i=0; i<d2->rowMax; i++)
        d->layout->setRowStretch (i, 0);

    for(int i=0; i<d2->columnMax; i++)
        d->layout->setColumnStretch (i, 0);
}

QList<medViewContainerCustom*> medViewContainerCustom::children() const
{
    return d2->children;
}
<commit_msg>initially set preset to invalid index in medViewContainerCustom<commit_after>/* medViewContainerCustom.cpp ---
 *
 * Author: Julien Wintz
 * Copyright (C) 2008 - Julien Wintz, Inria.
 * Created: Wed Mar 17 11:01:46 2010 (+0100)
 * Version: $Id$
 * Last-Updated: Mon Dec 20 11:26:53 2010 (+0100)
 *           By: Julien Wintz
 *     Update #: 69
 */

/* Commentary:
 *
 */

/* Change log:
 *
 */

#include "medViewContainer_p.h"
#include "medViewContainerCustom.h"
#include "medViewPool.h"

#include <dtkCore/dtkAbstractData.h>
#include <dtkCore/dtkAbstractView.h>
#include <dtkCore/dtkAbstractViewFactory.h>

#include <medCore/medAbstractView.h>
#include <medCore/medViewManager.h>

class medViewContainerCustomPrivate
{
public:
    QList<medViewContainerCustom*> children;
    int rowMax;
    int columnMax;
    int preset;
};

medViewContainerCustom::medViewContainerCustom (QWidget *parent) : medViewContainer(parent), d2 (new medViewContainerCustomPrivate)
{
    d2->rowMax    = 5;
    d2->columnMax = 5;
    d2->preset = 0;
}

medViewContainerCustom::~medViewContainerCustom()
{
    delete d2;
    d2 = NULL;
}

void medViewContainerCustom::split(int rows, int cols)
{
    if (d->view)
        return;

    this->clear();

    for(int i = 0 ; i < rows ; i++) {
        d->layout->setRowStretch(i, 0);
        for(int j = 0 ; j < cols ; j++) {
            medViewContainerCustom *container = new medViewContainerCustom(this);
	    connect (container, SIGNAL(viewAdded(dtkAbstractView*)),   this, SIGNAL (viewAdded(dtkAbstractView*)));
	    connect (container, SIGNAL(viewRemoved(dtkAbstractView*)), this, SIGNAL (viewRemoved(dtkAbstractView*)));
            d2->children.append (container);
            d->layout->addWidget(container, i, j);
            d->layout->setColumnStretch(j, 0);
        }
    }

    // in split, the preset is no valid anymore
    d2->preset = 0;

    this->setCurrent(NULL);
}

void medViewContainerCustom::setPreset(int preset)
{
    if (d2->preset == preset)
        return;

    d2->preset = preset;

    this->clear();

    medViewContainerCustom *custom1;
    medViewContainerCustom *custom2;
    medViewContainerCustom *custom3;
    medViewContainerCustom *custom4;

    switch(preset) {
    case B:
        custom1 = new medViewContainerCustom(this);
	custom2 = new medViewContainerCustom(this);
	connect (custom1, SIGNAL(viewAdded(dtkAbstractView*)), this, SIGNAL (viewAdded(dtkAbstractView*)));
	connect (custom2, SIGNAL(viewAdded(dtkAbstractView*)), this, SIGNAL (viewAdded(dtkAbstractView*)));
	connect (custom1, SIGNAL(viewRemoved(dtkAbstractView*)), this, SIGNAL (viewRemoved(dtkAbstractView*)));
	connect (custom2, SIGNAL(viewRemoved(dtkAbstractView*)), this, SIGNAL (viewRemoved(dtkAbstractView*)));
	d2->children.append (custom1);
	d2->children.append (custom2);
        d->layout->addWidget(custom1, 0, 0);
        d->layout->addWidget(custom2, 1, 0);
	d->layout->setRowStretch(0, 0);
	d->layout->setRowStretch(1, 0);
        break;
    case C:
        custom1 = new medViewContainerCustom(this);
        custom1->split(2, 1);
        custom2 = new medViewContainerCustom(this);
	connect (custom1, SIGNAL(viewAdded(dtkAbstractView*)), this, SIGNAL (viewAdded(dtkAbstractView*)));
	connect (custom2, SIGNAL(viewAdded(dtkAbstractView*)), this, SIGNAL (viewAdded(dtkAbstractView*)));
	connect (custom1, SIGNAL(viewRemoved(dtkAbstractView*)), this, SIGNAL (viewRemoved(dtkAbstractView*)));
	connect (custom2, SIGNAL(viewRemoved(dtkAbstractView*)), this, SIGNAL (viewRemoved(dtkAbstractView*)));
	d2->children.append (custom1);
	d2->children.append (custom2);
        d->layout->addWidget(custom1, 0, 0);
        d->layout->addWidget(custom2, 0, 1);
        d->layout->setColumnStretch(0, 1);
        d->layout->setColumnStretch(1, 2);
        break;
    case D:
        custom1 = new medViewContainerCustom(this);
        custom1->split(3, 1);
        custom2 = new medViewContainerCustom(this);
	connect (custom1, SIGNAL(viewAdded(dtkAbstractView*)), this, SIGNAL (viewAdded(dtkAbstractView*)));
	connect (custom2, SIGNAL(viewAdded(dtkAbstractView*)), this, SIGNAL (viewAdded(dtkAbstractView*)));
	connect (custom1, SIGNAL(viewRemoved(dtkAbstractView*)), this, SIGNAL (viewRemoved(dtkAbstractView*)));
	connect (custom2, SIGNAL(viewRemoved(dtkAbstractView*)), this, SIGNAL (viewRemoved(dtkAbstractView*)));
	d2->children.append (custom1);
	d2->children.append (custom2);
        d->layout->addWidget(custom1, 0, 0);
        d->layout->addWidget(custom2, 0, 1);
        d->layout->setColumnStretch(0, 1);
        d->layout->setColumnStretch(1, 2);
        break;
    case E:
        custom1 = new medViewContainerCustom(this);
	custom2 = new medViewContainerCustom(this);
	custom3 = new medViewContainerCustom(this);
	custom4 = new medViewContainerCustom(this);

	connect (custom1, SIGNAL(viewAdded(dtkAbstractView*)), this, SIGNAL (viewAdded(dtkAbstractView*)));
	connect (custom2, SIGNAL(viewAdded(dtkAbstractView*)), this, SIGNAL (viewAdded(dtkAbstractView*)));
	connect (custom3, SIGNAL(viewAdded(dtkAbstractView*)), this, SIGNAL (viewAdded(dtkAbstractView*)));
	connect (custom4, SIGNAL(viewAdded(dtkAbstractView*)), this, SIGNAL (viewAdded(dtkAbstractView*)));
	connect (custom1, SIGNAL(viewRemoved(dtkAbstractView*)), this, SIGNAL (viewRemoved(dtkAbstractView*)));
	connect (custom2, SIGNAL(viewRemoved(dtkAbstractView*)), this, SIGNAL (viewRemoved(dtkAbstractView*)));
	connect (custom3, SIGNAL(viewRemoved(dtkAbstractView*)), this, SIGNAL (viewRemoved(dtkAbstractView*)));
	connect (custom4, SIGNAL(viewRemoved(dtkAbstractView*)), this, SIGNAL (viewRemoved(dtkAbstractView*)));

	custom1->setViewProperty ("Orientation", "Axial");
	custom2->setViewProperty ("Orientation", "Sagittal");
	custom3->setViewProperty ("Orientation", "Coronal");
	custom4->setViewProperty ("Orientation", "3D");

	d2->children.append (custom1);
	d2->children.append (custom2);
	d2->children.append (custom3);
	d2->children.append (custom4);

	d->layout->addWidget(custom1, 0, 0);
	d->layout->addWidget(custom2, 0, 1);
	d->layout->addWidget(custom3, 1, 0);
	d->layout->addWidget(custom4, 1, 1);
	d->layout->setColumnStretch(0, 0);
	d->layout->setColumnStretch(1, 0);
	d->layout->setRowStretch(0, 0);
	d->layout->setRowStretch(1, 0);
        break;

    case A:
	default:
        custom1 = new medViewContainerCustom(this);
        custom2 = new medViewContainerCustom(this);
	connect (custom1, SIGNAL(viewAdded(dtkAbstractView*)), this, SIGNAL (viewAdded(dtkAbstractView*)));
	connect (custom2, SIGNAL(viewAdded(dtkAbstractView*)), this, SIGNAL (viewAdded(dtkAbstractView*)));
	connect (custom1, SIGNAL(viewRemoved(dtkAbstractView*)), this, SIGNAL (viewRemoved(dtkAbstractView*)));
	connect (custom2, SIGNAL(viewRemoved(dtkAbstractView*)), this, SIGNAL (viewRemoved(dtkAbstractView*)));
	d2->children.append (custom1);
	d2->children.append (custom2);
        d->layout->addWidget(custom1, 0, 0);
        d->layout->addWidget(custom2, 0, 1);
	d->layout->setColumnStretch(0, 0);
	d->layout->setColumnStretch(1, 0);
        break;

    };

    this->setCurrent(NULL);
}

void medViewContainerCustom::setView(dtkAbstractView *view)
{
    if (d2->children.count()==0) {
      if (view!=d->view) {
	if (d->layout->count())
	  d->layout->removeItem(d->layout->itemAt(0));

	if (d->view)
	  this->onViewClosing();

	/*
	  dtkAbstractView *cloneView = dtkAbstractViewFactory::instance()->create (view->description());
	  cloneView->setData ( static_cast<dtkAbstractData*>(view->data()) );
	  cloneView->reset();
	*/

	medViewContainer::setView (view);

	d->layout->setContentsMargins(1, 1, 1, 1);
	d->layout->addWidget(view->widget(), 0, 0);

	d->view = view;
	// d->view->reset();

	this->synchronize_2 (view);

	connect (view, SIGNAL (closing()),        this, SLOT (onViewClosing()));
	connect (view, SIGNAL (fullScreen(bool)), this, SLOT (onViewFullScreen(bool)));

	emit viewAdded (view);
      }
    }
    /*
    else {
      foreach (medViewContainerCustom *container, d2->children)
	container->setView (view);
    }
    */
}

dtkAbstractView *medViewContainerCustom::view (void) const
{
    return d->view;
}

QList<dtkAbstractView *> medViewContainerCustom::views (void) const
{
    QList<dtkAbstractView *> views;
    if (d2->children.count()==0) {
        if (d->view)
	  views << d->view;
    }
    else {
      foreach (medViewContainerCustom *container, d2->children)
	  views << container->views();
    }
    return views;
}

void medViewContainerCustom::synchronize_2 (dtkAbstractView *view)
{
    if (medViewContainerCustom *parent = dynamic_cast<medViewContainerCustom*>(this->parent())) {
        parent->synchronize_2(view);
    }
    else { // top level medViewContainerCustom
        if (medAbstractView *medView = dynamic_cast<medAbstractView*> (view) )
            d->pool->appendView (medView);
	connect (view, SIGNAL (becomeDaddy(bool)), this, SLOT (repaint()));
    }
}

void medViewContainerCustom::desynchronize_2 (dtkAbstractView *view)
{
    if (medViewContainerCustom *parent = dynamic_cast<medViewContainerCustom*>(this->parent())) {
        parent->desynchronize_2(view);
    }
    else { // top level medViewContainerCustom
        if (medAbstractView *medView = dynamic_cast<medAbstractView*> (view) )
            d->pool->removeView (medView);
	disconnect (view, SIGNAL (becomeDaddy(bool)), this, SLOT (repaint()));
    }
}

void medViewContainerCustom::onViewClosing (void)
{
    if (d->view) {
        this->onViewFullScreen2 (false, d->view); // in case view is full screen
        d->layout->removeWidget (d->view->widget());
        this->desynchronize_2 (d->view);
        disconnect (d->view, SIGNAL (closing()), this, SLOT (onViewClosing()));
	disconnect (d->view, SIGNAL (fullScreen(bool)), this, SLOT (onViewFullScreen(bool)));

	emit viewRemoved (d->view);

        d->view->close();

        d->view = NULL;
    }
}

void medViewContainerCustom::onViewFullScreen (bool value)
{
    if (medViewContainerCustom *parent = dynamic_cast<medViewContainerCustom*>(this->parent())) {
        parent->onViewFullScreen2 (value, dynamic_cast<dtkAbstractView *>(this->sender()) );
    }
    else { // top level medViewContainerCustom
        this->fullScreen (value, dynamic_cast<dtkAbstractView *>(this->sender()));
    }
}

void medViewContainerCustom::onViewFullScreen2 (bool value, dtkAbstractView *view)
{
    if (medViewContainerCustom *parent = dynamic_cast<medViewContainerCustom*>(this->parent())) {
        parent->onViewFullScreen2 (value, view );
    }
    else { // top level medViewContainerCustom
        this->fullScreen (value, view);
    }
}

void medViewContainerCustom::fullScreen (bool value, dtkAbstractView *view)
{
  if (d2->children.count()==0) { // no children = end widget
      if (!d->view ||(d->view && d->view!=view)) {
	  if (value)
	    this->hide();
	  else
	    this->show();
      }
  }
  else {
      foreach (medViewContainerCustom *custom, d2->children)
	  custom->fullScreen (value, view);
  }
}

void medViewContainerCustom::dragEnterEvent(QDragEnterEvent *event)
{
    this->setAttribute(Qt::WA_UpdatesDisabled, true);

    medViewContainer::dragEnterEvent(event);
}

void medViewContainerCustom::dragMoveEvent(QDragMoveEvent *event)
{
    medViewContainer::dragMoveEvent(event);
}

void medViewContainerCustom::dragLeaveEvent(QDragLeaveEvent *event)
{
    this->setAttribute(Qt::WA_UpdatesDisabled, false);

    medViewContainer::dragLeaveEvent(event);
}

void medViewContainerCustom::dropEvent(QDropEvent *event)
{
    this->setCurrent(this);

    this->setAttribute(Qt::WA_UpdatesDisabled, false);

    medViewContainer::dropEvent(event);
}

void medViewContainerCustom::focusInEvent(QFocusEvent *event)
{
    medViewContainer::focusInEvent(event);
}

void medViewContainerCustom::focusOutEvent(QFocusEvent *event)
{
    medViewContainer::focusOutEvent(event);
}

void medViewContainerCustom::clear (void)
{
    if (d->view)
        this->onViewClosing();

    foreach (medViewContainerCustom *custom, d2->children) {
        custom->clear();
	d->layout->removeWidget (custom);
	custom->deleteLater(); // safer than delete custom
    }
    d2->children.clear();

    for(int i=0; i<d2->rowMax; i++)
        d->layout->setRowStretch (i, 0);

    for(int i=0; i<d2->columnMax; i++)
        d->layout->setColumnStretch (i, 0);
}

QList<medViewContainerCustom*> medViewContainerCustom::children() const
{
    return d2->children;
}
<|endoftext|>


<commit_before>// Copyright (c) 2012 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/browser_about_handler.h"

#include <string>

#include "base/logging.h"
#include "base/strings/string_util.h"
#include "chrome/browser/lifetime/application_lifetime.h"
#include "chrome/browser/ui/browser_dialogs.h"
#include "chrome/common/net/url_fixer_upper.h"
#include "chrome/common/url_constants.h"

bool WillHandleBrowserAboutURL(GURL* url,
                               content::BrowserContext* browser_context) {
  // TODO(msw): Eliminate "about:*" constants and literals from code and tests,
  //            then hopefully we can remove this forced fixup.
  *url = URLFixerUpper::FixupURL(url->possibly_invalid_spec(), std::string());

  // Check that about: URLs are fixed up to chrome: by URLFixerUpper::FixupURL.
  DCHECK((*url == GURL(content::kAboutBlankURL)) ||
         !url->SchemeIs(chrome::kAboutScheme));

  // Only handle chrome://foo/, URLFixerUpper::FixupURL translates about:foo.
  if (!url->SchemeIs(chrome::kChromeUIScheme))
    return false;

  std::string host(url->host());
  std::string path;
  // Replace about with chrome-urls.
  if (host == chrome::kChromeUIAboutHost)
    host = chrome::kChromeUIChromeURLsHost;
  // Replace cache with view-http-cache.
  if (host == chrome::kChromeUICacheHost) {
    host = content::kChromeUINetworkViewCacheHost;
  // Replace sync with sync-internals (for legacy reasons).
  } else if (host == chrome::kChromeUISyncHost) {
    host = chrome::kChromeUISyncInternalsHost;
  // Redirect chrome://extensions.
  } else if (host == chrome::kChromeUIExtensionsHost) {
    host = chrome::kChromeUIUberHost;
    path = chrome::kChromeUIExtensionsHost + url->path();
  // Redirect chrome://settings/extensions (legacy URL).
  } else if (host == chrome::kChromeUISettingsHost &&
      url->path() == std::string("/") + chrome::kExtensionsSubPage) {
    host = chrome::kChromeUIUberHost;
    path = chrome::kChromeUIExtensionsHost;
  // Redirect chrome://history.
  } else if (host == chrome::kChromeUIHistoryHost) {
#if defined(OS_ANDROID)
    // On Android, redirect directly to chrome://history-frame since
    // uber page is unsupported.
    host = chrome::kChromeUIHistoryFrameHost;
#else
    host = chrome::kChromeUIUberHost;
    path = chrome::kChromeUIHistoryHost + url->path();
#endif
  // Redirect chrome://settings
  } else if (host == chrome::kChromeUISettingsHost) {
    host = chrome::kChromeUIUberHost;
    path = chrome::kChromeUISettingsHost + url->path();
  // Redirect chrome://help
  } else if (host == chrome::kChromeUIHelpHost) {
    host = chrome::kChromeUIUberHost;
    path = chrome::kChromeUIHelpHost + url->path();
  } else if (host == chrome::kChromeUIRestartHost) {
    // Call AttemptRestart after chrome::Navigate() completes to avoid access of
    // gtk objects after they are destoyed by BrowserWindowGtk::Close().
    base::MessageLoop::current()->PostTask(FROM_HERE,
        base::Bind(&chrome::AttemptRestart));
  } else if (host == chrome::kChromeUIQuitHost) {
    base::MessageLoop::current()->PostTask(FROM_HERE,
        base::Bind(&chrome::AttemptExit));
  }

  GURL::Replacements replacements;
  replacements.SetHostStr(host);
  if (!path.empty())
    replacements.SetPathStr(path);
  *url = url->ReplaceComponents(replacements);

  // Having re-written the URL, make the chrome: handler process it.
  return false;
}

bool HandleNonNavigationAboutURL(const GURL& url) {
  // chrome://ipc/ is currently buggy, so we disable it for official builds.
#if !defined(OFFICIAL_BUILD)

#if (defined(OS_MACOSX) || defined(OS_WIN)) && defined(IPC_MESSAGE_LOG_ENABLED)
  if (LowerCaseEqualsASCII(url.spec(), chrome::kChromeUIIPCURL)) {
    // Run the dialog. This will re-use the existing one if it's already up.
    chrome::ShowAboutIPCDialog();
    return true;
  }
#endif

#endif  // OFFICIAL_BUILD

  return false;
}
<commit_msg>Move non-navigation URL handlers to HandleNonNavigationAboutURL<commit_after>// Copyright (c) 2012 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/browser_about_handler.h"

#include <string>

#include "base/logging.h"
#include "base/strings/string_util.h"
#include "chrome/browser/lifetime/application_lifetime.h"
#include "chrome/browser/ui/browser_dialogs.h"
#include "chrome/common/net/url_fixer_upper.h"
#include "chrome/common/url_constants.h"

bool WillHandleBrowserAboutURL(GURL* url,
                               content::BrowserContext* browser_context) {
  // TODO(msw): Eliminate "about:*" constants and literals from code and tests,
  //            then hopefully we can remove this forced fixup.
  *url = URLFixerUpper::FixupURL(url->possibly_invalid_spec(), std::string());

  // Check that about: URLs are fixed up to chrome: by URLFixerUpper::FixupURL.
  DCHECK((*url == GURL(content::kAboutBlankURL)) ||
         !url->SchemeIs(chrome::kAboutScheme));

  // Only handle chrome://foo/, URLFixerUpper::FixupURL translates about:foo.
  if (!url->SchemeIs(chrome::kChromeUIScheme))
    return false;

  std::string host(url->host());
  std::string path;
  // Replace about with chrome-urls.
  if (host == chrome::kChromeUIAboutHost)
    host = chrome::kChromeUIChromeURLsHost;
  // Replace cache with view-http-cache.
  if (host == chrome::kChromeUICacheHost) {
    host = content::kChromeUINetworkViewCacheHost;
  // Replace sync with sync-internals (for legacy reasons).
  } else if (host == chrome::kChromeUISyncHost) {
    host = chrome::kChromeUISyncInternalsHost;
  // Redirect chrome://extensions.
  } else if (host == chrome::kChromeUIExtensionsHost) {
    host = chrome::kChromeUIUberHost;
    path = chrome::kChromeUIExtensionsHost + url->path();
  // Redirect chrome://settings/extensions (legacy URL).
  } else if (host == chrome::kChromeUISettingsHost &&
      url->path() == std::string("/") + chrome::kExtensionsSubPage) {
    host = chrome::kChromeUIUberHost;
    path = chrome::kChromeUIExtensionsHost;
  // Redirect chrome://history.
  } else if (host == chrome::kChromeUIHistoryHost) {
#if defined(OS_ANDROID)
    // On Android, redirect directly to chrome://history-frame since
    // uber page is unsupported.
    host = chrome::kChromeUIHistoryFrameHost;
#else
    host = chrome::kChromeUIUberHost;
    path = chrome::kChromeUIHistoryHost + url->path();
#endif
  // Redirect chrome://settings
  } else if (host == chrome::kChromeUISettingsHost) {
    host = chrome::kChromeUIUberHost;
    path = chrome::kChromeUISettingsHost + url->path();
  // Redirect chrome://help
  } else if (host == chrome::kChromeUIHelpHost) {
    host = chrome::kChromeUIUberHost;
    path = chrome::kChromeUIHelpHost + url->path();
  }

  GURL::Replacements replacements;
  replacements.SetHostStr(host);
  if (!path.empty())
    replacements.SetPathStr(path);
  *url = url->ReplaceComponents(replacements);

  // Having re-written the URL, make the chrome: handler process it.
  return false;
}

bool HandleNonNavigationAboutURL(const GURL& url) {
  const std::string host(url.host());

  if (host == chrome::kChromeUIRestartHost) {
    // Call AttemptRestart after chrome::Navigate() completes to avoid access of
    // gtk objects after they are destroyed by BrowserWindowGtk::Close().
    base::MessageLoop::current()->PostTask(FROM_HERE,
        base::Bind(&chrome::AttemptRestart));
    return true;
  } else if (host == chrome::kChromeUIQuitHost) {
    base::MessageLoop::current()->PostTask(FROM_HERE,
        base::Bind(&chrome::AttemptExit));
    return true;
  }

  // chrome://ipc/ is currently buggy, so we disable it for official builds.
#if !defined(OFFICIAL_BUILD)

#if (defined(OS_MACOSX) || defined(OS_WIN)) && defined(IPC_MESSAGE_LOG_ENABLED)
  if (LowerCaseEqualsASCII(url.spec(), chrome::kChromeUIIPCURL)) {
    // Run the dialog. This will re-use the existing one if it's already up.
    chrome::ShowAboutIPCDialog();
    return true;
  }
#endif

#endif  // OFFICIAL_BUILD

  return false;
}
<|endoftext|>


<commit_before>#include "CuteHMIQMLPlugin.hpp"

#include <cutehmi/CuteHMI.hpp>
#include <cutehmi/Prompt.hpp>
#include <cutehmi/Notification.hpp>

#include <QtQml>

void CuteHMIQMLPlugin::registerTypes(const char * uri)
{
	Q_ASSERT(uri == QLatin1String("CuteHMI"));

	qmlRegisterType<cutehmi::Prompt>(uri, 1, 0, "Prompt");
	qmlRegisterType<cutehmi::Notification>(uri, 1, 0, "Notification");
	qmlRegisterUncreatableType<cutehmi::PopupBridge>(uri, 1, 0, "PopupBridge", QObject::tr("cutehmi::PopupBridge instances can not be created within QML."));
	qmlRegisterUncreatableType<cutehmi::NotificationManager>(uri, 1, 0, "NotificationManager", QObject::tr("cutehmi::NotificationManager instances can not be created within QML."));
	qmlRegisterUncreatableType<cutehmi::Project>(uri, 1, 0, "Project", QObject::tr("cutehmi::Project instances can not be created within QML."));
	qmlRegisterUncreatableType<cutehmi::ProjectModel>(uri, 1, 0, "ProjectModel", QObject::tr("cutehmi::ProjectModel instances can not be created within QML."));
	qmlRegisterUncreatableType<const cutehmi::ProjectNode>(uri, 1, 0, "ProjectNode", QObject::tr("cutehmi::ProjectNode instances can not be created within QML."));
	qmlRegisterSingletonType<cutehmi::CuteHMI>(uri, 1, 0, "CuteHMI", CuteHMIProvider);
}

QObject * CuteHMIQMLPlugin::CuteHMIProvider(QQmlEngine * engine, QJSEngine * scriptEngine)
{
	Q_UNUSED(scriptEngine)

	cutehmi::CuteHMI * cuteHMI = & cutehmi::CuteHMI::Instance();
	engine->setObjectOwnership(cuteHMI, QQmlEngine::CppOwnership);
	return cuteHMI;
}

//(c)MP: Copyright © 2017, Michal Policht. All rights reserved.
//(c)MP: This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
<commit_msg>Use macros provided by 'cutehmi.metadata', instead of hard-coded values.<commit_after>#include "CuteHMIQMLPlugin.hpp"

#include <cutehmi/CuteHMI.hpp>
#include <cutehmi/Prompt.hpp>
#include <cutehmi/Notification.hpp>

#include <QtQml>

void CuteHMIQMLPlugin::registerTypes(const char * uri)
{
	Q_ASSERT(uri == QLatin1String("CuteHMI"));

	qmlRegisterType<cutehmi::Prompt>(uri, CUTEHMI_MAJOR, CUTEHMI_1_CURRENT, "Prompt");
	qmlRegisterType<cutehmi::Notification>(uri, CUTEHMI_MAJOR, CUTEHMI_1_CURRENT, "Notification");
	qmlRegisterUncreatableType<cutehmi::PopupBridge>(uri, CUTEHMI_MAJOR, CUTEHMI_1_CURRENT, "PopupBridge", QObject::tr("cutehmi::PopupBridge instances can not be created within QML."));
	qmlRegisterUncreatableType<cutehmi::NotificationManager>(uri, CUTEHMI_MAJOR, CUTEHMI_1_CURRENT, "NotificationManager", QObject::tr("cutehmi::NotificationManager instances can not be created within QML."));
	qmlRegisterUncreatableType<cutehmi::Project>(uri, CUTEHMI_MAJOR, CUTEHMI_1_CURRENT, "Project", QObject::tr("cutehmi::Project instances can not be created within QML."));
	qmlRegisterUncreatableType<cutehmi::ProjectModel>(uri, CUTEHMI_MAJOR, CUTEHMI_1_CURRENT, "ProjectModel", QObject::tr("cutehmi::ProjectModel instances can not be created within QML."));
	qmlRegisterUncreatableType<cutehmi::Plugin>(uri, CUTEHMI_MAJOR, CUTEHMI_1_CURRENT, "Plugin", QObject::tr("cutehmi::Plugin instances can not be created within QML."));
	qmlRegisterUncreatableType<const cutehmi::ProjectNode>(uri, CUTEHMI_MAJOR, CUTEHMI_1_CURRENT, "ProjectNode", QObject::tr("cutehmi::ProjectNode instances can not be created within QML."));
	qmlRegisterSingletonType<cutehmi::CuteHMI>(uri, CUTEHMI_MAJOR, CUTEHMI_1_CURRENT, "CuteHMI", CuteHMIProvider);
}

QObject * CuteHMIQMLPlugin::CuteHMIProvider(QQmlEngine * engine, QJSEngine * scriptEngine)
{
	Q_UNUSED(scriptEngine)

	cutehmi::CuteHMI * cuteHMI = & cutehmi::CuteHMI::Instance();
	engine->setObjectOwnership(cuteHMI, QQmlEngine::CppOwnership);
	return cuteHMI;
}

//(c)MP: Copyright © 2017, Michal Policht. All rights reserved.
//(c)MP: This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
<|endoftext|>