<commit_before>#pragma once
using namespace std;

#include <vector>
#include <regex>

#include "ICommand.hpp"
#include "Line.hpp"
#include "Utility.hpp"

namespace OCScript
{
	// OCScript̃RANXłB
	class Core
	{
	private:
		vector<ICommandExecutable*> _Commands;
		vector<Line> _ScriptStorage;
		int _CurrentLineIndex;
	public:

		// R}hǉ܂B
		// : ICommandExecutableR}h̃NX
		void AddCommand(ICommandExecutable *command)
		{
			_Commands.push_back(command);
		}

		// ɎssύX܂B
		// : s0n܂CfbNX
		void SetCurrentLineIndex(int lineIndex)
		{
			_CurrentLineIndex = lineIndex;
		}

		// XNvg ScriptStorage Ɉꊇǂݍ݂܂B
		// : s؂蕶̃xN^
		// O\̂郁\bhł
		void LoadScript(const vector<string> scriptLines)
		{
			vector<Line> lines;

			int lineIndex = 1;
			for (auto scriptLine : scriptLines)
			{
				smatch m1, m2;

				// sł͂Ȃ
				if (!regex_match(scriptLine, regex("^[ \t]*$")))
				{
					m1 = smatch();

					// \Ƀ}b`
					if (regex_match(scriptLine, m1, regex("^[ \t]*([a-zA-Z0-9._-]+)[ \t]*\\((.+)\\)[ \t]*;[ \t]*$")))
					{
						string commandName = m1[1];
						string paramsStr = m1[2];

						vector<string> paramsSourceVec = Utility::StrSplit(paramsStr, ',');
						vector<string> paramsDestVec;
						int paramIndex = 1;
						for (auto paramToken : paramsSourceVec)
						{
							string content;
							m1 = smatch();
							m2 = smatch();

							// NH[gẗł
							if (regex_match(paramToken, m1, regex("^[ \t]*\"(.*)\"[ \t]*$")) || regex_match(paramToken, m2, regex("^[ \t]*\'(.*)\'[ \t]*$")))
							{
								if (!m1.empty())
									content = m1[1];
								else if (!m2.empty())
									content = m2[1];
								else
									throw exception(("VXeG[܂B}b`ʂĂ܂B(s: " + to_string(lineIndex) + ")").c_str());
							}
							else
							{
								m1 = smatch();
								if (!regex_match(paramToken, m1, regex("^[ \t]*([^ \t]*)[ \t]*$")))
									throw exception(("͎̉ɃG[܂B(s: " + to_string(lineIndex) + ", ԍ: " + to_string(paramIndex) + ")").c_str());

								content = m1[1];
							}
							paramsDestVec.push_back(content);
							paramIndex++;
						}
						lines.push_back(Line(commandName, paramsDestVec));
					}
					else
						throw exception(("\G[܂B(s: " + to_string(lineIndex) + ")").c_str());
				}
				lineIndex++;
			}
			_ScriptStorage = vector<Line>(lines);
		}

		// XNvg ScriptStorage Ɉꊇǂݍ݂܂B
		// : XNvg̕
		// O\̂郁\bhł
		void LoadScript(const string scriptText)
		{
			vector<string> scriptLines = Utility::StrSplit(scriptText, '\n');
			LoadScript(scriptLines);
		}

		// s̑ΏۂƂȂĂXNvgs܂B
		void ExecuteCurrentLine()
		{
			if (_ScriptStorage.empty())
				throw("ScriptStorage̒głB");
		}
	};
}<commit_msg>fix typo<commit_after>#pragma once
using namespace std;

#include <vector>
#include <regex>

#include "ICommand.hpp"
#include "Line.hpp"
#include "Utility.hpp"

namespace OCScript
{
	// OCScript̃RANXłB
	class Core
	{
	private:
		vector<ICommandExecutable*> _Commands;
		vector<Line> _ScriptStorage;
		int _CurrentLineIndex;
	public:

		// R}hǉ܂B
		// : ICommandExecutableR}h̃NX
		void AddCommand(ICommandExecutable *command)
		{
			_Commands.push_back(command);
		}

		// ɎssύX܂B
		// : s0n܂CfbNX
		void SetCurrentLineIndex(int lineIndex)
		{
			_CurrentLineIndex = lineIndex;
		}

		// XNvg ScriptStorage Ɉꊇǂݍ݂܂B
		// : s؂蕶̃xN^
		// O\̂郁\bhł
		void LoadScript(const vector<string> scriptLines)
		{
			vector<Line> lines;

			int lineIndex = 1;
			for (auto scriptLine : scriptLines)
			{
				smatch m1, m2;

				// sł͂Ȃ
				if (!regex_match(scriptLine, regex("^[ \t]*$")))
				{
					m1 = smatch();

					// \Ƀ}b`
					if (regex_match(scriptLine, m1, regex("^[ \t]*([a-zA-Z0-9._-]+)[ \t]*\\((.+)\\)[ \t]*;[ \t]*$")))
					{
						string commandName = m1[1];
						string paramsStr = m1[2];

						vector<string> paramsSourceVec = Utility::StrSplit(paramsStr, ',');
						vector<string> paramsDestVec;
						int paramIndex = 1;
						for (auto paramToken : paramsSourceVec)
						{
							string content;
							m1 = smatch();
							m2 = smatch();

							// NH[gẗł
							if (regex_match(paramToken, m1, regex("^[ \t]*\"(.*)\"[ \t]*$")) || regex_match(paramToken, m2, regex("^[ \t]*\'(.*)\'[ \t]*$")))
							{
								if (!m1.empty())
									content = m1[1];
								else if (!m2.empty())
									content = m2[1];
								else
									throw exception(("VXeG[܂B}b`ʂĂ܂B(s: " + to_string(lineIndex) + ")").c_str());
							}
							else
							{
								m1 = smatch();
								if (!regex_match(paramToken, m1, regex("^[ \t]*([^ \t]*)[ \t]*$")))
									throw exception(("͎̉ɃG[܂B(s: " + to_string(lineIndex) + ", ԍ: " + to_string(paramIndex) + ")").c_str());

								content = m1[1];
							}
							paramsDestVec.push_back(content);
							paramIndex++;
						}
						lines.push_back(Line(commandName, paramsDestVec));
					}
					else
						throw exception(("\G[܂B(s: " + to_string(lineIndex) + ")").c_str());
				}
				lineIndex++;
			}
			_ScriptStorage = vector<Line>(lines);
		}

		// XNvg ScriptStorage Ɉꊇǂݍ݂܂B
		// : XNvg̕
		// O\̂郁\bhł
		void LoadScript(const string scriptText)
		{
			vector<string> scriptLines = Utility::StrSplit(scriptText, '\n');
			LoadScript(scriptLines);
		}

		// s̑ΏۂƂȂĂXNvgs܂B
		void ExecuteCurrentLine()
		{
			if (_ScriptStorage.empty())
				throw("ScriptStorage̒głB");
		}
	};
}<|endoftext|>


<commit_before>/**
@copyright MIT license; see @ref index or the accompanying LICENSE file.
*/

#include <Onsang/config.hpp>
#include <Onsang/aux.hpp>
#include <Onsang/String.hpp>
#include <Onsang/UI/Defs.hpp>
#include <Onsang/UI/TabbedView.hpp>

#include <duct/debug.hpp>

namespace Onsang {
namespace UI {

// Beard::ui::Widget::Base implementation

void
TabbedView::cache_geometry_impl() noexcept {
	m_container->cache_geometry();
	if (!get_geometry().is_static()) {
		auto const& ws = m_container->get_geometry().get_request_size();
		auto rs = get_geometry().get_request_size();
		rs.width  = max_ce(rs.width , ws.width);
		rs.height = max_ce(rs.height, ws.height);
		get_geometry().set_request_size(std::move(rs));
	}
}

void
TabbedView::reflow_impl(
	Rect const& area,
	bool const cache
) noexcept {
	base::reflow_impl(area, cache);
	m_container->reflow(area, false);
}

void
TabbedView::render_impl(
	UI::Widget::RenderData& rd
) noexcept {
	m_container->render(rd);
}

signed
TabbedView::num_children_impl() const noexcept {
	return 1;
}

UI::Widget::SPtr
TabbedView::get_child_impl(
	signed const index
) {
	DUCT_ASSERTE(0 == index);
	return m_container;
}

// UI::View implementation

unsigned
TabbedView::sub_view_index() noexcept {
	return m_container->m_position;
}

UI::View::SPtr
TabbedView::sub_view() noexcept {
	return m_container->empty()
		? UI::View::SPtr{}
		: std::dynamic_pointer_cast<UI::View>(
			m_container->m_tabs[m_container->m_position].widget
		)
	;
}

void
TabbedView::set_sub_view_impl(
	unsigned const index
) noexcept {
	m_container->set_current_tab(index);
}

unsigned
TabbedView::num_sub_views() noexcept {
	return m_container->m_tabs.size();
}

void
TabbedView::close_sub_view(
	unsigned index
) noexcept {
	if (index < m_container->m_tabs.size()) {
		m_container->remove(index);
	}
}

void
TabbedView::sub_view_title_changed(
	unsigned index
) noexcept {
	if (index < m_container->m_tabs.size()) {
		auto const& tab = m_container->m_tabs[index];
		auto const view = std::dynamic_pointer_cast<UI::View>(tab.widget);
		if (view) {
			m_container->set_title(index, view->view_title());
		}
	}
}

void
TabbedView::notify_command(
	UI::View* const /*parent_view*/,
	Hord::Cmd::UnitBase const& command,
	Hord::Cmd::type_info const& type_info
) noexcept {
	auto const& tabs = m_container->m_tabs;
	for (unsigned index = 0; index < tabs.size(); ++index) {
		auto& tab = tabs[index];
		auto const view = std::dynamic_pointer_cast<UI::View>(tab.widget);
		if (!view) {
			continue;
		}
		view->notify_command(this, command, type_info);
	}
}

} // namespace UI
} // namespace Onsang
<commit_msg>UI/TabbedView: set CSL description to self when last sub-view is closed.<commit_after>/**
@copyright MIT license; see @ref index or the accompanying LICENSE file.
*/

#include <Onsang/config.hpp>
#include <Onsang/aux.hpp>
#include <Onsang/String.hpp>
#include <Onsang/UI/Defs.hpp>
#include <Onsang/UI/TabbedView.hpp>
#include <Onsang/App.hpp>

#include <duct/debug.hpp>

namespace Onsang {
namespace UI {

// Beard::ui::Widget::Base implementation

void
TabbedView::cache_geometry_impl() noexcept {
	m_container->cache_geometry();
	if (!get_geometry().is_static()) {
		auto const& ws = m_container->get_geometry().get_request_size();
		auto rs = get_geometry().get_request_size();
		rs.width  = max_ce(rs.width , ws.width);
		rs.height = max_ce(rs.height, ws.height);
		get_geometry().set_request_size(std::move(rs));
	}
}

void
TabbedView::reflow_impl(
	Rect const& area,
	bool const cache
) noexcept {
	base::reflow_impl(area, cache);
	m_container->reflow(area, false);
}

void
TabbedView::render_impl(
	UI::Widget::RenderData& rd
) noexcept {
	m_container->render(rd);
}

signed
TabbedView::num_children_impl() const noexcept {
	return 1;
}

UI::Widget::SPtr
TabbedView::get_child_impl(
	signed const index
) {
	DUCT_ASSERTE(0 == index);
	return m_container;
}

// UI::View implementation

unsigned
TabbedView::sub_view_index() noexcept {
	return m_container->m_position;
}

UI::View::SPtr
TabbedView::sub_view() noexcept {
	return m_container->empty()
		? UI::View::SPtr{}
		: std::dynamic_pointer_cast<UI::View>(
			m_container->m_tabs[m_container->m_position].widget
		)
	;
}

void
TabbedView::set_sub_view_impl(
	unsigned const index
) noexcept {
	m_container->set_current_tab(index);
}

unsigned
TabbedView::num_sub_views() noexcept {
	return m_container->m_tabs.size();
}

void
TabbedView::close_sub_view(
	unsigned index
) noexcept {
	if (index < m_container->m_tabs.size()) {
		m_container->remove(index);
		if (m_container->m_tabs.empty()) {
			App::instance.m_ui.csline->clear_location();
			App::instance.m_ui.csline->set_description(view_description());
		}
	}
}

void
TabbedView::sub_view_title_changed(
	unsigned index
) noexcept {
	if (index < m_container->m_tabs.size()) {
		auto const& tab = m_container->m_tabs[index];
		auto const view = std::dynamic_pointer_cast<UI::View>(tab.widget);
		if (view) {
			m_container->set_title(index, view->view_title());
		}
	}
}

void
TabbedView::notify_command(
	UI::View* const /*parent_view*/,
	Hord::Cmd::UnitBase const& command,
	Hord::Cmd::type_info const& type_info
) noexcept {
	auto const& tabs = m_container->m_tabs;
	for (unsigned index = 0; index < tabs.size(); ++index) {
		auto& tab = tabs[index];
		auto const view = std::dynamic_pointer_cast<UI::View>(tab.widget);
		if (!view) {
			continue;
		}
		view->notify_command(this, command, type_info);
	}
}

} // namespace UI
} // namespace Onsang
<|endoftext|>


