<commit_before>/*
 * Copyright (c) MZ3 Project Team All rights reserved.
 * Code licensed under the BSD License:
 * http://www.mz3.jp/license.txt
 */
#include "stdafx.h"
#include "MixiParserUtil.h"

/// mixi pHTMLp[T
namespace mixi {

	/**
	 * ϊ(tEۂ𒊏oAmixi SetDate)
	 *
	 * @param line [in]  ܂ޕB
	 *                   F"2006N1119 17:12"
	 *                       "2007N0705 21:55
"
	 *                       "1008
"
	 *                       "1219927284" (G|bN)
	 * @param mixi [out] ͌ʂ SetDate ŕۑB
	 */
	bool ParserUtil::ParseDate(LPCTSTR line, CMixiData& mixi)
	{
		// ėp `
		if (wcsstr(line, L"") != NULL) {
			// K\̃RpC
			static MyRegex reg;
			if( !util::CompileRegex( reg, L"([0-9]{2,4})?N?([0-9]{1,2}?)([0-9]{1,2})[^0-9]*([0-9]{1,2})?:??([0-9]{2})?" ) ) {
				return false;
			}
			//
			if( reg.exec(line) && reg.results.size() == 6 ) {
				// o
				int year   = _wtoi( reg.results[1].str.c_str() );
				int month  = _wtoi( reg.results[2].str.c_str() );
				int day    = _wtoi( reg.results[3].str.c_str() );
				int hour   = _wtoi( reg.results[4].str.c_str() );
				int minute = _wtoi( reg.results[5].str.c_str() );
				//mixi.SetDate(year, month, day, hour, minute);

				if (year<1900) {
					// CTime  year<1900 T|[gĂȂ̂ŁAƂēo^B
					CString s;
					s.Format(_T("%02d/%02d %02d:%02d"), month, day, hour, minute);
					mixi.SetDate( s );
				} else {
					mixi.SetDate( CTime(year, month, day, hour, minute, 0) );
				}
				return true;
			}
		}

		CTime t;
		if (ParseDate(line, t)) {
			// ͐
			mixi.SetDate(t);
			return true;
		}

		CString msg = L"ɓtE܂ : [";
		msg += line;
		msg += L"]";
		MZ3LOGGER_DEBUG( msg );
		return false;
	}

	bool ParserUtil::ParseDate(LPCTSTR line, CTime& t_result)
	{
		// T1. RSS ` (YYYY-MM-DDT00:00:00Z)
		{
			// K\̃RpC
			static MyRegex reg;
			if( !util::CompileRegex( reg, L"([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})Z" ) ) {
				return false;
			}
			//
			if( reg.exec(line) && reg.results.size() == 7 ) {
				// o
				int year   = _wtoi( reg.results[1].str.c_str() );
				int month  = _wtoi( reg.results[2].str.c_str() );
				int day    = _wtoi( reg.results[3].str.c_str() );
				int hour   = _wtoi( reg.results[4].str.c_str() );
				int minute = _wtoi( reg.results[5].str.c_str() );

				CTime t(year, month, day, hour, minute, 0);
				t += CTimeSpan(0, 9, 0, 0);

				t_result = t;
				//mixi.SetDate(t.GetYear(), t.GetMonth(), t.GetDay(), t.GetHour(), t.GetMinute());
				return true;
			}
		}

		// T2. RSS ` (YYYY-MM-DDT00:00:00+09:00)
		{
			// K\̃RpC
			static MyRegex reg;
			if( !util::CompileRegex( reg, L"([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})\\+([0-9]{2}):([0-9]{2})" ) ) {
				return false;
			}
			//
			if( reg.exec(line) && reg.results.size() == 9 ) {
				// o
				int year   = _wtoi( reg.results[1].str.c_str() );
				int month  = _wtoi( reg.results[2].str.c_str() );
				int day    = _wtoi( reg.results[3].str.c_str() );
				int hour   = _wtoi( reg.results[4].str.c_str() );
				int minute = _wtoi( reg.results[5].str.c_str() );

				CTime t(year, month, day, hour, minute, 0);
//				t += CTimeSpan(0, 9, 0, 0);

				t_result = t;
				return true;
			}
		}

		// T3. RSS ` (Sun Dec 16 09:00:00 +0000 2007)
		// T3. RSS ` (Fri Dec 5 1:03:05 +0900 2008)
		{
			// K\̃RpC
			static MyRegex reg;
			if( !util::CompileRegex( reg, L"([a-zA-Z]{3}) ([a-zA-Z]{3}) ([0-9]{1,2}) ([0-9]{1,2}):([0-9]{2}):([0-9]{2}) \\+([0-9]{4}) ([0-9]{4})" ) ) {
				return false;
			}
			//
			if( reg.exec(line) && reg.results.size() == 9 ) {
				// o

				// N
				int year   = _wtoi( reg.results[8].str.c_str() );

				//
				int month  = ThreeCharMonthToInteger( reg.results[2].str.c_str() );
				int day    = _wtoi( reg.results[3].str.c_str() );
				int hour   = _wtoi( reg.results[4].str.c_str() );
				int minute = _wtoi( reg.results[5].str.c_str() );
				int sec    = _wtoi( reg.results[6].str.c_str() );

				CTime t(year, month, day, hour, minute, sec);

				int diff   = _wtoi( reg.results[7].str.c_str() );
				if (diff==0) {
					t += CTimeSpan(0, 9, 0, 0);
				}
				t_result = t;
				return true;
			}
		}

		// T4. RSS 2.0 ` (Mon, 16 Dec 2007 09:00:00 +0900)
		// T4. RSS 2.0 ` (Mon, 16 Dec 2007 09:00:00 GMT)
		{
			// K\̃RpC
			static MyRegex reg;
			if( !util::CompileRegex( reg, L"([a-zA-Z]{3}), ([0-9]{2}) ([a-zA-Z]{3}) ([0-9]{4}) ([0-9]{2}):([0-9]{2}):([0-9]{2}) (.*)" ) ) {
				return false;
			}
			//
			if( reg.exec(line) && reg.results.size() == 9 ) {
				// o

				// N
				int year   = _wtoi( reg.results[4].str.c_str() );

				//
				int month  = ThreeCharMonthToInteger( reg.results[3].str.c_str() );
				int day    = _wtoi( reg.results[2].str.c_str() );
				int hour   = _wtoi( reg.results[5].str.c_str() );
				int minute = _wtoi( reg.results[6].str.c_str() );
				int sec    = _wtoi( reg.results[7].str.c_str() );
				CTime t(year, month, day, hour, minute, sec);

				// ȈՎϊ
				const std::wstring& time_diff = reg.results[8].str;

				if (time_diff==L"GMT") {
					t += CTimeSpan(0, 9, 0, 0);
				}

				t_result = t;
				return true;
			}
		}

		// T5. epoch ` (1219927284)
		{
			// K\̃RpC
			static MyRegex reg;
			if( !util::CompileRegex( reg, L"^([0-9]*)$" ) ) {
				return false;
			}
			//
			if( reg.exec(line) && reg.results.size() == 2 ) {
				// o

				t_result = CTime(_wtoi(reg.results[1].str.c_str()));

				return true;
			}
		}
		return false;
	}

}
<commit_msg><commit_after>/*
 * Copyright (c) MZ3 Project Team All rights reserved.
 * Code licensed under the BSD License:
 * http://www.mz3.jp/license.txt
 */
#include "stdafx.h"
#include "MixiParserUtil.h"

/// mixi pHTMLp[T
namespace mixi {

	/**
	 * ϊ(tEۂ𒊏oAmixi SetDate)
	 *
	 * @param line [in]  ܂ޕB
	 *                   F"2006N1119 17:12"
	 *                       "2007N0705 21:55
"
	 *                       "1008
"
	 *                       "1219927284" (G|bN)
	 * @param mixi [out] ͌ʂ SetDate ŕۑB
	 */
	bool ParserUtil::ParseDate(LPCTSTR line, CMixiData& mixi)
	{
		// ėp `
		if (wcsstr(line, L"") != NULL) {
			// K\̃RpC
			static MyRegex reg;
			if( !util::CompileRegex( reg, L"([0-9]{2,4})?N?([0-9]{1,2}?)([0-9]{1,2})[^0-9]*([0-9]{1,2})?:??([0-9]{2})?" ) ) {
				return false;
			}
			//
			if( reg.exec(line) && reg.results.size() == 6 ) {
				// o
				int year   = _wtoi( reg.results[1].str.c_str() );
				int month  = _wtoi( reg.results[2].str.c_str() );
				int day    = _wtoi( reg.results[3].str.c_str() );
				int hour   = _wtoi( reg.results[4].str.c_str() );
				int minute = _wtoi( reg.results[5].str.c_str() );
				//mixi.SetDate(year, month, day, hour, minute);

				if (year<1900) {
					// CTime  year<1900 T|[gĂȂ̂ŁAƂēo^B
					CString s;
					s.Format(_T("%02d/%02d %02d:%02d"), month, day, hour, minute);
					mixi.SetDate( s );
				} else {
					mixi.SetDate( CTime(year, month, day, hour, minute, 0) );
				}
				return true;
			}
		}

		CTime t;
		if (ParseDate(line, t)) {
			// ͐
			mixi.SetDate(t);
			return true;
		}

		CString msg = L"ɓtE܂ : [";
		msg += line;
		msg += L"]";
		MZ3LOGGER_DEBUG( msg );
		return false;
	}

	bool ParserUtil::ParseDate(LPCTSTR line, CTime& t_result)
	{
		// T1. RSS ` (YYYY-MM-DDT00:00:00Z)
		{
			// K\̃RpC
			static MyRegex reg;
			if( !util::CompileRegex( reg, L"([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})Z" ) ) {
				return false;
			}
			//
			if( reg.exec(line) && reg.results.size() == 7 ) {
				// o
				int year   = _wtoi( reg.results[1].str.c_str() );
				int month  = _wtoi( reg.results[2].str.c_str() );
				int day    = _wtoi( reg.results[3].str.c_str() );
				int hour   = _wtoi( reg.results[4].str.c_str() );
				int minute = _wtoi( reg.results[5].str.c_str() );

				CTime t(year, month, day, hour, minute, 0);
				t += CTimeSpan(0, 9, 0, 0);

				t_result = t;
				//mixi.SetDate(t.GetYear(), t.GetMonth(), t.GetDay(), t.GetHour(), t.GetMinute());
				return true;
			}
		}

		// T2. RSS ` (YYYY-MM-DDT00:00:00+09:00)
		{
			// K\̃RpC
			static MyRegex reg;
			if( !util::CompileRegex( reg, L"([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})\\+([0-9]{2}):([0-9]{2})" ) ) {
				return false;
			}
			//
			if( reg.exec(line) && reg.results.size() == 9 ) {
				// o
				int year   = _wtoi( reg.results[1].str.c_str() );
				int month  = _wtoi( reg.results[2].str.c_str() );
				int day    = _wtoi( reg.results[3].str.c_str() );
				int hour   = _wtoi( reg.results[4].str.c_str() );
				int minute = _wtoi( reg.results[5].str.c_str() );

				CTime t(year, month, day, hour, minute, 0);
//				t += CTimeSpan(0, 9, 0, 0);

				t_result = t;
				return true;
			}
		}

		// T3. RSS ` (Sun Dec 16 09:00:00 +0000 2007)
		// T3. RSS ` (Fri Dec 5 1:03:05 +0900 2008)
		{
			// K\̃RpC
			static MyRegex reg;
			if( !util::CompileRegex( reg, L"([a-zA-Z]{3}) ([a-zA-Z]{3}) ([0-9]{1,2}) ([0-9]{1,2}):([0-9]{2}):([0-9]{2}) \\+([0-9]{4}) ([0-9]{4})" ) ) {
				return false;
			}
			//
			if( reg.exec(line) && reg.results.size() == 9 ) {
				// o

				// N
				int year   = _wtoi( reg.results[8].str.c_str() );

				//
				int month  = ThreeCharMonthToInteger( reg.results[2].str.c_str() );
				int day    = _wtoi( reg.results[3].str.c_str() );
				int hour   = _wtoi( reg.results[4].str.c_str() );
				int minute = _wtoi( reg.results[5].str.c_str() );
				int sec    = _wtoi( reg.results[6].str.c_str() );

				CTime t(year, month, day, hour, minute, sec);

				int diff   = _wtoi( reg.results[7].str.c_str() );
				if (diff==0) {
					t += CTimeSpan(0, 9, 0, 0);
				}
				t_result = t;
				return true;
			}
		}

		// T4. RSS 2.0 ` (Mon, 16 Dec 2007 09:00:00 +0900)
		// T4. RSS 2.0 ` (Mon, 16 Dec 2007 09:00:00 GMT)
		{
			// K\̃RpC
			static MyRegex reg;
			if( !util::CompileRegex( reg, L"([a-zA-Z]{3}), ([0-9]{2}) ([a-zA-Z]{3}) ([0-9]{4}) ([0-9]{2}):([0-9]{2}):([0-9]{2}) (.*)" ) ) {
				return false;
			}
			//
			if( reg.exec(line) && reg.results.size() == 9 ) {
				// o

				// N
				int year   = _wtoi( reg.results[4].str.c_str() );

				//
				int month  = ThreeCharMonthToInteger( reg.results[3].str.c_str() );
				int day    = _wtoi( reg.results[2].str.c_str() );
				int hour   = _wtoi( reg.results[5].str.c_str() );
				int minute = _wtoi( reg.results[6].str.c_str() );
				int sec    = _wtoi( reg.results[7].str.c_str() );
				CTime t(year, month, day, hour, minute, sec);

				// ȈՎϊ
				const std::wstring& time_diff = reg.results[8].str;

				if (time_diff==L"GMT") {
					t += CTimeSpan(0, 9, 0, 0);
				}

				t_result = t;
				return true;
			}
		}

		// T5. epoch ` (1219927284)
		{
			// K\̃RpC
			static MyRegex reg;
			if( !util::CompileRegex( reg, L"^([0-9]*)$" ) ) {
				return false;
			}
			//
			if( reg.exec(line) && reg.results.size() == 2 ) {
				// o

				t_result = CTime(_wtoi(reg.results[1].str.c_str()));

				return true;
			}
		}
		return false;
	}

}
<|endoftext|>


