<commit_before>#include "stdafx.h"
#include "Util.h"
#include <sys/stat.h>

std::wstring convertUtf8ToWString(const char* source)
{
	std::wstring result;

	int index = 0;
	while (source[index] != 0)
	{
		int extraBytes = 0;
		int value = source[index++];

		if ((value & 0xE0) == 0xC0)
		{
			extraBytes = 1;
			value &= 0x1F;
		} else if ((value & 0xF0) == 0xE0)
		{
			extraBytes = 2;
			value &= 0x0F;
		} else if (value > 0x7F)
		{
			// error
			return std::wstring();
		}

		for (int i = 0; i < extraBytes; i++)
		{
			int b = source[index++];
			if ((b & 0xC0) != 0x80)
			{
			// error
			return std::wstring();
			}

			value = (value << 6) | (b & 0x3F);
		}

		result.push_back(value);
	}

	return result;
}

std::string convertWStringToUtf8(const std::wstring& source)
{
	std::string result;

	for (size_t i = 0; i < source.size(); i++)
	{
		wchar_t character = source[i];
		if (character < 0x80)
		{
			result.push_back(character & 0x7F);
		} else if (character < 0x800)
		{
			result.push_back(0xC0 | (character >> 6) & 0x1F);
			result.push_back(0x80 | (character & 0x3F));
		} else {
			result.push_back(0xE0 | (character >> 12) & 0xF);
			result.push_back(0x80 | ((character >> 6) & 0x3F));
			result.push_back(0x80 | (character & 0x3F));
		}
	}

	return result;
}

std::wstring formatString(const wchar_t* format, ...)
{
	std::wstring result;
	va_list args;

	va_start(args,format);
	int length = _vscwprintf(format,args);
	if (length <= 0) // error
	{
		va_end(args);
		return L"";
	}

	wchar_t* buffer = (wchar_t*) alloca((length+1)*sizeof(wchar_t));
	length = _vsnwprintf(buffer,length+1,format,args);

	if (length >= 0)
		result = buffer;

	va_end(args);
	return result;
}

std::string formatString(const char* format, ...)
{
	std::string result;
	va_list args;

	va_start(args,format);

	int length = _vscprintf(format,args);
	if (length < 0) // error
	{
		va_end(args);
		return "";
	}

	char* buffer = (char*) alloca((length+1)*sizeof(char));
	length = _vsnprintf(buffer,length+1,format,args);

	if (length >= 0)
		result = buffer;

	va_end(args);
	return result;
}

std::wstring intToHexString(unsigned int value, int digits, bool prefix)
{
	std::wstring result;
	result.reserve((digits+prefix) ? 2 : 0);

	if (prefix)
	{
		result.push_back('0');
		result.push_back('x');
	}

	while (digits > 8)
	{
		result.push_back('0');
		digits--;
	}

	wchar_t buf[9];
	swprintf(buf,9,L"%0*X",digits,value);
	result += buf;

	return result;
}

std::wstring intToString(unsigned int value, int digits)
{
	std::wstring result;
	result.reserve(digits);

	while (digits > 8)
	{
		result.push_back(' ');
		digits--;
	}

	wchar_t buf[9];
	swprintf(buf,9,L"%*d",digits,value);
	result += buf;

	return result;
}

StringList getStringListFromArray(wchar_t** source, int count)
{
	StringList result;
	for (int i = 0; i < count; i++)
	{
		result.push_back(std::wstring(source[i]));
	}

	return result;
}

int fileSize(const std::wstring& fileName)
{
	struct _stat fileStat;
	int err = _wstat(fileName.c_str(), &fileStat );
	if (0 != err) return 0;
	return fileStat.st_size;
}

int fileSize(const std::string& fileName)
{
	struct _stat fileStat;
	int err = _stat(fileName.c_str(), &fileStat );
	if (0 != err) return -1;
	return fileStat.st_size;
}

bool fileExists(const std::wstring& strFilename)
{
	struct _stat stFileInfo;
	int intStat = _wstat(strFilename.c_str(),&stFileInfo);
	return intStat == 0;
}

bool fileExists(const std::string& strFilename)
{
	struct _stat stFileInfo;
	int intStat = _stat(strFilename.c_str(),&stFileInfo);
	return intStat == 0;
}

std::wstring toWLowercase(const std::string& str)
{
	std::wstring result;
	for (size_t i = 0; i < str.size(); i++)
	{
		result += tolower(str[i]);
	}

	return result;
}

std::wstring getFileNameFromPath(const std::wstring& path)
{
	int n = path.find_last_of(L"/\\");
	if (n == path.npos)
		return path;
	return path.substr(n);
}
<commit_msg>Remove unused old formatString functions<commit_after>#include "stdafx.h"
#include "Util.h"
#include <sys/stat.h>

std::wstring convertUtf8ToWString(const char* source)
{
	std::wstring result;

	int index = 0;
	while (source[index] != 0)
	{
		int extraBytes = 0;
		int value = source[index++];

		if ((value & 0xE0) == 0xC0)
		{
			extraBytes = 1;
			value &= 0x1F;
		} else if ((value & 0xF0) == 0xE0)
		{
			extraBytes = 2;
			value &= 0x0F;
		} else if (value > 0x7F)
		{
			// error
			return std::wstring();
		}

		for (int i = 0; i < extraBytes; i++)
		{
			int b = source[index++];
			if ((b & 0xC0) != 0x80)
			{
			// error
			return std::wstring();
			}

			value = (value << 6) | (b & 0x3F);
		}

		result.push_back(value);
	}

	return result;
}

std::string convertWStringToUtf8(const std::wstring& source)
{
	std::string result;

	for (size_t i = 0; i < source.size(); i++)
	{
		wchar_t character = source[i];
		if (character < 0x80)
		{
			result.push_back(character & 0x7F);
		} else if (character < 0x800)
		{
			result.push_back(0xC0 | (character >> 6) & 0x1F);
			result.push_back(0x80 | (character & 0x3F));
		} else {
			result.push_back(0xE0 | (character >> 12) & 0xF);
			result.push_back(0x80 | ((character >> 6) & 0x3F));
			result.push_back(0x80 | (character & 0x3F));
		}
	}

	return result;
}

std::wstring intToHexString(unsigned int value, int digits, bool prefix)
{
	std::wstring result;
	result.reserve((digits+prefix) ? 2 : 0);

	if (prefix)
	{
		result.push_back('0');
		result.push_back('x');
	}

	while (digits > 8)
	{
		result.push_back('0');
		digits--;
	}

	wchar_t buf[9];
	swprintf(buf,9,L"%0*X",digits,value);
	result += buf;

	return result;
}

std::wstring intToString(unsigned int value, int digits)
{
	std::wstring result;
	result.reserve(digits);

	while (digits > 8)
	{
		result.push_back(' ');
		digits--;
	}

	wchar_t buf[9];
	swprintf(buf,9,L"%*d",digits,value);
	result += buf;

	return result;
}

StringList getStringListFromArray(wchar_t** source, int count)
{
	StringList result;
	for (int i = 0; i < count; i++)
	{
		result.push_back(std::wstring(source[i]));
	}

	return result;
}

int fileSize(const std::wstring& fileName)
{
	struct _stat fileStat;
	int err = _wstat(fileName.c_str(), &fileStat );
	if (0 != err) return 0;
	return fileStat.st_size;
}

int fileSize(const std::string& fileName)
{
	struct _stat fileStat;
	int err = _stat(fileName.c_str(), &fileStat );
	if (0 != err) return -1;
	return fileStat.st_size;
}

bool fileExists(const std::wstring& strFilename)
{
	struct _stat stFileInfo;
	int intStat = _wstat(strFilename.c_str(),&stFileInfo);
	return intStat == 0;
}

bool fileExists(const std::string& strFilename)
{
	struct _stat stFileInfo;
	int intStat = _stat(strFilename.c_str(),&stFileInfo);
	return intStat == 0;
}

std::wstring toWLowercase(const std::string& str)
{
	std::wstring result;
	for (size_t i = 0; i < str.size(); i++)
	{
		result += tolower(str[i]);
	}

	return result;
}

std::wstring getFileNameFromPath(const std::wstring& path)
{
	int n = path.find_last_of(L"/\\");
	if (n == path.npos)
		return path;
	return path.substr(n);
}
<|endoftext|>


<commit_before>#define BOOST_PYTHON_STATIC_LIB
#include <boost/python.hpp>
#include <boost/python/numpy.hpp>
#include <iostream>
#include <omp.h>

#include "../Neural_Networks.h"

class Neural_Networks_Wrapper {
private:
	vector<Layer*> layer;

	Neural_Networks *NN;
public:
	Neural_Networks_Wrapper() {
		NN = new Neural_Networks();
	}
	Neural_Networks_Wrapper(int time_step) {
		NN = new Neural_Networks(time_step);
	}
	Neural_Networks_Wrapper(string path) {
		NN = new Neural_Networks(path);
	}
	~Neural_Networks_Wrapper() {
		delete NN;
	}