<commit_before>// Copyright (C) 2016 DNAnexus, Inc.
//
// This file is part of dx-toolkit (DNAnexus platform client libraries).
//
//   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.

// This function should be called before opt.setApiserverDxConfig() is called,
// since opt::setApiserverDxConfig() changes the value of dx::config::*, based on command line args

#include <string>
#include "ua_test.h"
#include "dxcpp/dxcpp.h"
#include "api_helper.h"
#include "options.h"
#include "api.h"
#include "round_robin_dns.h"

#if WINDOWS_BUILD
#include <windows.h>
#else
#include <sys/utsname.h>
#endif

using namespace std;
using namespace dx;
using namespace dx::config;

void runTests()
{
  version();
  printEnvironmentInfo(false);
  testWhoAmI();
  currentProject();
  proxySettings();
  osInfo();
  certificateFile();
  resolveAmazonS3();
  contactGoogle();
}

void version() {
  cout << "Upload Agent Version: " << UAVERSION;
#if OLD_KERNEL_SUPPORT
  cout << " (old-kernel-support)";
#endif
  cout << endl
       << "  git version: " << DXTOOLKIT_GITVERSION << endl
       << "  libboost version: " << (BOOST_VERSION / 100000) << "." << ((BOOST_VERSION / 100) % 1000) << "." << (BOOST_VERSION % 100) << endl
       << "  libcurl version: " << LIBCURL_VERSION_MAJOR << "." << LIBCURL_VERSION_MINOR << "." << LIBCURL_VERSION_PATCH << endl;
}

void osInfo(){
#if WINDOWS_BUILD
  OSVERSIONINFO vi;
  vi.dwOSVersionInfoSize = sizeof(vi);
  try {
    GetVersionEx(&vi);
    cout << "Operating System:" << endl
         << "  Windows: " << vi.dwMajorVersion << "." << vi.dwMinorVersion << "." << vi.dwBuildNumber
         << "." << vi.dwPlatformId << " " << vi.szCSDVersion << endl;
  } catch(exception &e){
    cout << "Unable to get OS information" << e.what() << endl;
  }
#else
  struct utsname uts;
  uname(&uts);
  cout << "Operating System:" << endl
       << "  Name:    " << uts.sysname << endl
       << "  Release: " << uts.release << endl
       << "  Version: " << uts.version << endl
       << "  Machine: " << uts.machine << endl;
#endif
}

void printEnvironmentInfo(bool printToken) {
  cout << "Upload Agent v" << UAVERSION << ", environment info:" << endl
       << "  API server protocol: " << APISERVER_PROTOCOL() << endl
       << "  API server host:     " << APISERVER_HOST() << endl
       << "  API server port:     " << APISERVER_PORT() << endl;

  if (printToken) {
    if (SECURITY_CONTEXT().size() != 0)
      cout << "  Auth token: " << SECURITY_CONTEXT()["auth_token"].get<string>() << endl;
    else
      cout << "  Auth token: " << endl;
  }
}

void currentProject() {
  string projID = CURRENT_PROJECT();
  try {
    if (projID.empty()) {
      cout << "  Current Project: None" << endl;
    } else {
      string projName = getProjectName(projID);
      cout << "  Current Project: " << projName << " (" << projID << ")" << endl;
    }
  } catch (DXAPIError &e) {
    cout << "  Current Project: "<< " (" << projID << ")" << e.what() << endl;
  }
}

bool getProxyValue(const char * name, string &value) {
  if (getenv(name) == NULL)
    return false;
  value = string(getenv(name));
  // Remove credentials from string
  std::size_t atSimbol = value.find_first_of("@");
  if (atSimbol != string::npos ) {
    if (value.substr(0, 7) == "http://") {
      value.replace(7, atSimbol-7, "****");
    } else if (value.substr(0, 8) == "https://") {
      value.replace(8, atSimbol-8, "****");
    } else {
      value.replace(0, atSimbol, "****");
    }
    cout << "  To see actual username and password run: echo $" << name << endl;
    cout << "  Note that special characters in username / password might prevent credentials from being resolved properly." << endl;
  }
  return true;
}

void proxySettings() {
  string value;
  cout << "Proxy Settings:" << endl;
  bool proxySet = false;
  if (getProxyValue("http_proxy", value))  { cout << "  http_proxy: " << value << endl; proxySet = true;}
  if (getProxyValue("https_proxy", value)) { cout << "  https_proxy: " << value << endl;proxySet = true;}
  if (getProxyValue("HTTP_PROXY", value))  { cout << "  HTTP_PROXY: " << value << endl;proxySet = true;}
  if (getProxyValue("HTTPS_PROXY", value)) { cout << "  HTTP_PROXY: " << value << endl;proxySet = true;}
  if (!proxySet) { cout << "  No proxy set in environment." << endl; }
}

void certificateFile() {
  cout << "CA Certificate: " << CA_CERT() << endl;
}

void testWhoAmI(){
  cout << "  Current User: ";
  try {
    JSON res = systemWhoami(string("{}"), false);
    cout  << res["id"].get<string>() << endl;
  } catch(DXAPIError &e) {
    cout << "Error contacting the api: " << e.what() << endl;
  } catch (DXConnectionError &e) {
    cout << "Error contacting the api: " << e.what() << endl;
  } catch (...) {
    cout << "Error contacting the api." << endl;
  }
}

void contactGoogle() {
  cout << "Testing connection:" << endl;
  try {
    string url = "http://www.google.com/";
    HttpRequest req = HttpRequest::request(dx::HTTP_GET, url);
    if (req.responseCode == 200) {
      cout << "  Sucessfully contacted google.com over http: (" << req.responseCode << ")" << endl;
    } else {
      cout << "  Unable to contact google.com over http: (" << req.responseCode << ")" << endl;
    }
  } catch (HttpRequestException &e) {
    cout << "Error contacting google over http: " << e.what();
  } catch (...) {
    cout << "Error contacting the api." << endl;
  }

  try {
    string url = "https://www.google.com/";
    HttpRequest req = HttpRequest::request(dx::HTTP_GET, url);
    if (req.responseCode == 200) {
      cout << "  Sucessfully contacted google.com over https: (" << req.responseCode << ")" << endl;
    } else {
      cout << "  Unable to contact google.com over https: (" << req.responseCode << ")" << endl;
    }
  } catch (HttpRequestException &e) {
    cout << "Error contacting google over https: " << e.what() << endl;
  } catch (...) {
    cout << "Error contacting google" << endl;
  }
}

void resolveAmazonS3(){
  cout << "Resolving Amazon S3:" << endl;
  string awsIP = getRandomIP("s3.amazonaws.com");
  if (awsIP.empty()){
    cout << "  Unable to resolve Amazon S3" << endl;
  } else {
    cout << "  Resolved to " << awsIP << endl;
  }
}

<commit_msg>Fix typo in log output<commit_after>// Copyright (C) 2016 DNAnexus, Inc.
//
// This file is part of dx-toolkit (DNAnexus platform client libraries).
//
//   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.

// This function should be called before opt.setApiserverDxConfig() is called,
// since opt::setApiserverDxConfig() changes the value of dx::config::*, based on command line args

#include <string>
#include "ua_test.h"
#include "dxcpp/dxcpp.h"
#include "api_helper.h"
#include "options.h"
#include "api.h"
#include "round_robin_dns.h"

#if WINDOWS_BUILD
#include <windows.h>
#else
#include <sys/utsname.h>
#endif

using namespace std;
using namespace dx;
using namespace dx::config;

void runTests()
{
  version();
  printEnvironmentInfo(false);
  testWhoAmI();
  currentProject();
  proxySettings();
  osInfo();
  certificateFile();
  resolveAmazonS3();
  contactGoogle();
}

void version() {
  cout << "Upload Agent Version: " << UAVERSION;
#if OLD_KERNEL_SUPPORT
  cout << " (old-kernel-support)";
#endif
  cout << endl
       << "  git version: " << DXTOOLKIT_GITVERSION << endl
       << "  libboost version: " << (BOOST_VERSION / 100000) << "." << ((BOOST_VERSION / 100) % 1000) << "." << (BOOST_VERSION % 100) << endl
       << "  libcurl version: " << LIBCURL_VERSION_MAJOR << "." << LIBCURL_VERSION_MINOR << "." << LIBCURL_VERSION_PATCH << endl;
}

void osInfo(){
#if WINDOWS_BUILD
  OSVERSIONINFO vi;
  vi.dwOSVersionInfoSize = sizeof(vi);
  try {
    GetVersionEx(&vi);
    cout << "Operating System:" << endl
         << "  Windows: " << vi.dwMajorVersion << "." << vi.dwMinorVersion << "." << vi.dwBuildNumber
         << "." << vi.dwPlatformId << " " << vi.szCSDVersion << endl;
  } catch(exception &e){
    cout << "Unable to get OS information" << e.what() << endl;
  }
#else
  struct utsname uts;
  uname(&uts);
  cout << "Operating System:" << endl
       << "  Name:    " << uts.sysname << endl
       << "  Release: " << uts.release << endl
       << "  Version: " << uts.version << endl
       << "  Machine: " << uts.machine << endl;
#endif
}

void printEnvironmentInfo(bool printToken) {
  cout << "Upload Agent v" << UAVERSION << ", environment info:" << endl
       << "  API server protocol: " << APISERVER_PROTOCOL() << endl
       << "  API server host:     " << APISERVER_HOST() << endl
       << "  API server port:     " << APISERVER_PORT() << endl;

  if (printToken) {
    if (SECURITY_CONTEXT().size() != 0)
      cout << "  Auth token: " << SECURITY_CONTEXT()["auth_token"].get<string>() << endl;
    else
      cout << "  Auth token: " << endl;
  }
}

void currentProject() {
  string projID = CURRENT_PROJECT();
  try {
    if (projID.empty()) {
      cout << "  Current Project: None" << endl;
    } else {
      string projName = getProjectName(projID);
      cout << "  Current Project: " << projName << " (" << projID << ")" << endl;
    }
  } catch (DXAPIError &e) {
    cout << "  Current Project: "<< " (" << projID << ")" << e.what() << endl;
  }
}

bool getProxyValue(const char * name, string &value) {
  if (getenv(name) == NULL)
    return false;
  value = string(getenv(name));
  // Remove credentials from string
  std::size_t atSimbol = value.find_first_of("@");
  if (atSimbol != string::npos ) {
    if (value.substr(0, 7) == "http://") {
      value.replace(7, atSimbol-7, "****");
    } else if (value.substr(0, 8) == "https://") {
      value.replace(8, atSimbol-8, "****");
    } else {
      value.replace(0, atSimbol, "****");
    }
    cout << "  To see actual username and password run: echo $" << name << endl;
    cout << "  Note that special characters in username / password might prevent credentials from being resolved properly." << endl;
  }
  return true;
}

void proxySettings() {
  string value;
  cout << "Proxy Settings:" << endl;
  bool proxySet = false;
  if (getProxyValue("http_proxy", value))  { cout << "  http_proxy: " << value << endl; proxySet = true;}
  if (getProxyValue("https_proxy", value)) { cout << "  https_proxy: " << value << endl;proxySet = true;}
  if (getProxyValue("HTTP_PROXY", value))  { cout << "  HTTP_PROXY: " << value << endl;proxySet = true;}
  if (getProxyValue("HTTPS_PROXY", value)) { cout << "  HTTP_PROXY: " << value << endl;proxySet = true;}
  if (!proxySet) { cout << "  No proxy set in environment." << endl; }
}

void certificateFile() {
  cout << "CA Certificate: " << CA_CERT() << endl;
}

void testWhoAmI(){
  cout << "  Current User: ";
  try {
    JSON res = systemWhoami(string("{}"), false);
    cout  << res["id"].get<string>() << endl;
  } catch(DXAPIError &e) {
    cout << "Error contacting the api: " << e.what() << endl;
  } catch (DXConnectionError &e) {
    cout << "Error contacting the api: " << e.what() << endl;
  } catch (...) {
    cout << "Error contacting the api." << endl;
  }
}

void contactGoogle() {
  cout << "Testing connection:" << endl;
  try {
    string url = "http://www.google.com/";
    HttpRequest req = HttpRequest::request(dx::HTTP_GET, url);
    if (req.responseCode == 200) {
      cout << "  Successfully contacted google.com over http: (" << req.responseCode << ")" << endl;
    } else {
      cout << "  Unable to contact google.com over http: (" << req.responseCode << ")" << endl;
    }
  } catch (HttpRequestException &e) {
    cout << "Error contacting google over http: " << e.what();
  } catch (...) {
    cout << "Error contacting the api." << endl;
  }

  try {
    string url = "https://www.google.com/";
    HttpRequest req = HttpRequest::request(dx::HTTP_GET, url);
    if (req.responseCode == 200) {
      cout << "  Successfully contacted google.com over https: (" << req.responseCode << ")" << endl;
    } else {
      cout << "  Unable to contact google.com over https: (" << req.responseCode << ")" << endl;
    }
  } catch (HttpRequestException &e) {
    cout << "Error contacting google over https: " << e.what() << endl;
  } catch (...) {
    cout << "Error contacting google" << endl;
  }
}

void resolveAmazonS3(){
  cout << "Resolving Amazon S3:" << endl;
  string awsIP = getRandomIP("s3.amazonaws.com");
  if (awsIP.empty()){
    cout << "  Unable to resolve Amazon S3" << endl;
  } else {
    cout << "  Resolved to " << awsIP << endl;
  }
}