<commit_before>#include "HalideRuntime.h"
#include "HalideRuntimeCuda.h"
#include "HalideRuntimeOpenGL.h"
#include "HalideRuntimeOpenCL.h"
#include "HalideRuntimeRenderscript.h"
#include "runtime_internal.h"

// This runtime module will contain extern declarations of the Halide
// API and the types it uses. It's useful for compiling modules that
// use the API without including a copy of it (e.g. JIT, NoRuntime).

// Can be generated via the following:
// cat src/runtime/runtime_internal.h src/runtime/HalideRuntime*.h | grep "^[^ ][^(]*halide_[^ ]*(" | grep -v '#define' | sed "s/[^(]*halide/halide/" | sed "s/(.*//" | sed "s/^h/    \(void *)\&h/" | sed "s/$/,/" | sort | uniq

namespace {
__attribute__((used)) void *runtime_api_functions[] = {
    (void *)&halide_copy_to_device,
    (void *)&halide_copy_to_host,
    (void *)&halide_cuda_detach_device_ptr,
    (void *)&halide_cuda_device_interface,
    (void *)&halide_cuda_get_device_ptr,
    (void *)&halide_cuda_initialize_kernels,
    (void *)&halide_cuda_run,
    (void *)&halide_cuda_wrap_device_ptr,
    (void *)&halide_current_time_ns,
    (void *)&halide_debug_to_file,
    (void *)&halide_device_free,
    (void *)&halide_device_free_as_destructor,
    (void *)&halide_device_malloc,
    (void *)&halide_device_release,
    (void *)&halide_device_sync,
    (void *)&halide_do_par_for,
    (void *)&halide_double_to_string,
    (void *)&halide_enumerate_registered_filters,
    (void *)&halide_error,
    (void *)&halide_error_access_out_of_bounds,
    (void *)&halide_error_bad_elem_size,
    (void *)&halide_error_bounds_inference_call_failed,
    (void *)&halide_error_buffer_allocation_too_large,
    (void *)&halide_error_buffer_argument_is_null,
    (void *)&halide_error_buffer_extents_too_large,
    (void *)&halide_error_constraints_make_required_region_smaller,
    (void *)&halide_error_constraint_violated,
    (void *)&halide_error_debug_to_file_failed,
    (void *)&halide_error_explicit_bounds_too_small,
    (void *)&halide_error_extern_stage_failed,
    (void *)&halide_error_out_of_memory,
    (void *)&halide_error_param_too_large_f64,
    (void *)&halide_error_param_too_large_i64,
    (void *)&halide_error_param_too_large_u64,
    (void *)&halide_error_param_too_small_f64,
    (void *)&halide_error_param_too_small_i64,
    (void *)&halide_error_param_too_small_u64,
    (void *)&halide_free,
    (void *)&halide_get_gpu_device,
    (void *)&halide_get_library_symbol,
    (void *)&halide_get_symbol,
    (void *)&halide_get_trace_file,
    (void *)&halide_int64_to_string,
    (void *)&halide_load_library,
    (void *)&halide_malloc,
    (void *)&halide_memoization_cache_cleanup,
    (void *)&halide_memoization_cache_lookup,
    (void *)&halide_memoization_cache_set_size,
    (void *)&halide_memoization_cache_store,
    (void *)&halide_mutex_cleanup,
    (void *)&halide_mutex_lock,
    (void *)&halide_mutex_unlock,
    (void *)&halide_opencl_detach_cl_mem,
    (void *)&halide_opencl_device_interface,
    (void *)&halide_opencl_get_cl_mem,
    (void *)&halide_opencl_get_device_type,
    (void *)&halide_opencl_get_platform_name,
    (void *)&halide_opencl_initialize_kernels,
    (void *)&halide_opencl_run,
    (void *)&halide_opencl_set_device_type,
    (void *)&halide_opencl_set_platform_name,
    (void *)&halide_opencl_wrap_cl_mem,
    (void *)&halide_opengl_context_lost,
    (void *)&halide_opengl_create_context,
    (void *)&halide_opengl_detach_texture,
    (void *)&halide_opengl_device_interface,
    (void *)&halide_opengl_get_proc_address,
    (void *)&halide_opengl_get_texture,
    (void *)&halide_opengl_initialize_kernels,
    (void *)&halide_opengl_run,
    (void *)&halide_opengl_wrap_render_target,
    (void *)&halide_opengl_wrap_texture,
    (void *)&halide_pointer_to_string,
    (void *)&halide_print,
    (void *)&halide_release_jit_module,
    (void *)&halide_renderscript_device_interface,
    (void *)&halide_renderscript_initialize_kernels,
    (void *)&halide_renderscript_run,
    (void *)&halide_set_gpu_device,
    (void *)&halide_set_num_threads,
    (void *)&halide_set_trace_file,
    (void *)&halide_shutdown_thread_pool,
    (void *)&halide_shutdown_trace,
    (void *)&halide_start_clock,
    (void *)&halide_string_to_string,
    (void *)&halide_trace,
    (void *)&halide_uint64_to_string,
    (void *)&halide_use_jit_module
};
}
<commit_msg>Add some more runtime functions to the runtime_api list<commit_after>#include "HalideRuntime.h"
#include "HalideRuntimeCuda.h"
#include "HalideRuntimeOpenGL.h"
#include "HalideRuntimeOpenCL.h"
#include "HalideRuntimeRenderscript.h"
#include "runtime_internal.h"

// This runtime module will contain extern declarations of the Halide
// API and the types it uses. It's useful for compiling modules that
// use the API without including a copy of it (e.g. JIT, NoRuntime).

// Can be generated via the following:
// cat src/runtime/runtime_internal.h src/runtime/HalideRuntime*.h | grep "^[^ ][^(]*halide_[^ ]*(" | grep -v '#define' | sed "s/[^(]*halide/halide/" | sed "s/(.*//" | sed "s/^h/    \(void *)\&h/" | sed "s/$/,/" | sort | uniq

namespace {
__attribute__((used)) void *runtime_api_functions[] = {
    (void *)&halide_copy_to_device,
    (void *)&halide_copy_to_host,
    (void *)&halide_cuda_detach_device_ptr,
    (void *)&halide_cuda_device_interface,
    (void *)&halide_cuda_get_device_ptr,
    (void *)&halide_cuda_initialize_kernels,
    (void *)&halide_cuda_run,
    (void *)&halide_cuda_wrap_device_ptr,
    (void *)&halide_current_time_ns,
    (void *)&halide_debug_to_file,
    (void *)&halide_device_free,
    (void *)&halide_device_free_as_destructor,
    (void *)&halide_device_malloc,
    (void *)&halide_device_release,
    (void *)&halide_device_sync,
    (void *)&halide_do_par_for,
    (void *)&halide_double_to_string,
    (void *)&halide_enumerate_registered_filters,
    (void *)&halide_error,
    (void *)&halide_error_access_out_of_bounds,
    (void *)&halide_error_bad_elem_size,
    (void *)&halide_error_bounds_inference_call_failed,
    (void *)&halide_error_buffer_allocation_too_large,
    (void *)&halide_error_buffer_argument_is_null,
    (void *)&halide_error_buffer_extents_too_large,
    (void *)&halide_error_constraints_make_required_region_smaller,
    (void *)&halide_error_constraint_violated,
    (void *)&halide_error_debug_to_file_failed,
    (void *)&halide_error_explicit_bounds_too_small,
    (void *)&halide_error_extern_stage_failed,
    (void *)&halide_error_out_of_memory,
    (void *)&halide_error_param_too_large_f64,
    (void *)&halide_error_param_too_large_i64,
    (void *)&halide_error_param_too_large_u64,
    (void *)&halide_error_param_too_small_f64,
    (void *)&halide_error_param_too_small_i64,
    (void *)&halide_error_param_too_small_u64,
    (void *)&halide_free,
    (void *)&halide_get_gpu_device,
    (void *)&halide_get_library_symbol,
    (void *)&halide_get_symbol,
    (void *)&halide_get_trace_file,
    (void *)&halide_int64_to_string,
    (void *)&halide_load_library,
    (void *)&halide_malloc,
    (void *)&halide_memoization_cache_cleanup,
    (void *)&halide_memoization_cache_lookup,
    (void *)&halide_memoization_cache_set_size,
    (void *)&halide_memoization_cache_store,
    (void *)&halide_mutex_cleanup,
    (void *)&halide_mutex_lock,
    (void *)&halide_mutex_unlock,
    (void *)&halide_opencl_detach_cl_mem,
    (void *)&halide_opencl_device_interface,
    (void *)&halide_opencl_get_cl_mem,
    (void *)&halide_opencl_get_device_type,
    (void *)&halide_opencl_get_platform_name,
    (void *)&halide_opencl_initialize_kernels,
    (void *)&halide_opencl_run,
    (void *)&halide_opencl_set_device_type,
    (void *)&halide_opencl_set_platform_name,
    (void *)&halide_opencl_wrap_cl_mem,
    (void *)&halide_opengl_context_lost,
    (void *)&halide_opengl_create_context,
    (void *)&halide_opengl_detach_texture,
    (void *)&halide_opengl_device_interface,
    (void *)&halide_opengl_get_proc_address,
    (void *)&halide_opengl_get_texture,
    (void *)&halide_opengl_initialize_kernels,
    (void *)&halide_opengl_run,
    (void *)&halide_opengl_wrap_render_target,
    (void *)&halide_opengl_wrap_texture,
    (void *)&halide_pointer_to_string,
    (void *)&halide_print,
    (void *)&halide_profiler_pipeline_start,
    (void *)&halide_profiler_get_state,
    (void *)&halide_profiler_reset,
    (void *)&halide_profiler_report,
    (void *)&halide_release_jit_module,
    (void *)&halide_renderscript_device_interface,
    (void *)&halide_renderscript_initialize_kernels,
    (void *)&halide_renderscript_run,
    (void *)&halide_set_gpu_device,
    (void *)&halide_set_num_threads,
    (void *)&halide_set_trace_file,
    (void *)&halide_shutdown_thread_pool,
    (void *)&halide_shutdown_trace,
    (void *)&halide_start_clock,
    (void *)&halide_string_to_string,
    (void *)&halide_trace,
    (void *)&halide_uint64_to_string,
    (void *)&halide_use_jit_module
};
}
<|endoftext|>


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

#include "Control.h"

#include <vector>
#include "Pid.h"
#include "defaultDevices.h"
#include "ActuatorInterfaces.h"
#include "ActuatorPwm.h"
#include "ActuatorTimeLimited.h"
#include "TempSensor.h"
#include "ActuatorSetPoint.h"
#include "ActuatorMutexDriver.h"
#include "ActuatorMutexGroup.h"
#include "json_writer.h"