	void Add_Layer(string properties, int number_maps, int map_width = 1, int map_height = 1, int map_depth = 1, int coordinate_y = -1) {
		layer.push_back(NN->Add(new Layer(properties, number_maps, map_width, map_height, map_depth), coordinate_y));
	}
	void Connect(int layer_index, int parent_layer_index, string properties) {
		layer[layer_index]->Connect(layer[parent_layer_index], properties);
	}
	void Initialize(double scale, double gamma = 1) {
		NN->Initialize(scale, gamma);
	}
	void Initialize(int seed, double scale, double gamma = 1) {
		srand(seed);
		NN->Initialize(scale, gamma);
	}
	void Save(string path) {
		NN->Save(path);
	}
	void Set_Number_Threads(int number_threads) {
		omp_set_num_threads(number_threads);
	}
	void Set_Time_Mask(int layer_index, boost::python::object time_mask) {
		Py_buffer time_mask_buffer;

		if (PyObject_GetBuffer(time_mask.ptr(), &time_mask_buffer, PyBUF_SIMPLE) != -1) {
			bool *time_mask = new bool[(layer[layer_index]->time_step) ? (layer[layer_index]->time_step) : (NN->time_step)];

			memcpy(time_mask, static_cast<bool*>(time_mask_buffer.buf), (layer[layer_index]->time_step) ? (layer[layer_index]->time_step) : (NN->time_step));
			layer[layer_index]->Set_Time_Mask(time_mask);

			PyBuffer_Release(&time_mask_buffer);
		}
	}
	void Test(boost::python::object input, boost::python::object output, int _length_data = 0) {
		boost::python::list length_data;

		if (_length_data) {
			length_data.append(_length_data);
		}
		Test(1, input, output, length_data);
	}
	void Test(int batch_size, boost::python::object input, boost::python::object output) {
		boost::python::list length_data;

		Test(batch_size, input, output, length_data);
	}
	void Test(int batch_size, boost::python::object input, boost::python::object output, boost::python::list &_length_data) {
		int *length_data = (len(_length_data)) ? (new int[batch_size]) : (nullptr);

		Py_buffer input_buffer;
		Py_buffer output_buffer;

		if (length_data) {
			for (int h = 0; h < batch_size; h++) {
				length_data[h] = boost::python::extract<int>(_length_data[h]);
			}
		}
		if (PyObject_GetBuffer(input.ptr(), &input_buffer, PyBUF_SIMPLE) != -1 && PyObject_GetBuffer(output.ptr(), &output_buffer, PyBUF_SIMPLE) != -1) {
			float ***input = new float**[NN->layer.front().size()];
			float ***output = new float**[NN->layer.back().size()];

			for (int i = 0, j = 0, index = 0; j < NN->layer[i].size(); j++) {
				input[j] = new float*[batch_size];

				for (int h = 0; h < batch_size; index += ((length_data) ? (length_data[h]) : ((NN->layer[i][j]->time_step) ? (NN->layer[i][j]->time_step) : (NN->time_step))) * NN->layer[i][j]->number_nodes, h++) {
					float *p = static_cast<float*>(input_buffer.buf);

					input[j][h] = &p[index];
				}
			}
			for (int i = NN->layer_height - 1, j = 0, index = 0; j < NN->layer[i].size(); j++) {
				output[j] = new float*[batch_size];

				for (int h = 0; h < batch_size; index += ((length_data) ? (length_data[h]) : ((NN->layer[i][j]->time_step) ? (NN->layer[i][j]->time_step) : (NN->time_step))) * NN->layer[i][j]->number_nodes, h++) {
					float *p = static_cast<float*>(output_buffer.buf);

					output[j][h] = &p[index];
				}
			}
			NN->Test(batch_size, input, output, length_data);

			for (int i = 0, j = 0; j < NN->layer[i].size(); j++) {
				delete[] input[j];
			}
			for (int i = NN->layer_height - 1, j = 0; j < NN->layer[i].size(); j++) {
				delete[] output[j];
			}
			delete[] input;
			delete[] output;

			PyBuffer_Release(&input_buffer);
			PyBuffer_Release(&output_buffer);
		}
		if (length_data) {
			delete[] length_data;
		}
	}

	double Train_CTC(int batch_size, int number_training, boost::python::object input, boost::python::list &reference, double learning_rate, double epsilon = 0, double noise_standard_deviation = 0) {
		boost::python::list length_data;

		boost::python::object target_output;

		return Train(batch_size, number_training, length_data, input, target_output, reference, learning_rate, epsilon, noise_standard_deviation);
	}
	double Train_CTC(int batch_size, int number_training, boost::python::list &length_data, boost::python::object input, boost::python::list &reference, double learning_rate, double epsilon = 0, double noise_standard_deviation = 0) {
		boost::python::object target_output;

		return Train(batch_size, number_training, length_data, input, target_output, reference, learning_rate, epsilon, noise_standard_deviation);
	}
	double Train(int batch_size, int number_training, boost::python::object input, boost::python::object target_output, double learning_rate, double epsilon = 0, double noise_standard_deviation = 0) {
		boost::python::list length_data;
		boost::python::list reference;

		return Train(batch_size, number_training, length_data, input, target_output, reference, learning_rate, epsilon, noise_standard_deviation);
	}
	double Train(int batch_size, int number_training, boost::python::list &length_data, boost::python::object input, boost::python::object target_output, double learning_rate, double epsilon = 0, double noise_standard_deviation = 0) {
		boost::python::list reference;

		return Train(batch_size, number_training, length_data, input, target_output, reference, learning_rate, epsilon, noise_standard_deviation);
	}
	double Train(int batch_size, int number_training, boost::python::list &_length_data, boost::python::object input, boost::python::object target_output, boost::python::list &_reference, double learning_rate, double epsilon = 0, double noise_standard_deviation = 0) {
		int *length_data = (len(_length_data)) ? (new int[number_training]) : (nullptr);

		double loss;

		vector<string> *reference = (len(_reference)) ? (new vector<string>[number_training]) : (nullptr);

		Py_buffer input_buffer;
		Py_buffer target_output_buffer;

		if (length_data) {
			for (int h = 0; h < number_training; h++) {
				length_data[h] = boost::python::extract<int>(_length_data[h]);
			}
		}
		if (reference) {
			for (int h = 0; h < number_training; h++) {
				for (int j = 0; j < len(_reference[h]); j++) {
					reference[h].push_back(boost::python::extract<string>(_reference[h][j]));
				}
			}
		}
		if (PyObject_GetBuffer(input.ptr(), &input_buffer, PyBUF_SIMPLE) != -1 && PyObject_GetBuffer(target_output.ptr(), &target_output_buffer, PyBUF_SIMPLE) != -1) {
			float ***input = new float**[NN->layer.front().size()];
			float ***target_output = new float**[NN->layer.back().size()];

			for (int i = 0, j = 0, index = 0; j < NN->layer[i].size(); j++) {
				input[j] = new float*[number_training];

				for (int h = 0; h < number_training; index += ((length_data) ? (length_data[h]) : ((NN->layer[i][j]->time_step) ? (NN->layer[i][j]->time_step) : (NN->time_step))) * NN->layer[i][j]->number_nodes, h++) {
					float *p = static_cast<float*>(input_buffer.buf);

					input[j][h] = &p[index];
				}
			}
			for (int i = NN->layer_height - 1, j = 0, index = 0; j < NN->layer[i].size(); j++) {
				target_output[j] = new float*[number_training];

				for (int h = 0; h < number_training; index += ((length_data) ? (length_data[h]) : ((NN->layer[i][j]->time_step) ? (NN->layer[i][j]->time_step) : (NN->time_step))) * NN->layer[i][j]->number_nodes, h++) {
					float *p = static_cast<float*>(target_output_buffer.buf);

					target_output[j][h] = &p[index];
				}
			}
			loss = NN->Train(batch_size, number_training, length_data, input, target_output, reference, learning_rate, epsilon, noise_standard_deviation);

			for (int i = 0, j = 0; j < NN->layer[i].size(); j++) {
				delete[] input[j];
			}
			for (int i = NN->layer_height - 1, j = 0; j < NN->layer[i].size(); j++) {
				delete[] target_output[j];
			}
			delete[] input;
			delete[] target_output;

			PyBuffer_Release(&input_buffer);
			PyBuffer_Release(&target_output_buffer);
		}
		if (length_data) {
			delete[] length_data;
		}
		if (reference) {
			delete[] reference;
		}
		return loss;
	}
};

BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(Add_Layer, Neural_Networks_Wrapper::Add_Layer, 2, 6);
BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(Initialize1, Neural_Networks_Wrapper::Initialize, 1, 2);
BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(Initialize2, Neural_Networks_Wrapper::Initialize, 2, 3);
BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(Test, Neural_Networks_Wrapper::Test, 2, 3);
BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(Train_CTC1, Neural_Networks_Wrapper::Train_CTC, 5, 7);
BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(Train_CTC2, Neural_Networks_Wrapper::Train_CTC, 6, 8);
BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(Train1, Neural_Networks_Wrapper::Train, 5, 7);
BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(Train2, Neural_Networks_Wrapper::Train, 6, 8);
BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(Train3, Neural_Networks_Wrapper::Train, 7, 9);

BOOST_PYTHON_MODULE(Neural_Networks) {
	using namespace boost::python;

	class_<Neural_Networks_Wrapper>("Neural_Networks", init<>())
	.def(init<int>())
	.def(init<string>())
	.def("Add_Layer", &Neural_Networks_Wrapper::Add_Layer, Add_Layer())
	.def("Connect", &Neural_Networks_Wrapper::Connect)
	.def("Initialize", static_cast<void(Neural_Networks_Wrapper::*)(double, double)>(&Neural_Networks_Wrapper::Initialize), Initialize1())
	.def("Initialize", static_cast<void(Neural_Networks_Wrapper::*)(int, double, double)>(&Neural_Networks_Wrapper::Initialize), Initialize2())
	.def("Save", &Neural_Networks_Wrapper::Save)
	.def("Set_Number_Threads", &Neural_Networks_Wrapper::Set_Number_Threads)
	.def("Set_Time_Mask", &Neural_Networks_Wrapper::Set_Time_Mask)
	.def("Test", static_cast<void(Neural_Networks_Wrapper::*)(boost::python::object, boost::python::object, int)>(&Neural_Networks_Wrapper::Test), Test())
	.def("Test", static_cast<void(Neural_Networks_Wrapper::*)(int, boost::python::object, boost::python::object)>(&Neural_Networks_Wrapper::Test))
	.def("Test", static_cast<void(Neural_Networks_Wrapper::*)(int, boost::python::object, boost::python::object, boost::python::list&)>(&Neural_Networks_Wrapper::Test))
	.def("Train", static_cast<double(Neural_Networks_Wrapper::*)(int, int, boost::python::object, boost::python::list&, double, double, double)>(&Neural_Networks_Wrapper::Train_CTC), Train_CTC1())
	.def("Train", static_cast<double(Neural_Networks_Wrapper::*)(int, int, boost::python::list&, boost::python::object, boost::python::list&, double, double, double)>(&Neural_Networks_Wrapper::Train_CTC), Train_CTC2())
	.def("Train", static_cast<double(Neural_Networks_Wrapper::*)(int, int, boost::python::object, boost::python::object, double, double, double)>(&Neural_Networks_Wrapper::Train), Train1())
	.def("Train", static_cast<double(Neural_Networks_Wrapper::*)(int, int, boost::python::list&, boost::python::object, boost::python::object, double, double, double)>(&Neural_Networks_Wrapper::Train), Train2())
	.def("Train", static_cast<double(Neural_Networks_Wrapper::*)(int, int, boost::python::list&, boost::python::object, boost::python::object, boost::python::list&, double, double, double)>(&Neural_Networks_Wrapper::Train), Train3())
	;
}<commit_msg>Delete Wrapper.cpp<commit_after><|endoftext|>


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