<|endoftext|>


<commit_before>#include <JeeLib.h>

volatile uint16_t rf69_crc;
volatile uint8_t rf69_buf[72];

// void rf69_set_cs (uint8_t pin) {
// }

// void rf69_spiInit () {
// }

uint8_t rf69_initialize (uint8_t id, uint8_t band, uint8_t group) {
    RF69::frf = band == RF12_433MHZ ? 0x6C4000L : // or 0x6C8000 for 434 MHz?
                band == RF12_868MHZ ? 0xD90000L : 0xE4C000L;
    RF69::group = group;
    RF69::node = id;
    delay(20); // needed to make RFM69 work properly on power-up
    RF69::configure_compat();
    return id;
}

uint8_t rf69_config (uint8_t show) {
    rf69_initialize(31, RF12_868MHZ, 5);
    return 31; // TODO
}

uint8_t rf69_recvDone () {
    rf69_crc = RF69::recvDone_compat((uint8_t*) rf69_buf);
    return rf69_crc != ~0;
}

uint8_t rf69_canSend () {
    return RF69::canSend();
}

// void rf69_sendStart (uint8_t hdr) {
// }

void rf69_sendStart (uint8_t hdr, const void* ptr, uint8_t len) {
    RF69::sendStart_compat(hdr, ptr, len);
}

// void rf69_sendStart (uint8_t hdr, const void* ptr, uint8_t len, uint8_t sync) {
// }

void rf69_sendNow (uint8_t hdr, const void* ptr, uint8_t len) {
    while (!rf69_canSend())
        rf69_recvDone();
    rf69_sendStart(hdr, ptr, len);
}

void rf69_sendWait (uint8_t mode) {
    // TODO
}

void rf69_onOff (uint8_t value) {
    // TODO
}

void rf69_sleep (char n) {
    // TODO
}

// char rf69_lowbat () {
// }

// void rf69_easyInit (uint8_t secs) {
// }

// char rf69_easyPoll () {
// }

// char rf69_easySend (const void* data, uint8_t size) {
// }

// void rf69_encrypt (const uint8_t*) {
// }

// uint16_t rf69_control (uint16_t cmd) {
// }
<commit_msg>fix rf69_config<commit_after>#include <JeeLib.h>
#include <avr/eeprom.h>
#include <util/crc16.h>

volatile uint16_t rf69_crc;
volatile uint8_t rf69_buf[72];

// void rf69_set_cs (uint8_t pin) {
// }

// void rf69_spiInit () {
// }

uint8_t rf69_initialize (uint8_t id, uint8_t band, uint8_t group) {
    RF69::frf = band == RF12_433MHZ ? 0x6C4000L : // or 0x6C8000 for 434 MHz?
                band == RF12_868MHZ ? 0xD90000L : 0xE4C000L;
    RF69::group = group;
    RF69::node = id;
    delay(20); // needed to make RFM69 work properly on power-up
    RF69::configure_compat();
    return id;
}

// same code as rf12_config, just calling rf69_initialize() instead
uint8_t rf69_config (uint8_t show) {
    uint16_t crc = ~0;
    for (uint8_t i = 0; i < RF12_EEPROM_SIZE; ++i)
        crc = _crc16_update(crc, eeprom_read_byte(RF12_EEPROM_ADDR + i));
    if (crc != 0)
        return 0;

    uint8_t nodeId = 0, group = 0;
    for (uint8_t i = 0; i < RF12_EEPROM_SIZE - 2; ++i) {
        uint8_t b = eeprom_read_byte(RF12_EEPROM_ADDR + i);
        if (i == 0)
            nodeId = b;
        else if (i == 1)
            group = b;
        else if (b == 0)
            break;
        else if (show)
            Serial.print((char) b);
    }
    if (show)
        Serial.println();

    rf69_initialize(nodeId, nodeId >> 6, group);
    return nodeId & RF12_HDR_MASK;
}

uint8_t rf69_recvDone () {
    rf69_crc = RF69::recvDone_compat((uint8_t*) rf69_buf);
    return rf69_crc != ~0;
}

uint8_t rf69_canSend () {
    return RF69::canSend();
}

// void rf69_sendStart (uint8_t hdr) {
// }

void rf69_sendStart (uint8_t hdr, const void* ptr, uint8_t len) {
    RF69::sendStart_compat(hdr, ptr, len);
}

// void rf69_sendStart (uint8_t hdr, const void* ptr, uint8_t len, uint8_t sync) {
// }

void rf69_sendNow (uint8_t hdr, const void* ptr, uint8_t len) {
    while (!rf69_canSend())
        rf69_recvDone();
    rf69_sendStart(hdr, ptr, len);
}

void rf69_sendWait (uint8_t mode) {
    // TODO
}

void rf69_onOff (uint8_t value) {
    // TODO
}

void rf69_sleep (char n) {
    // TODO
}

// char rf69_lowbat () {
// }

// void rf69_easyInit (uint8_t secs) {
// }

// char rf69_easyPoll () {
// }

// char rf69_easySend (const void* data, uint8_t size) {
// }

// void rf69_encrypt (const uint8_t*) {
// }

// uint16_t rf69_control (uint16_t cmd) {
// }
<|endoftext|>


<commit_before>/*-------------------------------------------------------------------------
 * drawElements Quality Program Tester Core
 * ----------------------------------------
 *
 * Copyright 2014 The Android Open Source Project
 *
 * 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.
 *
 *//*!
 * \file
 * \brief Generic Win32 window class.
 *//*--------------------------------------------------------------------*/

#include "tcuWin32Window.hpp"

namespace tcu
{

static LRESULT CALLBACK win32WindowProc (HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
	Win32Window* window = reinterpret_cast<Win32Window*>(GetWindowLongPtr(hWnd, GWLP_USERDATA));
	if (window)
		return window->windowProc(uMsg, wParam, lParam);
	else
		return DefWindowProc(hWnd, uMsg, wParam, lParam);
}

Win32Window::Win32Window (HINSTANCE instance, int width, int height)
	: m_window		(DE_NULL)
{
	try
	{
		static const char	s_className[]	= "dEQP Tester Core Class";
		static const char	s_windowName[]	= "dEQP Tester Core";

		{
			WNDCLASS wndClass;
			memset(&wndClass, 0, sizeof(wndClass));
			wndClass.style			= CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
			wndClass.lpfnWndProc	= win32WindowProc;
			wndClass.cbClsExtra		= 0;
			wndClass.cbWndExtra		= 0;
			wndClass.hInstance		= instance;
			wndClass.hIcon			= LoadIcon(NULL, IDI_APPLICATION);
			wndClass.hCursor		= LoadCursor(NULL, IDC_ARROW);
			wndClass.hbrBackground	= CreateSolidBrush(RGB(0, 0, 0));
			wndClass.lpszMenuName	= NULL;
			wndClass.lpszClassName	= s_className;

			RegisterClass(&wndClass);
		}

		m_window = CreateWindow(s_className, s_windowName,
								WS_CLIPCHILDREN | WS_OVERLAPPEDWINDOW,
								CW_USEDEFAULT, CW_USEDEFAULT,
								width, height,
								NULL, NULL, instance, NULL);

		if (!m_window)
			throw ResourceError("Failed to create Win32 window", "", __FILE__, __LINE__);

		// Store this as userdata
		SetWindowLongPtr(m_window, GWLP_USERDATA, (LONG_PTR)this);

		setSize(width, height);
	}
	catch (...)
	{
		if (m_window)
			DestroyWindow(m_window);

		throw;
	}
}

Win32Window::~Win32Window (void)
{
	if (m_window)
	{
		// Clear this pointer from windowproc
		SetWindowLongPtr(m_window, GWLP_USERDATA, 0);
	}

	DestroyWindow(m_window);
}

void Win32Window::setVisible (bool visible)
{
	ShowWindow(m_window, visible ? SW_SHOW : SW_HIDE);
}

void Win32Window::setSize (int width, int height)
{
	RECT rc;

	rc.left		= 0;
	rc.top		= 0;
	rc.right	= width;
	rc.bottom	= height;

	if (!AdjustWindowRect(&rc, GetWindowLong(m_window, GWL_STYLE), GetMenu(m_window) != NULL))
		throw tcu::TestError("AdjustWindowRect() failed", DE_NULL, __FILE__, __LINE__);

	if (!SetWindowPos(m_window, NULL, 0, 0,
					  rc.right - rc.left, rc.bottom - rc.top,
					  SWP_NOACTIVATE | SWP_NOCOPYBITS | SWP_NOMOVE | SWP_NOZORDER))
		throw tcu::TestError("SetWindowPos() failed", DE_NULL, __FILE__, __LINE__);
}

IVec2 Win32Window::getSize (void) const
{
	RECT rc;
	if (!GetClientRect(m_window, &rc))
		throw tcu::TestError("GetClientRect() failed", DE_NULL, __FILE__, __LINE__);

	return IVec2(rc.right - rc.left,
				 rc.bottom - rc.top);
}

void Win32Window::processEvents (void)
{
	MSG msg;
	while (PeekMessage(&msg, m_window, 0, 0, PM_REMOVE))
		DispatchMessage(&msg);
}

LRESULT Win32Window::windowProc (UINT uMsg, WPARAM wParam, LPARAM lParam)
{
	switch (uMsg)
	{
		// \todo [2014-03-12 pyry] Handle WM_SIZE?

		case WM_DESTROY:
			PostQuitMessage(0);
			return 0;

		case WM_KEYDOWN:
			if (wParam == VK_ESCAPE)
			{
				PostQuitMessage(0);
				return 0;
			}
			// fall-through

		default:
			return DefWindowProc(m_window, uMsg, wParam, lParam);
	}
}

} // tcu
<commit_msg>Win32Window cleanup<commit_after>/*-------------------------------------------------------------------------
 * drawElements Quality Program Tester Core
 * ----------------------------------------
 *
 * Copyright 2014 The Android Open Source Project
 *
 * 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.
 *
 *//*!
 * \file
 * \brief Generic Win32 window class.
 *//*--------------------------------------------------------------------*/

#include "tcuWin32Window.hpp"

namespace tcu
{

static LRESULT CALLBACK win32WindowProc (HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
	Win32Window* window = reinterpret_cast<Win32Window*>(GetWindowLongPtr(hWnd, GWLP_USERDATA));
	if (window)
		return window->windowProc(uMsg, wParam, lParam);
	else
		return DefWindowProc(hWnd, uMsg, wParam, lParam);
}

Win32Window::Win32Window (HINSTANCE instance, int width, int height)
	: m_window		(DE_NULL)
{
	try
	{
		static const char	s_className[]	= "dEQP Test Process Class";
		static const char	s_windowName[]	= "dEQP Test Process";

		{
			WNDCLASS wndClass;
			memset(&wndClass, 0, sizeof(wndClass));
			wndClass.style			= CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
			wndClass.lpfnWndProc	= win32WindowProc;
			wndClass.cbClsExtra		= 0;
			wndClass.cbWndExtra		= 0;
			wndClass.hInstance		= instance;
			wndClass.hIcon			= LoadIcon(NULL, IDI_APPLICATION);
			wndClass.hCursor		= LoadCursor(NULL, IDC_ARROW);
			wndClass.hbrBackground	= CreateSolidBrush(RGB(0, 0, 0));
			wndClass.lpszMenuName	= NULL;
			wndClass.lpszClassName	= s_className;

			RegisterClass(&wndClass);
		}

		m_window = CreateWindow(s_className, s_windowName,
								WS_CLIPCHILDREN | WS_OVERLAPPEDWINDOW,
								CW_USEDEFAULT, CW_USEDEFAULT,
								width, height,
								NULL, NULL, instance, NULL);

		if (!m_window)
			TCU_THROW(ResourceError, "Failed to create Win32 window");

		// Store this as userdata
		SetWindowLongPtr(m_window, GWLP_USERDATA, (LONG_PTR)this);

		setSize(width, height);
	}
	catch (...)
	{
		if (m_window)
			DestroyWindow(m_window);

		throw;
	}
}

Win32Window::~Win32Window (void)
{
	if (m_window)
	{
		// Clear this pointer from windowproc
		SetWindowLongPtr(m_window, GWLP_USERDATA, 0);
	}

	DestroyWindow(m_window);
}

void Win32Window::setVisible (bool visible)
{
	ShowWindow(m_window, visible ? SW_SHOW : SW_HIDE);
}

void Win32Window::setSize (int width, int height)
{
	RECT rc;

	rc.left		= 0;
	rc.top		= 0;
	rc.right	= width;
	rc.bottom	= height;

	if (!AdjustWindowRect(&rc, GetWindowLong(m_window, GWL_STYLE), GetMenu(m_window) != NULL))
		TCU_THROW(TestError, "AdjustWindowRect() failed");

	if (!SetWindowPos(m_window, NULL, 0, 0,
					  rc.right - rc.left, rc.bottom - rc.top,
					  SWP_NOACTIVATE | SWP_NOCOPYBITS | SWP_NOMOVE | SWP_NOZORDER))
		TCU_THROW(TestError, "SetWindowPos() failed");
}

IVec2 Win32Window::getSize (void) const
{
	RECT rc;
	if (!GetClientRect(m_window, &rc))
		TCU_THROW(TestError, "GetClientRect() failed");

	return IVec2(rc.right - rc.left,
				 rc.bottom - rc.top);
}

void Win32Window::processEvents (void)
{
	MSG msg;
	while (PeekMessage(&msg, m_window, 0, 0, PM_REMOVE))
		DispatchMessage(&msg);
}

LRESULT Win32Window::windowProc (UINT uMsg, WPARAM wParam, LPARAM lParam)
{
	switch (uMsg)
	{
		// \todo [2014-03-12 pyry] Handle WM_SIZE?

		case WM_DESTROY:
			PostQuitMessage(0);
			return 0;

		case WM_KEYDOWN:
			if (wParam == VK_ESCAPE)
			{
				PostQuitMessage(0);
				return 0;
			}
			// fall-through

		default:
			return DefWindowProc(m_window, uMsg, wParam, lParam);
	}
}

} // tcu
<|endoftext|>