Control::Control()
{
    // set up static devices for backwards compatibility with tempControl
    beer1Sensor = new TempSensor(defaultTempSensorBasic());
    beer1Sensor->setName("beer1");
    beer2Sensor = new TempSensor(defaultTempSensorBasic());
    beer2Sensor->setName("beer2");
    fridgeSensor = new TempSensor(defaultTempSensorBasic());
    fridgeSensor->setName("fridge");

    mutex = new ActuatorMutexGroup();

    heater1Mutex = new ActuatorMutexDriver(defaultActuator(), mutex);
    heater1 = new ActuatorPwm(heater1Mutex, 4); // period 4s

    heater2Mutex = new ActuatorMutexDriver(defaultActuator(), mutex);
    heater2 = new ActuatorPwm(heater2Mutex, 4); // period 4s

    coolerTimeLimited = new ActuatorTimeLimited(defaultActuator(), 120, 180); // 2 min minOn time, 3 min minOff
    coolerMutex = new ActuatorMutexDriver(coolerTimeLimited, mutex);
    cooler = new ActuatorPwm(coolerMutex, 1200); // period 20 min

    beer1Set = new SetPointSimple();
    beer2Set = new SetPointSimple();
    fridgeSet = new SetPointSimple();

    fridgeSetPointActuator = new ActuatorSetPoint(fridgeSet, fridgeSensor, beer1Set);
    fridgeSetPointActuator->setMin(-10.0);
    fridgeSetPointActuator->setMax(10.0);

    heater1Pid = new Pid(fridgeSensor, heater1, fridgeSet);
    heater1Pid->setName("heater1");

    coolerPid = new Pid(fridgeSensor, cooler, fridgeSet);
    coolerPid->setActuatorIsNegative(true);
    coolerPid->setName("cooler");

    heater2Pid = new Pid(beer2Sensor, heater2, beer2Set);
    heater2Pid->setName("heater2");

    beerToFridgePid = new Pid(beer1Sensor, fridgeSetPointActuator, beer1Set);
    beerToFridgePid->setName("beer2fridge");

    pids.push_back(heater1Pid);
    pids.push_back(heater2Pid);
    pids.push_back(coolerPid);
    pids.push_back(beerToFridgePid);

    sensors.push_back(fridgeSensor);
    sensors.push_back(beer1Sensor);
    sensors.push_back(beer2Sensor);

    actuators.push_back(cooler);
    actuators.push_back(heater1);
    actuators.push_back(heater2);

    beer1SetNamed = new SetPointNamed(beer1Set);
    beer1SetNamed->setName("beer1set");
    beer2SetNamed = new SetPointNamed(beer2Set);
    beer1SetNamed->setName("beer2set");
    fridgeSetNamed = new SetPointNamed(fridgeSet);
    fridgeSetNamed->setName("fridgeset");

    setpoints.push_back(beer1SetNamed);
    setpoints.push_back(beer2SetNamed);
    setpoints.push_back(fridgeSetNamed);

    mutex->setDeadTime(1800000); // 30 minutes
}

Control::~Control(){
    // in practice this is never used since the instance is global

#if 0
    delete heater1Mutex;
    delete heater1;

    delete heater2Mutex;
    delete heater2;

    delete coolerTimeLimited;
    delete coolerMutex;
    delete cooler;

    delete fridgeSetPointActuator;

    delete beer1Set;
    delete beer2Set;
    delete fridgeSet;

    delete beer1SetNamed;
    delete beer2SetNamed;
    delete fridgeSetNamed;

    delete mutex;

    delete heater1Pid;
    delete heater2Pid;
    delete coolerPid;
    delete beerToFridgePid;

    pids.clear();
    sensors.clear();
    actuators.clear();
#endif
}

// This update function should be called every second
void Control::update(){
    updateSensors();
    updatePids();
    updateActuators();
    mutex->update();
}

void Control::updatePids(){
    for ( auto &pid : pids ) {
        pid->update();
    }
}

// The actuator update should be called often to generate the PWM signal
void Control::updateSensors(){
    for ( auto &sensor : sensors ) {
        sensor->update();
    }
}

void Control::updateActuators(){
    for ( auto &actuator : actuators ) {
        actuator->update();
    }
}

void Control::serialize(JSON::Adapter& adapter){
    JSON::Class root(adapter, "Control");
    JSON_E(adapter, pids);
    JSON_E(adapter, sensors);
    JSON_E(adapter, actuators);
    JSON_T(adapter, setpoints);
}

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

#include "Control.h"

#include <vector>
#include "Pid.h"
#include "defaultDevices.h"
#include "ActuatorInterfaces.h"
#include "ActuatorPwm.h"
#include "ActuatorTimeLimited.h"
#include "TempSensor.h"
#include "ActuatorSetPoint.h"
#include "ActuatorMutexDriver.h"
#include "ActuatorMutexGroup.h"
#include "json_writer.h"

Control::Control()
{
    // set up static devices for backwards compatibility with tempControl
    beer1Sensor = new TempSensor(defaultTempSensorBasic());
    beer1Sensor->setName("beer1");
    beer2Sensor = new TempSensor(defaultTempSensorBasic());
    beer2Sensor->setName("beer2");
    fridgeSensor = new TempSensor(defaultTempSensorBasic());
    fridgeSensor->setName("fridge");

    mutex = new ActuatorMutexGroup();

    heater1Mutex = new ActuatorMutexDriver(defaultActuator(), mutex);
    heater1 = new ActuatorPwm(heater1Mutex, 4); // period 4s

    heater2Mutex = new ActuatorMutexDriver(defaultActuator(), mutex);
    heater2 = new ActuatorPwm(heater2Mutex, 4); // period 4s

    coolerTimeLimited = new ActuatorTimeLimited(defaultActuator(), 120, 180); // 2 min minOn time, 3 min minOff
    coolerMutex = new ActuatorMutexDriver(coolerTimeLimited, mutex);
    cooler = new ActuatorPwm(coolerMutex, 1200); // period 20 min

    beer1Set = new SetPointSimple();
    beer2Set = new SetPointSimple();
    fridgeSet = new SetPointSimple();

    fridgeSetPointActuator = new ActuatorSetPoint(fridgeSet, fridgeSensor, beer1Set);
    fridgeSetPointActuator->setMin(-10.0);
    fridgeSetPointActuator->setMax(10.0);

    heater1Pid = new Pid(fridgeSensor, heater1, fridgeSet);
    heater1Pid->setName("heater1");

    coolerPid = new Pid(fridgeSensor, cooler, fridgeSet);
    coolerPid->setActuatorIsNegative(true);
    coolerPid->setName("cooler");

    heater2Pid = new Pid(beer2Sensor, heater2, beer2Set);
    heater2Pid->setName("heater2");

    beerToFridgePid = new Pid(beer1Sensor, fridgeSetPointActuator, beer1Set);
    beerToFridgePid->setName("beer2fridge");

    pids.push_back(heater1Pid);
    pids.push_back(heater2Pid);
    pids.push_back(coolerPid);
    pids.push_back(beerToFridgePid);

    sensors.push_back(fridgeSensor);
    sensors.push_back(beer1Sensor);
    sensors.push_back(beer2Sensor);

    actuators.push_back(cooler);
    actuators.push_back(heater1);
    actuators.push_back(heater2);

    beer1SetNamed = new SetPointNamed(beer1Set);
    beer1SetNamed->setName("beer1set");
    beer2SetNamed = new SetPointNamed(beer2Set);
    beer1SetNamed->setName("beer2set");
    fridgeSetNamed = new SetPointNamed(fridgeSet);
    fridgeSetNamed->setName("fridgeset");

    setpoints.push_back(beer1SetNamed);
    setpoints.push_back(beer2SetNamed);
    setpoints.push_back(fridgeSetNamed);

    mutex->setDeadTime(1800000); // 30 minutes
}

Control::~Control(){
#if defined(ARDUINO) || defined(SPARK)
    // global control object is static and never destroyed.
    // omit proper destructor to save space.
#else
    delete heater1Mutex;
    delete heater1;

    delete heater2Mutex;
    delete heater2;

    delete coolerTimeLimited;
    delete coolerMutex;
    delete cooler;

    delete fridgeSetPointActuator;

    delete beer1Set;
    delete beer2Set;
    delete fridgeSet;

    delete beer1SetNamed;
    delete beer2SetNamed;
    delete fridgeSetNamed;

    delete mutex;

    delete heater1Pid;
    delete heater2Pid;
    delete coolerPid;
    delete beerToFridgePid;

    pids.clear();
    sensors.clear();
    actuators.clear();
#endif
}

// This update function should be called every second
void Control::update(){
    updateSensors();
    updatePids();
    updateActuators();
    mutex->update();
}

void Control::updatePids(){
    for ( auto &pid : pids ) {
        pid->update();
    }
}

// The actuator update should be called often to generate the PWM signal
void Control::updateSensors(){
    for ( auto &sensor : sensors ) {
        sensor->update();
    }
}

void Control::updateActuators(){
    for ( auto &actuator : actuators ) {
        actuator->update();
    }
}

void Control::serialize(JSON::Adapter& adapter){
    JSON::Class root(adapter, "Control");
    JSON_E(adapter, pids);
    JSON_E(adapter, sensors);
    JSON_E(adapter, actuators);
    JSON_T(adapter, setpoints);
}

Control control;
<|endoftext|>


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

#include "chrome/browser/external_tab_container.h"

#include "app/win_util.h"
#include "base/logging.h"
#include "base/win_util.h"
#include "chrome/browser/automation/automation_provider.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/extensions/extension_function_dispatcher.h"
#include "chrome/browser/load_notification_details.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/tab_contents/provisional_load_details.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/views/tab_contents/tab_contents_container.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/notification_service.h"
#include "chrome/test/automation/automation_messages.h"

static const wchar_t kWindowObjectKey[] = L"ChromeWindowObject";

// TODO(sanjeevr): The external_accel_table_ and external_accel_entry_count_
// member variables are now obsolete and we don't use them.
// We need to remove them.
ExternalTabContainer::ExternalTabContainer(
    AutomationProvider* automation)
    : automation_(automation),
      tab_contents_(NULL),
      external_accel_table_(NULL),
      external_accel_entry_count_(0),
      tab_contents_container_(NULL),
      tab_handle_(0),
      ignore_next_load_notification_(false) {
}

ExternalTabContainer::~ExternalTabContainer() {
  Uninitialize(GetNativeView());
}

bool ExternalTabContainer::Init(Profile* profile,
                                HWND parent,
                                const gfx::Rect& bounds,
                                DWORD style) {
  if (IsWindow()) {
    NOTREACHED();
    return false;
  }

  set_window_style(WS_POPUP);
  views::WidgetWin::Init(NULL, bounds, true);
  if (!IsWindow()) {
    NOTREACHED();
    return false;
  }

  // We don't ever remove the prop because the lifetime of this object
  // is the same as the lifetime of the window
  SetProp(GetNativeView(), kWindowObjectKey, this);

  views::FocusManager* focus_manager =
      views::FocusManager::GetFocusManager(GetNativeView());
  focus_manager->AddKeystrokeListener(this);

  tab_contents_ = new TabContents(profile, NULL, MSG_ROUTING_NONE, NULL);
  tab_contents_->set_delegate(this);
  tab_contents_->render_view_host()->AllowExternalHostBindings();

  // Create a TabContentsContainer to handle focus cycling using Tab and
  // Shift-Tab.
  tab_contents_container_ = new TabContentsContainer;
  SetContentsView(tab_contents_container_);

  // Note that SetTabContents must be called after AddChildView is called
  tab_contents_container_->ChangeTabContents(tab_contents_);

  NavigationController* controller = &tab_contents_->controller();
  registrar_.Add(this, NotificationType::NAV_ENTRY_COMMITTED,
                 Source<NavigationController>(controller));
  registrar_.Add(this, NotificationType::FAIL_PROVISIONAL_LOAD_WITH_ERROR,
                 Source<NavigationController>(controller));
  registrar_.Add(this, NotificationType::LOAD_STOP,
                 Source<NavigationController>(controller));
  NotificationService::current()->Notify(
      NotificationType::EXTERNAL_TAB_CREATED,
      Source<NavigationController>(controller),
      NotificationService::NoDetails());

  // We need WS_POPUP to be on the window during initialization, but
  // once initialized we apply the requested style which may or may not
  // include the popup bit.
  // Note that it's important to do this before we call SetParent since
  // during the SetParent call we will otherwise get a WA_ACTIVATE call
  // that causes us to steal the current focus.
  SetWindowLong(GWL_STYLE, (GetWindowLong(GWL_STYLE) & ~WS_POPUP) | style);

  // Now apply the parenting and style
  if (parent)
    SetParent(GetNativeView(), parent);

  ::ShowWindow(tab_contents_->GetNativeView(), SW_SHOWNA);
  return true;
}

void ExternalTabContainer::SetAccelerators(HACCEL accel_table,
                                           int accel_table_entry_count) {
  external_accel_table_ = accel_table;
  external_accel_entry_count_ = accel_table_entry_count;
}

void ExternalTabContainer::ProcessUnhandledAccelerator(const MSG& msg) {
  // We just received an accelerator key that we had sent to external host
  // back. Since the external host was not interested in handling this, we
  // need to dispatch this message as if we had just peeked this out. (we
  // also need to call TranslateMessage to generate a WM_CHAR if needed).
  TranslateMessage(&msg);
  DispatchMessage(&msg);
}