#include <vespa/vespalib/net/tls/tls_crypto_engine.h>
#include <vespa/vespalib/test/make_tls_options_for_testing.h>

vespalib::CryptoEngine::SP my_crypto_engine() {
    const char *env_str = getenv("CRYPTOENGINE");
    if (!env_str) {
        fprintf(stderr, "crypto engine: default\n");
        return vespalib::CryptoEngine::get_default();
    }
    std::string engine(env_str);
    if (engine == "xor") {
        fprintf(stderr, "crypto engine: xor\n");
        return std::make_shared<vespalib::XorCryptoEngine>();
    } else if (engine == "tls") {
        fprintf(stderr, "crypto engine: tls\n");
        return std::make_shared<vespalib::TlsCryptoEngine>(vespalib::test::make_tls_options_for_testing());
    }
    TEST_FATAL(("invalid crypto engine: " + engine).c_str());
    abort();
}
<commit_msg>no encryption when encryption is not specified<commit_after>// Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include <vespa/vespalib/net/tls/tls_crypto_engine.h>
#include <vespa/vespalib/test/make_tls_options_for_testing.h>

vespalib::CryptoEngine::SP my_crypto_engine() {
    const char *env_str = getenv("CRYPTOENGINE");
    if (!env_str) {
        fprintf(stderr, "crypto engine: null\n");
        return std::make_shared<vespalib::NullCryptoEngine>();
    }
    std::string engine(env_str);
    if (engine == "xor") {
        fprintf(stderr, "crypto engine: xor\n");
        return std::make_shared<vespalib::XorCryptoEngine>();
    } else if (engine == "tls") {
        fprintf(stderr, "crypto engine: tls\n");
        return std::make_shared<vespalib::TlsCryptoEngine>(vespalib::test::make_tls_options_for_testing());
    }
    TEST_FATAL(("invalid crypto engine: " + engine).c_str());
    abort();
}
<|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_frame/bho_loader.h"

#include <atlbase.h>
#include <atlcomcli.h>
#include <exdisp.h>

#include "chrome_frame/chrome_frame_helper_util.h"
#include "chrome_frame/event_hooker.h"
#include "chrome_tab.h"  // NOLINT

// Describes the window class we look for.
const wchar_t kStatusBarWindowClass[] = L"msctls_statusbar32";

BHOLoader::BHOLoader() : hooker_(new EventHooker()) {
}

BHOLoader::~BHOLoader() {
  if (hooker_) {
    delete hooker_;
    hooker_ = NULL;
  }
}

void BHOLoader::OnHookEvent(DWORD event, HWND window) {
  // Step 1: Make sure that we are in a process named iexplore.exe.
  if (IsNamedProcess(L"iexplore.exe")) {
    // Step 2: Check to see if the window is of the right class.
    // IE loads BHOs in the WM_CREATE handler of the tab window approximately
    // after it creates the status bar window. To be as close to IE as possible
    // in our simulation on BHO loading, we watch for the status bar to be
    // created and do our simulated BHO loading at that time.
    if (IsWindowOfClass(window, kStatusBarWindowClass)) {
      HWND parent_window = GetParent(window);
      // Step 3:
      // Parent window of status bar window is the web browser window. Try to
      // get its IWebBrowser2 interface
      CComPtr<IWebBrowser2> browser;
      UtilGetWebBrowserObjectFromWindow(parent_window, __uuidof(browser),
                                        reinterpret_cast<void**>(&browser));
      if (browser) {
        // TODO(robertshield): We may need to find a way to prevent doing this
        // twice. A marker of some kind would do. Ask during review for good
        // suggestions.

        // Step 4:
        // We have the IWebBrowser2 interface. Now create the BHO instance
        CComPtr<IObjectWithSite> bho_object;
        HRESULT error_code =  bho_object.CoCreateInstance(CLSID_ChromeFrameBHO,
                                                          NULL,
                                                          CLSCTX_INPROC_SERVER);

        if (SUCCEEDED(error_code) && bho_object) {
          // Step 5:
          // Initialize the BHO by calling SetSite and passing it IWebBrowser2
          error_code = bho_object->SetSite(browser);
          if (SUCCEEDED(error_code)) {
            // Step 6:
            // Now add the BHO to the collection of automation objects. This
            // will ensure that BHO will be accessible from the web pages as
            // any other BHO. Importantly, it will make sure that our BHO
            // will be cleaned up at the right time along with other BHOs.
            wchar_t bho_clsid_as_string[MAX_PATH] = {0};
            StringFromGUID2(CLSID_ChromeFrameBHO, bho_clsid_as_string,
                            ARRAYSIZE(bho_clsid_as_string));

            CComBSTR bho_clsid_as_string_bstr(bho_clsid_as_string);
            CComVariant object_variant(bho_object);

            browser->PutProperty(bho_clsid_as_string_bstr, object_variant);
          }
        }
      }
    }
  }
}

bool BHOLoader::StartHook() {
  return hooker_->StartHook();
}

void BHOLoader::StopHook() {
  hooker_->StopHook();
}

BHOLoader* BHOLoader::GetInstance() {
  static BHOLoader loader;
  return &loader;
}
<commit_msg>Prevent double loading of the Chrome Frame BHO when using the user-level injection technique.<commit_after>// 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_frame/bho_loader.h"

#include <atlbase.h>
#include <atlcomcli.h>
#include <exdisp.h>

#include "chrome_frame/chrome_frame_helper_util.h"
#include "chrome_frame/event_hooker.h"
#include "chrome_tab.h"  // NOLINT

// Describes the window class we look for.
const wchar_t kStatusBarWindowClass[] = L"msctls_statusbar32";

BHOLoader::BHOLoader() : hooker_(new EventHooker()) {
}

BHOLoader::~BHOLoader() {
  if (hooker_) {
    delete hooker_;
    hooker_ = NULL;
  }
}

void BHOLoader::OnHookEvent(DWORD event, HWND window) {
  // Step 1: Make sure that we are in a process named iexplore.exe.
  if (IsNamedProcess(L"iexplore.exe")) {
    // Step 2: Check to see if the window is of the right class.
    // IE loads BHOs in the WM_CREATE handler of the tab window approximately
    // after it creates the status bar window. To be as close to IE as possible
    // in our simulation on BHO loading, we watch for the status bar to be
    // created and do our simulated BHO loading at that time.
    if (IsWindowOfClass(window, kStatusBarWindowClass)) {
      // Check that the window was created on the current thread.
      DWORD thread_id = GetWindowThreadProcessId(window, NULL);
      _ASSERTE(thread_id == GetCurrentThreadId());

      HWND parent_window = GetParent(window);
      // Step 3:
      // Parent window of status bar window is the web browser window. Try to
      // get its IWebBrowser2 interface
      CComPtr<IWebBrowser2> browser;
      UtilGetWebBrowserObjectFromWindow(parent_window, __uuidof(browser),
                                        reinterpret_cast<void**>(&browser));
      if (browser) {
        // Figure out if we're already in the property map.
        wchar_t bho_clsid_as_string[MAX_PATH] = {0};
        StringFromGUID2(CLSID_ChromeFrameBHO, bho_clsid_as_string,
                        ARRAYSIZE(bho_clsid_as_string));
        CComBSTR bho_clsid_as_string_bstr(bho_clsid_as_string);

        CComVariant existing_bho;
        HRESULT hr = browser->GetProperty(bho_clsid_as_string_bstr,
                                          &existing_bho);

        if (existing_bho.vt != VT_DISPATCH || existing_bho.pdispVal == NULL) {
          // Step 4:
          // We have the IWebBrowser2 interface. Now create the BHO instance
          CComPtr<IObjectWithSite> bho_object;
          hr =  bho_object.CoCreateInstance(CLSID_ChromeFrameBHO,
                                            NULL,
                                            CLSCTX_INPROC_SERVER);

          _ASSERTE(bho_object);
          if (SUCCEEDED(hr) && bho_object) {
            // Step 5:
            // Initialize the BHO by calling SetSite and passing it IWebBrowser2
            hr = bho_object->SetSite(browser);
            _ASSERTE(bho_object);
            if (SUCCEEDED(hr)) {
              // Step 6:
              // Now add the BHO to the collection of automation objects. This
              // will ensure that BHO will be accessible from the web pages as
              // any other BHO. Importantly, it will make sure that our BHO
              // will be cleaned up at the right time along with other BHOs.
              CComVariant object_variant(bho_object);
              browser->PutProperty(bho_clsid_as_string_bstr, object_variant);
            }
          }
        }
      }
    }
  }
}

bool BHOLoader::StartHook() {
  return hooker_->StartHook();
}

void BHOLoader::StopHook() {
  hooker_->StopHook();
}

BHOLoader* BHOLoader::GetInstance() {
  static BHOLoader loader;
  return &loader;
}
<|endoftext|>


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

#ifndef __FRAMEWORK_CLASSES_MENUCONFIGURATION_HXX_
#define __FRAMEWORK_CLASSES_MENUCONFIGURATION_HXX_

//_________________________________________________________________________________________________________________
//  interface includes
//_________________________________________________________________________________________________________________