<commit_before>#include "Overlay.h"
#include "ui_Overlay.h"

#include "../Hearthstone.h"
#include "../Settings.h"

#ifdef Q_OS_MAC
#include <objc/objc-runtime.h>
#endif

#include <cassert>

#include <QJsonArray>
#include <QJsonObject>
#include <QJsonDocument>
#include <QFile>
#include <QMouseEvent>

#define CHECK_FOR_OVERLAY_HOVER_INTERVAL_MS 100

class OverlayHistoryWindow {
private:
  QString mTitle;
  OverlayHistoryList mHistory;

  QFont mRowFont;
  QFont mTitleFont;

  int mWidth;

  int mPadding;
  int mRowSpacing;

  int TitleHeight() const {
    QFontMetrics titleMetrics( mTitleFont );
    return titleMetrics.ascent() - titleMetrics.descent();
  }

  int Padding() const {
    return mPadding;
  }

  int RowSpacing() const {
    return mRowSpacing;
  }

  int RowHeight() const {
    QFontMetrics rowMetrics( mRowFont );
    return rowMetrics.ascent() - rowMetrics.descent();
  }

  int RowWidth() const {
    return Width() - Padding() * 2;
  }

  void DrawMana( QPainter& painter, int x, int y, int width, int height, int mana ) const {
    // Draw mana
    QPen origPen = painter.pen();
    QPen pen( QColor( 0, 52, 113 ) );
    pen.setCosmetic( true );
    pen.setWidth( 1 );
    painter.setPen( pen );

    QBrush brush( QColor( 40, 119, 238 ) );
    painter.setBrush( brush );

    QTransform transform;
    painter.translate( x + width * 0.5, y + height * 0.5 );
    painter.scale( width * 0.8, height * 0.8 );

    static const QPointF points[5] = {
      QPointF( 0.0, -1.0 ),
      QPointF( 1.0, -0.2 ),
      QPointF( 0.6, 1.0 ),
      QPointF( -0.6, 1.0 ),
      QPointF( -1.0, -0.2 ),
    };
    painter.drawConvexPolygon( points, 5 );
    painter.resetTransform();
    painter.setPen( origPen );

    painter.drawText( x, y, width, height, Qt::AlignCenter | Qt::AlignVCenter, QString::number( mana ) );
  }

  void DrawCardLine( QPainter& painter, int x, int y, int width, int height, const QString& name, int count ) const {
    painter.save();
    painter.drawText( x, y, width, height, Qt::AlignLeft | Qt::AlignVCenter | Qt::TextDontClip, name );

    if( count > 1 ) {
      int nameWidth = QFontMetrics( painter.font() ).width( name + " " );
      QString countString = QString( "x%1" ).arg( count );
      QFont font = painter.font();
      font.setBold( true );
      painter.setFont( font );
      painter.drawText( x + nameWidth, y, width - nameWidth, height, Qt::AlignLeft | Qt::AlignVCenter | Qt::TextDontClip, countString );
    }
    painter.restore();
  }

public:
  OverlayHistoryWindow( const QString& title, const OverlayHistoryList& history, int width, int padding, int rowSpacing, float titleFontSize, float rowFontSize )
    : mTitle( title ), mHistory( history ), mWidth( width ), mPadding( padding ), mRowSpacing( rowSpacing )
  {
    mRowFont.setPointSize( titleFontSize );
    mTitleFont.setPointSize( rowFontSize );
    mTitleFont.setUnderline( true );
    mTitleFont.setBold( true );
  }

  int Width() const {
    return mWidth;
  }

  int Height() const {
    return ( mHistory.count() - 1 ) * RowSpacing() + // Spacing between items
      mHistory.count() * RowHeight() + // Height per item
      TitleHeight() + RowSpacing() + // Title
      Padding() * 2; // Overall padding
  }

  void Paint( QPainter& painter, int x, int y ) const {
    painter.save();

    QRect rect( x, y, Width(), Height() );
    painter.setClipRect( rect );

    // BG
    QPen pen = QPen( QColor( 160, 160, 160 ) );
    pen.setWidth( 3 );
    painter.setPen( pen );
    painter.setBrush( QBrush( QColor( 70, 70, 70, 175 ) ) );
    painter.drawRoundedRect( rect, 10, 10 );

    // Title
    y += Padding();
    painter.setPen( QPen( Qt::white) );
    painter.setFont( mTitleFont );
    painter.drawText( x, y, Width(), TitleHeight(), Qt::AlignCenter | Qt::AlignVCenter | Qt::TextDontClip, mTitle );
    y += TitleHeight() + RowSpacing();

    // Lines
    painter.setPen( QPen( Qt::white) );
    painter.setFont( mRowFont );
    for( const QVariantMap& it : mHistory ) {
      int mx = x + Padding();
      DrawMana( painter, mx, y, RowHeight(), RowHeight(), it["mana"].toInt() );
      int cx = mx + RowHeight() + 5;
      DrawCardLine( painter, cx, y, RowWidth() - cx, RowHeight(), it["name"].toString(), it["count"].toInt() );
      y += RowHeight();
      y += RowSpacing();
    }

    painter.restore();
  }

};

Overlay::Overlay( QWidget *parent )
  : QMainWindow( parent ), mUI( new Ui::Overlay ), mShowPlayerHistory( PLAYER_UNKNOWN )
{
  mUI->setupUi( this );
  setWindowFlags( Qt::NoDropShadowWindowHint | Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint | Qt::WindowTransparentForInput );

#ifdef Q_OS_WIN
  setWindowFlags( windowFlags() | Qt::Tool );
#else
  setWindowFlags( windowFlags() | Qt::Window );
#endif

  setAttribute( Qt::WA_TranslucentBackground );
  setAttribute( Qt::WA_ShowWithoutActivating );

  connect( Hearthstone::Instance(), &Hearthstone::GameWindowChanged, this, &Overlay::HandleGameWindowChanged );
  connect( Hearthstone::Instance(), &Hearthstone::GameStarted, this, &Overlay::HandleGameStarted );
  connect( Hearthstone::Instance(), &Hearthstone::GameStopped, this, &Overlay::HandleGameStopped );
  connect( Hearthstone::Instance(), &Hearthstone::FocusChanged, this, &Overlay::HandleGameFocusChanged );

  connect( &mCheckForHoverTimer, &QTimer::timeout, this, &Overlay::CheckForHover );

  connect( Settings::Instance(), &Settings::OverlayEnabledChanged, this, &Overlay::HandleOverlaySettingChanged );

  hide();

#ifdef Q_OS_MAC
  WId windowObject = this->winId();
  objc_object* nsviewObject = reinterpret_cast<objc_object*>(windowObject);
  objc_object* nsWindowObject = objc_msgSend( nsviewObject, sel_registerName("window") );
  int NSWindowCollectionBehaviorCanJoinAllSpaces = 1 << 0;
  objc_msgSend( nsWindowObject, sel_registerName("setCollectionBehavior:"), NSWindowCollectionBehaviorCanJoinAllSpaces );

  // Ignore mouse events on Mac
  // Qt::WindowTransparentForInput bug
  // https://bugreports.qt.io/browse/QTBUG-45498
  objc_msgSend( nsWindowObject, sel_registerName("setIgnoresMouseEvents:"), 1 );
#endif
}

Overlay::~Overlay() {
  delete mUI;
}

void Overlay::CheckForHover() {
  QPoint mouseLoc = mapFromGlobal( QCursor::pos() );

  Player showPlayerHistory = PLAYER_UNKNOWN;

  if( mPlayerDeckRect.contains( mouseLoc ) ) {
    showPlayerHistory = PLAYER_SELF;
  } else if( mOpponentDeckRect.contains( mouseLoc ) ) {
    showPlayerHistory = PLAYER_OPPONENT;
  }

  if( mShowPlayerHistory != showPlayerHistory ) {
    mShowPlayerHistory = showPlayerHistory;
    update();
  }
}

void PaintHistoryInScreen( QPainter& painter, const OverlayHistoryWindow& wnd, const QPoint& pos ) {
  int padding = 10;

  QRect rect( pos.x() + 20, pos.y(), wnd.Width(), wnd.Height() );
  rect.translate( -qMax( rect.right() - painter.device()->width() + padding, 0 ), -qMax( rect.bottom() - painter.device()->height() + padding, 0 ) ); // fit to window
  wnd.Paint( painter, rect.x(), rect.y() );
}

void Overlay::paintEvent( QPaintEvent* ) {
  QString title;
  QRect rect;
  OverlayHistoryList *history = NULL;

  if( mShowPlayerHistory == PLAYER_SELF && mPlayerHistory.count() > 0 ) {
    title = "Cards drawn";
    history = &mPlayerHistory;
    rect = mPlayerDeckRect;
  } else if( mShowPlayerHistory == PLAYER_OPPONENT && mOpponentHistory.count() > 0 ) {
    title = "Cards played by opponent";
    history = &mOpponentHistory;
    rect = mOpponentDeckRect;
  }

  QPainter painter( this );
  painter.setRenderHint( QPainter::Antialiasing );

#ifdef Q_OS_WIN
  float rowFontSize = 9;
  float titleFontSize = 9;
#else
  float rowFontSize = 12;
  float titleFontSize = 12;
#endif

  int spacing = 8;
  int overlayWidth = 200;

  if( history ) {
    OverlayHistoryWindow wnd( title, *history, overlayWidth, spacing, spacing, titleFontSize, rowFontSize );
    QPoint pos = rect.center() + QPoint( rect.width() / 2 + 10, -wnd.Height() / 2 );
    PaintHistoryInScreen( painter, wnd, pos );
  }
}

void Overlay::HandleGameWindowChanged( int x, int y, int w, int h ) {
  // Order is important
  // Otherwise starting fullscreen on windows
  // will not show the overlay unless the FS mode is toggled
  setFixedSize( w, h );
  move( x, y );

  int minWidth = h * 4 / 3;
  mPlayerDeckRect = QRect( w / 2 + 0.440 * minWidth, h * 0.510, 0.05 * minWidth, h * 0.170 );
  mOpponentDeckRect = mPlayerDeckRect.translated( -0.005 * minWidth, -0.275 * h );

  Update();
}

void Overlay::Update() {
  bool showable = false;

  if( Hearthstone::Instance()->GameRunning() && Settings::Instance()->OverlayEnabled() ) {
    showable = true;
    if( !mCardDB.Loaded() ) {
      mCardDB.Load();
    }
  } else {
    if( mCardDB.Loaded() ) {
      mCardDB.Unload();
    }
  }

  if( showable && Hearthstone::Instance()->HasFocus() ) {
    hide(); // Minimize/Restore on Windows requires a hide() first
    show();
#ifdef Q_OS_WIN
    setAttribute( Qt::WA_QuitOnClose ); // otherwise taskkill /IM Track-o-Bot.exe does not work (http://www.qtcentre.org/threads/11713-Qt-Tool?p=62466#post62466)
#endif
  } else {
    hide();
  }

  update();
}

void Overlay::HandleGameStarted() {
  mCheckForHoverTimer.start( CHECK_FOR_OVERLAY_HOVER_INTERVAL_MS );
  Update();
}

void Overlay::HandleGameStopped() {
  mCheckForHoverTimer.stop();
  Update();
}

void Overlay::UpdateHistoryFor( Player player, const ::CardHistoryList& list ) {
  QMap< QString, QVariantMap > entries;

  for( const CardHistoryItem& it : list ) {
    const QString& cardId = it.cardId;

    if( cardId.isEmpty() ) {
      continue;
    }

    if( !mCardDB.Contains( cardId ) ) {
      DBG( "Card %s not found", qt2cstr( cardId ) );
      continue;
    }

    if( mCardDB.Type( cardId ) == "HERO_POWER" ) {
      continue;
    }

    if( it.player != player ) {
      continue;
    }

    QVariantMap& entry = entries[ cardId ];
    entry[ "count" ] = entry.value( "count", 0 ).toInt() + 1;
    entry[ "mana" ] = mCardDB.Cost( cardId );
    entry[ "name" ] = mCardDB.Name( cardId );
  }

  OverlayHistoryList* ref;
  if( player == PLAYER_SELF ) {
    ref = &mPlayerHistory;
  } else {
    ref = &mOpponentHistory;
  }

  *ref = entries.values();

  qSort( ref->begin(), ref->end(), []( const QVariantMap& a, const QVariantMap& b ) {
    if( a["mana"].toInt() == b["mana"].toInt() ) {
      return a["name"].toString() < b["name"].toString();
    } else {
      return a["mana"].toInt() < b["mana"].toInt();
    }
  });
}