void ExternalTabContainer::SetInitialFocus(bool reverse) {
  DCHECK(tab_contents_);
  if (tab_contents_) {
    static_cast<TabContents*>(tab_contents_)->Focus();
    static_cast<TabContents*>(tab_contents_)->SetInitialFocus(reverse);
  }
}

// static
bool ExternalTabContainer::IsExternalTabContainer(HWND window) {
  if (GetProp(window, kWindowObjectKey) != NULL)
    return true;

  return false;
}

// static
ExternalTabContainer* ExternalTabContainer::GetContainerForTab(
    HWND tab_window) {
  HWND parent_window = ::GetParent(tab_window);
  if (!::IsWindow(parent_window)) {
    return NULL;
  }
  if (!IsExternalTabContainer(parent_window)) {
    return NULL;
  }
  ExternalTabContainer* container = reinterpret_cast<ExternalTabContainer*>(
      GetProp(parent_window, kWindowObjectKey));
  return container;
}

////////////////////////////////////////////////////////////////////////////////
// ExternalTabContainer, TabContentsDelegate implementation:

void ExternalTabContainer::OpenURLFromTab(TabContents* source,
                           const GURL& url,
                           const GURL& referrer,
                           WindowOpenDisposition disposition,
                           PageTransition::Type transition) {
  switch (disposition) {
    case CURRENT_TAB:
    case SINGLETON_TAB:
    case NEW_FOREGROUND_TAB:
    case NEW_BACKGROUND_TAB:
    case NEW_WINDOW:
      if (automation_) {
        automation_->Send(new AutomationMsg_OpenURL(0, tab_handle_,
                                                    url, disposition));
      }
      break;
    default:
      break;
  }
}

void ExternalTabContainer::NavigationStateChanged(const TabContents* source,
                                                  unsigned changed_flags) {
  if (automation_) {
    automation_->Send(new AutomationMsg_NavigationStateChanged(0, tab_handle_,
                                                               changed_flags));
  }
}

void ExternalTabContainer::AddNewContents(TabContents* source,
                            TabContents* new_contents,
                            WindowOpenDisposition disposition,
                            const gfx::Rect& initial_pos,
                            bool user_gesture) {
  if (disposition == NEW_POPUP || disposition == NEW_WINDOW ||
      disposition == NEW_FOREGROUND_TAB || disposition == NEW_BACKGROUND_TAB) {
    Browser::BuildPopupWindowHelper(source, new_contents, initial_pos,
                                    Browser::TYPE_POPUP,
                                    tab_contents_->profile(), true);
  } else {
    NOTREACHED();
  }
}

void ExternalTabContainer::ActivateContents(TabContents* contents) {
}

void ExternalTabContainer::LoadingStateChanged(TabContents* source) {
}

void ExternalTabContainer::CloseContents(TabContents* source) {
}

void ExternalTabContainer::MoveContents(TabContents* source,
                                        const gfx::Rect& pos) {
}

bool ExternalTabContainer::IsPopup(TabContents* source) {
  return false;
}

void ExternalTabContainer::URLStarredChanged(TabContents* source,
                                             bool starred) {
}

void ExternalTabContainer::UpdateTargetURL(TabContents* source,
                                           const GURL& url) {
  if (automation_) {
    std::wstring url_string = CA2W(url.spec().c_str());
    automation_->Send(
        new AutomationMsg_UpdateTargetUrl(0, tab_handle_, url_string));
  }
}

void ExternalTabContainer::ContentsZoomChange(bool zoom_in) {
}

void ExternalTabContainer::ToolbarSizeChanged(TabContents* source,
                                              bool finished) {
}

void ExternalTabContainer::ForwardMessageToExternalHost(
    const std::string& message, const std::string& origin,
    const std::string& target) {
  if (automation_) {
    automation_->Send(
        new AutomationMsg_ForwardMessageToExternalHost(0, tab_handle_,
            message, origin, target));
  }
}

ExtensionFunctionDispatcher* ExternalTabContainer::
    CreateExtensionFunctionDispatcher(RenderViewHost* render_view_host,
                                      const std::string& extension_id) {
  return new ExtensionFunctionDispatcher(render_view_host, NULL, extension_id);
}

bool ExternalTabContainer::TakeFocus(bool reverse) {
  if (automation_) {
    views::FocusManager* focus_manager =
        views::FocusManager::GetFocusManager(GetNativeView());
    DCHECK(focus_manager);
    if (focus_manager) {
      focus_manager->ClearFocus();
      automation_->Send(new AutomationMsg_TabbedOut(0, tab_handle_,
          win_util::IsShiftPressed()));
    }
  }

  return true;
}

////////////////////////////////////////////////////////////////////////////////
// ExternalTabContainer, NotificationObserver implementation:

void ExternalTabContainer::Observe(NotificationType type,
                                   const NotificationSource& source,
                                   const NotificationDetails& details) {
  if (!automation_)
    return;

  static const int kHttpClientErrorStart = 400;
  static const int kHttpServerErrorEnd = 510;

  switch (type.value) {
    case NotificationType::LOAD_STOP: {
        const LoadNotificationDetails* load =
            Details<LoadNotificationDetails>(details).ptr();
        if (load != NULL && PageTransition::IsMainFrame(load->origin())) {
          automation_->Send(new AutomationMsg_TabLoaded(0, tab_handle_,
                                                        load->url()));
        }
        break;
      }
    case NotificationType::NAV_ENTRY_COMMITTED: {
        if (ignore_next_load_notification_) {
          ignore_next_load_notification_ = false;
          return;
        }

        const NavigationController::LoadCommittedDetails* commit =
            Details<NavigationController::LoadCommittedDetails>(details).ptr();

        if (commit->http_status_code >= kHttpClientErrorStart &&
            commit->http_status_code <= kHttpServerErrorEnd) {
          automation_->Send(new AutomationMsg_NavigationFailed(
              0, tab_handle_, commit->http_status_code, commit->entry->url()));

          ignore_next_load_notification_ = true;
        } else {
          // When the previous entry index is invalid, it will be -1, which
          // will still make the computation come out right (navigating to the
          // 0th entry will be +1).
          automation_->Send(new AutomationMsg_DidNavigate(
              0, tab_handle_, commit->type,
              commit->previous_entry_index -
                  tab_contents_->controller().last_committed_entry_index(),
              commit->entry->url()));
        }
        break;
      }
    case NotificationType::FAIL_PROVISIONAL_LOAD_WITH_ERROR: {
      const ProvisionalLoadDetails* load_details =
          Details<ProvisionalLoadDetails>(details).ptr();
      automation_->Send(new AutomationMsg_NavigationFailed(
          0, tab_handle_, load_details->error_code(), load_details->url()));

      ignore_next_load_notification_ = true;
      break;
    }
    default:
      NOTREACHED();
  }
}

////////////////////////////////////////////////////////////////////////////////
// ExternalTabContainer, views::WidgetWin overrides:

void ExternalTabContainer::OnDestroy() {
  Uninitialize(GetNativeView());
  WidgetWin::OnDestroy();
}

////////////////////////////////////////////////////////////////////////////////
// ExternalTabContainer, views::KeystrokeListener implementation:

bool ExternalTabContainer::ProcessKeyStroke(HWND window, UINT message,
                                            WPARAM wparam, LPARAM lparam) {
  if (!automation_) {
    return false;
  }
  if ((wparam == VK_TAB) && !win_util::IsCtrlPressed()) {
    // Tabs are handled separately (except if this is Ctrl-Tab or
    // Ctrl-Shift-Tab)
    return false;
  }

  unsigned int flags = HIWORD(lparam);
  bool alt = (flags & KF_ALTDOWN) != 0;
  if (!alt && (message == WM_SYSKEYUP || message == WM_KEYUP)) {
    // In case the Alt key is being released.
    alt = (wparam == VK_MENU);
  }

  if ((flags & KF_EXTENDED) || alt || (wparam >= VK_F1 && wparam <= VK_F24) ||
      wparam == VK_ESCAPE || wparam == VK_RETURN ||
      win_util::IsShiftPressed() || win_util::IsCtrlPressed()) {
    // If this is an extended key or if one or more of Alt, Shift and Control
    // are pressed, this might be an accelerator that the external host wants
    // to handle. If the host does not handle this accelerator, it will reflect
    // the accelerator back to us via the ProcessUnhandledAccelerator method.
    MSG msg = {0};
    msg.hwnd = window;
    msg.message = message;
    msg.wParam = wparam;
    msg.lParam = lparam;
    automation_->Send(new AutomationMsg_HandleAccelerator(0, tab_handle_, msg));
    return true;
  }

  return false;
}

////////////////////////////////////////////////////////////////////////////////
// ExternalTabContainer, private:

void ExternalTabContainer::Uninitialize(HWND window) {
  if (::IsWindow(window)) {
    views::FocusManager* focus_manager =
        views::FocusManager::GetFocusManager(window);
    if (focus_manager)
      focus_manager->RemoveKeystrokeListener(this);
  }

  if (tab_contents_) {
    NotificationService::current()->Notify(
        NotificationType::EXTERNAL_TAB_CLOSED,
        Source<NavigationController>(&tab_contents_->controller()),
        Details<ExternalTabContainer>(this));

    delete tab_contents_;
    tab_contents_ = NULL;
  }
}

<commit_msg>Rollin' back 17315. Looks to be breaking OpenPopupWindowWithPlugin in the UI Test on the builder.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/external_tab_container.h"

#include "app/win_util.h"
#include "base/logging.h"
#include "base/win_util.h"
#include "chrome/browser/automation/automation_provider.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/extensions/extension_function_dispatcher.h"
#include "chrome/browser/load_notification_details.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/tab_contents/provisional_load_details.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/views/tab_contents/tab_contents_container.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/notification_service.h"
#include "chrome/test/automation/automation_messages.h"

static const wchar_t kWindowObjectKey[] = L"ChromeWindowObject";

// TODO(sanjeevr): The external_accel_table_ and external_accel_entry_count_
// member variables are now obsolete and we don't use them.
// We need to remove them.
ExternalTabContainer::ExternalTabContainer(
    AutomationProvider* automation)
    : automation_(automation),
      tab_contents_(NULL),
      external_accel_table_(NULL),
      external_accel_entry_count_(0),
      tab_contents_container_(NULL),
      tab_handle_(0),
      ignore_next_load_notification_(false) {
}

ExternalTabContainer::~ExternalTabContainer() {
  Uninitialize(GetNativeView());
}

bool ExternalTabContainer::Init(Profile* profile,
                                HWND parent,
                                const gfx::Rect& bounds,
                                DWORD style) {
  if (IsWindow()) {
    NOTREACHED();
    return false;
  }

  set_window_style(WS_POPUP);
  views::WidgetWin::Init(NULL, bounds, true);
  if (!IsWindow()) {
    NOTREACHED();
    return false;
  }

  // We don't ever remove the prop because the lifetime of this object
  // is the same as the lifetime of the window
  SetProp(GetNativeView(), kWindowObjectKey, this);

  views::FocusManager* focus_manager =
      views::FocusManager::GetFocusManager(GetNativeView());
  focus_manager->AddKeystrokeListener(this);

  tab_contents_ = new TabContents(profile, NULL, MSG_ROUTING_NONE, NULL);
  tab_contents_->set_delegate(this);
  tab_contents_->render_view_host()->AllowExternalHostBindings();

  // Create a TabContentsContainer to handle focus cycling using Tab and
  // Shift-Tab.
  tab_contents_container_ = new TabContentsContainer;
  SetContentsView(tab_contents_container_);

  // Note that SetTabContents must be called after AddChildView is called
  tab_contents_container_->ChangeTabContents(tab_contents_);

  NavigationController* controller = &tab_contents_->controller();
  registrar_.Add(this, NotificationType::NAV_ENTRY_COMMITTED,
                 Source<NavigationController>(controller));
  registrar_.Add(this, NotificationType::FAIL_PROVISIONAL_LOAD_WITH_ERROR,
                 Source<NavigationController>(controller));
  registrar_.Add(this, NotificationType::LOAD_STOP,
                 Source<NavigationController>(controller));
  NotificationService::current()->Notify(
      NotificationType::EXTERNAL_TAB_CREATED,
      Source<NavigationController>(controller),
      NotificationService::NoDetails());

  // We need WS_POPUP to be on the window during initialization, but
  // once initialized we apply the requested style which may or may not
  // include the popup bit.
  // Note that it's important to do this before we call SetParent since
  // during the SetParent call we will otherwise get a WA_ACTIVATE call
  // that causes us to steal the current focus.
  SetWindowLong(GWL_STYLE, (GetWindowLong(GWL_STYLE) & ~WS_POPUP) | style);

  // Now apply the parenting and style
  if (parent)
    SetParent(GetNativeView(), parent);

  ::ShowWindow(tab_contents_->GetNativeView(), SW_SHOWNA);
  return true;
}