#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif

#ifndef _COM_SUN_STAR_LANG_WRAPPEDTARGETEXCEPTION_HPP_
#include <com/sun/star/lang/WrappedTargetException.hpp>
#endif

#ifndef _COM_SUN_STAR_IO_XINPUTSTREAM_HPP_
#include <com/sun/star/io/XInputStream.hpp>
#endif

#ifndef _COM_SUN_STAR_IO_XOUTPUTSTREAM_HPP_
#include <com/sun/star/io/XOutputStream.hpp>
#endif

#ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_
#include <com/sun/star/frame/XFrame.hpp>
#endif

//_________________________________________________________________________________________________________________
//  includes of other projects
//_________________________________________________________________________________________________________________

#include <vcl/menu.hxx>
#include <vcl/toolbox.hxx>

#define BOOKMARK_NEWMENU        ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "private:menu_bookmark_new" ))
#define BOOKMARK_WIZARDMENU     ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "private:menu_bookmark_wizard" ))
#define ADDONS_POPUPMENU        ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "private:menu_addons_popup" ))

// Prepare for inclusion by framework and sfx
// Please consider that there is a corresponding define also in sfxsids.hrc!! (SID_SFX_START)/(SID_ADDONS)
#define FWK_SID_SFX_START 5000
#define FWK_SID_ADDONS (FWK_SID_SFX_START+1678)

const USHORT START_ITEMID_PICKLIST      = 4500;
const USHORT END_ITEMID_PICKLIST        = 4599;
const USHORT MAX_ITEMCOUNT_PICKLIST     =   99; // difference between START_... & END_... for picklist / must be changed too, if these values are changed!
const USHORT START_ITEMID_WINDOWLIST    = 4600;
const USHORT END_ITEMID_WINDOWLIST      = 4699;
const USHORT ITEMID_ADDONLIST           = FWK_SID_ADDONS;

namespace framework
{

class MenuConfiguration
{
    public:
        struct Attributes
        {
            ::rtl::OUString aTargetFrame;
            ::rtl::OUString aImageId;
        };

        MenuConfiguration(
            ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& rServiceManager );

        virtual ~MenuConfiguration();

        MenuBar* CreateMenuBarFromConfiguration(
            ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& rInputStream )
            throw ( ::com::sun::star::lang::WrappedTargetException );

        PopupMenu* CreateBookmarkMenu(
                ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame,
                const ::rtl::OUString& aURL )
            throw ( ::com::sun::star::lang::WrappedTargetException );

        PopupMenu* CreateAddonMenu(
                ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame )
            throw ( ::com::sun::star::lang::WrappedTargetException );

        ToolBox* CreateToolBoxFromConfiguration(
            ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& rInputStream )
            throw ( ::com::sun::star::lang::WrappedTargetException );

        void StoreMenuBar( MenuBar* pMenuBar,
                      ::com::sun::star::uno::Reference< ::com::sun::star::io::XOutputStream >& rOutputStream )
            throw ( ::com::sun::star::lang::WrappedTargetException );

        void StoreToolBox( ToolBox* pToolBox,
                      ::com::sun::star::uno::Reference< ::com::sun::star::io::XOutputStream >& rOutputStream )
            throw ( ::com::sun::star::lang::WrappedTargetException );

    private:
        ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& m_rxServiceManager;
};

}

#endif // __FRAMEWORK_CLASSES_MENUCONFIGURATION_HXX_

<commit_msg>INTEGRATION: CWS fwk01 (1.8.44); FILE MERGED 2003/03/19 13:10:50 cd 1.8.44.2: #107568# Support Add-On help menu items directly in the Office help menu 2003/03/10 14:02:54 cd 1.8.44.1: #107568# Added support for Add-Ons help integration<commit_after>/*************************************************************************
 *
 *  $RCSfile: menuconfiguration.hxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: hr $ $Date: 2003-04-04 17:12:32 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef __FRAMEWORK_CLASSES_MENUCONFIGURATION_HXX_
#define __FRAMEWORK_CLASSES_MENUCONFIGURATION_HXX_

//_________________________________________________________________________________________________________________
//  interface includes
//_________________________________________________________________________________________________________________

#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif

#ifndef _COM_SUN_STAR_LANG_WRAPPEDTARGETEXCEPTION_HPP_
#include <com/sun/star/lang/WrappedTargetException.hpp>
#endif

#ifndef _COM_SUN_STAR_IO_XINPUTSTREAM_HPP_
#include <com/sun/star/io/XInputStream.hpp>
#endif

#ifndef _COM_SUN_STAR_IO_XOUTPUTSTREAM_HPP_
#include <com/sun/star/io/XOutputStream.hpp>
#endif

#ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_
#include <com/sun/star/frame/XFrame.hpp>
#endif

//_________________________________________________________________________________________________________________
//  includes of other projects
//_________________________________________________________________________________________________________________

#include <vcl/menu.hxx>
#include <vcl/toolbox.hxx>

#define BOOKMARK_NEWMENU        ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "private:menu_bookmark_new" ))
#define BOOKMARK_WIZARDMENU     ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "private:menu_bookmark_wizard" ))
#define ADDONS_POPUPMENU        ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "private:menu_addons_popup" ))

// Prepare for inclusion by framework and sfx
// Please consider that there is a corresponding define also in sfxsids.hrc!! (SID_SFX_START)/(SID_ADDONS)
#define FWK_SID_SFX_START 5000
#define FWK_SID_ADDONS (FWK_SID_SFX_START+1678)
#define FWK_SID_ADDONHELP (FWK_SID_SFX_START+1684)

const USHORT START_ITEMID_PICKLIST      = 4500;
const USHORT END_ITEMID_PICKLIST        = 4599;
const USHORT MAX_ITEMCOUNT_PICKLIST     =   99; // difference between START_... & END_... for picklist / must be changed too, if these values are changed!
const USHORT START_ITEMID_WINDOWLIST    = 4600;
const USHORT END_ITEMID_WINDOWLIST      = 4699;
const USHORT ITEMID_ADDONLIST           = FWK_SID_ADDONS;
const USHORT ITEMID_ADDONHELP           = FWK_SID_ADDONHELP;

namespace framework
{

class MenuConfiguration
{
    public:
        struct Attributes
        {
            Attributes( const ::rtl::OUString& aFrame, const ::rtl::OUString& aImageIdStr ) :
                aTargetFrame( aFrame ), aImageId( aImageIdStr ) {}

            ::rtl::OUString aTargetFrame;
            ::rtl::OUString aImageId;
        };

        MenuConfiguration(
            ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& rServiceManager );

        virtual ~MenuConfiguration();

        MenuBar* CreateMenuBarFromConfiguration(
            ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& rInputStream )
            throw ( ::com::sun::star::lang::WrappedTargetException );

        PopupMenu* CreateBookmarkMenu(
                ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame,
                const ::rtl::OUString& aURL )
            throw ( ::com::sun::star::lang::WrappedTargetException );

        ToolBox* CreateToolBoxFromConfiguration(
            ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& rInputStream )
            throw ( ::com::sun::star::lang::WrappedTargetException );

        void StoreMenuBar( MenuBar* pMenuBar,
                      ::com::sun::star::uno::Reference< ::com::sun::star::io::XOutputStream >& rOutputStream )
            throw ( ::com::sun::star::lang::WrappedTargetException );

        void StoreToolBox( ToolBox* pToolBox,
                      ::com::sun::star::uno::Reference< ::com::sun::star::io::XOutputStream >& rOutputStream )
            throw ( ::com::sun::star::lang::WrappedTargetException );

        static BOOL IsPickListItemId( USHORT nId );
        static BOOL IsWindowListItemId( USHORT nId );

    private:
        ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& m_rxServiceManager;
};

}

#endif // __FRAMEWORK_CLASSES_MENUCONFIGURATION_HXX_

<|endoftext|>