void Overlay::HandleCardsDrawnUpdate( const ::CardHistoryList& cardsDrawn ) {
  UpdateHistoryFor( PLAYER_OPPONENT, cardsDrawn );
  UpdateHistoryFor( PLAYER_SELF, cardsDrawn );
  Update();
}

void Overlay::HandleOverlaySettingChanged( bool enabled ) {
  UNUSED_ARG( enabled );

  Update();
}

void Overlay::HandleGameFocusChanged( bool focus ) {
  DBG( "HandleFocusChanged %d", focus );
  Update();
}
<commit_msg>Adapting overlay text for small displays. 2x is now printed in front of the card text.<commit_after>#include "Overlay.h"
#include "ui_Overlay.h"

#include "../Hearthstone.h"
#include "../Settings.h"

#ifdef Q_OS_MAC
#include <objc/objc-runtime.h>
#endif

#include <cassert>

#include <QJsonArray>
#include <QJsonObject>
#include <QJsonDocument>
#include <QFile>
#include <QMouseEvent>

#define CHECK_FOR_OVERLAY_HOVER_INTERVAL_MS 100

class OverlayHistoryWindow {
private:
  QString mTitle;
  OverlayHistoryList mHistory;

  QFont mRowFont;
  QFont mTitleFont;

  int mWidth;

  int mPadding;
  int mRowSpacing;

  int TitleHeight() const {
    QFontMetrics titleMetrics( mTitleFont );
    return titleMetrics.ascent() - titleMetrics.descent();
  }

  int Padding() const {
    return mPadding;
  }

  int RowSpacing() const {
    return mRowSpacing;
  }

  int RowHeight() const {
    QFontMetrics rowMetrics( mRowFont );
    return rowMetrics.ascent() - rowMetrics.descent();
  }

  int RowWidth() const {
    return Width() - Padding() * 2;
  }

  void DrawMana( QPainter& painter, int x, int y, int width, int height, int mana ) const {
    // Draw mana
    QPen origPen = painter.pen();
    QPen pen( QColor( 0, 52, 113 ) );
    pen.setCosmetic( true );
    pen.setWidth( 1 );
    painter.setPen( pen );

    QBrush brush( QColor( 40, 119, 238 ) );
    painter.setBrush( brush );

    QTransform transform;
    painter.translate( x + width * 0.5, y + height * 0.5 );
    painter.scale( width * 0.8, height * 0.8 );

    static const QPointF points[5] = {
      QPointF( 0.0, -1.0 ),
      QPointF( 1.0, -0.2 ),
      QPointF( 0.6, 1.0 ),
      QPointF( -0.6, 1.0 ),
      QPointF( -1.0, -0.2 ),
    };
    painter.drawConvexPolygon( points, 5 );
    painter.resetTransform();
    painter.setPen( origPen );

    painter.drawText( x, y, width, height, Qt::AlignCenter | Qt::AlignVCenter, QString::number( mana ) );
  }

  void DrawCardLine( QPainter& painter, int x, int y, int width, int height, const QString& name, int count ) const {
    painter.save();
	QString text = name;

	if( count > 1 ) {
      text.prepend(QString( "%1x " ).arg( count ));
      QFont font = painter.font();
      font.setBold( true );
      painter.setFont( font );
    }

    painter.drawText( x, y, width, height, Qt::AlignLeft | Qt::AlignVCenter | Qt::TextDontClip, text );
    painter.restore();
  }

public:
  OverlayHistoryWindow( const QString& title, const OverlayHistoryList& history, int width, int padding, int rowSpacing, float titleFontSize, float rowFontSize )
    : mTitle( title ), mHistory( history ), mWidth( width ), mPadding( padding ), mRowSpacing( rowSpacing )
  {
    mRowFont.setPointSize( titleFontSize );
    mTitleFont.setPointSize( rowFontSize );
    mTitleFont.setUnderline( true );
    mTitleFont.setBold( true );
  }

  int Width() const {
    return mWidth;
  }

  int Height() const {
    return ( mHistory.count() - 1 ) * RowSpacing() + // Spacing between items
      mHistory.count() * RowHeight() + // Height per item
      TitleHeight() + RowSpacing() + // Title
      Padding() * 2; // Overall padding
  }

  void Paint( QPainter& painter, int x, int y ) const {
    painter.save();

    QRect rect( x, y, Width(), Height() );
    painter.setClipRect( rect );

    // BG
    QPen pen = QPen( QColor( 160, 160, 160 ) );
    pen.setWidth( 3 );
    painter.setPen( pen );
    painter.setBrush( QBrush( QColor( 70, 70, 70, 175 ) ) );
    painter.drawRoundedRect( rect, 10, 10 );

    // Title
    y += Padding();
    painter.setPen( QPen( Qt::white) );
    painter.setFont( mTitleFont );
    painter.drawText( x, y, Width(), TitleHeight(), Qt::AlignCenter | Qt::AlignVCenter | Qt::TextDontClip, mTitle );
    y += TitleHeight() + RowSpacing();

    // Lines
    painter.setPen( QPen( Qt::white) );
    painter.setFont( mRowFont );
    for( const QVariantMap& it : mHistory ) {
      int mx = x + Padding();
      DrawMana( painter, mx, y, RowHeight(), RowHeight(), it["mana"].toInt() );
      int cx = mx + RowHeight() + 5;
      DrawCardLine( painter, cx, y, RowWidth() - cx, RowHeight(), it["name"].toString(), it["count"].toInt() );
      y += RowHeight();
      y += RowSpacing();
    }

    painter.restore();
  }

};

Overlay::Overlay( QWidget *parent )
  : QMainWindow( parent ), mUI( new Ui::Overlay ), mShowPlayerHistory( PLAYER_UNKNOWN )
{
  mUI->setupUi( this );
  setWindowFlags( Qt::NoDropShadowWindowHint | Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint | Qt::WindowTransparentForInput );

#ifdef Q_OS_WIN
  setWindowFlags( windowFlags() | Qt::Tool );
#else
  setWindowFlags( windowFlags() | Qt::Window );
#endif

  setAttribute( Qt::WA_TranslucentBackground );
  setAttribute( Qt::WA_ShowWithoutActivating );

  connect( Hearthstone::Instance(), &Hearthstone::GameWindowChanged, this, &Overlay::HandleGameWindowChanged );
  connect( Hearthstone::Instance(), &Hearthstone::GameStarted, this, &Overlay::HandleGameStarted );
  connect( Hearthstone::Instance(), &Hearthstone::GameStopped, this, &Overlay::HandleGameStopped );
  connect( Hearthstone::Instance(), &Hearthstone::FocusChanged, this, &Overlay::HandleGameFocusChanged );

  connect( &mCheckForHoverTimer, &QTimer::timeout, this, &Overlay::CheckForHover );

  connect( Settings::Instance(), &Settings::OverlayEnabledChanged, this, &Overlay::HandleOverlaySettingChanged );

  hide();

#ifdef Q_OS_MAC
  WId windowObject = this->winId();
  objc_object* nsviewObject = reinterpret_cast<objc_object*>(windowObject);
  objc_object* nsWindowObject = objc_msgSend( nsviewObject, sel_registerName("window") );
  int NSWindowCollectionBehaviorCanJoinAllSpaces = 1 << 0;
  objc_msgSend( nsWindowObject, sel_registerName("setCollectionBehavior:"), NSWindowCollectionBehaviorCanJoinAllSpaces );

  // Ignore mouse events on Mac
  // Qt::WindowTransparentForInput bug
  // https://bugreports.qt.io/browse/QTBUG-45498
  objc_msgSend( nsWindowObject, sel_registerName("setIgnoresMouseEvents:"), 1 );
#endif
}

Overlay::~Overlay() {
  delete mUI;
}

void Overlay::CheckForHover() {
  QPoint mouseLoc = mapFromGlobal( QCursor::pos() );

  Player showPlayerHistory = PLAYER_UNKNOWN;

  if( mPlayerDeckRect.contains( mouseLoc ) ) {
    showPlayerHistory = PLAYER_SELF;
  } else if( mOpponentDeckRect.contains( mouseLoc ) ) {
    showPlayerHistory = PLAYER_OPPONENT;
  }

  if( mShowPlayerHistory != showPlayerHistory ) {
    mShowPlayerHistory = showPlayerHistory;
    update();
  }
}

void PaintHistoryInScreen( QPainter& painter, const OverlayHistoryWindow& wnd, const QPoint& pos ) {
  int padding = 10;

  QRect rect( pos.x() + 20, pos.y(), wnd.Width(), wnd.Height() );
  rect.translate( -qMax( rect.right() - painter.device()->width() + padding, 0 ), -qMax( rect.bottom() - painter.device()->height() + padding, 0 ) ); // fit to window
  wnd.Paint( painter, rect.x(), rect.y() );
}

void Overlay::paintEvent( QPaintEvent* ) {
  QString title;
  QRect rect;
  OverlayHistoryList *history = NULL;

  if( mShowPlayerHistory == PLAYER_SELF && mPlayerHistory.count() > 0 ) {
    title = "Cards drawn";
    history = &mPlayerHistory;
    rect = mPlayerDeckRect;
  } else if( mShowPlayerHistory == PLAYER_OPPONENT && mOpponentHistory.count() > 0 ) {
    title = "Opponent played";
    history = &mOpponentHistory;
    rect = mOpponentDeckRect;
  }

  QPainter painter( this );
  painter.setRenderHint( QPainter::Antialiasing );

#ifdef Q_OS_WIN
  float rowFontSize = 9;
  float titleFontSize = 9;
#else
  float rowFontSize = 12;
  float titleFontSize = 12;
#endif

  int spacing = 8;
  int overlayWidth = 200;

  if( history ) {
    OverlayHistoryWindow wnd( title, *history, overlayWidth, spacing, spacing, titleFontSize, rowFontSize );
    QPoint pos = rect.center() + QPoint( rect.width() / 2 + 10, -wnd.Height() / 2 );
    PaintHistoryInScreen( painter, wnd, pos );
  }
}

void Overlay::HandleGameWindowChanged( int x, int y, int w, int h ) {
  // Order is important
  // Otherwise starting fullscreen on windows
  // will not show the overlay unless the FS mode is toggled
  setFixedSize( w, h );
  move( x, y );

  int minWidth = h * 4 / 3;
  mPlayerDeckRect = QRect( w / 2 + 0.440 * minWidth, h * 0.510, 0.05 * minWidth, h * 0.170 );
  mOpponentDeckRect = mPlayerDeckRect.translated( -0.005 * minWidth, -0.275 * h );

  Update();
}

void Overlay::Update() {
  bool showable = false;

  if( Hearthstone::Instance()->GameRunning() && Settings::Instance()->OverlayEnabled() ) {
    showable = true;
    if( !mCardDB.Loaded() ) {
      mCardDB.Load();
    }
  } else {
    if( mCardDB.Loaded() ) {
      mCardDB.Unload();
    }
  }

  if( showable && Hearthstone::Instance()->HasFocus() ) {
    hide(); // Minimize/Restore on Windows requires a hide() first
    show();
#ifdef Q_OS_WIN
    setAttribute( Qt::WA_QuitOnClose ); // otherwise taskkill /IM Track-o-Bot.exe does not work (http://www.qtcentre.org/threads/11713-Qt-Tool?p=62466#post62466)
#endif
  } else {
    hide();
  }

  update();
}

void Overlay::HandleGameStarted() {
  mCheckForHoverTimer.start( CHECK_FOR_OVERLAY_HOVER_INTERVAL_MS );
  Update();
}

void Overlay::HandleGameStopped() {
  mCheckForHoverTimer.stop();
  Update();
}

void Overlay::UpdateHistoryFor( Player player, const ::CardHistoryList& list ) {
  QMap< QString, QVariantMap > entries;

  for( const CardHistoryItem& it : list ) {
    const QString& cardId = it.cardId;

    if( cardId.isEmpty() ) {
      continue;
    }

    if( !mCardDB.Contains( cardId ) ) {
      DBG( "Card %s not found", qt2cstr( cardId ) );
      continue;
    }

    if( mCardDB.Type( cardId ) == "HERO_POWER" ) {
      continue;
    }

    if( it.player != player ) {
      continue;
    }

    QVariantMap& entry = entries[ cardId ];
    entry[ "count" ] = entry.value( "count", 0 ).toInt() + 1;
    entry[ "mana" ] = mCardDB.Cost( cardId );
    entry[ "name" ] = mCardDB.Name( cardId );
  }

  OverlayHistoryList* ref;
  if( player == PLAYER_SELF ) {
    ref = &mPlayerHistory;
  } else {
    ref = &mOpponentHistory;
  }

  *ref = entries.values();

  qSort( ref->begin(), ref->end(), []( const QVariantMap& a, const QVariantMap& b ) {
    if( a["mana"].toInt() == b["mana"].toInt() ) {
      return a["name"].toString() < b["name"].toString();
    } else {
      return a["mana"].toInt() < b["mana"].toInt();
    }
  });
}

void Overlay::HandleCardsDrawnUpdate( const ::CardHistoryList& cardsDrawn ) {
  UpdateHistoryFor( PLAYER_OPPONENT, cardsDrawn );
  UpdateHistoryFor( PLAYER_SELF, cardsDrawn );
  Update();
}