void ExternalTabContainer::SetAccelerators(HACCEL accel_table,
                                           int accel_table_entry_count) {
  external_accel_table_ = accel_table;
  external_accel_entry_count_ = accel_table_entry_count;
}

void ExternalTabContainer::ProcessUnhandledAccelerator(const MSG& msg) {
  // We just received an accelerator key that we had sent to external host
  // back. Since the external host was not interested in handling this, we
  // need to dispatch this message as if we had just peeked this out. (we
  // also need to call TranslateMessage to generate a WM_CHAR if needed).
  TranslateMessage(&msg);
  DispatchMessage(&msg);
}

void ExternalTabContainer::SetInitialFocus(bool reverse) {
  DCHECK(tab_contents_);
  if (tab_contents_) {
    static_cast<TabContents*>(tab_contents_)->Focus();
    static_cast<TabContents*>(tab_contents_)->SetInitialFocus(reverse);
  }
}

// static
bool ExternalTabContainer::IsExternalTabContainer(HWND window) {
  if (GetProp(window, kWindowObjectKey) != NULL)
    return true;

  return false;
}

// static
ExternalTabContainer* ExternalTabContainer::GetContainerForTab(
    HWND tab_window) {
  HWND parent_window = ::GetParent(tab_window);
  if (!::IsWindow(parent_window)) {
    return NULL;
  }
  if (!IsExternalTabContainer(parent_window)) {
    return NULL;
  }
  ExternalTabContainer* container = reinterpret_cast<ExternalTabContainer*>(
      GetProp(parent_window, kWindowObjectKey));
  return container;
}

////////////////////////////////////////////////////////////////////////////////
// ExternalTabContainer, TabContentsDelegate implementation:

void ExternalTabContainer::OpenURLFromTab(TabContents* source,
                           const GURL& url,
                           const GURL& referrer,
                           WindowOpenDisposition disposition,
                           PageTransition::Type transition) {
  switch (disposition) {
    case CURRENT_TAB:
    case SINGLETON_TAB:
    case NEW_FOREGROUND_TAB:
    case NEW_BACKGROUND_TAB:
    case NEW_WINDOW:
      if (automation_) {
        automation_->Send(new AutomationMsg_OpenURL(0, tab_handle_,
                                                    url, disposition));
      }
      break;
    default:
      break;
  }
}

void ExternalTabContainer::NavigationStateChanged(const TabContents* source,
                                                  unsigned changed_flags) {
  if (automation_) {
    automation_->Send(new AutomationMsg_NavigationStateChanged(0, tab_handle_,
                                                               changed_flags));
  }
}

void ExternalTabContainer::AddNewContents(TabContents* source,
                            TabContents* new_contents,
                            WindowOpenDisposition disposition,
                            const gfx::Rect& initial_pos,
                            bool user_gesture) {
  if (disposition == NEW_POPUP || disposition == NEW_WINDOW) {
    Browser::BuildPopupWindowHelper(source, new_contents, initial_pos,
                                    Browser::TYPE_POPUP,
                                    tab_contents_->profile(), true);
  } else {
    NOTREACHED();
  }
}

void ExternalTabContainer::ActivateContents(TabContents* contents) {
}

void ExternalTabContainer::LoadingStateChanged(TabContents* source) {
}

void ExternalTabContainer::CloseContents(TabContents* source) {
}

void ExternalTabContainer::MoveContents(TabContents* source,
                                        const gfx::Rect& pos) {
}

bool ExternalTabContainer::IsPopup(TabContents* source) {
  return false;
}

void ExternalTabContainer::URLStarredChanged(TabContents* source,
                                             bool starred) {
}

void ExternalTabContainer::UpdateTargetURL(TabContents* source,
                                           const GURL& url) {
  if (automation_) {
    std::wstring url_string = CA2W(url.spec().c_str());
    automation_->Send(
        new AutomationMsg_UpdateTargetUrl(0, tab_handle_, url_string));
  }
}

void ExternalTabContainer::ContentsZoomChange(bool zoom_in) {
}

void ExternalTabContainer::ToolbarSizeChanged(TabContents* source,
                                              bool finished) {
}

void ExternalTabContainer::ForwardMessageToExternalHost(
    const std::string& message, const std::string& origin,
    const std::string& target) {
  if(automation_) {
    automation_->Send(
        new AutomationMsg_ForwardMessageToExternalHost(0, tab_handle_,
            message, origin, target));
  }
}

ExtensionFunctionDispatcher* ExternalTabContainer::
    CreateExtensionFunctionDispatcher(RenderViewHost* render_view_host,
                                      const std::string& extension_id) {
  return new ExtensionFunctionDispatcher(render_view_host, NULL, extension_id);
}

bool ExternalTabContainer::TakeFocus(bool reverse) {
  if (automation_) {
    views::FocusManager* focus_manager =
        views::FocusManager::GetFocusManager(GetNativeView());
    DCHECK(focus_manager);
    if (focus_manager) {
      focus_manager->ClearFocus();
      automation_->Send(new AutomationMsg_TabbedOut(0, tab_handle_,
          win_util::IsShiftPressed()));
    }
  }

  return true;
}

////////////////////////////////////////////////////////////////////////////////
// ExternalTabContainer, NotificationObserver implementation:

void ExternalTabContainer::Observe(NotificationType type,
                                   const NotificationSource& source,
                                   const NotificationDetails& details) {
  if (!automation_)
    return;

  static const int kHttpClientErrorStart = 400;
  static const int kHttpServerErrorEnd = 510;

  switch (type.value) {
    case NotificationType::LOAD_STOP: {
        const LoadNotificationDetails* load =
            Details<LoadNotificationDetails>(details).ptr();
        if (load != NULL && PageTransition::IsMainFrame(load->origin())) {
          automation_->Send(new AutomationMsg_TabLoaded(0, tab_handle_,
                                                        load->url()));
        }
        break;
      }
    case NotificationType::NAV_ENTRY_COMMITTED: {
        if (ignore_next_load_notification_) {
          ignore_next_load_notification_ = false;
          return;
        }

        const NavigationController::LoadCommittedDetails* commit =
            Details<NavigationController::LoadCommittedDetails>(details).ptr();

        if (commit->http_status_code >= kHttpClientErrorStart &&
            commit->http_status_code <= kHttpServerErrorEnd) {
          automation_->Send(new AutomationMsg_NavigationFailed(
              0, tab_handle_, commit->http_status_code, commit->entry->url()));

          ignore_next_load_notification_ = true;
        } else {
          // When the previous entry index is invalid, it will be -1, which
          // will still make the computation come out right (navigating to the
          // 0th entry will be +1).
          automation_->Send(new AutomationMsg_DidNavigate(
              0, tab_handle_, commit->type,
              commit->previous_entry_index -
                  tab_contents_->controller().last_committed_entry_index(),
              commit->entry->url()));
        }
        break;
      }
    case NotificationType::FAIL_PROVISIONAL_LOAD_WITH_ERROR: {
      const ProvisionalLoadDetails* load_details =
          Details<ProvisionalLoadDetails>(details).ptr();
      automation_->Send(new AutomationMsg_NavigationFailed(
          0, tab_handle_, load_details->error_code(), load_details->url()));

      ignore_next_load_notification_ = true;
      break;
    }
    default:
      NOTREACHED();
  }
}

////////////////////////////////////////////////////////////////////////////////
// ExternalTabContainer, views::WidgetWin overrides:

void ExternalTabContainer::OnDestroy() {
  Uninitialize(GetNativeView());
  WidgetWin::OnDestroy();
}

////////////////////////////////////////////////////////////////////////////////
// ExternalTabContainer, views::KeystrokeListener implementation:

bool ExternalTabContainer::ProcessKeyStroke(HWND window, UINT message,
                                            WPARAM wparam, LPARAM lparam) {
  if (!automation_) {
    return false;
  }
  if ((wparam == VK_TAB) && !win_util::IsCtrlPressed()) {
    // Tabs are handled separately (except if this is Ctrl-Tab or
    // Ctrl-Shift-Tab)
    return false;
  }

  unsigned int flags = HIWORD(lparam);
  bool alt = (flags & KF_ALTDOWN) != 0;
  if (!alt && (message == WM_SYSKEYUP || message == WM_KEYUP)) {
    // In case the Alt key is being released.
    alt = (wparam == VK_MENU);
  }

  if ((flags & KF_EXTENDED) || alt || (wparam >= VK_F1 && wparam <= VK_F24) ||
      wparam == VK_ESCAPE || wparam == VK_RETURN ||
      win_util::IsShiftPressed() || win_util::IsCtrlPressed()) {
    // If this is an extended key or if one or more of Alt, Shift and Control
    // are pressed, this might be an accelerator that the external host wants
    // to handle. If the host does not handle this accelerator, it will reflect
    // the accelerator back to us via the ProcessUnhandledAccelerator method.
    MSG msg = {0};
    msg.hwnd = window;
    msg.message = message;
    msg.wParam = wparam;
    msg.lParam = lparam;
    automation_->Send(new AutomationMsg_HandleAccelerator(0, tab_handle_, msg));
    return true;
  }

  return false;
}

////////////////////////////////////////////////////////////////////////////////
// ExternalTabContainer, private:

void ExternalTabContainer::Uninitialize(HWND window) {
  if (::IsWindow(window)) {
    views::FocusManager* focus_manager =
        views::FocusManager::GetFocusManager(window);
    if (focus_manager)
      focus_manager->RemoveKeystrokeListener(this);
  }

  if (tab_contents_) {
    NotificationService::current()->Notify(
        NotificationType::EXTERNAL_TAB_CLOSED,
        Source<NavigationController>(&tab_contents_->controller()),
        Details<ExternalTabContainer>(this));

    delete tab_contents_;
    tab_contents_ = NULL;
  }
}

<|endoftext|>


<commit_before>// Copyright (c) 2010 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/history/download_types.h"

DownloadCreateInfo::DownloadCreateInfo(const FilePath& path,
                                       const GURL& url,
                                       base::Time start_time,
                                       int64 received_bytes,
                                       int64 total_bytes,
                                       int32 state,
                                       int32 download_id)
    : path(path),
      url(url),
      path_uniquifier(0),
      start_time(start_time),
      received_bytes(received_bytes),
      total_bytes(total_bytes),
      state(state),
      download_id(download_id),
      child_id(-1),
      render_view_id(-1),
      request_id(-1),
      db_handle(0),
      prompt_user_for_save_location(false),
      is_dangerous(false),
      is_extension_install(false) {
}

DownloadCreateInfo::DownloadCreateInfo()
    : path_uniquifier(0),
      received_bytes(0),
      total_bytes(0),
      state(-1),
      download_id(-1),
      child_id(-1),
      render_view_id(-1),
      request_id(-1),
      db_handle(0),
      prompt_user_for_save_location(false),
      is_dangerous(false),
      is_extension_install(false) {
}

DownloadCreateInfo::~DownloadCreateInfo() {
}
<commit_msg>Removed download_types.cc; no longer used.<commit_after><|endoftext|>


<commit_before>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include "disk_mem_usage_sampler.h"
#include <vespa/vespalib/util/timer.h>
#include <vespa/searchlib/common/lambdatask.h>
#include <experimental/filesystem>
#include <unistd.h>

using search::makeLambdaTask;