<commit_before>/*
 * esteid-browser-plugin - a browser plugin for Estonian EID card
 *
 * Copyright (C) 2010  Estonian Informatics Centre
 * Copyright (C) 2010  Smartlink OÜ
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "GtkUI.h"

#include <stdio.h>
#include <iostream>

#include "X11/pininputdialog.h"
#include "X11/PluginWindowX11.h"
#include "X11/whitelistdialog.h"

#include "debug.h"

#ifndef WHITELISTDIALOG_UI
#define WHITELISTDIALOG_UI "whitelistdialog.ui"
#endif

#ifndef PININPUTDIALOG_UI
#define PININPUTDIALOG_UI "pininputdialog.ui"
#endif

GtkUI::GtkUI(boost::shared_ptr<UICallbacks> cb)
    : PluginUI(cb),
      m_dialog_up(false)
{
    Gtk::Main::init_gtkmm_internals();

    Glib::RefPtr<Gtk::Builder> refGlade = Gtk::Builder::create();
    // Load the GtkBuilder file
    try {
        refGlade->add_from_file(WHITELISTDIALOG_UI);
    } catch(const Glib::Error& ex) {
        std::cerr << ex.what() << std::endl;
    }
    refGlade->get_widget_derived("WhitelistDialog", m_whitelistDialog);

    Glib::RefPtr<Gtk::Builder> refGlade2 = Gtk::Builder::create();
    // Load the GtkBuilder file
    try {
        refGlade2->add_from_file(PININPUTDIALOG_UI);
    } catch(const Glib::Error& ex) {
        std::cerr << ex.what() << std::endl;
    }
    refGlade2->get_widget_derived("PinInputDialog", m_pinInputDialog);

    // connect signals
    if (m_pinInputDialog) {
        m_pinInputConnection = m_pinInputDialog->signal_response().connect( sigc::mem_fun(*this,
                    &GtkUI::on_pininputdialog_response) );
    }
    if (m_whitelistDialog) {
        m_whitelistDialog->signal_response().connect( sigc::mem_fun(*this,
                    &GtkUI::on_whitelistdialog_response) );
    }
}

GtkUI::~GtkUI()
{
    delete m_whitelistDialog;
    delete m_pinInputDialog;
}

GdkWindow* GtkUI::browserWindow()
{
    if (m_window) {
        FB::PluginWindowX11* wnd = dynamic_cast<FB::PluginWindowX11*>(m_window);
        return gdk_window_foreign_new(wnd->getBrowserWindow());
    }

    return NULL;
}

void GtkUI::PromptForPinAsync(const std::string& subject,
        const std::string& docUrl, const std::string& docHash,
        int pinPadTimeout, bool retry, int tries)
{
    if (!m_pinInputDialog)
        throw std::runtime_error("PinInputDialog not loaded");

    if (m_dialog_up) {
        // Bring the window to the front
        m_pinInputDialog->present();
        return;
    }

    m_pinInputDialog->setSubject(subject);
    m_pinInputDialog->setUrl(docUrl);
    m_pinInputDialog->setHash(docHash);
    m_pinInputDialog->setPinPadTimeout(pinPadTimeout);
    m_pinInputDialog->setRetry(retry);
    m_pinInputDialog->setTries(tries);

    m_pinInputDialog->setParent(browserWindow());

    m_pinInputDialog->show();
    m_dialog_up = true;
}

#ifdef SUPPORT_OLD_APIS
std::string GtkUI::PromptForPin(const std::string& subject,
        const std::string& docUrl, const std::string& docHash,
        int pinPadTimeout, bool retry, int tries)
{
    if (!m_pinInputDialog)
        throw std::runtime_error("PinInputDialog not loaded");

    m_pinInputDialog->setSubject(subject);
    m_pinInputDialog->setUrl(docUrl);
    m_pinInputDialog->setHash(docHash);
    m_pinInputDialog->setPinPadTimeout(pinPadTimeout);
    m_pinInputDialog->setRetry(retry);
    m_pinInputDialog->setTries(tries);

    m_pinInputDialog->setParent(browserWindow());

    // temporarily block asynchronous API signals
    m_pinInputConnection.block();
    // run dialog
    m_pinInputDialog->run();
    m_pinInputDialog->hide();
    // unblock the signal
    m_pinInputConnection.unblock();

    std::string pin = m_pinInputDialog->getPin();

    // make sure the dialog doesn't cache PIN
    m_pinInputDialog->clearPin();

    return pin;
}
#endif

void GtkUI::ClosePinPrompt()
{
}

void GtkUI::ShowPinBlockedMessage(int pin)
{
    if (m_dialog_up)
        return;

    Gtk::MessageDialog dialog(_("PIN2 blocked"), false, Gtk::MESSAGE_WARNING);
    dialog.set_secondary_text(_("Please run ID card Utility to unlock the PIN."));
    m_dialog_up = true;
    dialog.run();
    m_dialog_up = false;
}

void GtkUI::ShowSettings(PluginSettings& settings, const std::string& pageUrl)
{
    m_settings = &settings;

    if (!m_whitelistDialog)
        throw std::runtime_error("WhitelistDialog not loaded");

    if (m_dialog_up) {
        // Bring the window to the front
        m_whitelistDialog->present();
        return;
    }

    if (pageUrl.length() > 0)
        m_whitelistDialog->setEntryText(pageUrl);

    m_whitelistDialog->clear();
    m_whitelistDialog->addDefaultSites(m_settings->defaultWhitelist());
    m_whitelistDialog->addSites(m_settings->whitelist());

    m_whitelistDialog->setParent(browserWindow());

    m_whitelistDialog->show_all();
    m_dialog_up = true;
}

void GtkUI::on_pininputdialog_response(int response_id)
{
    std::string pin;

    m_pinInputDialog->hide();
    m_dialog_up = false;

    if (response_id == Gtk::RESPONSE_OK) {
        pin = m_pinInputDialog->getPin();
        m_callbacks->onPinEntered(pin);
    } else {
        m_callbacks->onPinCancelled();
    }

    // make sure the dialog doesn't cache PIN
    m_pinInputDialog->clearPin();
}

void GtkUI::on_whitelistdialog_response(int response_id)
{
    if (response_id == Gtk::RESPONSE_OK) {
        m_settings->setWhitelist(m_whitelistDialog->getWhitelist());
        try {
            m_settings->save();
        } catch(const std::exception& e) {
            Gtk::MessageDialog dialog(_("Error saving settings"), false, Gtk::MESSAGE_ERROR);
            dialog.set_secondary_text(e.what());
            dialog.run();
        }
    }

    m_whitelistDialog->hide();
    m_dialog_up = false;
}
<commit_msg>esteid-browser-plugin: Check pininputdialog return code before handling the PIN<commit_after>/*
 * esteid-browser-plugin - a browser plugin for Estonian EID card
 *
 * Copyright (C) 2010  Estonian Informatics Centre
 * Copyright (C) 2010  Smartlink OÜ
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "GtkUI.h"

#include <stdio.h>
#include <iostream>

#include "X11/pininputdialog.h"
#include "X11/PluginWindowX11.h"
#include "X11/whitelistdialog.h"

#include "debug.h"

#ifndef WHITELISTDIALOG_UI
#define WHITELISTDIALOG_UI "whitelistdialog.ui"
#endif

#ifndef PININPUTDIALOG_UI
#define PININPUTDIALOG_UI "pininputdialog.ui"
#endif

GtkUI::GtkUI(boost::shared_ptr<UICallbacks> cb)
    : PluginUI(cb),
      m_dialog_up(false)
{
    Gtk::Main::init_gtkmm_internals();

    Glib::RefPtr<Gtk::Builder> refGlade = Gtk::Builder::create();
    // Load the GtkBuilder file
    try {
        refGlade->add_from_file(WHITELISTDIALOG_UI);
    } catch(const Glib::Error& ex) {
        std::cerr << ex.what() << std::endl;
    }
    refGlade->get_widget_derived("WhitelistDialog", m_whitelistDialog);

    Glib::RefPtr<Gtk::Builder> refGlade2 = Gtk::Builder::create();
    // Load the GtkBuilder file
    try {
        refGlade2->add_from_file(PININPUTDIALOG_UI);
    } catch(const Glib::Error& ex) {
        std::cerr << ex.what() << std::endl;
    }
    refGlade2->get_widget_derived("PinInputDialog", m_pinInputDialog);

    // connect signals
    if (m_pinInputDialog) {
        m_pinInputConnection = m_pinInputDialog->signal_response().connect( sigc::mem_fun(*this,
                    &GtkUI::on_pininputdialog_response) );
    }
    if (m_whitelistDialog) {
        m_whitelistDialog->signal_response().connect( sigc::mem_fun(*this,
                    &GtkUI::on_whitelistdialog_response) );
    }
}

GtkUI::~GtkUI()
{
    delete m_whitelistDialog;
    delete m_pinInputDialog;
}

GdkWindow* GtkUI::browserWindow()
{
    if (m_window) {
        FB::PluginWindowX11* wnd = dynamic_cast<FB::PluginWindowX11*>(m_window);
        return gdk_window_foreign_new(wnd->getBrowserWindow());
    }

    return NULL;
}

void GtkUI::PromptForPinAsync(const std::string& subject,
        const std::string& docUrl, const std::string& docHash,
        int pinPadTimeout, bool retry, int tries)
{
    if (!m_pinInputDialog)
        throw std::runtime_error("PinInputDialog not loaded");

    if (m_dialog_up) {
        // Bring the window to the front
        m_pinInputDialog->present();
        return;
    }

    m_pinInputDialog->setSubject(subject);
    m_pinInputDialog->setUrl(docUrl);
    m_pinInputDialog->setHash(docHash);
    m_pinInputDialog->setPinPadTimeout(pinPadTimeout);
    m_pinInputDialog->setRetry(retry);
    m_pinInputDialog->setTries(tries);

    m_pinInputDialog->setParent(browserWindow());

    m_pinInputDialog->show();
    m_dialog_up = true;
}

#ifdef SUPPORT_OLD_APIS
std::string GtkUI::PromptForPin(const std::string& subject,
        const std::string& docUrl, const std::string& docHash,
        int pinPadTimeout, bool retry, int tries)
{
    if (!m_pinInputDialog)
        throw std::runtime_error("PinInputDialog not loaded");

    m_pinInputDialog->setSubject(subject);
    m_pinInputDialog->setUrl(docUrl);
    m_pinInputDialog->setHash(docHash);
    m_pinInputDialog->setPinPadTimeout(pinPadTimeout);
    m_pinInputDialog->setRetry(retry);
    m_pinInputDialog->setTries(tries);

    m_pinInputDialog->setParent(browserWindow());

    // temporarily block asynchronous API signals
    m_pinInputConnection.block();
    // run dialog
    int response_id = m_pinInputDialog->run();
    m_pinInputDialog->hide();
    // unblock the signal
    m_pinInputConnection.unblock();

    std::string pin;
    if (response_id == Gtk::RESPONSE_OK)
        pin = m_pinInputDialog->getPin();
    else
        pin = "";

    // make sure the dialog doesn't cache PIN
    m_pinInputDialog->clearPin();

    return pin;
}
#endif

void GtkUI::ClosePinPrompt()
{
}

void GtkUI::ShowPinBlockedMessage(int pin)
{
    if (m_dialog_up)
        return;

    Gtk::MessageDialog dialog(_("PIN2 blocked"), false, Gtk::MESSAGE_WARNING);
    dialog.set_secondary_text(_("Please run ID card Utility to unlock the PIN."));
    m_dialog_up = true;
    dialog.run();
    m_dialog_up = false;
}

void GtkUI::ShowSettings(PluginSettings& settings, const std::string& pageUrl)
{
    m_settings = &settings;

    if (!m_whitelistDialog)
        throw std::runtime_error("WhitelistDialog not loaded");

    if (m_dialog_up) {
        // Bring the window to the front
        m_whitelistDialog->present();
        return;
    }

    if (pageUrl.length() > 0)
        m_whitelistDialog->setEntryText(pageUrl);

    m_whitelistDialog->clear();
    m_whitelistDialog->addDefaultSites(m_settings->defaultWhitelist());
    m_whitelistDialog->addSites(m_settings->whitelist());

    m_whitelistDialog->setParent(browserWindow());

    m_whitelistDialog->show_all();
    m_dialog_up = true;
}

void GtkUI::on_pininputdialog_response(int response_id)
{
    std::string pin;

    m_pinInputDialog->hide();
    m_dialog_up = false;

    if (response_id == Gtk::RESPONSE_OK) {
        pin = m_pinInputDialog->getPin();
        m_callbacks->onPinEntered(pin);
    } else {
        m_callbacks->onPinCancelled();
    }

    // make sure the dialog doesn't cache PIN
    m_pinInputDialog->clearPin();
}

void GtkUI::on_whitelistdialog_response(int response_id)
{
    if (response_id == Gtk::RESPONSE_OK) {
        m_settings->setWhitelist(m_whitelistDialog->getWhitelist());
        try {
            m_settings->save();
        } catch(const std::exception& e) {
            Gtk::MessageDialog dialog(_("Error saving settings"), false, Gtk::MESSAGE_ERROR);
            dialog.set_secondary_text(e.what());
            dialog.run();
        }
    }

    m_whitelistDialog->hide();
    m_dialog_up = false;
}
<|endoftext|>


<commit_before>#include <pybind11/pybind11.h>

#include <vector>

#include <boost/function_output_iterator.hpp>

#include <osmium/osm/object_comparisons.hpp>
#include <osmium/io/any_input.hpp>
#include <osmium/io/any_output.hpp>
#include <osmium/io/output_iterator.hpp>
#include <osmium/handler.hpp>
#include <osmium/handler/node_locations_for_ways.hpp>
#include <osmium/index/map/all.hpp>
#include <osmium/object_pointer_collection.hpp>
#include <osmium/visitor.hpp>

#include "base_handler.h"
#include "osmium_module.h"

namespace py = pybind11;

namespace {

    /**
     *  Copy the first OSM object with a given Id to the output. Keep
     *  track of the Id of each object to do this.
     *
     *  We are using this functor class instead of a simple lambda, because the
     *  lambda doesn't build on MSVC.
     */
    class copy_first_with_id {
        osmium::io::Writer* writer;
        osmium::object_id_type id = 0;

    public:
        explicit copy_first_with_id(osmium::io::Writer& w) :
            writer(&w) {
        }

        void operator()(const osmium::OSMObject& obj) {
            if (obj.id() != id) {
                if (obj.visible()) {
                    (*writer)(obj);
                }
                id = obj.id();
            }
        }

    };