void Overlay::HandleOverlaySettingChanged( bool enabled ) {
  UNUSED_ARG( enabled );

  Update();
}

void Overlay::HandleGameFocusChanged( bool focus ) {
  DBG( "HandleFocusChanged %d", focus );
  Update();
}
<|endoftext|>


<commit_before>#pragma once

#include <unordered_map>
#include <cmath>

namespace euler::primes {

/**
 * Return a N+1 size array of booleans such that
 * mask[a] is true iff a is a composite number.
 */
template<int N>
constexpr std::array<bool, N + 1> composite_mask() {

    static_assert(N >= 0, "N must be non-negative.");

    std::array<bool, N + 1> mask = {true, true};

    for (int i = 2; i*i <= N; ++i)
        if (!mask[i])
            for (int j = i * i; j <= N; j += i)
                mask[j] = true;
    return mask;
}
template<> constexpr std::array<bool, 1> composite_mask<0>() { return {true}; };
template<> constexpr std::array<bool, 2> composite_mask<1>() { return {true, true}; };

/**
 * Fill a supplied map with (p : a) pairs where a is
 * the largest power of p which divides n.
 */
template<typename Integer = int,
         typename Power = int,
         typename Maptype = std::unordered_map<Integer, Power>>
void prime_map(Integer n, Maptype &map) {

    Integer d = 2;

    while (d * d <= n) {
        while (n % d == 0) {
            if (map.count(d)) {
                map[d] += 1;
            } else {
                map.emplace(d, 1);
            }
            n /= d;
        }
        ++d;
    }

    if (n > 1)
        map.emplace(n, 1);
};

/**
 * Return the number of divisors for n^(power).
 */
template<typename Integer = int, typename Power = int>
Integer number_of_divisors(Integer n, Power power = 1) {
    std::unordered_map<Integer, Integer> primes;
    prime_map(n, primes);
    Integer count = 1;
    for (auto [p, a] : primes) {
        count *= power * a + 1;
    }
    return count;
}
}
<commit_msg>Add missing includes.<commit_after>#pragma once

#include <cmath>
#include <array>
#include <unordered_map>

namespace euler::primes {

/**
 * Return a N+1 size array of booleans such that
 * mask[a] is true iff a is a composite number.
 */
template<int N>
constexpr std::array<bool, N + 1> composite_mask() {

    static_assert(N >= 0, "N must be non-negative.");

    std::array<bool, N + 1> mask = {true, true};

    for (int i = 2; i*i <= N; ++i)
        if (!mask[i])
            for (int j = i * i; j <= N; j += i)
                mask[j] = true;
    return mask;
}
template<> constexpr std::array<bool, 1> composite_mask<0>() { return {true}; };
template<> constexpr std::array<bool, 2> composite_mask<1>() { return {true, true}; };

/**
 * Fill a supplied map with (p : a) pairs where a is
 * the largest power of p which divides n.
 */
template<typename Integer = int,
         typename Power = int,
         typename Maptype = std::unordered_map<Integer, Power>>
void prime_map(Integer n, Maptype &map) {

    Integer d = 2;

    while (d * d <= n) {
        while (n % d == 0) {
            if (map.count(d)) {
                map[d] += 1;
            } else {
                map.emplace(d, 1);
            }
            n /= d;
        }
        ++d;
    }

    if (n > 1)
        map.emplace(n, 1);
};

/**
 * Return the number of divisors for n^(power).
 */
template<typename Integer = int, typename Power = int>
Integer number_of_divisors(Integer n, Power power = 1) {
    std::unordered_map<Integer, Integer> primes;
    prime_map(n, primes);
    Integer count = 1;
    for (auto [p, a] : primes) {
        count *= power * a + 1;
    }
    return count;
}
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: backingwindow.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2008-03-12 10:10:06 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef FRAMEWORK_BACKINGWINDOW_HXX
#define FRAMEWORK_BACKINGWINDOW_HXX

#include "rtl/ustring.hxx"

#include "vcl/button.hxx"
#include "vcl/fixed.hxx"
#include "vcl/bitmapex.hxx"
#include "vcl/toolbox.hxx"

#include "svtools/moduleoptions.hxx"

#include "com/sun/star/frame/XDispatchProvider.hpp"
#include "com/sun/star/frame/XDesktop.hpp"
#include "com/sun/star/frame/XTerminateListener.hpp"
#include "com/sun/star/document/XEventListener.hpp"
#include "com/sun/star/document/XEventBroadcaster.hpp"
#include "com/sun/star/util/XURLTransformer.hpp"
#include "com/sun/star/ui/dialogs/XFilePicker.hpp"
#include "com/sun/star/ui/dialogs/XFilePickerControlAccess.hpp"
#include "com/sun/star/ui/dialogs/XFilterManager.hpp"
#include "com/sun/star/ui/dialogs/XFolderPicker.hpp"
#include "com/sun/star/ui/dialogs/TemplateDescription.hpp"
#include "com/sun/star/ui/dialogs/ExecutableDialogResults.hpp"

#include <set>

namespace framework
{
        // To get the transparent mouse-over look, the closer is actually a toolbox
    // overload DataChange to handle style changes correctly
    class DecoToolBox : public ToolBox
    {
        Size maMinSize;

        using Window::ImplInit;
    public:
                DecoToolBox( Window* pParent, WinBits nStyle = 0 );
                DecoToolBox( Window* pParent, const ResId& rResId );

        void    DataChanged( const DataChangedEvent& rDCEvt );

        void    calcMinSize();
        Size    getMinSize();
    };

    class BackingWindow : public Window
    {
        com::sun::star::uno::Reference<com::sun::star::frame::XDesktop>                  mxDesktop;
        com::sun::star::uno::Reference<com::sun::star::frame::XDispatchProvider >        mxDesktopDispatchProvider;
        com::sun::star::uno::Reference<com::sun::star::document::XEventBroadcaster>      mxBroadcaster;

        FixedText                       maWelcome;
        Size                            maWelcomeSize;
        FixedText                       maProduct;
        Size                            maProductSize;
        FixedText                       maCreateText;
        Size                            maCreateSize;
        FixedText                       maWriterText;
        ImageButton                     maWriterButton;
        FixedText                       maCalcText;
        ImageButton                     maCalcButton;
        FixedText                       maImpressText;
        ImageButton                     maImpressButton;
        FixedText                       maDrawText;
        ImageButton                     maDrawButton;
        FixedText                       maDBText;
        ImageButton                     maDBButton;
        FixedText                       maOpenText;
        ImageButton                     maOpenButton;
        FixedText                       maTemplateText;
        ImageButton                     maTemplateButton;

        DecoToolBox                     maToolbox;

        BitmapEx                        maBackgroundLeft;
        BitmapEx                        maBackgroundMiddle;
        BitmapEx                        maBackgroundRight;

        String                          maWelcomeString;
        String                          maProductString;
        String                          maCreateString;
        String                          maOpenString;
        String                          maTemplateString;

        Font                            maTextFont;
        Rectangle                       maControlRect;

        long                            mnColumnWidth[2];
        Color                           maLabelTextColor;
        Color                           maWelcomeTextColor;

        Size                            maButtonImageSize;

        static const long nBtnPos = 240;
        static const int nItemId_Extensions = 1;
        static const int nItemId_Reg = 2;
        static const int nItemId_Info = 3;
        static const int nShadowTop = 32;
        static const int nShadowLeft = 35;
        static const int nShadowRight = 45;
        static const int nShadowBottom = 50;

        void loadImage( const ResId& i_rId, ImageButton& i_rButton );

        void layoutButtonAndText( const char* i_pURL, int nColumn, const std::set<rtl::OUString>& i_rURLS,
                                  SvtModuleOptions& i_rOpt, SvtModuleOptions::EModule i_eMod,
                                  ImageButton& i_rBtn, FixedText& i_rText,
                                  const String& i_rStr = String()
                                  );

        bool executeFileOpen();
        void dispatchURL( const rtl::OUString& i_rURL,
                          const rtl::OUString& i_rTarget = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "_default" ) ),
                          const com::sun::star::uno::Reference< com::sun::star::frame::XDispatchProvider >& i_xProv = com::sun::star::uno::Reference< com::sun::star::frame::XDispatchProvider >(),
                          const com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue >& = com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue >()
                          );

        DECL_LINK( ClickHdl, Button* );
        DECL_LINK( ToolboxHdl, void* );
        public:
        BackingWindow( Window* pParent );
        ~BackingWindow();

        virtual void        Paint( const Rectangle& rRect );
        virtual void        Resize();
    };

}

#endif
<commit_msg>INTEGRATION: CWS vcl87 (1.3.2); FILE MERGED 2008/03/18 15:30:35 pl 1.3.2.6: #i87065# initControls only after menubar is set in attachFrame 2008/03/17 16:45:37 pl 1.3.2.5: #i87124# reuse menu file open implementation via dispatch 2008/03/17 15:59:34 pl 1.3.2.4: #i87056# accelerator handling in StartCenter 2008/03/17 13:00:48 pl 1.3.2.3: #i87065# lazy initControls to get menu bar accelerators 2008/03/15 15:34:44 pl 1.3.2.2: #i86671# create mnemonics on the fly 2008/03/15 14:49:15 pl 1.3.2.1: #i86929# change tab order in StartCenter<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: backingwindow.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: kz $ $Date: 2008-04-03 17:11:50 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef FRAMEWORK_BACKINGWINDOW_HXX
#define FRAMEWORK_BACKINGWINDOW_HXX

#include "rtl/ustring.hxx"

#include "vcl/button.hxx"
#include "vcl/fixed.hxx"
#include "vcl/bitmapex.hxx"
#include "vcl/toolbox.hxx"

#include "svtools/moduleoptions.hxx"
#include "svtools/acceleratorexecute.hxx"

#include "com/sun/star/frame/XDispatchProvider.hpp"
#include "com/sun/star/frame/XDesktop.hpp"
#include "com/sun/star/frame/XFrame.hpp"
#include "com/sun/star/frame/XTerminateListener.hpp"
#include "com/sun/star/document/XEventListener.hpp"
#include "com/sun/star/document/XEventBroadcaster.hpp"
#include "com/sun/star/util/XURLTransformer.hpp"
#include "com/sun/star/ui/dialogs/XFilePicker.hpp"
#include "com/sun/star/ui/dialogs/XFilePickerControlAccess.hpp"
#include "com/sun/star/ui/dialogs/XFilterManager.hpp"
#include "com/sun/star/ui/dialogs/XFolderPicker.hpp"
#include "com/sun/star/ui/dialogs/TemplateDescription.hpp"
#include "com/sun/star/ui/dialogs/ExecutableDialogResults.hpp"

#include <set>

class MnemonicGenerator;

namespace framework
{
        // To get the transparent mouse-over look, the closer is actually a toolbox
    // overload DataChange to handle style changes correctly
    class DecoToolBox : public ToolBox
    {
        Size maMinSize;

        using Window::ImplInit;
    public:
                DecoToolBox( Window* pParent, WinBits nStyle = 0 );
                DecoToolBox( Window* pParent, const ResId& rResId );

        void    DataChanged( const DataChangedEvent& rDCEvt );

        void    calcMinSize();
        Size    getMinSize();
    };

    class BackingWindow : public Window
    {
        com::sun::star::uno::Reference<com::sun::star::frame::XDesktop>                  mxDesktop;
        com::sun::star::uno::Reference<com::sun::star::frame::XDispatchProvider >        mxDesktopDispatchProvider;
        com::sun::star::uno::Reference<com::sun::star::frame::XFrame>                    mxFrame;
        com::sun::star::uno::Reference<com::sun::star::document::XEventBroadcaster>      mxBroadcaster;

        FixedText                       maWelcome;
        Size                            maWelcomeSize;
        FixedText                       maProduct;
        Size                            maProductSize;
        FixedText                       maCreateText;
        Size                            maCreateSize;
        FixedText                       maWriterText;
        ImageButton                     maWriterButton;
        FixedText                       maCalcText;
        ImageButton                     maCalcButton;
        FixedText                       maImpressText;
        ImageButton                     maImpressButton;
        FixedText                       maDrawText;
        ImageButton                     maDrawButton;
        FixedText                       maDBText;
        ImageButton                     maDBButton;
        FixedText                       maTemplateText;
        ImageButton                     maTemplateButton;
        FixedText                       maOpenText;
        ImageButton                     maOpenButton;

        DecoToolBox                     maToolbox;

        BitmapEx                        maBackgroundLeft;
        BitmapEx                        maBackgroundMiddle;
        BitmapEx                        maBackgroundRight;

        String                          maWelcomeString;
        String                          maProductString;
        String                          maCreateString;
        String                          maOpenString;
        String                          maTemplateString;

        Font                            maTextFont;
        Rectangle                       maControlRect;

        long                            mnColumnWidth[2];
        Color                           maLabelTextColor;
        Color                           maWelcomeTextColor;

        Size                            maButtonImageSize;

        bool                            mbInitControls;
        svt::AcceleratorExecute*        mpAccExec;

        static const long nBtnPos = 240;
        static const int nItemId_Extensions = 1;
        static const int nItemId_Reg = 2;
        static const int nItemId_Info = 3;
        static const int nShadowTop = 32;
        static const int nShadowLeft = 35;
        static const int nShadowRight = 45;
        static const int nShadowBottom = 50;