namespace proton {

DiskMemUsageSampler::DiskMemUsageSampler(const std::string &protonBaseDir,
                                         const std::string &vespaHomeDir,
                                         const Config &config)
    : _filter(config.hwInfo),
      _protonBaseDir(protonBaseDir),
      _vespaHomeDir(vespaHomeDir),
      _sampleInterval(60.0),
      _periodicTimer()
{
    setConfig(config);
}

DiskMemUsageSampler::~DiskMemUsageSampler()
{
    _periodicTimer.reset();
}

void
DiskMemUsageSampler::setConfig(const Config &config)
{
    _periodicTimer.reset();
    _filter.setConfig(config.filterConfig);
    _sampleInterval = config.sampleInterval;
    sampleUsage();
    _periodicTimer = std::make_unique<vespalib::Timer>();
    _periodicTimer->scheduleAtFixedRate(makeLambdaTask([this]()
                                                       { sampleUsage(); }),
                                        _sampleInterval, _sampleInterval);
}

void
DiskMemUsageSampler::sampleUsage()
{
    sampleMemoryUsage();
    sampleDiskUsage();
}

namespace {

namespace fs = std::experimental::filesystem;

uint64_t
sampleDiskUsageInDirectory(const fs::path &path)
{
    uint64_t result = 0;
    for (const auto &elem : fs::recursive_directory_iterator(path,
                                                             fs::directory_options::skip_permission_denied)) {
        if (fs::is_regular_file(elem.path()) && !fs::is_symlink(elem.path())) {
            result += fs::file_size(elem.path());
        }
    }
    return result;
}

uint64_t
sampleDiskUsageOnFileSystem(const fs::path &path)
{
    auto space_info = fs::space(path);
    return (space_info.capacity - space_info.available);
}

}

void
DiskMemUsageSampler::sampleDiskUsage()
{
    bool slowDisk = _filter.getHwInfo().slowDisk();
    _filter.setDiskStats(slowDisk ? sampleDiskUsageOnFileSystem(_protonBaseDir) :
                         sampleDiskUsageInDirectory(_vespaHomeDir));
}

void
DiskMemUsageSampler::sampleMemoryUsage()
{
    _filter.setMemoryStats(vespalib::ProcessMemoryStats::create());
}

} // namespace proton
<commit_msg>Disable directory scan for now, it causes bad behavior when system believes disk is fast while it is a spinning disk.<commit_after>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include "disk_mem_usage_sampler.h"
#include <vespa/vespalib/util/timer.h>
#include <vespa/searchlib/common/lambdatask.h>
#include <experimental/filesystem>
#include <unistd.h>

using search::makeLambdaTask;

namespace proton {

DiskMemUsageSampler::DiskMemUsageSampler(const std::string &protonBaseDir,
                                         const std::string &vespaHomeDir,
                                         const Config &config)
    : _filter(config.hwInfo),
      _protonBaseDir(protonBaseDir),
      _vespaHomeDir(vespaHomeDir),
      _sampleInterval(60.0),
      _periodicTimer()
{
    setConfig(config);
}

DiskMemUsageSampler::~DiskMemUsageSampler()
{
    _periodicTimer.reset();
}

void
DiskMemUsageSampler::setConfig(const Config &config)
{
    _periodicTimer.reset();
    _filter.setConfig(config.filterConfig);
    _sampleInterval = config.sampleInterval;
    sampleUsage();
    _periodicTimer = std::make_unique<vespalib::Timer>();
    _periodicTimer->scheduleAtFixedRate(makeLambdaTask([this]()
                                                       { sampleUsage(); }),
                                        _sampleInterval, _sampleInterval);
}

void
DiskMemUsageSampler::sampleUsage()
{
    sampleMemoryUsage();
    sampleDiskUsage();
}

namespace {

namespace fs = std::experimental::filesystem;

uint64_t
sampleDiskUsageInDirectory(const fs::path &path)
{
    uint64_t result = 0;
    for (const auto &elem : fs::recursive_directory_iterator(path,
                                                             fs::directory_options::skip_permission_denied)) {
        if (fs::is_regular_file(elem.path()) && !fs::is_symlink(elem.path())) {
            result += fs::file_size(elem.path());
        }
    }
    return result;
}

uint64_t
sampleDiskUsageOnFileSystem(const fs::path &path)
{
    auto space_info = fs::space(path);
    return (space_info.capacity - space_info.available);
}

}

void
DiskMemUsageSampler::sampleDiskUsage()
{
    bool slowDisk = _filter.getHwInfo().slowDisk() || true;
    _filter.setDiskStats(slowDisk ? sampleDiskUsageOnFileSystem(_protonBaseDir) :
                         sampleDiskUsageInDirectory(_vespaHomeDir));
}

void
DiskMemUsageSampler::sampleMemoryUsage()
{
    _filter.setMemoryStats(vespalib::ProcessMemoryStats::create());
}

} // namespace proton
<|endoftext|>


<commit_before>// Copyright (c) 2009 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/views/panel_controller.h"

#include <gdk/gdkx.h>
extern "C" {
#include <X11/Xlib.h>
}

#include "app/resource_bundle.h"
#include "base/logging.h"
#include "base/singleton.h"
#include "base/scoped_ptr.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/gtk/browser_window_gtk.h"
#include "chrome/browser/views/tabs/tab_overview_types.h"
#include "chrome/common/x11_util.h"
#include "grit/app_resources.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "views/controls/button/image_button.h"
#include "views/controls/label.h"
#include "views/event.h"
#include "views/view.h"
#include "views/widget/widget_gtk.h"

static int close_button_width;
static int close_button_height;
static SkBitmap* close_button_n;
static SkBitmap* close_button_h;
static SkBitmap* close_button_p;
static gfx::Font* title_font = NULL;

namespace {

const int kTitleWidth = 200;
const int kTitleHeight = 24;
const int kTitlePad = 8;
const int kButtonPad = 8;

static bool resources_initialized;
static void InitializeResources() {
  if (resources_initialized) {
    return;
  }

  resources_initialized = true;
  ResourceBundle& rb = ResourceBundle::GetSharedInstance();
  title_font = new gfx::Font(rb.GetFont(ResourceBundle::BaseFont));
  close_button_n = rb.GetBitmapNamed(IDR_TAB_CLOSE);
  close_button_h = rb.GetBitmapNamed(IDR_TAB_CLOSE_H);
  close_button_p = rb.GetBitmapNamed(IDR_TAB_CLOSE_P);
  close_button_width = close_button_n->width();
  close_button_height = close_button_n->height();
}

}  // namespace

PanelController::PanelController(BrowserWindowGtk* browser_window)
    :  browser_window_(browser_window),
       panel_(browser_window->window()),
       panel_xid_(x11_util::GetX11WindowFromGtkWidget(GTK_WIDGET(panel_))),
       expanded_(true),
       mouse_down_(false),
       dragging_(false) {
  title_window_ = new views::WidgetGtk(views::WidgetGtk::TYPE_WINDOW);
  gfx::Rect title_bounds(
      0, 0, browser_window->GetNormalBounds().width(), kTitleHeight);
  title_window_->Init(NULL, title_bounds);
  title_ = title_window_->GetNativeView();
  title_xid_ = x11_util::GetX11WindowFromGtkWidget(title_);

  TabOverviewTypes* tab_overview = TabOverviewTypes::instance();
  tab_overview->SetWindowType(
      title_,
      TabOverviewTypes::WINDOW_TYPE_CHROME_PANEL_TITLEBAR,
      NULL);
  std::vector<int> type_params;
  type_params.push_back(title_xid_);
  type_params.push_back(expanded_ ? 1 : 0);
  tab_overview->SetWindowType(
      GTK_WIDGET(panel_),
      TabOverviewTypes::WINDOW_TYPE_CHROME_PANEL,
      &type_params);

  g_signal_connect(
      panel_, "client-event", G_CALLBACK(OnPanelClientEvent), this);

  title_content_ = new TitleContentView(this);
  title_window_->SetContentsView(title_content_);
  title_window_->Show();
}

void PanelController::UpdateTitleBar() {
  title_content_->title_label()->SetText(
      browser_window_->browser()->GetCurrentPageTitle());
}

bool PanelController::TitleMousePressed(const views::MouseEvent& event) {
  if (!event.IsOnlyLeftMouseButton()) {
    return false;
  }
  gfx::Point abs_location = event.location();
  views::View::ConvertPointToScreen(title_content_, &abs_location);
  mouse_down_ = true;
  mouse_down_abs_x_ = abs_location.x();
  mouse_down_abs_y_ = abs_location.y();
  mouse_down_offset_x_ = event.x();
  mouse_down_offset_y_ = event.y();
  dragging_ = false;
  return true;
}

void PanelController::TitleMouseReleased(
    const views::MouseEvent& event, bool canceled) {
  if (!event.IsOnlyLeftMouseButton()) {
    return;
  }
  // Only handle clicks that started in our window.
  if (!mouse_down_) {
    return;
  }

  mouse_down_ = false;
  if (!dragging_) {
    TabOverviewTypes::Message msg(
        TabOverviewTypes::Message::WM_SET_PANEL_STATE);
    msg.set_param(0, panel_xid_);
    msg.set_param(1, expanded_ ? 0 : 1);
    TabOverviewTypes::instance()->SendMessage(msg);
  } else {
    TabOverviewTypes::Message msg(
        TabOverviewTypes::Message::WM_NOTIFY_PANEL_DRAG_COMPLETE);
    msg.set_param(0, panel_xid_);
    TabOverviewTypes::instance()->SendMessage(msg);
    dragging_ = false;
  }
}

bool PanelController::TitleMouseDragged(const views::MouseEvent& event) {
  if (!mouse_down_) {
    return false;
  }

  gfx::Point abs_location = event.location();
  views::View::ConvertPointToScreen(title_content_, &abs_location);
  if (!dragging_) {
    if (views::View::ExceededDragThreshold(
        abs_location.x() - mouse_down_abs_x_,
        abs_location.y() - mouse_down_abs_y_)) {
      dragging_ = true;
    }
  }
  if (dragging_) {
    TabOverviewTypes::Message msg(TabOverviewTypes::Message::WM_MOVE_PANEL);
    msg.set_param(0, panel_xid_);
    msg.set_param(1, abs_location.x() - mouse_down_offset_x_);
    msg.set_param(2, abs_location.y() - mouse_down_offset_y_);
    TabOverviewTypes::instance()->SendMessage(msg);
  }
  return true;
}

// static
bool PanelController::OnPanelClientEvent(
    GtkWidget* widget,
    GdkEventClient* event,
    PanelController* panel_controller) {
  return panel_controller->PanelClientEvent(event);
}

bool PanelController::PanelClientEvent(GdkEventClient* event) {
  TabOverviewTypes::Message msg;
  TabOverviewTypes::instance()->DecodeMessage(*event, &msg);
  if (msg.type() == TabOverviewTypes::Message::CHROME_NOTIFY_PANEL_STATE) {
    expanded_ = msg.param(0);
  }
  return true;
}

void PanelController::Close() {
  title_window_->Close();
}

void PanelController::ButtonPressed(views::Button* sender) {
  if (sender == title_content_->close_button()) {
    browser_window_->Close();
  }
}

PanelController::TitleContentView::TitleContentView(
    PanelController* panel_controller)
        : panel_controller_(panel_controller) {
  InitializeResources();
  close_button_ = new views::ImageButton(panel_controller_);
  close_button_->SetImage(views::CustomButton::BS_NORMAL, close_button_n);
  close_button_->SetImage(views::CustomButton::BS_HOT, close_button_h);
  close_button_->SetImage(views::CustomButton::BS_PUSHED, close_button_p);
  AddChildView(close_button_);

  title_label_ = new views::Label(std::wstring(), *title_font);
  title_label_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
  AddChildView(title_label_);

  set_background(views::Background::CreateSolidBackground(0xdd, 0xdd, 0xdd, 1));
}

void PanelController::TitleContentView::Layout() {
  close_button_->SetBounds(
      bounds().width() - (close_button_width + kButtonPad),
      (bounds().height() - close_button_height) / 2,
      close_button_width,
      close_button_height);
  title_label_->SetBounds(
      kTitlePad,
      0,
      bounds().width() - (kTitlePad + close_button_width + 2 * kButtonPad),
      bounds().height());
}

bool PanelController::TitleContentView::OnMousePressed(
    const views::MouseEvent& event) {
  return panel_controller_->TitleMousePressed(event);
}

void PanelController::TitleContentView::OnMouseReleased(
    const views::MouseEvent& event, bool canceled) {
  return panel_controller_->TitleMouseReleased(event, canceled);
}

bool PanelController::TitleContentView::OnMouseDragged(
    const views::MouseEvent& event) {
  return panel_controller_->TitleMouseDragged(event);
}

<commit_msg>Fixed compile breakage resulting from wstring to string16 change.<commit_after>// Copyright (c) 2009 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/views/panel_controller.h"

#include <gdk/gdkx.h>
extern "C" {
#include <X11/Xlib.h>
}

#include "app/resource_bundle.h"
#include "base/logging.h"
#include "base/singleton.h"
#include "base/scoped_ptr.h"
#include "base/string_util.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/gtk/browser_window_gtk.h"
#include "chrome/browser/views/tabs/tab_overview_types.h"
#include "chrome/common/x11_util.h"
#include "grit/app_resources.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "views/controls/button/image_button.h"
#include "views/controls/label.h"
#include "views/event.h"
#include "views/view.h"
#include "views/widget/widget_gtk.h"

static int close_button_width;
static int close_button_height;
static SkBitmap* close_button_n;
static SkBitmap* close_button_h;
static SkBitmap* close_button_p;
static gfx::Font* title_font = NULL;