class MergeInputReader
{
public:
    void apply(BaseHandler& handler, std::string const &idx = "",
               bool simplify = true)
    {
        if (idx.empty())
            apply_without_location(handler, simplify);
        else
            apply_with_location(handler, idx, simplify);
    }

    void apply_to_reader(osmium::io::Reader &reader, osmium::io::Writer &writer,
                         bool with_history = true)
    {
        auto input = osmium::io::make_input_iterator_range<osmium::OSMObject>(reader);
        if (with_history) {
            // For history files this is a straightforward sort of the change
            // files followed by a merge with the input file.
            objects.sort(osmium::object_order_type_id_version());

            auto out = osmium::io::make_output_iterator(writer);
            std::set_union(objects.begin(),
                    objects.end(),
                    input.begin(),
                    input.end(),
                    out);
        } else {
            // For normal data files we sort with the largest version of each
            // object first and then only copy this last version of any object
            // to the output.
            objects.sort(osmium::object_order_type_id_reverse_version());

            auto output_it = boost::make_function_output_iterator(
                    copy_first_with_id(writer)
                    );

            std::set_union(objects.begin(),
                    objects.end(),
                    input.begin(),
                    input.end(),
                    output_it,
                    osmium::object_order_type_id_reverse_version());
        }
    }

    size_t add_file(std::string const &filename)
    { return internal_add(osmium::io::File(filename)); }

    size_t add_buffer(py::buffer const &buf, std::string const &format)
    {
        Py_buffer pybuf;
        PyObject_GetBuffer(buf.ptr(), &pybuf, PyBUF_C_CONTIGUOUS);

        return internal_add(osmium::io::File(reinterpret_cast<char const *>(pybuf.buf),
                                             (size_t) pybuf.len,
                                             format.c_str()));
    }

private:
    void apply_without_location(BaseHandler& handler, bool simplify = true)
    {
        if (simplify) {
            objects.sort(osmium::object_order_type_id_reverse_version());
            osmium::item_type prev_type = osmium::item_type::undefined;
            osmium::object_id_type prev_id = 0;
            for (const auto &item: objects) {
                if (item.type() != prev_type || item.id() != prev_id) {
                    prev_type = item.type();
                    prev_id = item.id();
                    osmium::apply_item(item, handler);
                }
            }
        } else {
            objects.sort(osmium::object_order_type_id_version());
            osmium::apply(objects.cbegin(), objects.cend(), handler);
        }

        objects = osmium::ObjectPointerCollection();
        changes.clear();
    }

    void apply_with_location(BaseHandler& handler, std::string const &idx,
                             bool simplify = true)
    {
        using Index_fab =
            osmium::index::MapFactory<osmium::unsigned_object_id_type, osmium::Location>;
        using Index_type =
            osmium::index::map::Map<osmium::unsigned_object_id_type, osmium::Location>;
        auto index = Index_fab::instance().create_map(idx);
        osmium::handler::NodeLocationsForWays<Index_type> location_handler(*index);
        location_handler.ignore_errors();

        if (simplify) {
            objects.sort(osmium::object_order_type_id_reverse_version());
            osmium::item_type prev_type = osmium::item_type::undefined;
            osmium::object_id_type prev_id = 0;
            for (auto &item: objects) {
                if (item.type() != prev_type || item.id() != prev_id) {
                    prev_type = item.type();
                    prev_id = item.id();
                    osmium::apply_item(item, location_handler, handler);
                }
            }
        } else {
            objects.sort(osmium::object_order_type_id_version());
            osmium::apply(objects.begin(), objects.end(), location_handler, handler);
        }

        objects = osmium::ObjectPointerCollection();
        changes.clear();
    }

    size_t internal_add(osmium::io::File change_file)
    {
        size_t sz = 0;

        osmium::io::Reader reader(change_file, osmium::osm_entity_bits::nwr);
        while (osmium::memory::Buffer buffer = reader.read()) {
            osmium::apply(buffer, objects);
            sz += buffer.committed();
            changes.push_back(std::move(buffer));
        }

        return sz;
    }

    std::vector<osmium::memory::Buffer> changes;
    osmium::ObjectPointerCollection objects;
};

}

void init_merge_input_reader(py::module &m)
{
    py::class_<MergeInputReader>(m, "MergeInputReader",
        "Collects data from multiple input files, sorts and optionally "
        "deduplicates the data before applying it to a handler.")
        .def(py::init<>())
        .def("apply", &MergeInputReader::apply,
             py::arg("handler"), py::arg("idx")="", py::arg("simplify")=true,
             "Apply collected data to a handler. The data will be sorted first. "
             "If `simplify` is true (default) then duplicates will be eliminated "
             "and only the newest version of each object kept. If `idx` is given "
             "a node location cache with the given type will be created and "
             "applied when creating the ways. Note that a diff file normally does "
             "not contain all node locations to reconstruct changed ways. If the "
             "full way geometries are needed, create a persistent node location "
             "cache during initial import of the area and reuse it when processing "
             "diffs. After the data "
             "has been applied the buffer of the MergeInputReader is empty and "
             "new data can be added for the next round of application.")
        .def("apply_to_reader", &MergeInputReader::apply_to_reader,
             py::arg("reader"), py::arg("writer"), py::arg("with_history")=false,
             "Apply the collected data to data from the given `reader` and write "
             "the result to `writer`. This function can be used to merge the diff "
             "data together with other OSM data (for example when updating a "
             "planet file. If `with_history` is true, then the collected data will "
             "be applied verbatim without removing duplicates. This is important "
             "when using OSM history files as input.")
        .def("add_file", &MergeInputReader::add_file,
             py::arg("file"),
             "Add data from a file to the internal cache. The file type will be "
             "determined from the file extension.")
        .def("add_buffer", &MergeInputReader::add_buffer,
             py::arg("buffer"), py::arg("format"),
             "Add data from a byte buffer. The format of the input data must "
             "be given in the `format` argument as a string. The data will be "
             "copied into internal buffers, so that the input buffer can be "
             "safely discarded after the function has been called.")
    ;
};
<commit_msg>remove default parameters in MergeInputReader<commit_after>#include <pybind11/pybind11.h>

#include <vector>

#include <boost/function_output_iterator.hpp>

#include <osmium/osm/object_comparisons.hpp>
#include <osmium/io/any_input.hpp>
#include <osmium/io/any_output.hpp>
#include <osmium/io/output_iterator.hpp>
#include <osmium/handler.hpp>
#include <osmium/handler/node_locations_for_ways.hpp>
#include <osmium/index/map/all.hpp>
#include <osmium/object_pointer_collection.hpp>
#include <osmium/visitor.hpp>

#include "base_handler.h"
#include "osmium_module.h"

namespace py = pybind11;

namespace {

    /**
     *  Copy the first OSM object with a given Id to the output. Keep
     *  track of the Id of each object to do this.
     *
     *  We are using this functor class instead of a simple lambda, because the
     *  lambda doesn't build on MSVC.
     */
    class copy_first_with_id {
        osmium::io::Writer* writer;
        osmium::object_id_type id = 0;

    public:
        explicit copy_first_with_id(osmium::io::Writer& w) :
            writer(&w) {
        }

        void operator()(const osmium::OSMObject& obj) {
            if (obj.id() != id) {
                if (obj.visible()) {
                    (*writer)(obj);
                }
                id = obj.id();
            }
        }

    };

class MergeInputReader
{
public:
    void apply(BaseHandler& handler, std::string const &idx, bool simplify)
    {
        if (idx.empty())
            apply_without_location(handler, simplify);
        else
            apply_with_location(handler, idx, simplify);
    }