        void loadImage( const ResId& i_rId, ImageButton& i_rButton );

        void layoutButtonAndText( const char* i_pURL, int nColumn, const std::set<rtl::OUString>& i_rURLS,
                                  SvtModuleOptions& i_rOpt, SvtModuleOptions::EModule i_eMod,
                                  ImageButton& i_rBtn, FixedText& i_rText,
                                  MnemonicGenerator& i_rMnemonicGen,
                                  const String& i_rStr = String()
                                  );

        void dispatchURL( const rtl::OUString& i_rURL,
                          const rtl::OUString& i_rTarget = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "_default" ) ),
                          const com::sun::star::uno::Reference< com::sun::star::frame::XDispatchProvider >& i_xProv = com::sun::star::uno::Reference< com::sun::star::frame::XDispatchProvider >(),
                          const com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue >& = com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue >()
                          );

        DECL_LINK( ClickHdl, Button* );
        DECL_LINK( ToolboxHdl, void* );

        void initControls();
        public:
        BackingWindow( Window* pParent );
        ~BackingWindow();

        virtual void        Paint( const Rectangle& rRect );
        virtual void        Resize();
        virtual long        Notify( NotifyEvent& rNEvt );

        void setOwningFrame( const com::sun::star::uno::Reference< com::sun::star::frame::XFrame >& xFrame );
    };

}

#endif
<|endoftext|>


<commit_before>/****************************************************************/
/*               DO NOT MODIFY THIS HEADER                      */
/* MOOSE - Multiphysics Object Oriented Simulation Environment  */
/*                                                              */
/*           (c) 2010 Battelle Energy Alliance, LLC             */
/*                   ALL RIGHTS RESERVED                        */
/*                                                              */
/*          Prepared by Battelle Energy Alliance, LLC           */
/*            Under Contract No. DE-AC07-05ID14517              */
/*            With the U. S. Department of Energy               */
/*                                                              */
/*            See COPYRIGHT for full restrictions               */
/****************************************************************/

// Moose
#include "FindContactPoint.h"
#include "LineSegment.h"

// libMesh
#include "libmesh/boundary_info.h"
#include "libmesh/elem.h"
#include "libmesh/plane.h"
#include "libmesh/fe_interface.h"
#include "libmesh/dense_matrix.h"
#include "libmesh/dense_vector.h"
#include "libmesh/fe_base.h"

namespace Moose
{

/**
 * Finds the closest point (called the contact point) on the master_elem on side "side" to the slave_point.
 *
 * @param master_elem The element on the master side of the interface
 * @param side The side number of the side of the master element
 * @param slave_point The physical space coordinates of the slave node
 * @param contact_ref The reference coordinate position of the contact point
 * @param contact_phys The physical space coordinates of the contact point
 * @param distance The distance between the slave_point and the contact point
 * @param normal The unit normal at the contact_point
 * @param contact_point_on_side whether or not the contact_point actually lies on _that_ side of the element.
 */
void
findContactPoint(PenetrationLocator::PenetrationInfo & p_info,
                 FEBase * _fe, FEType & _fe_type, const Point & slave_point,
                 bool start_with_centroid, const Real tangential_tolerance,
                 bool & contact_point_on_side)
{
  const Elem * master_elem = p_info._elem;

  unsigned int dim = master_elem->dim();

  const Elem * side = p_info._side;

  const std::vector<Point> & phys_point = _fe->get_xyz();

  const std::vector<RealGradient> & dxyz_dxi = _fe->get_dxyzdxi();
  const std::vector<RealGradient> & d2xyz_dxi2 = _fe->get_d2xyzdxi2();
  const std::vector<RealGradient> & d2xyz_dxieta = _fe->get_d2xyzdxideta();

  const std::vector<RealGradient> & dxyz_deta = _fe->get_dxyzdeta();
  const std::vector<RealGradient> & d2xyz_deta2 = _fe->get_d2xyzdeta2();
  const std::vector<RealGradient> & d2xyz_detaxi = _fe->get_d2xyzdxideta();

  if (dim == 1)
  {
    unsigned left(0);
    unsigned right(left);
    Real leftCoor((*master_elem->get_node(0))(0));
    Real rightCoor(left);
    for (unsigned i(1); i < master_elem->n_nodes(); ++i)
    {
      Real coor = (*master_elem->get_node(i))(0);
      if (coor < leftCoor)
      {
        left = i;
        leftCoor = coor;
      }
      if (coor > rightCoor)
      {
        right = i;
        rightCoor = coor;
      }
    }
    unsigned nearestNode(left);
    Point nearestPoint(leftCoor, 0, 0);
    if (side->node(0) == right)
    {
      nearestNode = right;
      nearestPoint(0) = rightCoor;
    }
    p_info._closest_point_ref = FEInterface::inverse_map(dim, _fe_type, master_elem, nearestPoint, TOLERANCE, false);
    p_info._closest_point = nearestPoint;
    p_info._normal = Point(left == nearestNode ? -1 : 1, 0, 0);
    p_info._distance = (p_info._closest_point - slave_point) * p_info._normal;
    p_info._dxyzdxi = dxyz_dxi;
    p_info._dxyzdeta = dxyz_deta;
    p_info._d2xyzdxideta = d2xyz_dxieta;
    p_info._side_phi = _fe->get_phi();
    contact_point_on_side = true;
    return;
  }

  Point ref_point;

  if(start_with_centroid)
    ref_point = FEInterface::inverse_map(dim-1, _fe_type, side, side->centroid(), TOLERANCE, false);
  else
    ref_point = p_info._closest_point_ref;

  std::vector<Point> points(1);
  points[0] = ref_point;
  _fe->reinit(side, &points);
  RealGradient d = slave_point - phys_point[0];

  Real update_size = 9999999;

  //Least squares
  for(unsigned int it=0; it<3 && update_size > TOLERANCE*1e3; ++it)
  {

    DenseMatrix<Real> jac(dim-1, dim-1);

    jac(0,0) = -(dxyz_dxi[0] * dxyz_dxi[0]);

    if(dim-1 == 2)
    {
      jac(1,0) = -(dxyz_dxi[0] * dxyz_deta[0]);

      jac(0,1) = -(dxyz_deta[0] * dxyz_dxi[0]);
      jac(1,1) = -(dxyz_deta[0] * dxyz_deta[0]);
    }

    DenseVector<Real> rhs(dim-1);

    rhs(0) = dxyz_dxi[0]*d;

    if(dim-1 == 2)
      rhs(1) = dxyz_deta[0]*d;

    DenseVector<Real> update(dim-1);

    jac.lu_solve(rhs, update);

    ref_point(0) -= update(0);

    if(dim-1 == 2)
      ref_point(1) -= update(1);

    points[0] = ref_point;
    _fe->reinit(side, &points);
    d = slave_point - phys_point[0];

    update_size = update.l2_norm();
  }

  update_size = 9999999;

  unsigned nit=0;

  // Newton Loop
  for(; nit<12 && update_size > TOLERANCE*TOLERANCE; nit++)
  {
    d = slave_point - phys_point[0];

    DenseMatrix<Real> jac(dim-1, dim-1);

    jac(0,0) = (d2xyz_dxi2[0]*d)-(dxyz_dxi[0] * dxyz_dxi[0]);

    if(dim-1 == 2)
    {
      jac(1,0) = (d2xyz_dxieta[0]*d)-(dxyz_dxi[0] * dxyz_deta[0]);

      jac(0,1) = (d2xyz_detaxi[0]*d)-(dxyz_deta[0] * dxyz_dxi[0]);
      jac(1,1) = (d2xyz_deta2[0]*d)-(dxyz_deta[0] * dxyz_deta[0]);
    }

    DenseVector<Real> rhs(dim-1);

    rhs(0) = -dxyz_dxi[0]*d;

    if(dim-1 == 2)
      rhs(1) = -dxyz_deta[0]*d;

    DenseVector<Real> update(dim-1);

    jac.lu_solve(rhs, update);

    ref_point(0) += update(0);

    if(dim-1 == 2)
      ref_point(1) += update(1);

    points[0] = ref_point;
    _fe->reinit(side, &points);
    d = slave_point - phys_point[0];

    update_size = update.l2_norm();
  }

/*
  if(nit == 12 && update_size > TOLERANCE*TOLERANCE)
    std::cerr<<"Warning!  Newton solve for contact point failed to converge!"<<std::endl;
*/

  p_info._closest_point_ref = ref_point;
  p_info._closest_point = phys_point[0];
  p_info._distance = d.size();

  if(dim-1 == 2)
  {
    p_info._normal = dxyz_dxi[0].cross(dxyz_deta[0]);
    p_info._normal /= p_info._normal.size();
  }
  else
  {
    p_info._normal = RealGradient(dxyz_dxi[0](1),-dxyz_dxi[0](0));
    p_info._normal /= p_info._normal.size();
  }

  // If the point has not penetrated the face, make the distance negative
  const Real dot(d * p_info._normal);
  if (dot > 0.0)
    p_info._distance = -p_info._distance;

  contact_point_on_side = FEInterface::on_reference_element(ref_point, side->type());

  p_info._tangential_distance = 0.0;

  if (!contact_point_on_side)
  {
    p_info._closest_point_on_face_ref=ref_point;
    restrictPointToFace(p_info._closest_point_on_face_ref,side,p_info._off_edge_nodes);

    points[0] = p_info._closest_point_on_face_ref;
    _fe->reinit(side, &points);
    Point closest_point_on_face(phys_point[0]);

    RealGradient off_face = closest_point_on_face - p_info._closest_point;
    Real tangential_distance = off_face.size();
    p_info._tangential_distance = tangential_distance;
    if (tangential_distance <= tangential_tolerance)
    {
      contact_point_on_side = true;
    }
  }

  const std::vector<std::vector<Real> > & phi = _fe->get_phi();

  points[0] = p_info._closest_point_ref;
  _fe->reinit(side, &points);

  p_info._side_phi = phi;
  p_info._dxyzdxi = dxyz_dxi;
  p_info._dxyzdeta = dxyz_deta;
  p_info._d2xyzdxideta = d2xyz_dxieta;

}

void restrictPointToFace(Point& p,
                         const Elem* side,
                         std::vector<Node*> &off_edge_nodes)
{
  const ElemType t(side->type());
  off_edge_nodes.clear();
  Real &xi   = p(0);
  Real &eta  = p(1);

  switch (t)
  {
    case EDGE2:
    case EDGE3:
    case EDGE4:
    {
      // The reference 1D element is [-1,1].
      if (xi < -1.0)
      {
        xi = -1.0;
        off_edge_nodes.push_back(side->get_node(0));
      }
      else if (xi > 1.0)
      {
        xi = 1.0;
        off_edge_nodes.push_back(side->get_node(1));
      }
      break;
    }

    case TRI3:
    case TRI6:
    {
      // The reference triangle is isosceles
      // and is bound by xi=0, eta=0, and xi+eta=1.

      if (xi <= 0.0 && eta <= 0.0)
      {
        xi = 0.0;
        eta = 0.0;
        off_edge_nodes.push_back(side->get_node(0));
      }
      else if (xi > 0.0 && xi < 1.0
               && eta < 0.0)
      {
        eta = 0.0;
        off_edge_nodes.push_back(side->get_node(0));
        off_edge_nodes.push_back(side->get_node(1));
      }
      else if (eta > 0.0 && eta < 1.0
               && xi < 0.0)
      {
        xi = 0.0;
        off_edge_nodes.push_back(side->get_node(2));
        off_edge_nodes.push_back(side->get_node(0));
      }
      else if (xi >= 1.0
               && (eta - xi) <= -1.0)
      {
        xi = 1.0;
        eta = 0.0;
        off_edge_nodes.push_back(side->get_node(1));
      }
      else if (eta >= 1.0
               && (eta - xi) >= 1.0)
      {
        xi = 0.0;
        eta = 1.0;
        off_edge_nodes.push_back(side->get_node(2));
      }
      else if ((xi + eta) > 1.0)
      {
        Real delta = (xi+eta-1.0)/2.0;
        xi -= delta;
        eta -= delta;
        off_edge_nodes.push_back(side->get_node(1));
        off_edge_nodes.push_back(side->get_node(2));
      }
      break;
    }

    case QUAD4:
    case QUAD8:
    case QUAD9:
    {
      // The reference quadrilateral element is [-1,1]^2.
      if (xi < -1.0)
      {
        xi = -1.0;
        if (eta < -1.0)
        {
          eta = -1.0;
          off_edge_nodes.push_back(side->get_node(0));
        }
        else if (eta > 1.0)
        {
          eta = 1.0;
          off_edge_nodes.push_back(side->get_node(3));
        }
        else
        {
          off_edge_nodes.push_back(side->get_node(3));
          off_edge_nodes.push_back(side->get_node(0));
        }
      }
      else if (xi > 1.0)
      {
        xi = 1.0;
        if (eta < -1.0)
        {
          eta = -1.0;
          off_edge_nodes.push_back(side->get_node(1));
        }
        else if (eta > 1.0)
        {
          eta = 1.0;
          off_edge_nodes.push_back(side->get_node(2));
        }
        else
        {
          off_edge_nodes.push_back(side->get_node(1));
          off_edge_nodes.push_back(side->get_node(2));
        }
      }
      else
      {
        if (eta < -1.0)
        {
          eta = -1.0;
          off_edge_nodes.push_back(side->get_node(0));
          off_edge_nodes.push_back(side->get_node(1));
        }
        else if (eta > 1.0)
        {
          eta = 1.0;
          off_edge_nodes.push_back(side->get_node(2));
          off_edge_nodes.push_back(side->get_node(3));
        }
      }
      break;
    }

    default:
    {
      mooseError("Unsupported face type: "<<t);
      break;
    }
  }
}

} //namespace Moose