namespace {

const int kTitleWidth = 200;
const int kTitleHeight = 24;
const int kTitlePad = 8;
const int kButtonPad = 8;

static bool resources_initialized;
static void InitializeResources() {
  if (resources_initialized) {
    return;
  }

  resources_initialized = true;
  ResourceBundle& rb = ResourceBundle::GetSharedInstance();
  title_font = new gfx::Font(rb.GetFont(ResourceBundle::BaseFont));
  close_button_n = rb.GetBitmapNamed(IDR_TAB_CLOSE);
  close_button_h = rb.GetBitmapNamed(IDR_TAB_CLOSE_H);
  close_button_p = rb.GetBitmapNamed(IDR_TAB_CLOSE_P);
  close_button_width = close_button_n->width();
  close_button_height = close_button_n->height();
}

}  // namespace

PanelController::PanelController(BrowserWindowGtk* browser_window)
    :  browser_window_(browser_window),
       panel_(browser_window->window()),
       panel_xid_(x11_util::GetX11WindowFromGtkWidget(GTK_WIDGET(panel_))),
       expanded_(true),
       mouse_down_(false),
       dragging_(false) {
  title_window_ = new views::WidgetGtk(views::WidgetGtk::TYPE_WINDOW);
  gfx::Rect title_bounds(
      0, 0, browser_window->GetNormalBounds().width(), kTitleHeight);
  title_window_->Init(NULL, title_bounds);
  title_ = title_window_->GetNativeView();
  title_xid_ = x11_util::GetX11WindowFromGtkWidget(title_);

  TabOverviewTypes* tab_overview = TabOverviewTypes::instance();
  tab_overview->SetWindowType(
      title_,
      TabOverviewTypes::WINDOW_TYPE_CHROME_PANEL_TITLEBAR,
      NULL);
  std::vector<int> type_params;
  type_params.push_back(title_xid_);
  type_params.push_back(expanded_ ? 1 : 0);
  tab_overview->SetWindowType(
      GTK_WIDGET(panel_),
      TabOverviewTypes::WINDOW_TYPE_CHROME_PANEL,
      &type_params);

  g_signal_connect(
      panel_, "client-event", G_CALLBACK(OnPanelClientEvent), this);

  title_content_ = new TitleContentView(this);
  title_window_->SetContentsView(title_content_);
  title_window_->Show();
}

void PanelController::UpdateTitleBar() {
  title_content_->title_label()->SetText(
      UTF16ToWideHack(browser_window_->browser()->GetCurrentPageTitle()));
}

bool PanelController::TitleMousePressed(const views::MouseEvent& event) {
  if (!event.IsOnlyLeftMouseButton()) {
    return false;
  }
  gfx::Point abs_location = event.location();
  views::View::ConvertPointToScreen(title_content_, &abs_location);
  mouse_down_ = true;
  mouse_down_abs_x_ = abs_location.x();
  mouse_down_abs_y_ = abs_location.y();
  mouse_down_offset_x_ = event.x();
  mouse_down_offset_y_ = event.y();
  dragging_ = false;
  return true;
}

void PanelController::TitleMouseReleased(
    const views::MouseEvent& event, bool canceled) {
  if (!event.IsOnlyLeftMouseButton()) {
    return;
  }
  // Only handle clicks that started in our window.
  if (!mouse_down_) {
    return;
  }

  mouse_down_ = false;
  if (!dragging_) {
    TabOverviewTypes::Message msg(
        TabOverviewTypes::Message::WM_SET_PANEL_STATE);
    msg.set_param(0, panel_xid_);
    msg.set_param(1, expanded_ ? 0 : 1);
    TabOverviewTypes::instance()->SendMessage(msg);
  } else {
    TabOverviewTypes::Message msg(
        TabOverviewTypes::Message::WM_NOTIFY_PANEL_DRAG_COMPLETE);
    msg.set_param(0, panel_xid_);
    TabOverviewTypes::instance()->SendMessage(msg);
    dragging_ = false;
  }
}

bool PanelController::TitleMouseDragged(const views::MouseEvent& event) {
  if (!mouse_down_) {
    return false;
  }

  gfx::Point abs_location = event.location();
  views::View::ConvertPointToScreen(title_content_, &abs_location);
  if (!dragging_) {
    if (views::View::ExceededDragThreshold(
        abs_location.x() - mouse_down_abs_x_,
        abs_location.y() - mouse_down_abs_y_)) {
      dragging_ = true;
    }
  }
  if (dragging_) {
    TabOverviewTypes::Message msg(TabOverviewTypes::Message::WM_MOVE_PANEL);
    msg.set_param(0, panel_xid_);
    msg.set_param(1, abs_location.x() - mouse_down_offset_x_);
    msg.set_param(2, abs_location.y() - mouse_down_offset_y_);
    TabOverviewTypes::instance()->SendMessage(msg);
  }
  return true;
}

// static
bool PanelController::OnPanelClientEvent(
    GtkWidget* widget,
    GdkEventClient* event,
    PanelController* panel_controller) {
  return panel_controller->PanelClientEvent(event);
}

bool PanelController::PanelClientEvent(GdkEventClient* event) {
  TabOverviewTypes::Message msg;
  TabOverviewTypes::instance()->DecodeMessage(*event, &msg);
  if (msg.type() == TabOverviewTypes::Message::CHROME_NOTIFY_PANEL_STATE) {
    expanded_ = msg.param(0);
  }
  return true;
}

void PanelController::Close() {
  title_window_->Close();
}

void PanelController::ButtonPressed(views::Button* sender) {
  if (sender == title_content_->close_button()) {
    browser_window_->Close();
  }
}

PanelController::TitleContentView::TitleContentView(
    PanelController* panel_controller)
        : panel_controller_(panel_controller) {
  InitializeResources();
  close_button_ = new views::ImageButton(panel_controller_);
  close_button_->SetImage(views::CustomButton::BS_NORMAL, close_button_n);
  close_button_->SetImage(views::CustomButton::BS_HOT, close_button_h);
  close_button_->SetImage(views::CustomButton::BS_PUSHED, close_button_p);
  AddChildView(close_button_);

  title_label_ = new views::Label(std::wstring(), *title_font);
  title_label_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
  AddChildView(title_label_);

  set_background(views::Background::CreateSolidBackground(0xdd, 0xdd, 0xdd, 1));
}

void PanelController::TitleContentView::Layout() {
  close_button_->SetBounds(
      bounds().width() - (close_button_width + kButtonPad),
      (bounds().height() - close_button_height) / 2,
      close_button_width,
      close_button_height);
  title_label_->SetBounds(
      kTitlePad,
      0,
      bounds().width() - (kTitlePad + close_button_width + 2 * kButtonPad),
      bounds().height());
}

bool PanelController::TitleContentView::OnMousePressed(
    const views::MouseEvent& event) {
  return panel_controller_->TitleMousePressed(event);
}

void PanelController::TitleContentView::OnMouseReleased(
    const views::MouseEvent& event, bool canceled) {
  return panel_controller_->TitleMouseReleased(event, canceled);
}

bool PanelController::TitleContentView::OnMouseDragged(
    const views::MouseEvent& event) {
  return panel_controller_->TitleMouseDragged(event);
}

<|endoftext|>


<commit_before>//------------------------------------------------------------------------------
// Copyright (c) 2016 by contributors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//------------------------------------------------------------------------------

/*
Author: Chao Ma (mctt90@gmail.com)

This file tests the FFMScore class.
*/

#include "gtest/gtest.h"

#include "src/base/common.h"
#include "src/data/data_structure.h"
#include "src/data/hyper_parameters.h"

#include "src/score/score_function.h"
#include "src/score/ffm_score.h"

namespace xLearn {

index_t K = 24;
index_t Kfeat = 3;
index_t kfield = 3;
index_t kLength = Kfeat + 1 + Kfeat*kfield*K;

TEST(FFM_TEST, calc_score) {
  SparseRow row(Kfeat+1, true);
  std::vector<real_t> w(kLength, 1.0);
  // Init SparseRow
  for (index_t i = 1; i <= Kfeat; ++i) {
    row.idx[i] = i;
    row.field[i] = i;
    row.X[i] = 2.0;
  }
  row.idx[0] = 0;   // bias
  row.field[0] = 0;
  row.X[0] = 1.0;
  HyperParam hyper_param;
  hyper_param.num_feature = Kfeat;
  hyper_param.num_K = K;
  hyper_param.num_field = kfield;
  FFMScore score;
  score.Initialize(hyper_param);
  real_t val = score.CalcScore(&row, &w);
  // 7 + 24*4*3 = 295.0
  EXPECT_FLOAT_EQ(val, 295.0);
}

TEST(FFM_TEST, calc_grad) {
  // Reset hyper parameters
  K = 24;
  Kfeat = 100;
  kfield = 100;
  kLength = Kfeat + 1 + Kfeat*kfield*K;
  // Create SparseRow
  SparseRow row(Kfeat+1, true);
  for (index_t i = 0; i < Kfeat+1; ++i) {
    row.idx[i] = i;
    row.X[i] = 2.0;
    row.field[i] = i;
  }
  // Create model
  std::vector<real_t> w(kLength, 3.0);
  // Create updater
  Updater* updater = new Updater();
  HyperParam hyper_param;
  hyper_param.learning_rate = 0.1;
  updater->Initialize(hyper_param);
  // Create score function
  FFMScore score;
  hyper_param.num_feature = Kfeat;
  hyper_param.num_K = K;
  hyper_param.num_field = kfield;
  score.Initialize(hyper_param);
  score.CalcGrad(&row, w, 1.0, updater);
  // Test
  for (index_t i = 0; i < Kfeat+1; ++i) {
    EXPECT_FLOAT_EQ(w[i], 2.8);
  }
  for (index_t i = Kfeat+1; i < kLength; ++i) {
    if (w[i] != 3.0) {
      EXPECT_FLOAT_EQ(w[i], 1.8);
    }
  }
  // Test speed
  int line = 1000;
  for (int i = 0 ; i < line; ++i) {
    score.CalcGrad(&row, w, 1.0, updater);
  }
}

} // namespace xLearn
<commit_msg>update<commit_after>//------------------------------------------------------------------------------
// Copyright (c) 2016 by contributors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//------------------------------------------------------------------------------

/*
Author: Chao Ma (mctt90@gmail.com)

This file tests the FFMScore class.
*/

#include "gtest/gtest.h"

#include "src/base/common.h"
#include "src/data/data_structure.h"
#include "src/data/hyper_parameters.h"

#include "src/score/score_function.h"
#include "src/score/ffm_score.h"

namespace xLearn {

index_t K = 24;
index_t Kfeat = 3;
index_t kfield = 3;
index_t kLength = Kfeat + 1 + Kfeat*kfield*K;

TEST(FFM_TEST, calc_score) {
  SparseRow row(Kfeat+1, true);
  std::vector<real_t> w(kLength, 1.0);
  // Init SparseRow
  for (index_t i = 1; i <= Kfeat; ++i) {
    row.idx[i] = i;
    row.field[i] = i;
    row.X[i] = 2.0;
  }
  row.idx[0] = 0;   // bias
  row.field[0] = 0;
  row.X[0] = 1.0;
  HyperParam hyper_param;
  hyper_param.num_feature = Kfeat;
  hyper_param.num_K = K;
  hyper_param.num_field = kfield;
  FFMScore score;
  score.Initialize(hyper_param);
  real_t val = score.CalcScore(&row, &w);
  // 7 + 24*4*3 = 295.0
  EXPECT_FLOAT_EQ(val, 295.0);
}

TEST(FFM_TEST, calc_grad) {
  // Reset hyper parameters
  K = 24;
  Kfeat = 100;
  kfield = 100;
  kLength = Kfeat + 1 + Kfeat*kfield*K;
  // Create SparseRow
  SparseRow row(Kfeat+1, true);
  for (index_t i = 0; i < Kfeat+1; ++i) {
    row.idx[i] = i;
    row.X[i] = 2.0;
    row.field[i] = i;
  }
  // Create model
  std::vector<real_t> w(kLength, 3.0);
  // Create updater
  Updater* updater = new Updater();
  HyperParam hyper_param;
  hyper_param.learning_rate = 0.1;
  updater->Initialize(hyper_param);
  // Create score function
  FFMScore score;
  hyper_param.num_feature = Kfeat;
  hyper_param.num_K = K;
  hyper_param.num_field = kfield;
  score.Initialize(hyper_param);
  score.CalcGrad(&row, w, 1.0, updater);
  // Test
  for (index_t i = 0; i < Kfeat+1; ++i) {
    EXPECT_FLOAT_EQ(w[i], 2.8);
  }
  for (index_t i = Kfeat+1; i < kLength; ++i) {
    if (w[i] != 3.0) {
      EXPECT_FLOAT_EQ(w[i], 1.8);
    }
  }
}

} // namespace xLearn
<|endoftext|>


<commit_before>//--------------------------------------------------------------------*- C++ -*-
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author:  Axel Naumann <axel@cern.ch>
//------------------------------------------------------------------------------