    void apply_to_reader(osmium::io::Reader &reader, osmium::io::Writer &writer,
                         bool with_history)
    {
        auto input = osmium::io::make_input_iterator_range<osmium::OSMObject>(reader);
        if (with_history) {
            // For history files this is a straightforward sort of the change
            // files followed by a merge with the input file.
            objects.sort(osmium::object_order_type_id_version());

            auto out = osmium::io::make_output_iterator(writer);
            std::set_union(objects.begin(),
                    objects.end(),
                    input.begin(),
                    input.end(),
                    out);
        } else {
            // For normal data files we sort with the largest version of each
            // object first and then only copy this last version of any object
            // to the output.
            objects.sort(osmium::object_order_type_id_reverse_version());

            auto output_it = boost::make_function_output_iterator(
                    copy_first_with_id(writer)
                    );

            std::set_union(objects.begin(),
                    objects.end(),
                    input.begin(),
                    input.end(),
                    output_it,
                    osmium::object_order_type_id_reverse_version());
        }
    }

    size_t add_file(std::string const &filename)
    { return internal_add(osmium::io::File(filename)); }

    size_t add_buffer(py::buffer const &buf, std::string const &format)
    {
        Py_buffer pybuf;
        PyObject_GetBuffer(buf.ptr(), &pybuf, PyBUF_C_CONTIGUOUS);

        return internal_add(osmium::io::File(reinterpret_cast<char const *>(pybuf.buf),
                                             (size_t) pybuf.len,
                                             format.c_str()));
    }

private:
    void apply_without_location(BaseHandler& handler, bool simplify)
    {
        if (simplify) {
            objects.sort(osmium::object_order_type_id_reverse_version());
            osmium::item_type prev_type = osmium::item_type::undefined;
            osmium::object_id_type prev_id = 0;
            for (const auto &item: objects) {
                if (item.type() != prev_type || item.id() != prev_id) {
                    prev_type = item.type();
                    prev_id = item.id();
                    osmium::apply_item(item, handler);
                }
            }
        } else {
            objects.sort(osmium::object_order_type_id_version());
            osmium::apply(objects.cbegin(), objects.cend(), handler);
        }

        objects = osmium::ObjectPointerCollection();
        changes.clear();
    }

    void apply_with_location(BaseHandler& handler, std::string const &idx,
                             bool simplify)
    {
        using Index_fab =
            osmium::index::MapFactory<osmium::unsigned_object_id_type, osmium::Location>;
        using Index_type =
            osmium::index::map::Map<osmium::unsigned_object_id_type, osmium::Location>;
        auto index = Index_fab::instance().create_map(idx);
        osmium::handler::NodeLocationsForWays<Index_type> location_handler(*index);
        location_handler.ignore_errors();

        if (simplify) {
            objects.sort(osmium::object_order_type_id_reverse_version());
            osmium::item_type prev_type = osmium::item_type::undefined;
            osmium::object_id_type prev_id = 0;
            for (auto &item: objects) {
                if (item.type() != prev_type || item.id() != prev_id) {
                    prev_type = item.type();
                    prev_id = item.id();
                    osmium::apply_item(item, location_handler, handler);
                }
            }
        } else {
            objects.sort(osmium::object_order_type_id_version());
            osmium::apply(objects.begin(), objects.end(), location_handler, handler);
        }

        objects = osmium::ObjectPointerCollection();
        changes.clear();
    }

    size_t internal_add(osmium::io::File change_file)
    {
        size_t sz = 0;

        osmium::io::Reader reader(change_file, osmium::osm_entity_bits::nwr);
        while (osmium::memory::Buffer buffer = reader.read()) {
            osmium::apply(buffer, objects);
            sz += buffer.committed();
            changes.push_back(std::move(buffer));
        }

        return sz;
    }

    std::vector<osmium::memory::Buffer> changes;
    osmium::ObjectPointerCollection objects;
};

}

void init_merge_input_reader(py::module &m)
{
    py::class_<MergeInputReader>(m, "MergeInputReader",
        "Collects data from multiple input files, sorts and optionally "
        "deduplicates the data before applying it to a handler.")
        .def(py::init<>())
        .def("apply", &MergeInputReader::apply,
             py::arg("handler"), py::arg("idx")="", py::arg("simplify")=true,
             "Apply collected data to a handler. The data will be sorted first. "
             "If `simplify` is true (default) then duplicates will be eliminated "
             "and only the newest version of each object kept. If `idx` is given "
             "a node location cache with the given type will be created and "
             "applied when creating the ways. Note that a diff file normally does "
             "not contain all node locations to reconstruct changed ways. If the "
             "full way geometries are needed, create a persistent node location "
             "cache during initial import of the area and reuse it when processing "
             "diffs. After the data "
             "has been applied the buffer of the MergeInputReader is empty and "
             "new data can be added for the next round of application.")
        .def("apply_to_reader", &MergeInputReader::apply_to_reader,
             py::arg("reader"), py::arg("writer"), py::arg("with_history")=false,
             "Apply the collected data to data from the given `reader` and write "
             "the result to `writer`. This function can be used to merge the diff "
             "data together with other OSM data (for example when updating a "
             "planet file. If `with_history` is true, then the collected data will "
             "be applied verbatim without removing duplicates. This is important "
             "when using OSM history files as input.")
        .def("add_file", &MergeInputReader::add_file,
             py::arg("file"),
             "Add data from a file to the internal cache. The file type will be "
             "determined from the file extension.")
        .def("add_buffer", &MergeInputReader::add_buffer,
             py::arg("buffer"), py::arg("format"),
             "Add data from a byte buffer. The format of the input data must "
             "be given in the `format` argument as a string. The data will be "
             "copied into internal buffers, so that the input buffer can be "
             "safely discarded after the function has been called.")
    ;
};
<|endoftext|>


<commit_before>//=============================================================================================================
/**
 * @file     main.cpp
 * @author   Juan Garcia-Prieto <juangpc@gmail.com>;
 *           Lorenz Esch <lesch@mgh.harvard.edu>;
 *           Wayne Mead <wayne.mead@uth.tmc.edu>;
 *           John C. Mosher <John.C.Mosher@uth.tmc.edu>;
 *           Matti Hamalainen <msh@nmr.mgh.harvard.edu>;
 * @version  dev
 * @date     September, 2019
 *
 * @section  LICENSE
 *
 * Copyright (C) 2019, Juan Garcia-Prieto, Lorenz Esch, Matti Hamalainen, Wayne Mead, John C. Mosher. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification, are permitted provided that
 * the following conditions are met:
 *     * Redistributions of source code must retain the above copyright notice, this list of conditions and the
 *       following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
 *       the following disclaimer in the documentation and/or other materials provided with the distribution.
 *     * Neither the name of MNE-CPP authors nor the names of its contributors may be used
 *       to endorse or promote products derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
 * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 *
 * @brief     Application for anonymizing patient and personal health information from a fiff file.
 *
 */

//=============================================================================================================
// INCLUDES
//=============================================================================================================

#include "settingscontrollerCL.h"
#include "mainwindow.h"
#include <utils/generics/applicationlogger.h>

//=============================================================================================================
// Eigen
//=============================================================================================================

//=============================================================================================================
// QT INCLUDES
//=============================================================================================================

#include <QApplication>
#include <QCoreApplication>
//#include <QMainWindow>

//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================

using namespace UTILSLIB;

//=============================================================================================================
// MAIN
//=============================================================================================================
/**
 * @brief Creates a QApplication or a QCoreApplication according tu user's preference for a command line or a
 *  GUI application.
 *
 * @details Handles input arguments and searches for a "--no-gui" option. If found, this will create a
 *  QCoreApplication so that main can execute the appplication as a command line one. If not found, it creates a
 *  QApplication so that main can execute a GUI.
 *
 * @see QT Documentation
 * @see https://doc.qt.io/qt-5/qapplication.html#details
 *
 * @param [in] argc (argument count) number of arguments on the command line.
 * @param [in] argv (argument vector) an array of pointers to arrays of characters.
 *
 * @return Pointer to a QApplication or a QCoreApplication.
 */
QCoreApplication* createApplication(int &argc, char *argv[])
{
    for (int i = 1; i < argc; ++i)
    {
        if (!qstrcmp(argv[i], "--gui"))
        {
            return new QApplication(argc, argv);
        }
    }
    return new QCoreApplication(argc, argv);
}

/**
 * The function main marks the entry point of the program.
 * By default, main has the storage class extern.
 *
 * @param [in] argc (argument count) is an integer that indicates how many arguments were entered on the command line when the program was started.
 * @param [in] argv (argument vector) is an array of pointers to arrays of character objects. The array objects are null-terminated strings, representing the arguments that were entered on the command line when the program was started.
 *
 * @return the value that was set to exit() (which is 0 if exit() is called via quit()).
 */
int main(int argc, char* argv[])
{
    qInstallMessageHandler(ApplicationLogger::customLogWriter);

    QScopedPointer<QCoreApplication> qtApp(createApplication(argc, argv));

    QString nameStr("MNE Anonymize");
    QString versionStr("dev");

    qtApp->setApplicationName(nameStr);
    qtApp->setApplicationVersion(versionStr);

    if (qobject_cast<QApplication *>(qtApp.data())) {
        // to do -> develop GUI version...
        //create reader object and parse data
//        MainWindow w;
//        w.show();
    } else {
        // start non-GUI version...
        MNEANONYMIZE::SettingsControllerCL controllerCL(qtApp->arguments());
    }

    return qtApp->exec();

}
<commit_msg>remove local name and version variables in main<commit_after>//=============================================================================================================
/**
 * @file     main.cpp
 * @author   Juan Garcia-Prieto <juangpc@gmail.com>;
 *           Lorenz Esch <lesch@mgh.harvard.edu>;
 *           Wayne Mead <wayne.mead@uth.tmc.edu>;
 *           John C. Mosher <John.C.Mosher@uth.tmc.edu>;
 *           Matti Hamalainen <msh@nmr.mgh.harvard.edu>;
 * @version  dev
 * @date     September, 2019
 *
 * @section  LICENSE
 *
 * Copyright (C) 2019, Juan Garcia-Prieto, Lorenz Esch, Matti Hamalainen, Wayne Mead, John C. Mosher. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification, are permitted provided that
 * the following conditions are met:
 *     * Redistributions of source code must retain the above copyright notice, this list of conditions and the
 *       following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
 *       the following disclaimer in the documentation and/or other materials provided with the distribution.
 *     * Neither the name of MNE-CPP authors nor the names of its contributors may be used
 *       to endorse or promote products derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
 * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 *
 * @brief     Application for anonymizing patient and personal health information from a fiff file.
 *
 */