<commit_msg>Fix bug in 1D<commit_after>/****************************************************************/
/*               DO NOT MODIFY THIS HEADER                      */
/* MOOSE - Multiphysics Object Oriented Simulation Environment  */
/*                                                              */
/*           (c) 2010 Battelle Energy Alliance, LLC             */
/*                   ALL RIGHTS RESERVED                        */
/*                                                              */
/*          Prepared by Battelle Energy Alliance, LLC           */
/*            Under Contract No. DE-AC07-05ID14517              */
/*            With the U. S. Department of Energy               */
/*                                                              */
/*            See COPYRIGHT for full restrictions               */
/****************************************************************/

// Moose
#include "FindContactPoint.h"
#include "LineSegment.h"

// libMesh
#include "libmesh/boundary_info.h"
#include "libmesh/elem.h"
#include "libmesh/plane.h"
#include "libmesh/fe_interface.h"
#include "libmesh/dense_matrix.h"
#include "libmesh/dense_vector.h"
#include "libmesh/fe_base.h"

namespace Moose
{

/**
 * Finds the closest point (called the contact point) on the master_elem on side "side" to the slave_point.
 *
 * @param master_elem The element on the master side of the interface
 * @param side The side number of the side of the master element
 * @param slave_point The physical space coordinates of the slave node
 * @param contact_ref The reference coordinate position of the contact point
 * @param contact_phys The physical space coordinates of the contact point
 * @param distance The distance between the slave_point and the contact point
 * @param normal The unit normal at the contact_point
 * @param contact_point_on_side whether or not the contact_point actually lies on _that_ side of the element.
 */
void
findContactPoint(PenetrationLocator::PenetrationInfo & p_info,
                 FEBase * _fe, FEType & _fe_type, const Point & slave_point,
                 bool start_with_centroid, const Real tangential_tolerance,
                 bool & contact_point_on_side)
{
  const Elem * master_elem = p_info._elem;

  unsigned int dim = master_elem->dim();

  const Elem * side = p_info._side;

  const std::vector<Point> & phys_point = _fe->get_xyz();

  const std::vector<RealGradient> & dxyz_dxi = _fe->get_dxyzdxi();
  const std::vector<RealGradient> & d2xyz_dxi2 = _fe->get_d2xyzdxi2();
  const std::vector<RealGradient> & d2xyz_dxieta = _fe->get_d2xyzdxideta();

  const std::vector<RealGradient> & dxyz_deta = _fe->get_dxyzdeta();
  const std::vector<RealGradient> & d2xyz_deta2 = _fe->get_d2xyzdeta2();
  const std::vector<RealGradient> & d2xyz_detaxi = _fe->get_d2xyzdxideta();

  if (dim == 1)
  {
    Node * left(master_elem->get_node(0));
    Node * right(left);
    Real leftCoor((*left)(0));
    Real rightCoor(leftCoor);
    for (unsigned i(1); i < master_elem->n_nodes(); ++i)
    {
      Node * curr = master_elem->get_node(i);
      Real coor = (*curr)(0);
      if (coor < leftCoor)
      {
        left = curr;
        leftCoor = coor;
      }
      if (coor > rightCoor)
      {
        right = curr;
        rightCoor = coor;
      }
    }
    Node * nearestNode(left);
    Point nearestPoint(leftCoor, 0, 0);
    if (side->node(0) == right->id())
    {
      nearestNode = right;
      nearestPoint(0) = rightCoor;
    }
    else if (side->node(0) != left->id())
    {
      mooseError("Error findContactPoint.  Logic error in 1D");
    }
    p_info._closest_point_ref = FEInterface::inverse_map(dim, _fe_type, master_elem, nearestPoint, TOLERANCE, false);
    p_info._closest_point = nearestPoint;
    p_info._normal = Point(left == nearestNode ? -1 : 1, 0, 0);
    p_info._distance = (p_info._closest_point - slave_point) * p_info._normal;
    p_info._dxyzdxi = dxyz_dxi;
    p_info._dxyzdeta = dxyz_deta;
    p_info._d2xyzdxideta = d2xyz_dxieta;
    p_info._side_phi = _fe->get_phi();
    contact_point_on_side = true;
    return;
  }

  Point ref_point;

  if(start_with_centroid)
    ref_point = FEInterface::inverse_map(dim-1, _fe_type, side, side->centroid(), TOLERANCE, false);
  else
    ref_point = p_info._closest_point_ref;

  std::vector<Point> points(1);
  points[0] = ref_point;
  _fe->reinit(side, &points);
  RealGradient d = slave_point - phys_point[0];

  Real update_size = 9999999;

  //Least squares
  for(unsigned int it=0; it<3 && update_size > TOLERANCE*1e3; ++it)
  {

    DenseMatrix<Real> jac(dim-1, dim-1);

    jac(0,0) = -(dxyz_dxi[0] * dxyz_dxi[0]);

    if(dim-1 == 2)
    {
      jac(1,0) = -(dxyz_dxi[0] * dxyz_deta[0]);

      jac(0,1) = -(dxyz_deta[0] * dxyz_dxi[0]);
      jac(1,1) = -(dxyz_deta[0] * dxyz_deta[0]);
    }

    DenseVector<Real> rhs(dim-1);

    rhs(0) = dxyz_dxi[0]*d;

    if(dim-1 == 2)
      rhs(1) = dxyz_deta[0]*d;

    DenseVector<Real> update(dim-1);

    jac.lu_solve(rhs, update);

    ref_point(0) -= update(0);

    if(dim-1 == 2)
      ref_point(1) -= update(1);

    points[0] = ref_point;
    _fe->reinit(side, &points);
    d = slave_point - phys_point[0];

    update_size = update.l2_norm();
  }

  update_size = 9999999;

  unsigned nit=0;

  // Newton Loop
  for(; nit<12 && update_size > TOLERANCE*TOLERANCE; nit++)
  {
    d = slave_point - phys_point[0];

    DenseMatrix<Real> jac(dim-1, dim-1);

    jac(0,0) = (d2xyz_dxi2[0]*d)-(dxyz_dxi[0] * dxyz_dxi[0]);

    if(dim-1 == 2)
    {
      jac(1,0) = (d2xyz_dxieta[0]*d)-(dxyz_dxi[0] * dxyz_deta[0]);

      jac(0,1) = (d2xyz_detaxi[0]*d)-(dxyz_deta[0] * dxyz_dxi[0]);
      jac(1,1) = (d2xyz_deta2[0]*d)-(dxyz_deta[0] * dxyz_deta[0]);
    }

    DenseVector<Real> rhs(dim-1);

    rhs(0) = -dxyz_dxi[0]*d;

    if(dim-1 == 2)
      rhs(1) = -dxyz_deta[0]*d;

    DenseVector<Real> update(dim-1);

    jac.lu_solve(rhs, update);

    ref_point(0) += update(0);

    if(dim-1 == 2)
      ref_point(1) += update(1);

    points[0] = ref_point;
    _fe->reinit(side, &points);
    d = slave_point - phys_point[0];

    update_size = update.l2_norm();
  }

/*
  if(nit == 12 && update_size > TOLERANCE*TOLERANCE)
    std::cerr<<"Warning!  Newton solve for contact point failed to converge!"<<std::endl;
*/

  p_info._closest_point_ref = ref_point;
  p_info._closest_point = phys_point[0];
  p_info._distance = d.size();

  if(dim-1 == 2)
  {
    p_info._normal = dxyz_dxi[0].cross(dxyz_deta[0]);
    p_info._normal /= p_info._normal.size();
  }
  else
  {
    p_info._normal = RealGradient(dxyz_dxi[0](1),-dxyz_dxi[0](0));
    p_info._normal /= p_info._normal.size();
  }

  // If the point has not penetrated the face, make the distance negative
  const Real dot(d * p_info._normal);
  if (dot > 0.0)
    p_info._distance = -p_info._distance;

  contact_point_on_side = FEInterface::on_reference_element(ref_point, side->type());

  p_info._tangential_distance = 0.0;

  if (!contact_point_on_side)
  {
    p_info._closest_point_on_face_ref=ref_point;
    restrictPointToFace(p_info._closest_point_on_face_ref,side,p_info._off_edge_nodes);

    points[0] = p_info._closest_point_on_face_ref;
    _fe->reinit(side, &points);
    Point closest_point_on_face(phys_point[0]);

    RealGradient off_face = closest_point_on_face - p_info._closest_point;
    Real tangential_distance = off_face.size();
    p_info._tangential_distance = tangential_distance;
    if (tangential_distance <= tangential_tolerance)
    {
      contact_point_on_side = true;
    }
  }

  const std::vector<std::vector<Real> > & phi = _fe->get_phi();

  points[0] = p_info._closest_point_ref;
  _fe->reinit(side, &points);

  p_info._side_phi = phi;
  p_info._dxyzdxi = dxyz_dxi;
  p_info._dxyzdeta = dxyz_deta;
  p_info._d2xyzdxideta = d2xyz_dxieta;

}

void restrictPointToFace(Point& p,
                         const Elem* side,
                         std::vector<Node*> &off_edge_nodes)
{
  const ElemType t(side->type());
  off_edge_nodes.clear();
  Real &xi   = p(0);
  Real &eta  = p(1);

  switch (t)
  {
    case EDGE2:
    case EDGE3:
    case EDGE4:
    {
      // The reference 1D element is [-1,1].
      if (xi < -1.0)
      {
        xi = -1.0;
        off_edge_nodes.push_back(side->get_node(0));
      }
      else if (xi > 1.0)
      {
        xi = 1.0;
        off_edge_nodes.push_back(side->get_node(1));
      }
      break;
    }

    case TRI3:
    case TRI6:
    {
      // The reference triangle is isosceles
      // and is bound by xi=0, eta=0, and xi+eta=1.

      if (xi <= 0.0 && eta <= 0.0)
      {
        xi = 0.0;
        eta = 0.0;
        off_edge_nodes.push_back(side->get_node(0));
      }
      else if (xi > 0.0 && xi < 1.0
               && eta < 0.0)
      {
        eta = 0.0;
        off_edge_nodes.push_back(side->get_node(0));
        off_edge_nodes.push_back(side->get_node(1));
      }
      else if (eta > 0.0 && eta < 1.0
               && xi < 0.0)
      {
        xi = 0.0;
        off_edge_nodes.push_back(side->get_node(2));
        off_edge_nodes.push_back(side->get_node(0));
      }
      else if (xi >= 1.0
               && (eta - xi) <= -1.0)
      {
        xi = 1.0;
        eta = 0.0;
        off_edge_nodes.push_back(side->get_node(1));
      }
      else if (eta >= 1.0
               && (eta - xi) >= 1.0)
      {
        xi = 0.0;
        eta = 1.0;
        off_edge_nodes.push_back(side->get_node(2));
      }
      else if ((xi + eta) > 1.0)
      {
        Real delta = (xi+eta-1.0)/2.0;
        xi -= delta;
        eta -= delta;
        off_edge_nodes.push_back(side->get_node(1));
        off_edge_nodes.push_back(side->get_node(2));
      }
      break;
    }

    case QUAD4:
    case QUAD8:
    case QUAD9:
    {
      // The reference quadrilateral element is [-1,1]^2.
      if (xi < -1.0)
      {
        xi = -1.0;
        if (eta < -1.0)
        {
          eta = -1.0;
          off_edge_nodes.push_back(side->get_node(0));
        }
        else if (eta > 1.0)
        {
          eta = 1.0;
          off_edge_nodes.push_back(side->get_node(3));
        }
        else
        {
          off_edge_nodes.push_back(side->get_node(3));
          off_edge_nodes.push_back(side->get_node(0));
        }
      }
      else if (xi > 1.0)
      {
        xi = 1.0;
        if (eta < -1.0)
        {
          eta = -1.0;
          off_edge_nodes.push_back(side->get_node(1));
        }
        else if (eta > 1.0)
        {
          eta = 1.0;
          off_edge_nodes.push_back(side->get_node(2));
        }
        else
        {
          off_edge_nodes.push_back(side->get_node(1));
          off_edge_nodes.push_back(side->get_node(2));
        }
      }
      else
      {
        if (eta < -1.0)
        {
          eta = -1.0;
          off_edge_nodes.push_back(side->get_node(0));
          off_edge_nodes.push_back(side->get_node(1));
        }
        else if (eta > 1.0)
        {
          eta = 1.0;
          off_edge_nodes.push_back(side->get_node(2));
          off_edge_nodes.push_back(side->get_node(3));
        }
      }
      break;
    }

    default:
    {
      mooseError("Unsupported face type: "<<t);
      break;
    }
  }
}

} //namespace Moose

<|endoftext|>


<commit_before><commit_msg>error: 'pGen' was not declared in this scope<commit_after><|endoftext|>