#include "cling/Interpreter/CIFactory.h"

#include "ChainedConsumer.h"

#include "clang/AST/ASTContext.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Basic/Version.h"
#include "clang/Frontend/TextDiagnosticPrinter.h"
#include "clang/Lex/Pragma.h"
#include "clang/Lex/Preprocessor.h"

#include "llvm/LLVMContext.h"
#include "llvm/Target/TargetOptions.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"

using namespace clang;

namespace cling {
  //
  //  Dummy function so we can use dladdr to find the executable path.
  //
  void locate_cling_executable()
  {
  }

  CompilerInstance* CIFactory::createCI(llvm::StringRef code,
                                        int argc,
                                        const char* const *argv,
                                        const char* llvmdir) {
    return createCI(llvm::MemoryBuffer::getMemBuffer(code), 0, argc, argv, llvmdir);
  }

  CompilerInstance* CIFactory::createCI(llvm::MemoryBuffer* buffer,
                                        PragmaNamespace* Pragma,
                                        int argc,
                                        const char* const *argv,
                                        const char* llvmdir){
    // main's argv[0] is skipped!

    if (!Pragma) {
      Pragma = new PragmaNamespace("cling");
    }

    // Create an instance builder, passing the llvmdir and arguments.
    //
    //  Initialize the llvm library.
    //
    // If not set, exception handling will not be turned on
    llvm::JITExceptionHandling = true;
    llvm::InitializeNativeTarget();
    llvm::InitializeAllAsmPrinters();
    llvm::sys::Path resource_path;
    if (llvmdir) {
      resource_path = llvmdir;
      resource_path.appendComponent("lib");
      resource_path.appendComponent("clang");
      resource_path.appendComponent(CLANG_VERSION_STRING);
    } else {
      // FIXME: The first arg really does need to be argv[0] on FreeBSD.
      //
      // Note: The second arg is not used for Apple, FreeBSD, Linux,
      //       or cygwin, and can only be used on systems which support
      //       the use of dladdr().
      //
      // Note: On linux and cygwin this uses /proc/self/exe to find the path.
      //
      // Note: On Apple it uses _NSGetExecutablePath().
      //
      // Note: On FreeBSD it uses getprogpath().
      //
      // Note: Otherwise it uses dladdr().
      //
      resource_path = CompilerInvocation::GetResourcesPath("cling",
                                       (void*)(intptr_t) locate_cling_executable
                                                           );
    }

    // Create and setup a compiler instance.
    CompilerInstance* CI = new CompilerInstance();
    {
      //
      //  Buffer the error messages while we process
      //  the compiler options.
      //

      // Needed when we call CreateFromArgs
      CI->createDiagnostics(0, 0);
      CompilerInvocation::CreateFromArgs
        (CI->getInvocation(), argv, argv + argc, CI->getDiagnostics());

      // Reset the diagnostics options that came from CreateFromArgs
      DiagnosticOptions& DiagOpts = CI->getDiagnosticOpts();
      DiagOpts.ShowColors = 1;
      DiagnosticConsumer* Client = new TextDiagnosticPrinter(llvm::errs(), DiagOpts);
      CI->createDiagnostics(0, 0, Client);

      // Set the language options, which cling needs
      SetClingCustomLangOpts(CI->getLangOpts());

      if (CI->getHeaderSearchOpts().UseBuiltinIncludes &&
          CI->getHeaderSearchOpts().ResourceDir.empty()) {
        CI->getHeaderSearchOpts().ResourceDir = resource_path.str();
      }
      CI->getInvocation().getPreprocessorOpts().addMacroDef("__CLING__");
      if (CI->getDiagnostics().hasErrorOccurred()) {
        delete CI;
        CI = 0;
        return 0;
      }
    }
    CI->setTarget(TargetInfo::CreateTargetInfo(CI->getDiagnostics(),
                                               CI->getTargetOpts()));
    if (!CI->hasTarget()) {
      delete CI;
      CI = 0;
      return 0;
    }
    CI->getTarget().setForcedLangOptions(CI->getLangOpts());
    SetClingTargetLangOpts(CI->getLangOpts(), CI->getTarget());

    // Set up source and file managers
    CI->createFileManager();
    CI->createSourceManager(CI->getFileManager());

    // Set up the memory buffer
    if (buffer)
      CI->getSourceManager().createMainFileIDForMemBuffer(buffer);

    // Set up the preprocessor
    CI->createPreprocessor();
    Preprocessor& PP = CI->getPreprocessor();
    PP.AddPragmaHandler(Pragma);
    PP.getBuiltinInfo().InitializeBuiltins(PP.getIdentifierTable(),
                                           PP.getLangOptions());
    /*NoBuiltins = */ //true);

    // Set up the ASTContext
    ASTContext *Ctx = new ASTContext(CI->getLangOpts(),
                                     PP.getSourceManager(), &CI->getTarget(), PP.getIdentifierTable(),
                                     PP.getSelectorTable(), PP.getBuiltinInfo(), 0);
    CI->setASTContext(Ctx);
    //CI->getSourceManager().clearIDTables(); //do we really need it?

    // Set up the ASTConsumers
    CI->setASTConsumer(new ChainedConsumer());

    // Set up Sema
    CodeCompleteConsumer* CCC = 0;
    CI->createSema(TU_Prefix, CCC);

    // Set CodeGen options
    // CI->getCodeGenOpts().DebugInfo = 1; // want debug info
    // CI->getCodeGenOpts().EmitDeclMetadata = 1; // For unloading, for later
    CI->getCodeGenOpts().OptimizationLevel = 0; // see pure SSA, that come out
    assert((CI->getCodeGenOpts().VerifyModule = 1) && "When asserts are on, let's also assert the module");
    return CI;
  }

  void CIFactory::SetClingCustomLangOpts(LangOptions& Opts) {
    Opts.EmitAllDecls = 1;
  }

  void CIFactory::SetClingTargetLangOpts(LangOptions& Opts,
                                         const TargetInfo& Target) {
    if (Target.getTriple().getOS() == llvm::Triple::Win32) {
      Opts.MicrosoftExt = 1;
      Opts.MSCVersion = 1300;
      // Should fix http://llvm.org/bugs/show_bug.cgi?id=10528
      Opts.DelayedTemplateParsing = 1;
    }
  }
} // end namespace
<commit_msg>Typo<commit_after>//--------------------------------------------------------------------*- C++ -*-
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author:  Axel Naumann <axel@cern.ch>
//------------------------------------------------------------------------------

#include "cling/Interpreter/CIFactory.h"

#include "ChainedConsumer.h"

#include "clang/AST/ASTContext.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Basic/Version.h"
#include "clang/Frontend/TextDiagnosticPrinter.h"
#include "clang/Lex/Pragma.h"
#include "clang/Lex/Preprocessor.h"

#include "llvm/LLVMContext.h"
#include "llvm/Target/TargetOptions.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"

using namespace clang;

namespace cling {
  //
  //  Dummy function so we can use dladdr to find the executable path.
  //
  void locate_cling_executable()
  {
  }

  CompilerInstance* CIFactory::createCI(llvm::StringRef code,
                                        int argc,
                                        const char* const *argv,
                                        const char* llvmdir) {
    return createCI(llvm::MemoryBuffer::getMemBuffer(code), 0, argc, argv, llvmdir);
  }

  CompilerInstance* CIFactory::createCI(llvm::MemoryBuffer* buffer,
                                        PragmaNamespace* Pragma,
                                        int argc,
                                        const char* const *argv,
                                        const char* llvmdir){
    // main's argv[0] is skipped!

    if (!Pragma) {
      Pragma = new PragmaNamespace("cling");
    }

    // Create an instance builder, passing the llvmdir and arguments.
    //
    //  Initialize the llvm library.
    //
    // If not set, exception handling will not be turned on
    llvm::JITExceptionHandling = true;
    llvm::InitializeNativeTarget();
    llvm::InitializeAllAsmPrinters();
    llvm::sys::Path resource_path;
    if (llvmdir) {
      resource_path = llvmdir;
      resource_path.appendComponent("lib");
      resource_path.appendComponent("clang");
      resource_path.appendComponent(CLANG_VERSION_STRING);
    } else {
      // FIXME: The first arg really does need to be argv[0] on FreeBSD.
      //
      // Note: The second arg is not used for Apple, FreeBSD, Linux,
      //       or cygwin, and can only be used on systems which support
      //       the use of dladdr().
      //
      // Note: On linux and cygwin this uses /proc/self/exe to find the path.
      //
      // Note: On Apple it uses _NSGetExecutablePath().
      //
      // Note: On FreeBSD it uses getprogpath().
      //
      // Note: Otherwise it uses dladdr().
      //
      resource_path = CompilerInvocation::GetResourcesPath("cling",
                                       (void*)(intptr_t) locate_cling_executable
                                                           );
    }

    // Create and setup a compiler instance.
    CompilerInstance* CI = new CompilerInstance();
    {
      //
      //  Buffer the error messages while we process
      //  the compiler options.
      //

      // Needed when we call CreateFromArgs
      CI->createDiagnostics(0, 0);
      CompilerInvocation::CreateFromArgs
        (CI->getInvocation(), argv, argv + argc, CI->getDiagnostics());

      // Reset the diagnostics options that came from CreateFromArgs
      DiagnosticOptions& DiagOpts = CI->getDiagnosticOpts();
      DiagOpts.ShowColors = 1;
      DiagnosticConsumer* Client = new TextDiagnosticPrinter(llvm::errs(), DiagOpts);
      CI->createDiagnostics(0, 0, Client);

      // Set the language options, which cling needs
      SetClingCustomLangOpts(CI->getLangOpts());

      if (CI->getHeaderSearchOpts().UseBuiltinIncludes &&
          CI->getHeaderSearchOpts().ResourceDir.empty()) {
        CI->getHeaderSearchOpts().ResourceDir = resource_path.str();
      }
      CI->getInvocation().getPreprocessorOpts().addMacroDef("__CLING__");
      if (CI->getDiagnostics().hasErrorOccurred()) {
        delete CI;
        CI = 0;
        return 0;
      }
    }
    CI->setTarget(TargetInfo::CreateTargetInfo(CI->getDiagnostics(),
                                               CI->getTargetOpts()));
    if (!CI->hasTarget()) {
      delete CI;
      CI = 0;
      return 0;
    }
    CI->getTarget().setForcedLangOptions(CI->getLangOpts());
    SetClingTargetLangOpts(CI->getLangOpts(), CI->getTarget());

    // Set up source and file managers
    CI->createFileManager();
    CI->createSourceManager(CI->getFileManager());

    // Set up the memory buffer
    if (buffer)
      CI->getSourceManager().createMainFileIDForMemBuffer(buffer);

    // Set up the preprocessor
    CI->createPreprocessor();
    Preprocessor& PP = CI->getPreprocessor();
    PP.AddPragmaHandler(Pragma);
    PP.getBuiltinInfo().InitializeBuiltins(PP.getIdentifierTable(),
                                           PP.getLangOptions());
    /*NoBuiltins = */ //true);

    // Set up the ASTContext
    ASTContext *Ctx = new ASTContext(CI->getLangOpts(),
                                     PP.getSourceManager(), &CI->getTarget(), PP.getIdentifierTable(),
                                     PP.getSelectorTable(), PP.getBuiltinInfo(), 0);
    CI->setASTContext(Ctx);
    //CI->getSourceManager().clearIDTables(); //do we really need it?

    // Set up the ASTConsumers
    CI->setASTConsumer(new ChainedConsumer());

    // Set up Sema
    CodeCompleteConsumer* CCC = 0;
    CI->createSema(TU_Prefix, CCC);

    // Set CodeGen options
    // CI->getCodeGenOpts().DebugInfo = 1; // want debug info
    // CI->getCodeGenOpts().EmitDeclMetadata = 1; // For unloading, for later
    CI->getCodeGenOpts().OptimizationLevel = 0; // see pure SSA, that comes out
    assert((CI->getCodeGenOpts().VerifyModule = 1) && "When asserts are on, let's also assert the module");
    return CI;
  }

  void CIFactory::SetClingCustomLangOpts(LangOptions& Opts) {
    Opts.EmitAllDecls = 1;
  }

  void CIFactory::SetClingTargetLangOpts(LangOptions& Opts,
                                         const TargetInfo& Target) {
    if (Target.getTriple().getOS() == llvm::Triple::Win32) {
      Opts.MicrosoftExt = 1;
      Opts.MSCVersion = 1300;
      // Should fix http://llvm.org/bugs/show_bug.cgi?id=10528
      Opts.DelayedTemplateParsing = 1;
    }
  }
} // end namespace
<|endoftext|>


<commit_before><commit_msg>Adding face orientation heuristic<commit_after><|endoftext|>