//=============================================================================================================
// INCLUDES
//=============================================================================================================

#include "settingscontrollerCL.h"
#include "mainwindow.h"
#include <utils/generics/applicationlogger.h>

//=============================================================================================================
// Eigen
//=============================================================================================================

//=============================================================================================================
// QT INCLUDES
//=============================================================================================================

#include <QApplication>
#include <QCoreApplication>
//#include <QMainWindow>

//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================

using namespace UTILSLIB;

//=============================================================================================================
// MAIN
//=============================================================================================================
/**
 * @brief Creates a QApplication or a QCoreApplication according tu user's preference for a command line or a
 *  GUI application.
 *
 * @details Handles input arguments and searches for a "--no-gui" option. If found, this will create a
 *  QCoreApplication so that main can execute the appplication as a command line one. If not found, it creates a
 *  QApplication so that main can execute a GUI.
 *
 * @see QT Documentation
 * @see https://doc.qt.io/qt-5/qapplication.html#details
 *
 * @param [in] argc (argument count) number of arguments on the command line.
 * @param [in] argv (argument vector) an array of pointers to arrays of characters.
 *
 * @return Pointer to a QApplication or a QCoreApplication.
 */
QCoreApplication* createApplication(int &argc, char *argv[])
{
    for (int i = 1; i < argc; ++i)
    {
        if (!qstrcmp(argv[i], "--gui"))
        {
            return new QApplication(argc, argv);
        }
    }
    return new QCoreApplication(argc, argv);
}

/**
 * The function main marks the entry point of the program.
 * By default, main has the storage class extern.
 *
 * @param [in] argc (argument count) is an integer that indicates how many arguments were entered on the command line when the program was started.
 * @param [in] argv (argument vector) is an array of pointers to arrays of character objects. The array objects are null-terminated strings, representing the arguments that were entered on the command line when the program was started.
 *
 * @return the value that was set to exit() (which is 0 if exit() is called via quit()).
 */
int main(int argc, char* argv[])
{
    qInstallMessageHandler(ApplicationLogger::customLogWriter);

    QScopedPointer<QCoreApplication> qtApp(createApplication(argc, argv));

    qtApp->setApplicationName("MNE Anonymize");
    qtApp->setApplicationVersion("dev");

    if (qobject_cast<QApplication *>(qtApp.data())) {
        // to do -> develop GUI version...
        //create reader object and parse data
//        MainWindow w;
//        w.show();
    } else {
        // start non-GUI version...
        MNEANONYMIZE::SettingsControllerCL controllerCL(qtApp->arguments());
    }

    return qtApp->exec();

}
<|endoftext|>


<commit_before>// ======================================================================== //
// Copyright 2009-2017 Intel Corporation                                    //
//                                                                          //
// 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.                                           //
// ======================================================================== //

// sg
#include "TetVolume.h"
#include "../common/Data.h"

namespace ospray {
  namespace sg {

    std::string TetVolume::toString() const
    {
      return "ospray::sg::TetVolume";
    }

    box3f TetVolume::bounds() const
    {
      return child("bounds").valueAs<box3f>();
    }

    void TetVolume::preCommit(RenderContext &ctx)
    {
      auto ospVolume = (OSPVolume)valueAs<OSPObject>();
      if (ospVolume) {
        ospCommit(ospVolume);
        if (child("isosurfaceEnabled").valueAs<bool>() == true
            && isosurfacesGeometry) {
          OSPData isovaluesData = ospNewData(1, OSP_FLOAT,
            &child("isosurface").valueAs<float>());
          ospSetData(isosurfacesGeometry, "isovalues", isovaluesData);
          ospCommit(isosurfacesGeometry);
        }
        return;
      }

      ospVolume = ospNewVolume("tetrahedral_volume");
      setValue((OSPObject)ospVolume);

      if (!hasChild("vertices"))
        throw std::runtime_error("#osp:sg TetVolume -> no 'vertices' array!");
      else if (!hasChild("tetrahedra"))
        throw std::runtime_error("#osp:sg TetVolume -> no 'tetrahedra' array!");
      else if (!hasChild("field"))
        throw std::runtime_error("#osp:sg TetVolume -> no 'field' array!");

      auto vertices   = child("vertices").nodeAs<DataBuffer>();
      auto tetrahedra = child("tetrahedra").nodeAs<DataBuffer>();
      auto field      = child("field").nodeAs<DataBuffer>();

      ospcommon::box3f bounds;
      for (int i = 0; i < vertices->size(); ++i)
        bounds.extend(vertices->get<vec3f>(i));
      child("bounds").setValue(bounds);

      vec2f voxelRange(field->get<float>(0), field->get<float>(0));

      for (int i = 1; i < field->size(); ++i) {
        auto value = field->get<float>(i);
        if (value < voxelRange.x)
          voxelRange.x = value;
        else if (value > voxelRange.y)
          voxelRange.y = value;
      }

      child("voxelRange").setValue(voxelRange);
      child("isosurface").setMinMax(voxelRange.x, voxelRange.y);
      float iso = child("isosurface").valueAs<float>();
      if (iso < voxelRange.x || iso > voxelRange.y)
        child("isosurface").setValue((voxelRange.y-voxelRange.x)/2.f);
      child("transferFunction")["valueRange"].setValue(voxelRange);

      //NOTE: These children are removed because they are not yet implemnted
      //      in the base Tetrahedral volume in OSPRay!
      child("gradientShadingEnabled").setValue(false);
      child("singleShade").setValue(false);
      child("adaptiveSampling").setValue(false);
    }

    void TetVolume::postCommit(RenderContext &ctx)
    {
      auto ospVolume = (OSPVolume)valueAs<OSPObject>();
      ospSetObject(ospVolume, "transferFunction",
                   child("transferFunction").valueAs<OSPObject>());
      ospCommit(ospVolume);
    }

    OSP_REGISTER_SG_NODE(TetVolume);

  } // ::ospray::sg
} // ::ospray
<commit_msg>adaptive sampling "works", so not turning it off by default in sg node<commit_after>// ======================================================================== //
// Copyright 2009-2017 Intel Corporation                                    //
//                                                                          //
// 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.                                           //
// ======================================================================== //

// sg
#include "TetVolume.h"
#include "../common/Data.h"

namespace ospray {
  namespace sg {

    std::string TetVolume::toString() const
    {
      return "ospray::sg::TetVolume";
    }

    box3f TetVolume::bounds() const
    {
      return child("bounds").valueAs<box3f>();
    }

    void TetVolume::preCommit(RenderContext &ctx)
    {
      auto ospVolume = (OSPVolume)valueAs<OSPObject>();
      if (ospVolume) {
        ospCommit(ospVolume);
        if (child("isosurfaceEnabled").valueAs<bool>() == true
            && isosurfacesGeometry) {
          OSPData isovaluesData = ospNewData(1, OSP_FLOAT,
            &child("isosurface").valueAs<float>());
          ospSetData(isosurfacesGeometry, "isovalues", isovaluesData);
          ospCommit(isosurfacesGeometry);
        }
        return;
      }

      ospVolume = ospNewVolume("tetrahedral_volume");
      setValue((OSPObject)ospVolume);

      if (!hasChild("vertices"))
        throw std::runtime_error("#osp:sg TetVolume -> no 'vertices' array!");
      else if (!hasChild("tetrahedra"))
        throw std::runtime_error("#osp:sg TetVolume -> no 'tetrahedra' array!");
      else if (!hasChild("field"))
        throw std::runtime_error("#osp:sg TetVolume -> no 'field' array!");

      auto vertices   = child("vertices").nodeAs<DataBuffer>();
      auto tetrahedra = child("tetrahedra").nodeAs<DataBuffer>();
      auto field      = child("field").nodeAs<DataBuffer>();

      ospcommon::box3f bounds;
      for (int i = 0; i < vertices->size(); ++i)
        bounds.extend(vertices->get<vec3f>(i));
      child("bounds").setValue(bounds);

      vec2f voxelRange(field->get<float>(0), field->get<float>(0));

      for (int i = 1; i < field->size(); ++i) {
        auto value = field->get<float>(i);
        if (value < voxelRange.x)
          voxelRange.x = value;
        else if (value > voxelRange.y)
          voxelRange.y = value;
      }

      child("voxelRange").setValue(voxelRange);
      child("isosurface").setMinMax(voxelRange.x, voxelRange.y);
      float iso = child("isosurface").valueAs<float>();
      if (iso < voxelRange.x || iso > voxelRange.y)
        child("isosurface").setValue((voxelRange.y-voxelRange.x)/2.f);
      child("transferFunction")["valueRange"].setValue(voxelRange);

      //NOTE: These children are removed because they are not yet implemnted
      //      in the base Tetrahedral volume in OSPRay!
      child("gradientShadingEnabled").setValue(false);
      child("singleShade").setValue(false);
    }

    void TetVolume::postCommit(RenderContext &ctx)
    {
      auto ospVolume = (OSPVolume)valueAs<OSPObject>();
      ospSetObject(ospVolume, "transferFunction",
                   child("transferFunction").valueAs<OSPObject>());
      ospCommit(ospVolume);
    }

    OSP_REGISTER_SG_NODE(TetVolume);

  } // ::ospray::sg
} // ::ospray
<|endoftext|>