<commit_before>#include <cstddef>
#include <cstddef>
#include <fstream>
#include <iomanip>

#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include <ShlObj.h>

#include <windows.storage.h>
#include <windows.system.h>
#include <wrl.h>

#define WIDEIFYIMP(x) L##x
#define WIDEIFY(x) WIDEIFYIMP(x)

#include <queue>

#include <experimental/filesystem>
namespace fs = std::experimental::filesystem;

#include <UWP/UWP.hpp>

#include <UWP/DumperIPC.hpp>

void OpenTempState()
{
	Microsoft::WRL::ComPtr<ABI::Windows::Storage::IApplicationDataStatics> AppDataStatics;

	if(
		RoGetActivationFactory(
			Microsoft::WRL::Wrappers::HStringReference(RuntimeClass_Windows_Storage_ApplicationData).Get(),
			__uuidof(AppDataStatics), &AppDataStatics
		) < 0
	)
	{
		// Error getting ApplicationData statics
	}

	Microsoft::WRL::ComPtr<ABI::Windows::Storage::IApplicationData> AppData;
	if( AppDataStatics->get_Current(&AppData) < 0 )
	{
		// Error getting current IApplicationData
	}

	Microsoft::WRL::ComPtr<ABI::Windows::System::ILauncherStatics3> LauncherStatics;
	if(
		RoGetActivationFactory(
			Microsoft::WRL::Wrappers::HStringReference(RuntimeClass_Windows_System_Launcher).Get(),
			__uuidof(LauncherStatics), &LauncherStatics
		) < 0
	)
	{
		// Error getting Launcher statics
	}

	Microsoft::WRL::ComPtr<ABI::Windows::Storage::IStorageFolder> TemporaryFolder;

	if( AppData->get_TemporaryFolder(&TemporaryFolder) < 0 )
	{
		// Failed to get folder
		return;
	}

	Microsoft::WRL::ComPtr<ABI::Windows::Foundation::IAsyncOperation<bool>> Result;
	LauncherStatics->LaunchFolderAsync(
		TemporaryFolder.Get(),
		&Result
	);
}

std::uint32_t __stdcall DumperThread(void* DLLHandle)
{
	std::wstring DumpPath = fs::path(UWP::Current::Storage::GetTemporaryPath()) / L"DUMP";

	IPC::SetTargetThread(GetCurrentThreadId());

	IPC::PushMessage(L"UWPDumper Build date(%ls : %ls)\n", WIDEIFY(__DATE__), WIDEIFY(__TIME__));
	IPC::PushMessage(L"\t-https://github.com/Wunkolo/UWPDumper\n");
	IPC::PushMessage(L"Publisher:\n\t%s\n", UWP::Current::GetPublisher().c_str());
	IPC::PushMessage(L"Publisher ID:\n\t%s\n", UWP::Current::GetPublisherID().c_str());
	IPC::PushMessage(L"Publisher Path:\n\t%s\n", UWP::Current::Storage::GetPublisherPath().c_str());
	IPC::PushMessage(L"Package Path:\n\t%s\n", UWP::Current::GetPackagePath().c_str());
	IPC::PushMessage(L"Package Name:\n\t%s\n", UWP::Current::GetFullName().c_str());
	IPC::PushMessage(L"Family Name:\n\t%s\n", UWP::Current::GetFamilyName().c_str());

	IPC::PushMessage(L"Dump Path:\n\t%s\n", DumpPath.c_str());

	std::vector<fs::directory_entry> FileList;

	for( auto& Entry : fs::recursive_directory_iterator(".") )
	{
		if( fs::is_regular_file(Entry.path()) )
		{
			FileList.push_back(Entry);
		}
	}

	IPC::PushMessage(L"\tDumping %zu files\n", FileList.size());

	std::size_t i = 0;
	for( const auto& File : FileList )
	{
		const fs::path WritePath = DumpPath + File.path().wstring().substr(1);
		const std::wstring ReadPath = File.path().wstring();
		IPC::PushMessage(
			L"%*.*s %*.u bytes %*zu/%zu\n",
			60, 60,
			ReadPath.c_str() + (ReadPath.length() > 60 ? (ReadPath.length() - (60)) : 0),
			15,
			fs::file_size(File),
			20,
			++i,
			FileList.size()
		);

		std::error_code ErrorCode;
		if( fs::create_directories(WritePath.parent_path(), ErrorCode) == false && ErrorCode )
		{
			const std::string ErrorMessage(ErrorCode.message());
			std::wstring WErrorMessage;
			WErrorMessage.assign(ErrorMessage.begin(), ErrorMessage.end());
			IPC::PushMessage(
				L"Error creating subfolder: %s\n\t%s\n",
				WritePath.parent_path().c_str(),
				WErrorMessage.c_str()
			);
			continue;
		}

		std::ifstream SourceFile(ReadPath, std::ios::binary);
		if( !SourceFile.is_open() )
		{
			IPC::PushMessage(
				L"Error opening %s for reading\n",
				ReadPath.c_str()
			);
			continue;
		}

		std::ofstream DestFile(WritePath, std::ios::binary);
		if( !DestFile.is_open() )
		{
			IPC::PushMessage(
				L"Error opening %s for writing\n",
				WritePath.c_str()
			);
			continue;
		}

		if( SourceFile && DestFile )
		{
			DestFile << SourceFile.rdbuf();
		}
		else
		{
			IPC::PushMessage(
				L"Error copying:\n"
				"\t%s\n"
				"\tto\n"
				"\t%s\n",
				File.path().c_str(),
				WritePath.c_str()
			);
		}
	}

	IPC::PushMessage(L"Dump complete!\n\tPath:\n\t%s\n", DumpPath.c_str());
	OpenTempState();
	IPC::ClearTargetThread();

	FreeLibraryAndExitThread(
		reinterpret_cast<HMODULE>(DLLHandle),
		EXIT_SUCCESS
	);
}

std::int32_t __stdcall DllMain(HINSTANCE hDLL, std::uint32_t Reason, void* Reserved)
{
	switch( Reason )
	{
	case DLL_PROCESS_ATTACH:
	{
		if( IPC::GetTargetProcess() == GetCurrentProcessId() )
		{
			// We are the target process to be dumped
			CreateThread(
				nullptr,
				0,
				reinterpret_cast<unsigned long(__stdcall*)(void*)>(&DumperThread),
				hDLL,
				0,
				nullptr
			);
		}
	}
	case DLL_PROCESS_DETACH:
	case DLL_THREAD_ATTACH:
	case DLL_THREAD_DETACH:
	default:
	{
		return true;
	}
	}

	return false;
}
<commit_msg>Fix current directory resolution<commit_after>#include <cstddef>
#include <cstddef>
#include <fstream>
#include <iomanip>

#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include <ShlObj.h>

#include <windows.storage.h>
#include <windows.system.h>
#include <wrl.h>

#define WIDEIFYIMP(x) L##x
#define WIDEIFY(x) WIDEIFYIMP(x)

#include <queue>

#include <experimental/filesystem>
namespace fs = std::experimental::filesystem;

#include <UWP/UWP.hpp>

#include <UWP/DumperIPC.hpp>

void OpenTempState()
{
	Microsoft::WRL::ComPtr<ABI::Windows::Storage::IApplicationDataStatics> AppDataStatics;

	if(
		RoGetActivationFactory(
			Microsoft::WRL::Wrappers::HStringReference(RuntimeClass_Windows_Storage_ApplicationData).Get(),
			__uuidof(AppDataStatics), &AppDataStatics
		) < 0
	)
	{
		// Error getting ApplicationData statics
	}

	Microsoft::WRL::ComPtr<ABI::Windows::Storage::IApplicationData> AppData;
	if( AppDataStatics->get_Current(&AppData) < 0 )
	{
		// Error getting current IApplicationData
	}

	Microsoft::WRL::ComPtr<ABI::Windows::System::ILauncherStatics3> LauncherStatics;
	if(
		RoGetActivationFactory(
			Microsoft::WRL::Wrappers::HStringReference(RuntimeClass_Windows_System_Launcher).Get(),
			__uuidof(LauncherStatics), &LauncherStatics
		) < 0
	)
	{
		// Error getting Launcher statics
	}

	Microsoft::WRL::ComPtr<ABI::Windows::Storage::IStorageFolder> TemporaryFolder;

	if( AppData->get_TemporaryFolder(&TemporaryFolder) < 0 )
	{
		// Failed to get folder
		return;
	}

	Microsoft::WRL::ComPtr<ABI::Windows::Foundation::IAsyncOperation<bool>> Result;
	LauncherStatics->LaunchFolderAsync(
		TemporaryFolder.Get(),
		&Result
	);
}

std::uint32_t __stdcall DumperThread(void* DLLHandle)
{
	std::wstring DumpPath = fs::path(UWP::Current::Storage::GetTemporaryPath()) / L"DUMP";

	IPC::SetTargetThread(GetCurrentThreadId());

	IPC::PushMessage(L"UWPDumper Build date(%ls : %ls)\n", WIDEIFY(__DATE__), WIDEIFY(__TIME__));
	IPC::PushMessage(L"\t-https://github.com/Wunkolo/UWPDumper\n");
	IPC::PushMessage(L"Publisher:\n\t%s\n", UWP::Current::GetPublisher().c_str());
	IPC::PushMessage(L"Publisher ID:\n\t%s\n", UWP::Current::GetPublisherID().c_str());
	IPC::PushMessage(L"Publisher Path:\n\t%s\n", UWP::Current::Storage::GetPublisherPath().c_str());
	IPC::PushMessage(L"Package Path:\n\t%s\n", UWP::Current::GetPackagePath().c_str());
	IPC::PushMessage(L"Package Name:\n\t%s\n", UWP::Current::GetFullName().c_str());
	IPC::PushMessage(L"Family Name:\n\t%s\n", UWP::Current::GetFamilyName().c_str());

	IPC::PushMessage(L"Dump Path:\n\t%s\n", DumpPath.c_str());

	std::vector<fs::directory_entry> FileList;

	for( auto& Entry : fs::recursive_directory_iterator(UWP::Current::GetPackagePath()) )
	{
		if( fs::is_regular_file(Entry.path()) )
		{
			FileList.push_back(Entry);
		}
	}

	IPC::PushMessage(L"\tDumping %zu files\n", FileList.size());

	std::size_t i = 0;
	for( const auto& File : FileList )
	{
		const fs::path WritePath = DumpPath + File.path().wstring().substr(UWP::Current::GetPackagePath().length());
		const std::wstring ReadPath = File.path().wstring();
		IPC::PushMessage(
			L"%*.*s %*.u bytes %*zu/%zu\n",
			60, 60,
			ReadPath.c_str() + (ReadPath.length() > 60 ? (ReadPath.length() - (60)) : 0),
			15,
			fs::file_size(File),
			20,
			++i,
			FileList.size()
		);

		std::error_code ErrorCode;
		if( fs::create_directories(WritePath.parent_path(), ErrorCode) == false && ErrorCode )
		{
			const std::string ErrorMessage(ErrorCode.message());
			std::wstring WErrorMessage;
			WErrorMessage.assign(ErrorMessage.begin(), ErrorMessage.end());
			IPC::PushMessage(
				L"Error creating subfolder: %s\n\t%s\n",
				WritePath.parent_path().c_str(),
				WErrorMessage.c_str()
			);
			continue;
		}

		std::ifstream SourceFile(ReadPath, std::ios::binary);
		if( !SourceFile.is_open() )
		{
			IPC::PushMessage(
				L"Error opening %s for reading\n",
				ReadPath.c_str()
			);
			continue;
		}

		std::ofstream DestFile(WritePath, std::ios::binary);
		if( !DestFile.is_open() )
		{
			IPC::PushMessage(
				L"Error opening %s for writing\n",
				WritePath.c_str()
			);
			continue;
		}

		if( SourceFile && DestFile )
		{
			DestFile << SourceFile.rdbuf();
		}
		else
		{
			IPC::PushMessage(
				L"Error copying:\n"
				"\t%s\n"
				"\tto\n"
				"\t%s\n",
				File.path().c_str(),
				WritePath.c_str()
			);
		}
	}

	IPC::PushMessage(L"Dump complete!\n\tPath:\n\t%s\n", DumpPath.c_str());
	OpenTempState();
	IPC::ClearTargetThread();

	FreeLibraryAndExitThread(
		reinterpret_cast<HMODULE>(DLLHandle),
		EXIT_SUCCESS
	);
}

std::int32_t __stdcall DllMain(HINSTANCE hDLL, std::uint32_t Reason, void* Reserved)
{
	switch( Reason )
	{
	case DLL_PROCESS_ATTACH:
	{
		if( IPC::GetTargetProcess() == GetCurrentProcessId() )
		{
			// We are the target process to be dumped
			CreateThread(
				nullptr,
				0,
				reinterpret_cast<unsigned long(__stdcall*)(void*)>(&DumperThread),
				hDLL,
				0,
				nullptr
			);
		}
	}
	case DLL_PROCESS_DETACH:
	case DLL_THREAD_ATTACH:
	case DLL_THREAD_DETACH:
	default:
	{
		return true;
	}
	}

	return false;
}
<|endoftext|>


<commit_before>// Ouzel by Elviss Strazdins

#ifndef OUZEL_MATH_SIMD_HPP
#define OUZEL_MATH_SIMD_HPP

#if defined(__SSE__) || defined(_M_X64) || _M_IX86_FP >= 1
#  define OUZEL_SIMD_SSE
#endif
#if defined(__SSE2__) || defined(_M_X64) || _M_IX86_FP >= 2
#  define OUZEL_SIMD_SSE2
#endif
#if defined(__ARM_NEON__)
#  define OUZEL_SIMD_NEON
#  if defined(__x86_64__)
#    define OUZEL_SIMD_NEON64
#  endif
#endif

#endif // OUZEL_MATH_SIMD_HPP
<commit_msg>Fix the ARM64 check<commit_after>// Ouzel by Elviss Strazdins

#ifndef OUZEL_MATH_SIMD_HPP
#define OUZEL_MATH_SIMD_HPP

#if defined(__SSE__) || defined(_M_X64) || _M_IX86_FP >= 1
#  define OUZEL_SIMD_SSE
#endif
#if defined(__SSE2__) || defined(_M_X64) || _M_IX86_FP >= 2
#  define OUZEL_SIMD_SSE2
#endif
#if defined(__ARM_NEON__)
#  define OUZEL_SIMD_NEON
#  if defined(__aarch64__)
#    define OUZEL_SIMD_NEON64
#  endif
#endif

#endif // OUZEL_MATH_SIMD_HPP
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2016 Shanghai Jiao Tong University.
 *     All rights reserved.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing,
 *  software distributed under the License is distributed on an "AS
 *  IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
 *  express or implied.  See the License for the specific language
 *  governing permissions and limitations under the License.
 *
 * For more about this software visit:
 *
 *      http://ipads.se.sjtu.edu.cn/projects/wukong
 *
 */

#pragma once

#include <string>
#include <fstream>
#include <iostream>
#include <stdio.h>
#include <dirent.h>
#include <algorithm>
#include <boost/mpi.hpp>
#include <boost/unordered_map.hpp>
#include <boost/algorithm/string/predicate.hpp>

#include "global.hpp"
#include "hdfs.hpp"
#include "type.hpp"

// utils
#include "assertion.hpp"

// #define USE_BITRIE  // use bi-tire to store ID-STR mapping (reduce memory usage)
#ifdef USE_BITRIE
#include "bitrie.hpp"
#endif

using namespace std;

class StringServer {
private:
#ifdef USE_BITRIE
    bitrie<char, sid_t> bimap;  // ID-STRING (bi-)map
#else
    boost::unordered_map<string, sid_t> simap;  // STRING to ID
    boost::unordered_map<sid_t, string> ismap;  // ID to STRING
#endif

public:
    // the data type of predicate/attribute: sid=0, integer=1, float=2, double=3
    boost::unordered_map<sid_t, char> pid2type;

    uint64_t next_index_id;
    uint64_t next_normal_id;

    StringServer(string dname) {
        uint64_t start = timer::get_usec();

        next_index_id = 0;
        next_normal_id = 0;

        if (boost::starts_with(dname, "hdfs:")) {
            if (!wukong::hdfs::has_hadoop()) {
                logstream(LOG_ERROR) << "attempting to load ID-mapping files from HDFS "
                                     << "but Wukong was built without HDFS."
                                     << LOG_endl;
                exit(-1);
            }
            load_from_hdfs(dname);
        } else
            load_from_posixfs(dname);

        uint64_t end = timer::get_usec();
        logstream(LOG_INFO) << "loading string server is finished ("
                            << (end - start) / 1000 << " ms)" << LOG_endl;
    }

#ifdef USE_BITRIE
    bool exist(sid_t sid) { return bimap.exist(sid); }

    bool exist(string str) { return bimap.exist(str); }

    string id2str(sid_t sid) { return bimap[sid]; }

    sid_t str2id(string str) { return bimap[str]; }

    void add(string str, sid_t sid) { bimap.insert_kv(str, sid); }

    void shrink() { bimap.storage_resize(); }
#else
    bool exist(sid_t sid) { return ismap.find(sid) != ismap.end(); }

    bool exist(string str) { return simap.find(str) != simap.end(); }

    string id2str(sid_t sid) { return ismap[sid]; }

    sid_t str2id(string str) { return simap[str]; }

    void add(string str, sid_t sid) { simap[str] = sid; ismap[sid] = str; }

    void shrink() { }
#endif

private:
    /* load ID mapping files from a shared filesystem (e.g., NFS) */
    void load_from_posixfs(string dname) {
        DIR *dir = opendir(dname.c_str());
        if (dir == NULL) {
            logstream(LOG_ERROR) << "failed to open the directory of ID-mapping files ("
                                 << dname << ")." << LOG_endl;
            exit(-1);
        }

        struct dirent *ent;
        while ((ent = readdir(dir)) != NULL) {
            if (ent->d_name[0] == '.')
                continue;

            string fname(dname + ent->d_name);
            if (boost::ends_with(fname, "/str_index")
                    || boost::ends_with(fname, "/str_normal")) {
                logstream(LOG_INFO) << "loading ID-mapping file: " << fname << LOG_endl;
                ifstream file(fname.c_str());
                string str;
                sid_t id;
                while (file >> str >> id) {
                    add(str, id);  // add a new ID-STRING (bi-direction) pair
                    if (boost::ends_with(fname, "/str_index"))
                        pid2type[id] = (char)SID_t;
                }
                if (boost::ends_with(fname, "/str_index"))
                    next_index_id = ++id;
                else
                    next_normal_id = ++id;
                file.close();
            }

            // load the attribute index from the str_attr_index file
            // it contains by (string, predicate-ID, predicate-type)
            // predicate type: SID_t, INT_t, FLOAT_t, DOUBLE_t
            //
            // NOTE: the predicates/attributes in str_attr_index should be exclusive
            //       to the predicates/attributes in str_index
            if (boost::ends_with(fname, "/str_attr_index")) {
                logstream(LOG_INFO) << "loading ID-mapping (attribute) file: " << fname << LOG_endl;
                ifstream file(fname.c_str());
                string str;
                sid_t id;
                char type;
                while (file >> str >> id >> type) {
                    add(str, id);  // add a new ID-STRING (bi-direction) pair
                    pid2type[id] = (char)type;

                    // FIXME: dynamic loading (next_index_id)
                    logstream(LOG_INFO) << " attribute[" << id << "] = " << type << LOG_endl;
                }
                file.close();
            }
        }

        shrink();  // save memory
    }

    /* load ID mapping files from HDFS */
    void load_from_hdfs(string dname) {
        wukong::hdfs &hdfs = wukong::hdfs::get_hdfs();
        vector<string> files = hdfs.list_files(dname);

        for (int i = 0; i < files.size(); i++) {
            string fname = files[i];
            // NOTE: users may use a short path (w/o ip:port)
            // e.g., hdfs:/xxx/xxx/
            if (boost::ends_with(fname, "/str_index")
                    || boost::ends_with(fname, "/str_normal")) {
                logstream(LOG_INFO) << "loading ID-mapping file from HDFS: " << fname << LOG_endl;
                wukong::hdfs::fstream file(hdfs, fname);
                string str;
                sid_t id;
                while (file >> str >> id) {
                    add(str, id);  // add a new ID-STRING (bi-direction) pair
                    if (boost::ends_with(fname, "/str_index"))
                        pid2type[id] = (char)SID_t;
                }
                if (boost::ends_with(fname, "/str_index"))
                    next_index_id = ++id;
                else
                    next_normal_id = ++id;
                file.close();
            }

            // load the attribute index from the str_attr_index file
            // it contains by (string, predicate-ID, predicate-type)
            // predicate type: SID_t, INT_t, FLOAT_t, DOUBLE_t
            //
            // NOTE: the predicates/attributes in str_attr_index should be exclusive
            //       to the predicates/attributes in str_index
            if (boost::ends_with(fname, "/str_attr_index")) {
                logstream(LOG_INFO) << "loading ID-mapping (attribute) file: " << fname << LOG_endl;
                wukong::hdfs::fstream file(hdfs, fname);
                string str;
                sid_t id;
                char type;
                while (file >> str >> id >> type) {
                    add(str, id); // add a new ID-STRING (bi-direction) pair
                    pid2type[id] = (char)type;

                    // FIXME: dynamic loading (next_index_id)
                    logstream(LOG_INFO) << " attribute[" << id << "] = " << type << LOG_endl;
                }
                file.close();
            }
        }

        shrink();  // save memory
    }
};
<commit_msg>fix problem for attr<commit_after>/*
 * Copyright (c) 2016 Shanghai Jiao Tong University.
 *     All rights reserved.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing,
 *  software distributed under the License is distributed on an "AS
 *  IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
 *  express or implied.  See the License for the specific language
 *  governing permissions and limitations under the License.
 *
 * For more about this software visit:
 *
 *      http://ipads.se.sjtu.edu.cn/projects/wukong
 *
 */

#pragma once

#include <string>
#include <fstream>
#include <iostream>
#include <stdio.h>
#include <dirent.h>
#include <algorithm>
#include <boost/mpi.hpp>
#include <boost/unordered_map.hpp>
#include <boost/algorithm/string/predicate.hpp>

#include "global.hpp"
#include "hdfs.hpp"
#include "type.hpp"

// utils
#include "assertion.hpp"

// #define USE_BITRIE  // use bi-tire to store ID-STR mapping (reduce memory usage)
#ifdef USE_BITRIE
#include "bitrie.hpp"
#endif

using namespace std;

class StringServer {
private:
#ifdef USE_BITRIE
    bitrie<char, sid_t> bimap;  // ID-STRING (bi-)map
#else
    boost::unordered_map<string, sid_t> simap;  // STRING to ID
    boost::unordered_map<sid_t, string> ismap;  // ID to STRING
#endif

public:
    // the data type of predicate/attribute: sid=0, integer=1, float=2, double=3
    boost::unordered_map<sid_t, char> pid2type;

    uint64_t next_index_id;
    uint64_t next_normal_id;

    StringServer(string dname) {
        uint64_t start = timer::get_usec();

        next_index_id = 0;
        next_normal_id = 0;

        if (boost::starts_with(dname, "hdfs:")) {
            if (!wukong::hdfs::has_hadoop()) {
                logstream(LOG_ERROR) << "attempting to load ID-mapping files from HDFS "
                                     << "but Wukong was built without HDFS."
                                     << LOG_endl;
                exit(-1);
            }
            load_from_hdfs(dname);
        } else
            load_from_posixfs(dname);

        uint64_t end = timer::get_usec();
        logstream(LOG_INFO) << "loading string server is finished ("
                            << (end - start) / 1000 << " ms)" << LOG_endl;
    }

#ifdef USE_BITRIE
    bool exist(sid_t sid) { return bimap.exist(sid); }

    bool exist(string str) { return bimap.exist(str); }

    string id2str(sid_t sid) { return bimap[sid]; }

    sid_t str2id(string str) { return bimap[str]; }

    void add(string str, sid_t sid) { bimap.insert_kv(str, sid); }

    void shrink() { bimap.storage_resize(); }
#else
    bool exist(sid_t sid) { return ismap.find(sid) != ismap.end(); }

    bool exist(string str) { return simap.find(str) != simap.end(); }

    string id2str(sid_t sid) { return ismap[sid]; }

    sid_t str2id(string str) { return simap[str]; }

    void add(string str, sid_t sid) { simap[str] = sid; ismap[sid] = str; }

    void shrink() { }
#endif

private:
    /* load ID mapping files from a shared filesystem (e.g., NFS) */
    void load_from_posixfs(string dname) {
        DIR *dir = opendir(dname.c_str());
        if (dir == NULL) {
            logstream(LOG_ERROR) << "failed to open the directory of ID-mapping files ("
                                 << dname << ")." << LOG_endl;
            exit(-1);
        }

        struct dirent *ent;
        while ((ent = readdir(dir)) != NULL) {
            if (ent->d_name[0] == '.')
                continue;

            string fname(dname + ent->d_name);
            if (boost::ends_with(fname, "/str_index")
                    || boost::ends_with(fname, "/str_normal")) {
                logstream(LOG_INFO) << "loading ID-mapping file: " << fname << LOG_endl;
                ifstream file(fname.c_str());
                string str;
                sid_t id;
                while (file >> str >> id) {
                    add(str, id);  // add a new ID-STRING (bi-direction) pair
                    if (boost::ends_with(fname, "/str_index"))
                        pid2type[id] = (char)SID_t;
                }
                if (boost::ends_with(fname, "/str_index"))
                    next_index_id = ++id;
                else
                    next_normal_id = ++id;
                file.close();
            }

            // load the attribute index from the str_attr_index file
            // it contains by (string, predicate-ID, predicate-type)
            // predicate type: SID_t, INT_t, FLOAT_t, DOUBLE_t
            //
            // NOTE: the predicates/attributes in str_attr_index should be exclusive
            //       to the predicates/attributes in str_index
            if (boost::ends_with(fname, "/str_attr_index")) {
                logstream(LOG_INFO) << "loading ID-mapping (attribute) file: " << fname << LOG_endl;
                ifstream file(fname.c_str());
                string str;
                sid_t id;
                int type;
                while (file >> str >> id >> type) {
                    add(str, id);  // add a new ID-STRING (bi-direction) pair
                    pid2type[id] = (char)type;

                    // FIXME: dynamic loading (next_index_id)
                    logstream(LOG_INFO) << " attribute[" << id << "] = " << type << LOG_endl;
                }
                file.close();
            }
        }

        shrink();  // save memory
    }

    /* load ID mapping files from HDFS */
    void load_from_hdfs(string dname) {
        wukong::hdfs &hdfs = wukong::hdfs::get_hdfs();
        vector<string> files = hdfs.list_files(dname);

        for (int i = 0; i < files.size(); i++) {
            string fname = files[i];
            // NOTE: users may use a short path (w/o ip:port)
            // e.g., hdfs:/xxx/xxx/
            if (boost::ends_with(fname, "/str_index")
                    || boost::ends_with(fname, "/str_normal")) {
                logstream(LOG_INFO) << "loading ID-mapping file from HDFS: " << fname << LOG_endl;
                wukong::hdfs::fstream file(hdfs, fname);
                string str;
                sid_t id;
                while (file >> str >> id) {
                    add(str, id);  // add a new ID-STRING (bi-direction) pair
                    if (boost::ends_with(fname, "/str_index"))
                        pid2type[id] = (char)SID_t;
                }
                if (boost::ends_with(fname, "/str_index"))
                    next_index_id = ++id;
                else
                    next_normal_id = ++id;
                file.close();
            }

            // load the attribute index from the str_attr_index file
            // it contains by (string, predicate-ID, predicate-type)
            // predicate type: SID_t, INT_t, FLOAT_t, DOUBLE_t
            //
            // NOTE: the predicates/attributes in str_attr_index should be exclusive
            //       to the predicates/attributes in str_index
            if (boost::ends_with(fname, "/str_attr_index")) {
                logstream(LOG_INFO) << "loading ID-mapping (attribute) file: " << fname << LOG_endl;
                wukong::hdfs::fstream file(hdfs, fname);
                string str;
                sid_t id;
                char type;
                while (file >> str >> id >> type) {
                    add(str, id); // add a new ID-STRING (bi-direction) pair
                    pid2type[id] = (char)type;

                    // FIXME: dynamic loading (next_index_id)
                    logstream(LOG_INFO) << " attribute[" << id << "] = " << type << LOG_endl;
                }
                file.close();
            }
        }

        shrink();  // save memory
    }
};
<|endoftext|>


<commit_before>/*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

   Copyright (c) 2008 Scientific Computing and Imaging Institute,
   University of Utah.

   Permission is hereby granted, free of charge, to any person obtaining a
   copy of this software and associated documentation files (the "Software"),
   to deal in the Software without restriction, including without limitation
   the rights to use, copy, modify, merge, publish, distribute, sublicense,
   and/or sell copies of the Software, and to permit persons to whom the
   Software is furnished to do so, subject to the following conditions:

   The above copyright notice and this permission notice shall be included
   in all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
   DEALINGS IN THE SOFTWARE.
*/

/**
  \file    AbstrConverter.cpp
  \author  Jens Krueger
           SCI Institute
           University of Utah
  \date    December 2008
*/

#include "StdTuvokDefines.h"

#include <algorithm>
#include <iterator>
#include <string>
#ifdef DETECTED_OS_WINDOWS
# include <array>
#else
# include <tr1/array>
#endif
#include "AbstrConverter.h"
#include "IOManager.h"  // for the size defines
#include "Controller/Controller.h"
#include "UVF/Histogram1DDataBlock.h"
#include "Quantize.h"

using namespace tuvok;

bool AbstrConverter::CanRead(const std::string& fn,
                             const std::tr1::array<int8_t, 512>&) const
{
  std::string ext = SysTools::GetExt(fn);
  std::transform(ext.begin(), ext.end(), ext.begin(),
                 (int(*)(int))std::toupper);
  return SupportedExtension(ext);
}

/// @param ext the extension for the filename
/// @return true if the filename is a supported extension for this converter
bool AbstrConverter::SupportedExtension(const std::string& ext) const
{
  return std::find(m_vSupportedExt.begin(), m_vSupportedExt.end(), ext) !=
          m_vSupportedExt.end();
}

const std::string
AbstrConverter::Process8Bits(UINT64 iHeaderSkip,
                             const std::string& strFilename,
                             const std::string& strTargetFilename,
                             UINT64 iSize, bool bSigned,
                             Histogram1DDataBlock* Histogram1D) {
  size_t iCurrentInCoreSize = GetIncoreSize();

  LargeRAWFile InputData(strFilename, iHeaderSkip);
  InputData.Open(false);
  UINT64 iPercent = iSize / 100;

  if (!InputData.IsOpen()) return "";

  std::vector<UINT64> aHist(256);
  std::fill(aHist.begin(), aHist.end(), 0);

  std::string strSignChangedFile;
  if (bSigned)  {
    MESSAGE("Changing signed to unsigned char and computing 1D histogram...");
    LargeRAWFile OutputData(strTargetFilename);
    OutputData.Create(iSize);

    if (!OutputData.IsOpen()) {
      InputData.Close();
      return "";
    }

    signed char* pInData = new signed char[iCurrentInCoreSize];

    UINT64 iPos = 0;
    while (iPos < iSize)  {
      size_t iRead = InputData.ReadRAW((unsigned char*)pInData, iCurrentInCoreSize);
      if (iRead == 0) break;

      for (size_t i = 0;i<iRead;i++) {
        pInData[i] += 128;
        if (Histogram1D) aHist[(unsigned char)pInData[i]]++;
      }
      OutputData.WriteRAW((unsigned char*)pInData, iRead);
      iPos += UINT64(iRead);
    }

    if (iPos < iSize) {
      WARNING("Specified size and real datasize mismatch");
    }

    delete [] pInData;
    strSignChangedFile = strTargetFilename;
    OutputData.Close();
  } else {
    if (Histogram1D) {
      MESSAGE("Computing 1D Histogram...");
      unsigned char* pInData = new unsigned char[iCurrentInCoreSize];

      UINT64 iPos = 0;
      UINT64 iDivLast = 0;
      while (iPos < iSize)  {
        size_t iRead = InputData.ReadRAW((unsigned char*)pInData, iCurrentInCoreSize);
        if (iRead == 0) break;
        for (size_t i = 0;i<iRead;i++) aHist[pInData[i]]++;
        iPos += UINT64(iRead);

        if (iPercent > 1 && (100*iPos)/iSize > iDivLast) {
          MESSAGE("Computing 1D Histogram (%u%% complete)",
                  static_cast<unsigned>((100*iPos)/iSize));
          iDivLast = (100*iPos)/iSize;
        }
      }

      if (iPos < iSize) {
        WARNING("Specified size and real datasize mismatch");
      }

      MESSAGE("1D Histogram complete");
      delete [] pInData;
    }
    strSignChangedFile = strFilename;
  }

  InputData.Close();
  if ( Histogram1D ) Histogram1D->SetHistogram(aHist);

  return strSignChangedFile;
}

size_t AbstrConverter::GetIncoreSize() {
  if (Controller::Instance().IOMan())
    return size_t(Controller::Instance().IOMan()->GetIncoresize());
  else
    return DEFAULT_INCORESIZE;
}

const std::string
AbstrConverter::QuantizeTo8Bit(UINT64 iHeaderSkip,
                               const std::string& strFilename,
                               const std::string& strTargetFilename,
                               UINT64 iComponentSize,
                               UINT64 iSize,
                               bool bSigned,
                               bool bIsFloat,
                               Histogram1DDataBlock* Histogram1D) {
  std::string intermFile = "";
  switch (iComponentSize) {
    case 8:
      intermFile = Process8Bits(iHeaderSkip, strFilename,
                                strTargetFilename, iSize, bSigned,
                                Histogram1D);
      break;
    case 16 :
      if(bSigned) {
        intermFile = Quantize<short, unsigned char>(iHeaderSkip, strFilename,
                                                    strTargetFilename, iSize,
                                                    Histogram1D);
      } else {
        intermFile = Quantize<unsigned short, unsigned char>
                             (iHeaderSkip, strFilename,
                              strTargetFilename, iSize, Histogram1D);
      }
      break;
    case 32 :
      if (bIsFloat) {
        intermFile = Quantize<float, unsigned char>(iHeaderSkip, strFilename,
                                          strTargetFilename, iSize,
                                          Histogram1D);
      } else {
        if(bSigned) {
          intermFile = Quantize<int, unsigned char>(iHeaderSkip, strFilename,
                                          strTargetFilename, iSize, Histogram1D);
        } else {
          intermFile = Quantize<unsigned, unsigned char>(iHeaderSkip, strFilename,
                                               strTargetFilename, iSize,
                                               Histogram1D);
        }
      }
      break;
    case 64 :
      if (bIsFloat) {
        intermFile = Quantize<double, unsigned char>(iHeaderSkip, strFilename,
                                           strTargetFilename, iSize,
                                           Histogram1D);
      } else {
        if(bSigned) {
          intermFile = Quantize<boost::int64_t, unsigned char>(
            iHeaderSkip, strFilename, strTargetFilename, iSize, Histogram1D
          );
        } else {
          intermFile = Quantize<UINT64, unsigned char>(iHeaderSkip, strFilename,
                                             strTargetFilename, iSize,
                                             Histogram1D);
        }
      }
      break;
  }

  return intermFile;
}
<commit_msg>Fix win32 compilation error.<commit_after>/*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

   Copyright (c) 2008 Scientific Computing and Imaging Institute,
   University of Utah.

   Permission is hereby granted, free of charge, to any person obtaining a
   copy of this software and associated documentation files (the "Software"),
   to deal in the Software without restriction, including without limitation
   the rights to use, copy, modify, merge, publish, distribute, sublicense,
   and/or sell copies of the Software, and to permit persons to whom the
   Software is furnished to do so, subject to the following conditions:

   The above copyright notice and this permission notice shall be included
   in all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
   DEALINGS IN THE SOFTWARE.
*/

/**
  \file    AbstrConverter.cpp
  \author  Jens Krueger
           SCI Institute
           University of Utah
  \date    December 2008
*/

#include "StdTuvokDefines.h"

#include <algorithm>
#include <iterator>
#include <string>
#ifdef DETECTED_OS_WINDOWS
# include <array>
#else
# include <tr1/array>
#endif
#include <cctype>
#include "AbstrConverter.h"
#include "IOManager.h"  // for the size defines
#include "Controller/Controller.h"
#include "UVF/Histogram1DDataBlock.h"
#include "Quantize.h"

using namespace tuvok;

bool AbstrConverter::CanRead(const std::string& fn,
                             const std::tr1::array<int8_t, 512>&) const
{
  std::string ext = SysTools::GetExt(fn);
  std::transform(ext.begin(), ext.end(), ext.begin(),
                 (int(*)(int))std::toupper);
  return SupportedExtension(ext);
}

/// @param ext the extension for the filename
/// @return true if the filename is a supported extension for this converter
bool AbstrConverter::SupportedExtension(const std::string& ext) const
{
  return std::find(m_vSupportedExt.begin(), m_vSupportedExt.end(), ext) !=
          m_vSupportedExt.end();
}

const std::string
AbstrConverter::Process8Bits(UINT64 iHeaderSkip,
                             const std::string& strFilename,
                             const std::string& strTargetFilename,
                             UINT64 iSize, bool bSigned,
                             Histogram1DDataBlock* Histogram1D) {
  size_t iCurrentInCoreSize = GetIncoreSize();

  LargeRAWFile InputData(strFilename, iHeaderSkip);
  InputData.Open(false);
  UINT64 iPercent = iSize / 100;

  if (!InputData.IsOpen()) return "";

  std::vector<UINT64> aHist(256);
  std::fill(aHist.begin(), aHist.end(), 0);

  std::string strSignChangedFile;
  if (bSigned)  {
    MESSAGE("Changing signed to unsigned char and computing 1D histogram...");
    LargeRAWFile OutputData(strTargetFilename);
    OutputData.Create(iSize);

    if (!OutputData.IsOpen()) {
      InputData.Close();
      return "";
    }

    signed char* pInData = new signed char[iCurrentInCoreSize];

    UINT64 iPos = 0;
    while (iPos < iSize)  {
      size_t iRead = InputData.ReadRAW((unsigned char*)pInData, iCurrentInCoreSize);
      if (iRead == 0) break;

      for (size_t i = 0;i<iRead;i++) {
        pInData[i] += 128;
        if (Histogram1D) aHist[(unsigned char)pInData[i]]++;
      }
      OutputData.WriteRAW((unsigned char*)pInData, iRead);
      iPos += UINT64(iRead);
    }

    if (iPos < iSize) {
      WARNING("Specified size and real datasize mismatch");
    }

    delete [] pInData;
    strSignChangedFile = strTargetFilename;
    OutputData.Close();
  } else {
    if (Histogram1D) {
      MESSAGE("Computing 1D Histogram...");
      unsigned char* pInData = new unsigned char[iCurrentInCoreSize];

      UINT64 iPos = 0;
      UINT64 iDivLast = 0;
      while (iPos < iSize)  {
        size_t iRead = InputData.ReadRAW((unsigned char*)pInData, iCurrentInCoreSize);
        if (iRead == 0) break;
        for (size_t i = 0;i<iRead;i++) aHist[pInData[i]]++;
        iPos += UINT64(iRead);

        if (iPercent > 1 && (100*iPos)/iSize > iDivLast) {
          MESSAGE("Computing 1D Histogram (%u%% complete)",
                  static_cast<unsigned>((100*iPos)/iSize));
          iDivLast = (100*iPos)/iSize;
        }
      }

      if (iPos < iSize) {
        WARNING("Specified size and real datasize mismatch");
      }

      MESSAGE("1D Histogram complete");
      delete [] pInData;
    }
    strSignChangedFile = strFilename;
  }

  InputData.Close();
  if ( Histogram1D ) Histogram1D->SetHistogram(aHist);

  return strSignChangedFile;
}

size_t AbstrConverter::GetIncoreSize() {
  if (Controller::Instance().IOMan())
    return size_t(Controller::Instance().IOMan()->GetIncoresize());
  else
    return DEFAULT_INCORESIZE;
}

const std::string
AbstrConverter::QuantizeTo8Bit(UINT64 iHeaderSkip,
                               const std::string& strFilename,
                               const std::string& strTargetFilename,
                               UINT64 iComponentSize,
                               UINT64 iSize,
                               bool bSigned,
                               bool bIsFloat,
                               Histogram1DDataBlock* Histogram1D) {
  std::string intermFile = "";
  switch (iComponentSize) {
    case 8:
      intermFile = Process8Bits(iHeaderSkip, strFilename,
                                strTargetFilename, iSize, bSigned,
                                Histogram1D);
      break;
    case 16 :
      if(bSigned) {
        intermFile = Quantize<short, unsigned char>(iHeaderSkip, strFilename,
                                                    strTargetFilename, iSize,
                                                    Histogram1D);
      } else {
        intermFile = Quantize<unsigned short, unsigned char>
                             (iHeaderSkip, strFilename,
                              strTargetFilename, iSize, Histogram1D);
      }
      break;
    case 32 :
      if (bIsFloat) {
        intermFile = Quantize<float, unsigned char>(iHeaderSkip, strFilename,
                                          strTargetFilename, iSize,
                                          Histogram1D);
      } else {
        if(bSigned) {
          intermFile = Quantize<int, unsigned char>(iHeaderSkip, strFilename,
                                          strTargetFilename, iSize, Histogram1D);
        } else {
          intermFile = Quantize<unsigned, unsigned char>(iHeaderSkip, strFilename,
                                               strTargetFilename, iSize,
                                               Histogram1D);
        }
      }
      break;
    case 64 :
      if (bIsFloat) {
        intermFile = Quantize<double, unsigned char>(iHeaderSkip, strFilename,
                                           strTargetFilename, iSize,
                                           Histogram1D);
      } else {
        if(bSigned) {
          intermFile = Quantize<boost::int64_t, unsigned char>(
            iHeaderSkip, strFilename, strTargetFilename, iSize, Histogram1D
          );
        } else {
          intermFile = Quantize<UINT64, unsigned char>(iHeaderSkip, strFilename,
                                             strTargetFilename, iSize,
                                             Histogram1D);
        }
      }
      break;
  }

  return intermFile;
}
<|endoftext|>


<commit_before>#include "Hotkeys.h"

#include <CommCtrl.h>

#include "../3RVX/HotkeyInfo.h"
#include "../3RVX/HotkeyManager.h"
#include "../3RVX/Logger.h"
#include "../3RVX/Settings.h"
#include "../3RVX/SkinInfo.h"

#include "HotkeyPrompt.h"
#include "KeyGrabber.h"
#include "resource.h"

void Hotkeys::Initialize() {
    using std::placeholders::_1;

    INIT_CONTROL(LST_KEYS, ListView, _keyList);
    _keyList.OnItemChange = std::bind(&Hotkeys::OnKeyListItemChange, this, _1);
    INIT_CONTROL(BTN_ADD, Button, _add);
    _add.OnClick = std::bind(&Hotkeys::OnAddButtonClick, this);
    INIT_CONTROL(BTN_REMOVE, Button, _remove);
    _remove.OnClick = std::bind(&Hotkeys::OnRemoveButtonClick, this);

    INIT_CONTROL(BTN_KEYS, Button, _keys);
    _keys.OnClick = std::bind(&Hotkeys::OnKeysButtonClick, this);

    INIT_CONTROL(CMB_ACTION, ComboBox, _action);
    _action.OnSelectionChange = std::bind(&Hotkeys::OnActionChange, this);

    INIT_CONTROL(LBL_ARG, Label, _argLabel);
    INIT_CONTROL(CHK_ARG, Checkbox, _argCheck);
    _argCheck.OnClick = std::bind(&Hotkeys::OnArgCheckChange, this);
    INIT_CONTROL(CMB_ARG, ComboBox, _argCombo);
    _argCombo.OnSelectionChange = std::bind(&Hotkeys::OnArgComboChange, this);
    INIT_CONTROL(ED_ARG, EditBox, _argEdit);
}

void Hotkeys::LoadSettings() {
    Settings *settings = Settings::Instance();

    /* Make highlighted items span the entire row in the list view */
    _keyList.AddListExStyle(LVS_EX_FULLROWSELECT);

    RECT dims = _keyList.ScreenDimensions();
    int width = dims.right - dims.left;

    _keyList.AddColumn(hotkeysColumnStr, (int) (width * .485));
    _keyList.AddColumn(actionColumnStr, (int) (width * .445));

    for (std::wstring action : HotkeyInfo::ActionNames) {
        _action.AddItem(action);
    }

    std::unordered_map<int, HotkeyInfo> hotkeys = settings->Hotkeys();
    for (auto it = hotkeys.begin(); it != hotkeys.end(); ++it) {
        _keyInfo.push_back(it->second);
    }

    for (unsigned int i = 0; i < _keyInfo.size(); ++i) {
        HotkeyInfo hki = _keyInfo[i];
        std::wstring hkStr = HotkeyManager::HotkeysToString(hki.keyCombination);
        int idx = _keyList.AddItem(hkStr);
        _keyList.ItemText(idx, 1, HotkeyInfo::ActionNames[hki.action]);
    }

    _keyList.Selection(0);
    LoadSelection();
}

void Hotkeys::SaveSettings() {
    if (_hWnd == NULL) {
        return;
    }

    CLOG(L"Saving: Hotkeys");
    Settings *settings = Settings::Instance();
    settings->Hotkeys(_keyInfo);
}

void Hotkeys::LoadSelection() {
    int idx = _keyList.Selection();
    if (idx < 0) {
        _keys.Disable();
        _action.Disable();
        return;
    }
    LoadSelection(idx);
}

void Hotkeys::LoadSelection(int index) {
    HotkeyInfo selection = _keyInfo[index];
    _keys.Enable();
    _action.Enable();

    _keys.Text(L"");
    if (selection.keyCombination > 0) {
        std::wstring keyStr
            = HotkeyManager::HotkeysToString(selection.keyCombination);
        _keys.Text(keyStr);
        _keyList.ItemText(index, 0, keyStr);
    }

    _action.Select(-1);
    int action = selection.action;
    if (action >= 0) {
        _keyList.ItemText(index, 1, HotkeyInfo::ActionNames[action]);
        LoadActionParameters(action, selection);
        _action.Select(action);
    }
}

void Hotkeys::LoadActionParameters(int action, HotkeyInfo &selection) {
    bool showLabel = false;
    bool showCheck = false;
    bool showCombo = false;
    bool showEdit = false;

    /* Clean things up */
    _argLabel.Text(L"");
    _argCheck.Text(L"");
    _argCheck.Checked(false);
    _argCombo.Clear();
    _argEdit.Clear();

    switch ((HotkeyInfo::HotkeyActions) action) {
    case HotkeyInfo::IncreaseVolume:
    case HotkeyInfo::DecreaseVolume:
        _argCheck.Text(L"Amount:");
        _argEdit.PlaceRightOf(_argCheck);
        _argEdit.X(_action.X());
        _argCombo.AddItem(L"Volume Units");
        _argCombo.AddItem(L"Percent");
        _argCombo.PlaceRightOf(_argEdit);

        showCheck = true;
        showCombo = true;
        showEdit = true;
        OnArgCheckChange();
        break;

    case HotkeyInfo::EjectDrive:
        _argLabel.Text(L"Drive:");
        for (int i = 0; i < 26; ++i) {
            wchar_t ch = (wchar_t) i + 65;
            _argCombo.AddItem(std::wstring(1, ch));
        }

        if (selection.HasArgs()) {
            _argCombo.Select(selection.args[0]);
        }

        showLabel = true;
        showCombo = true;
        break;

    case HotkeyInfo::MediaKey:
        _argLabel.Text(L"Key:");
        for (std::wstring keys : HotkeyInfo::MediaKeyNames) {
            _argCombo.AddItem(keys);
        }
        if (selection.HasArgs()) {
            _argCombo.Select(selection.args[0]);
        }

        showLabel = true;
        showCombo = true;
        break;
    }

    _argLabel.Visible(showLabel);
    _argCheck.Visible(showCheck);
    _argCombo.Visible(showCombo);
    _argEdit.Visible(showEdit);
}

bool Hotkeys::OnAddButtonClick() {
    int items = _keyList.Count();
    for (int i = 0; i < items; ++i) {
        if (_keyList.ItemText(i, 0) == L"" && _keyList.ItemText(i, 1) == L"") {
            /* We found a blank item already in the list */
            _keyList.Selection(i);
            return true;
        }
    }

    HotkeyInfo hi;
    _keyInfo.push_back(hi);
    int idx = _keyList.InsertItem(items, L"");
    _keyList.ItemText(idx, 1, L"");
    _keyList.Selection(idx);
    return true;
}

bool Hotkeys::OnRemoveButtonClick() {
    int sel = _keyList.Selection();
    if (sel < 0) {
        return false;
    }

    _keyInfo.erase(_keyInfo.begin() + sel);
    _keyList.RemoveItem(sel);

    /* Select the item closest to the previous selection: */
    _keyList.Selection(sel);

    /* This handles disabling the other controls if the last item was removed:*/
    if (_keyList.Count() <= 0) {
        LoadSelection();
    }

    return true;
}

bool Hotkeys::OnActionChange() {
    int actionIdx = _action.SelectionIndex();
    int selectionIdx = _keyList.Selection();
    HotkeyInfo &currentListSelection = _keyInfo[selectionIdx];
    currentListSelection.action = (HotkeyInfo::HotkeyActions) actionIdx;
    LoadSelection(selectionIdx);
    return true;
}

bool Hotkeys::OnKeysButtonClick() {
    HotkeyPrompt::Show(_hWnd);
    KeyGrabber::Instance()->Unhook();
    int keyCombo = KeyGrabber::Instance()->KeyCombination();
    if (keyCombo > 0) {
        std::wstring keyStr = HotkeyManager::HotkeysToString(keyCombo);
        _keys.Text(keyStr);
        int sel = _keyList.Selection();
        _keyInfo[sel].keyCombination = keyCombo;
        LoadSelection(sel);
    }
    return true;
}

void Hotkeys::OnKeyListItemChange(NMLISTVIEW *lv) {
    if (lv->uChanged & LVIF_STATE) {
        if (lv->uNewState & LVIS_SELECTED) {
            OnKeyListSelectionChange(lv->iItem);
        }
    }
}

void Hotkeys::OnKeyListSelectionChange(int index) {
    HotkeyInfo current = _keyInfo[index];
    CLOG(L"Selecting key combination %d:", index);
    QCLOG(L"%s", current.ToString().c_str());
    LoadSelection(index);
}

bool Hotkeys::OnArgComboChange() {
    int selectionIdx = _keyList.Selection();
    HotkeyInfo *current = &_keyInfo[selectionIdx];

    HotkeyInfo::HotkeyActions action
        = (HotkeyInfo::HotkeyActions) _action.SelectionIndex();

    switch (action) {
    case HotkeyInfo::EjectDrive:
    case HotkeyInfo::MediaKey:
        current->AllocateArg(0);
        current->args[0] = _argCombo.Selection();
        break;
    }

    LoadSelection(selectionIdx);
    return true;
}

bool Hotkeys::OnArgCheckChange() {
    int selectionIdx = _keyList.Selection();
    if (selectionIdx == -1) {
        return false;
    }

    HotkeyInfo *current = &_keyInfo[selectionIdx];

    HotkeyInfo::HotkeyActions action
        = (HotkeyInfo::HotkeyActions) _action.SelectionIndex();

    switch (action) {
    case HotkeyInfo::IncreaseVolume:
    case HotkeyInfo::DecreaseVolume:
        if (_argCheck.Checked() == false) {
            _argEdit.Clear();
            current->args.clear();
        }
        break;
    }

    _argCombo.Enabled(_argCheck.Checked());
    _argEdit.Enabled(_argCheck.Checked());
    return true;
}

void Hotkeys::UpdateEditArgument() {
    HotkeyInfo *current = &_keyInfo[_listSelection];

    HotkeyInfo::HotkeyActions action
        = (HotkeyInfo::HotkeyActions) _action.SelectionIndex();

    switch (action) {
    case HotkeyInfo::IncreaseVolume:
    case HotkeyInfo::DecreaseVolume:
    case HotkeyInfo::SetVolume:
        if (_argEdit.Text() != L"") {
            current->AllocateArg(0);
            current->args[0] = _argEdit.Text();
        }

        break;
    }
}

void Hotkeys::DefaultArgControlStates() {
    _argLabel.Visible(false);
    _argCheck.Visible(false);
    _argCombo.Visible(false);
    _argEdit.Visible(false);
    _argLabel.Text(L"");
    _argCheck.Text(L"");
    _argCheck.Checked(false);
    _argCombo.Clear();
    _argCombo.Width(_action.Width());
    _argCombo.PlaceRightOf(_argLabel);
    _argCombo.X(_action.X());
    _argEdit.Clear();
    _argEdit.Width(_action.Width());
    _argEdit.PlaceRightOf(_argLabel);
    _argEdit.X(_action.X());
}

void Hotkeys::VolumeArgControlStates(HotkeyInfo &selection) {
    _argCheck.Text(amountVolArgStr);
    _argCheck.Checked(selection.HasArgs());
    _argEdit.Enabled(_argCheck.Checked());
    _argEdit.Width(_argEdit.EmSize() * 6);
    _argEdit.PlaceRightOf(_argCheck);
    _argEdit.X(_action.X());
    _argCombo.Enabled(_argCheck.Checked());
    _argCombo.AddItem(unitsVolArgStr);
    _argCombo.AddItem(percentVolArgStr);
    _argCombo.Select(0);
    _argCombo.PlaceRightOf(_argEdit);
    _argCombo.Width(_action.Width() - (_argCombo.X() - _action.X()));

    if (selection.HasArg(0)) {
        _argEdit.Text(selection.args[0]);
    }
    if (selection.HasArg(1)) {
        _argCombo.Select(selection.ArgToInt(1));
    }
}
<commit_msg>Sync edit box before save<commit_after>#include "Hotkeys.h"

#include <CommCtrl.h>

#include "../3RVX/HotkeyInfo.h"
#include "../3RVX/HotkeyManager.h"
#include "../3RVX/Logger.h"
#include "../3RVX/Settings.h"
#include "../3RVX/SkinInfo.h"

#include "HotkeyPrompt.h"
#include "KeyGrabber.h"
#include "resource.h"

void Hotkeys::Initialize() {
    using std::placeholders::_1;

    INIT_CONTROL(LST_KEYS, ListView, _keyList);
    _keyList.OnItemChange = std::bind(&Hotkeys::OnKeyListItemChange, this, _1);
    INIT_CONTROL(BTN_ADD, Button, _add);
    _add.OnClick = std::bind(&Hotkeys::OnAddButtonClick, this);
    INIT_CONTROL(BTN_REMOVE, Button, _remove);
    _remove.OnClick = std::bind(&Hotkeys::OnRemoveButtonClick, this);

    INIT_CONTROL(BTN_KEYS, Button, _keys);
    _keys.OnClick = std::bind(&Hotkeys::OnKeysButtonClick, this);

    INIT_CONTROL(CMB_ACTION, ComboBox, _action);
    _action.OnSelectionChange = std::bind(&Hotkeys::OnActionChange, this);

    INIT_CONTROL(LBL_ARG, Label, _argLabel);
    INIT_CONTROL(CHK_ARG, Checkbox, _argCheck);
    _argCheck.OnClick = std::bind(&Hotkeys::OnArgCheckChange, this);
    INIT_CONTROL(CMB_ARG, ComboBox, _argCombo);
    _argCombo.OnSelectionChange = std::bind(&Hotkeys::OnArgComboChange, this);
    INIT_CONTROL(ED_ARG, EditBox, _argEdit);
}

void Hotkeys::LoadSettings() {
    Settings *settings = Settings::Instance();

    /* Make highlighted items span the entire row in the list view */
    _keyList.AddListExStyle(LVS_EX_FULLROWSELECT);

    RECT dims = _keyList.ScreenDimensions();
    int width = dims.right - dims.left;

    _keyList.AddColumn(hotkeysColumnStr, (int) (width * .485));
    _keyList.AddColumn(actionColumnStr, (int) (width * .445));

    for (std::wstring action : HotkeyInfo::ActionNames) {
        _action.AddItem(action);
    }

    std::unordered_map<int, HotkeyInfo> hotkeys = settings->Hotkeys();
    for (auto it = hotkeys.begin(); it != hotkeys.end(); ++it) {
        _keyInfo.push_back(it->second);
    }

    for (unsigned int i = 0; i < _keyInfo.size(); ++i) {
        HotkeyInfo hki = _keyInfo[i];
        std::wstring hkStr = HotkeyManager::HotkeysToString(hki.keyCombination);
        int idx = _keyList.AddItem(hkStr);
        _keyList.ItemText(idx, 1, HotkeyInfo::ActionNames[hki.action]);
    }

    _keyList.Selection(0);
    LoadSelection();
}

void Hotkeys::SaveSettings() {
    if (_hWnd == NULL) {
        return;
    }

    /* If the edit box was the last thing the user touched, then we need to
     * manually sync the changes here. */
    UpdateEditArgument();

    CLOG(L"Saving: Hotkeys");
    Settings *settings = Settings::Instance();
    settings->Hotkeys(_keyInfo);
}

void Hotkeys::LoadSelection() {
    int idx = _keyList.Selection();
    if (idx < 0) {
        _keys.Disable();
        _action.Disable();
        return;
    }
    LoadSelection(idx);
}

void Hotkeys::LoadSelection(int index) {
    HotkeyInfo selection = _keyInfo[index];
    _keys.Enable();
    _action.Enable();

    _keys.Text(L"");
    if (selection.keyCombination > 0) {
        std::wstring keyStr
            = HotkeyManager::HotkeysToString(selection.keyCombination);
        _keys.Text(keyStr);
        _keyList.ItemText(index, 0, keyStr);
    }

    _action.Select(-1);
    int action = selection.action;
    if (action >= 0) {
        _keyList.ItemText(index, 1, HotkeyInfo::ActionNames[action]);
        LoadActionParameters(action, selection);
        _action.Select(action);
    }
}

void Hotkeys::LoadActionParameters(int action, HotkeyInfo &selection) {
    bool showLabel = false;
    bool showCheck = false;
    bool showCombo = false;
    bool showEdit = false;

    /* Clean things up */
    _argLabel.Text(L"");
    _argCheck.Text(L"");
    _argCheck.Checked(false);
    _argCombo.Clear();
    _argEdit.Clear();

    switch ((HotkeyInfo::HotkeyActions) action) {
    case HotkeyInfo::IncreaseVolume:
    case HotkeyInfo::DecreaseVolume:
        _argCheck.Text(L"Amount:");
        _argEdit.PlaceRightOf(_argCheck);
        _argEdit.X(_action.X());
        _argCombo.AddItem(L"Volume Units");
        _argCombo.AddItem(L"Percent");
        _argCombo.PlaceRightOf(_argEdit);

        showCheck = true;
        showCombo = true;
        showEdit = true;
        OnArgCheckChange();
        break;

    case HotkeyInfo::EjectDrive:
        _argLabel.Text(L"Drive:");
        for (int i = 0; i < 26; ++i) {
            wchar_t ch = (wchar_t) i + 65;
            _argCombo.AddItem(std::wstring(1, ch));
        }

        if (selection.HasArgs()) {
            _argCombo.Select(selection.args[0]);
        }

        showLabel = true;
        showCombo = true;
        break;

    case HotkeyInfo::MediaKey:
        _argLabel.Text(L"Key:");
        for (std::wstring keys : HotkeyInfo::MediaKeyNames) {
            _argCombo.AddItem(keys);
        }
        if (selection.HasArgs()) {
            _argCombo.Select(selection.args[0]);
        }

        showLabel = true;
        showCombo = true;
        break;
    }

    _argLabel.Visible(showLabel);
    _argCheck.Visible(showCheck);
    _argCombo.Visible(showCombo);
    _argEdit.Visible(showEdit);
}

bool Hotkeys::OnAddButtonClick() {
    int items = _keyList.Count();
    for (int i = 0; i < items; ++i) {
        if (_keyList.ItemText(i, 0) == L"" && _keyList.ItemText(i, 1) == L"") {
            /* We found a blank item already in the list */
            _keyList.Selection(i);
            return true;
        }
    }

    HotkeyInfo hi;
    _keyInfo.push_back(hi);
    int idx = _keyList.InsertItem(items, L"");
    _keyList.ItemText(idx, 1, L"");
    _keyList.Selection(idx);
    return true;
}

bool Hotkeys::OnRemoveButtonClick() {
    int sel = _keyList.Selection();
    if (sel < 0) {
        return false;
    }

    _keyInfo.erase(_keyInfo.begin() + sel);
    _keyList.RemoveItem(sel);

    /* Select the item closest to the previous selection: */
    _keyList.Selection(sel);

    /* This handles disabling the other controls if the last item was removed:*/
    if (_keyList.Count() <= 0) {
        LoadSelection();
    }

    return true;
}

bool Hotkeys::OnActionChange() {
    int actionIdx = _action.SelectionIndex();
    int selectionIdx = _keyList.Selection();
    HotkeyInfo &currentListSelection = _keyInfo[selectionIdx];
    currentListSelection.action = (HotkeyInfo::HotkeyActions) actionIdx;
    LoadSelection(selectionIdx);
    return true;
}

bool Hotkeys::OnKeysButtonClick() {
    HotkeyPrompt::Show(_hWnd);
    KeyGrabber::Instance()->Unhook();
    int keyCombo = KeyGrabber::Instance()->KeyCombination();
    if (keyCombo > 0) {
        std::wstring keyStr = HotkeyManager::HotkeysToString(keyCombo);
        _keys.Text(keyStr);
        int sel = _keyList.Selection();
        _keyInfo[sel].keyCombination = keyCombo;
        LoadSelection(sel);
    }
    return true;
}

void Hotkeys::OnKeyListItemChange(NMLISTVIEW *lv) {
    if (lv->uChanged & LVIF_STATE) {
        if (lv->uNewState & LVIS_SELECTED) {
            OnKeyListSelectionChange(lv->iItem);
        }
    }
}

void Hotkeys::OnKeyListSelectionChange(int index) {
    HotkeyInfo current = _keyInfo[index];
    CLOG(L"Selecting key combination %d:", index);
    QCLOG(L"%s", current.ToString().c_str());
    LoadSelection(index);
}

bool Hotkeys::OnArgComboChange() {
    int selectionIdx = _keyList.Selection();
    HotkeyInfo *current = &_keyInfo[selectionIdx];

    HotkeyInfo::HotkeyActions action
        = (HotkeyInfo::HotkeyActions) _action.SelectionIndex();

    switch (action) {
    case HotkeyInfo::EjectDrive:
    case HotkeyInfo::MediaKey:
        current->AllocateArg(0);
        current->args[0] = _argCombo.Selection();
        break;
    }

    LoadSelection(selectionIdx);
    return true;
}

bool Hotkeys::OnArgCheckChange() {
    int selectionIdx = _keyList.Selection();
    if (selectionIdx == -1) {
        return false;
    }

    HotkeyInfo *current = &_keyInfo[selectionIdx];

    HotkeyInfo::HotkeyActions action
        = (HotkeyInfo::HotkeyActions) _action.SelectionIndex();

    switch (action) {
    case HotkeyInfo::IncreaseVolume:
    case HotkeyInfo::DecreaseVolume:
        if (_argCheck.Checked() == false) {
            _argEdit.Clear();
            current->args.clear();
        }
        break;
    }

    _argCombo.Enabled(_argCheck.Checked());
    _argEdit.Enabled(_argCheck.Checked());
    return true;
}

void Hotkeys::UpdateEditArgument() {
    HotkeyInfo *current = &_keyInfo[_listSelection];

    HotkeyInfo::HotkeyActions action
        = (HotkeyInfo::HotkeyActions) _action.SelectionIndex();

    switch (action) {
    case HotkeyInfo::IncreaseVolume:
    case HotkeyInfo::DecreaseVolume:
    case HotkeyInfo::SetVolume:
        if (_argEdit.Text() != L"") {
            current->AllocateArg(0);
            current->args[0] = _argEdit.Text();
        }

        break;
    }
}

void Hotkeys::DefaultArgControlStates() {
    _argLabel.Visible(false);
    _argCheck.Visible(false);
    _argCombo.Visible(false);
    _argEdit.Visible(false);
    _argLabel.Text(L"");
    _argCheck.Text(L"");
    _argCheck.Checked(false);
    _argCombo.Clear();
    _argCombo.Width(_action.Width());
    _argCombo.PlaceRightOf(_argLabel);
    _argCombo.X(_action.X());
    _argEdit.Clear();
    _argEdit.Width(_action.Width());
    _argEdit.PlaceRightOf(_argLabel);
    _argEdit.X(_action.X());
}

void Hotkeys::VolumeArgControlStates(HotkeyInfo &selection) {
    _argCheck.Text(amountVolArgStr);
    _argCheck.Checked(selection.HasArgs());
    _argEdit.Enabled(_argCheck.Checked());
    _argEdit.Width(_argEdit.EmSize() * 6);
    _argEdit.PlaceRightOf(_argCheck);
    _argEdit.X(_action.X());
    _argCombo.Enabled(_argCheck.Checked());
    _argCombo.AddItem(unitsVolArgStr);
    _argCombo.AddItem(percentVolArgStr);
    _argCombo.Select(0);
    _argCombo.PlaceRightOf(_argEdit);
    _argCombo.Width(_action.Width() - (_argCombo.X() - _action.X()));

    if (selection.HasArg(0)) {
        _argEdit.Text(selection.args[0]);
    }
    if (selection.HasArg(1)) {
        _argCombo.Select(selection.ArgToInt(1));
    }
}
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtGui module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the either Technology Preview License Agreement or the
** Beta Release License Agreement.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://www.qtsoftware.com/contact.
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qdirectionrecognizer_p.h"

#include <math.h>

QT_BEGIN_NAMESPACE

enum {
    DistanceDelta = 20
};

QDirectionSimpleRecognizer::QDirectionSimpleRecognizer()
{
}

Direction QDirectionSimpleRecognizer::addPosition(const QPoint &pos)
{
    if (!directions.isEmpty()) {
        const QPoint tmp = pos - directions.back().point;
        if (tmp.manhattanLength() < 5)
            return Direction();
    }
    if (lastPoint.isNull()) {
        lastPoint = pos;
        return Direction();
    }
    int dx = pos.x() - lastPoint.x();
    int dy = pos.y() - lastPoint.y();
    Qt::DirectionType direction = Qt::NoDirection;
    if (dx < 0) {
        if (-1*dx >= DistanceDelta/2)
            direction = Qt::LeftDirection;
    } else {
        if (dx >= DistanceDelta/2)
            direction = Qt::RightDirection;
    }
    if (dy < 0) {
        if (-1*dy >= DistanceDelta/2)
            direction = Qt::UpDirection;
    } else {
        if (dy >= DistanceDelta/2)
            direction = Qt::DownDirection;
    }
    if (direction == Qt::NoDirection)
        return Direction();

    lastPoint = pos;
    directions.push_back(Direction(direction, pos));
    return Direction(direction, pos);
}

DirectionList QDirectionSimpleRecognizer::getDirections() const
{
    return directions;
}

void QDirectionSimpleRecognizer::reset()
{
    directions.clear();
    lastPoint = QPoint();
}

/// QDirectionDiagonalRecognizer

QDirectionDiagonalRecognizer::QDirectionDiagonalRecognizer()
{
}

Direction QDirectionDiagonalRecognizer::addPosition(const QPoint &pos)
{
    if (!directions.isEmpty()) {
        const QPoint tmp = pos - directions.back().point;
        if (tmp.manhattanLength() < 5)
            return Direction();
    }
    if (lastPoint.isNull()) {
        lastPoint = pos;
        return Direction();
    }
    int dx = pos.x() - lastPoint.x();
    int dy = pos.y() - lastPoint.y();
    int distance = sqrt(static_cast<double>(dx*dx + dy*dy));
    if (distance < DistanceDelta/2)
        return Direction();

    Qt::DirectionType direction = Qt::NoDirection;
    double angle = atan(1.0*qAbs(lastPoint.y() - pos.y())/qAbs(pos.x() - lastPoint.x())) * 180. / M_PI;
    if (dx < 0 && dy <= 0) {
        angle = 180 - angle;
    } else if (dx <= 0 && dy > 0) {
        angle += 180;
    } else if (dx > 0 && dy > 0) {
        angle = 360-angle;
    }
    if (angle < 0)
        angle += 360;
    if (angle <= 20)
        direction = Qt::RightDirection;
    else if (angle <= 65)
        direction = Qt::RightUpDirection;
    else if (angle <= 110)
        direction = Qt::UpDirection;
    else if (angle <= 155)
        direction = Qt::LeftUpDirection;
    else if (angle <= 200)
        direction = Qt::LeftDirection;
    else if (angle <= 245)
        direction = Qt::LeftDownDirection;
    else if (angle <= 290)
        direction = Qt::DownDirection;
    else if (angle <= 335)
        direction = Qt::RightDownDirection;
    else
        direction = Qt::RightDirection;

    if (direction == Qt::NoDirection)
        return Direction();

    lastPoint = pos;
    directions.push_back(Direction(direction, pos));
    return Direction(direction, pos);
}

DirectionList QDirectionDiagonalRecognizer::getDirections() const
{
    return directions;
}

void QDirectionDiagonalRecognizer::reset()
{
    directions.clear();
    lastPoint = QPoint();
}

QT_END_NAMESPACE
<commit_msg>Fixed compile with Windows CE 5.<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtGui module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the either Technology Preview License Agreement or the
** Beta Release License Agreement.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://www.qtsoftware.com/contact.
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qdirectionrecognizer_p.h"

#include <math.h>

#ifndef M_PI
#define M_PI 3.141592653589793238462643
#endif

QT_BEGIN_NAMESPACE

enum {
    DistanceDelta = 20
};

QDirectionSimpleRecognizer::QDirectionSimpleRecognizer()
{
}

Direction QDirectionSimpleRecognizer::addPosition(const QPoint &pos)
{
    if (!directions.isEmpty()) {
        const QPoint tmp = pos - directions.back().point;
        if (tmp.manhattanLength() < 5)
            return Direction();
    }
    if (lastPoint.isNull()) {
        lastPoint = pos;
        return Direction();
    }
    int dx = pos.x() - lastPoint.x();
    int dy = pos.y() - lastPoint.y();
    Qt::DirectionType direction = Qt::NoDirection;
    if (dx < 0) {
        if (-1*dx >= DistanceDelta/2)
            direction = Qt::LeftDirection;
    } else {
        if (dx >= DistanceDelta/2)
            direction = Qt::RightDirection;
    }
    if (dy < 0) {
        if (-1*dy >= DistanceDelta/2)
            direction = Qt::UpDirection;
    } else {
        if (dy >= DistanceDelta/2)
            direction = Qt::DownDirection;
    }
    if (direction == Qt::NoDirection)
        return Direction();

    lastPoint = pos;
    directions.push_back(Direction(direction, pos));
    return Direction(direction, pos);
}

DirectionList QDirectionSimpleRecognizer::getDirections() const
{
    return directions;
}

void QDirectionSimpleRecognizer::reset()
{
    directions.clear();
    lastPoint = QPoint();
}

/// QDirectionDiagonalRecognizer

QDirectionDiagonalRecognizer::QDirectionDiagonalRecognizer()
{
}

Direction QDirectionDiagonalRecognizer::addPosition(const QPoint &pos)
{
    if (!directions.isEmpty()) {
        const QPoint tmp = pos - directions.back().point;
        if (tmp.manhattanLength() < 5)
            return Direction();
    }
    if (lastPoint.isNull()) {
        lastPoint = pos;
        return Direction();
    }
    int dx = pos.x() - lastPoint.x();
    int dy = pos.y() - lastPoint.y();
    int distance = sqrt(static_cast<double>(dx*dx + dy*dy));
    if (distance < DistanceDelta/2)
        return Direction();

    Qt::DirectionType direction = Qt::NoDirection;
    double angle = atan(1.0*qAbs(lastPoint.y() - pos.y())/qAbs(pos.x() - lastPoint.x())) * 180. / M_PI;
    if (dx < 0 && dy <= 0) {
        angle = 180 - angle;
    } else if (dx <= 0 && dy > 0) {
        angle += 180;
    } else if (dx > 0 && dy > 0) {
        angle = 360-angle;
    }
    if (angle < 0)
        angle += 360;
    if (angle <= 20)
        direction = Qt::RightDirection;
    else if (angle <= 65)
        direction = Qt::RightUpDirection;
    else if (angle <= 110)
        direction = Qt::UpDirection;
    else if (angle <= 155)
        direction = Qt::LeftUpDirection;
    else if (angle <= 200)
        direction = Qt::LeftDirection;
    else if (angle <= 245)
        direction = Qt::LeftDownDirection;
    else if (angle <= 290)
        direction = Qt::DownDirection;
    else if (angle <= 335)
        direction = Qt::RightDownDirection;
    else
        direction = Qt::RightDirection;

    if (direction == Qt::NoDirection)
        return Direction();

    lastPoint = pos;
    directions.push_back(Direction(direction, pos));
    return Direction(direction, pos);
}

DirectionList QDirectionDiagonalRecognizer::getDirections() const
{
    return directions;
}

void QDirectionDiagonalRecognizer::reset()
{
    directions.clear();
    lastPoint = QPoint();
}

QT_END_NAMESPACE
<|endoftext|>


<commit_before>// Copyright (c) 2018 Chris Ohk, Youngjoong Kim, SeungHyun Jeon

// We are making my contributions/submissions to this project solely in our
// personal capacity and are not conveying any rights to any intellectual
// property of any third parties.

#include <hspp/Cards/Cards.h>

#include <better-enums/enum.h>
#include <clara.hpp>

#ifdef HEARTHSTONEPP_WINDOWS
#include <filesystem>
#endif
#ifdef HEARTHSTONEPP_LINUX
#include <experimental/filesystem>
#endif
#include <fstream>
#include <iostream>
#include <regex>
#include <string>
#include <vector>

using namespace Hearthstonepp;

#ifndef HEARTHSTONEPP_MACOSX
namespace filesystem = std::experimental::filesystem;
#endif

inline std::string ToString(const clara::Opt& opt)
{
    std::ostringstream oss;
    oss << (clara::Parser() | opt);
    return oss.str();
}

inline std::string ToString(const clara::Parser& p)
{
    std::ostringstream oss;
    oss << p;
    return oss.str();
}

inline std::vector<GameTag> CheckAbilityImpl(const std::string& path)
{
    std::map<std::string, GameTag> abilityStrMap = {
        { "Adapt", GameTag::ADAPT },
        { "Charge", GameTag::CHARGE },
        { "DivineShield", GameTag::DIVINE_SHIELD },
        { "Freeze", GameTag::FREEZE },
        { "Poisonous", GameTag::POISONOUS },
        { "Stealth", GameTag::STEALTH },
        { "Taunt", GameTag::TAUNT },
        { "Windfury", GameTag::WINDFURY }
    };

    std::vector<GameTag> result;

#ifndef HEARTHSTONEPP_MACOSX
    const filesystem::path p(
        path + "/Tests/UnitTests/Tasks/BasicTasks/CombatTaskTests.cpp");

    if (!filesystem::exists(p))
    {
        std::cerr << p << " does not exist\n";
        exit(EXIT_FAILURE);
    }

    if (!filesystem::is_regular_file(p))
    {
        std::cerr << p << " exists, but is not regular file\n";
        exit(EXIT_FAILURE);
    }

    std::ifstream abilityFile;
    abilityFile.open(p.string());

    if (!abilityFile.is_open())
    {
        std::cerr << p << " couldn't open\n";
        exit(EXIT_FAILURE);
    }

    std::string line;
    while (std::getline(abilityFile, line))
    {
        for (auto& ability : abilityStrMap)
        {
            std::string sentence = "TEST(CombatTask, " + ability.first + ")";
            if (line.find(sentence, 0) != std::string::npos)
            {
                result.emplace_back(ability.second);
                break;
            }
        }
    }

#else
    std::cerr
        << "CheckAbilityImpl skip: apple-clang doesn't support <filesystem>\n";
    exit(EXIT_FAILURE);
#endif

    return result;
}

inline std::vector<Card> QueryCardSetList(const std::string& projectPath,
                                          CardSet cardSet, bool implCardOnly)
{
    if (cardSet == +CardSet::ALL)
    {
        return Cards::GetInstance()->GetAllCards();
    }

    std::vector<GameTag> abilityList{};
    if (implCardOnly)
    {
        abilityList = CheckAbilityImpl(projectPath);
    }

    std::vector<Card> result;
    for (auto& card : Cards::GetInstance()->FindCardBySet(cardSet))
    {
        if (implCardOnly)
        {
            bool isAbilityImpl = true;
            for (auto& mechanic : card.mechanics)
            {
                if (std::find(abilityList.begin(), abilityList.end(),
                              mechanic) == abilityList.end())
                {
                    isAbilityImpl = false;
                    break;
                }
            }

            if (!isAbilityImpl || (card.cardType != +CardType::MINION &&
                                   card.cardType != +CardType::HERO &&
                                   card.cardType != +CardType::HERO_POWER &&
                                   card.cardType != +CardType::WEAPON))
            {
                result.emplace_back(card);
            }
        }
        else
        {
            result.emplace_back(card);
        }
    }

    return result;
}

inline bool CheckCardImpl(const std::string& path, const std::string& id)
{
#ifndef HEARTHSTONEPP_MACOSX
    const filesystem::path p(path + "/Tests/UnitTests/CardSets");

    if (!filesystem::exists(p))
    {
        std::cerr << p << " does not exist\n";
        exit(EXIT_FAILURE);
    }

    if (!filesystem::is_directory(p))
    {
        std::cerr << p << " exists, but is not directory\n";
        exit(EXIT_FAILURE);
    }

    for (auto&& file : filesystem::recursive_directory_iterator(p))
    {
        std::regex fileNamePattern(R"(.*\\(.*)\..*$)");
        std::smatch match;

        std::string pathStr = file.path().string();

        if (std::regex_match(pathStr, match, fileNamePattern))
        {
            if (match[1] == id)
            {
                return true;
            }
        }
    }
#else
    std::cerr
        << "CheckCardImpl skip: apple-clang doesn't support <filesystem>\n";
    exit(EXIT_FAILURE);
#endif

    return false;
}

inline void ExportFile(const std::string& projectPath,
                       CardSet cardSet, std::vector<Card>& cards)
{
    std::ofstream outputFile("result.md");
    if (outputFile)
    {
        size_t allCardNum = 0;
        size_t toImplCardNum = 0;
        size_t impledCardNum = 0;

        for (auto& card : Cards::GetInstance()->FindCardBySet(cardSet))
        {
            if (card.isCollectible)
            {
                allCardNum++;
            }
        }

        outputFile << "Set | ID | Name | Implemented\n";
        outputFile << ":---: | :---: | :---: | :---:\n";

        for (auto& card : cards)
        {
            if (!card.isCollectible)
            {
                continue;
            }

            toImplCardNum++;

            std::string mechanicStr;
            for (auto& mechanic : card.mechanics)
            {
                mechanicStr += mechanic._to_string();
            }

            const bool isImplemented = CheckCardImpl(projectPath, card.id);
            if (isImplemented)
            {
                impledCardNum++;
            }

            outputFile << card.cardSet._to_string() << " | " << card.id << " | "
                       << card.name << " | " << (isImplemented ? 'O' : ' ')
                       << '\n';
        }

        // Adds the number of card that implemented by ability
        impledCardNum += (allCardNum - toImplCardNum);
        const size_t implPercent = static_cast<size_t>(
            static_cast<double>(impledCardNum) / allCardNum * 100);
        outputFile << '\n';
        outputFile << "- Progress: " << implPercent << "% (" << impledCardNum
                   << " of " << allCardNum << " Cards)";

        std::cout << "Export file is completed.\n";
        exit(EXIT_SUCCESS);
    }

    std::cerr << "Failed to write file result.md\n";
    exit(EXIT_FAILURE);
}

int main(int argc, char* argv[])
{
    // Parse command
    bool showHelp = false;
    bool isExportAllCard = false;
    bool implCardOnly = false;
    std::string cardSetName;
    std::string projectPath;

    // Parsing
    auto parser = clara::Help(showHelp) |
                  clara::Opt(isExportAllCard)["-a"]["--all"](
                      "Export a list of all expansion cards") |
                  clara::Opt(cardSetName, "cardSet")["-c"]["--cardset"](
                      "Export a list of specific expansion cards") |
                  clara::Opt(implCardOnly)["-i"]["--implcardonly"](
                      "Export a list of cards that need to be implemented") |
                  clara::Opt(projectPath, "path")["-p"]["--path"](
                      "Specify Hearthstone++ project path");

    auto result = parser.parse(clara::Args(argc, argv));
    if (!result)
    {
        std::cerr << "Error in command line: " << result.errorMessage() << '\n';
        exit(EXIT_FAILURE);
    }

    if (showHelp)
    {
        std::cout << ToString(parser) << '\n';
        exit(EXIT_SUCCESS);
    }

    if (projectPath.empty())
    {
        std::cout << "You should input Hearthstone++ project path\n";
        exit(EXIT_FAILURE);
    }

    CardSet cardSet = CardSet::INVALID;

    if (isExportAllCard)
    {
        cardSet = CardSet::ALL;
    }
    else if (!cardSetName.empty())
    {
        const auto convertedCardSet =
            CardSet::_from_string_nothrow(cardSetName.c_str());
        if (!convertedCardSet)
        {
            std::cerr << "Invalid card set name: " << cardSetName << '\n';
            exit(EXIT_FAILURE);
        }

        cardSet = *convertedCardSet;
    }

    std::vector<Card> cards =
        QueryCardSetList(projectPath, cardSet, implCardOnly);

    if (cards.empty())
    {
        std::cerr << "Your search did not generate any hits.\n";
        exit(EXIT_SUCCESS);
    }

    ExportFile(projectPath, cardSet, cards);

    exit(EXIT_SUCCESS);
}<commit_msg>feat(improve-tool): Excludes 9 hero cards from CardSet::CORE<commit_after>// Copyright (c) 2018 Chris Ohk, Youngjoong Kim, SeungHyun Jeon

// We are making my contributions/submissions to this project solely in our
// personal capacity and are not conveying any rights to any intellectual
// property of any third parties.

#include <hspp/Cards/Cards.h>

#include <better-enums/enum.h>
#include <clara.hpp>

#ifdef HEARTHSTONEPP_WINDOWS
#include <filesystem>
#endif
#ifdef HEARTHSTONEPP_LINUX
#include <experimental/filesystem>
#endif
#include <fstream>
#include <iostream>
#include <regex>
#include <string>
#include <vector>

using namespace Hearthstonepp;

#ifndef HEARTHSTONEPP_MACOSX
namespace filesystem = std::experimental::filesystem;
#endif

inline std::string ToString(const clara::Opt& opt)
{
    std::ostringstream oss;
    oss << (clara::Parser() | opt);
    return oss.str();
}

inline std::string ToString(const clara::Parser& p)
{
    std::ostringstream oss;
    oss << p;
    return oss.str();
}

inline std::vector<GameTag> CheckAbilityImpl(const std::string& path)
{
    std::map<std::string, GameTag> abilityStrMap = {
        { "Adapt", GameTag::ADAPT },
        { "Charge", GameTag::CHARGE },
        { "DivineShield", GameTag::DIVINE_SHIELD },
        { "Freeze", GameTag::FREEZE },
        { "Poisonous", GameTag::POISONOUS },
        { "Stealth", GameTag::STEALTH },
        { "Taunt", GameTag::TAUNT },
        { "Windfury", GameTag::WINDFURY }
    };

    std::vector<GameTag> result;

#ifndef HEARTHSTONEPP_MACOSX
    const filesystem::path p(
        path + "/Tests/UnitTests/Tasks/BasicTasks/CombatTaskTests.cpp");

    if (!filesystem::exists(p))
    {
        std::cerr << p << " does not exist\n";
        exit(EXIT_FAILURE);
    }

    if (!filesystem::is_regular_file(p))
    {
        std::cerr << p << " exists, but is not regular file\n";
        exit(EXIT_FAILURE);
    }

    std::ifstream abilityFile;
    abilityFile.open(p.string());

    if (!abilityFile.is_open())
    {
        std::cerr << p << " couldn't open\n";
        exit(EXIT_FAILURE);
    }

    std::string line;
    while (std::getline(abilityFile, line))
    {
        for (auto& ability : abilityStrMap)
        {
            std::string sentence = "TEST(CombatTask, " + ability.first + ")";
            if (line.find(sentence, 0) != std::string::npos)
            {
                result.emplace_back(ability.second);
                break;
            }
        }
    }

#else
    std::cerr
        << "CheckAbilityImpl skip: apple-clang doesn't support <filesystem>\n";
    exit(EXIT_FAILURE);
#endif

    return result;
}

inline std::vector<Card> QueryCardSetList(const std::string& projectPath,
                                          CardSet cardSet, bool implCardOnly)
{
    if (cardSet == +CardSet::ALL)
    {
        return Cards::GetInstance()->GetAllCards();
    }

    std::vector<GameTag> abilityList{};
    if (implCardOnly)
    {
        abilityList = CheckAbilityImpl(projectPath);
    }

    std::vector<Card> result;
    for (auto& card : Cards::GetInstance()->FindCardBySet(cardSet))
    {
        if (implCardOnly)
        {
            bool isAbilityImpl = true;
            for (auto& mechanic : card.mechanics)
            {
                if (std::find(abilityList.begin(), abilityList.end(),
                              mechanic) == abilityList.end())
                {
                    isAbilityImpl = false;
                    break;
                }
            }

            if (!isAbilityImpl || (card.cardType != +CardType::MINION &&
                                   card.cardType != +CardType::HERO &&
                                   card.cardType != +CardType::HERO_POWER &&
                                   card.cardType != +CardType::WEAPON))
            {
                result.emplace_back(card);
            }
        }
        else
        {
            result.emplace_back(card);
        }
    }

    return result;
}

inline bool CheckCardImpl(const std::string& path, const std::string& id)
{
#ifndef HEARTHSTONEPP_MACOSX
    const filesystem::path p(path + "/Tests/UnitTests/CardSets");

    if (!filesystem::exists(p))
    {
        std::cerr << p << " does not exist\n";
        exit(EXIT_FAILURE);
    }

    if (!filesystem::is_directory(p))
    {
        std::cerr << p << " exists, but is not directory\n";
        exit(EXIT_FAILURE);
    }

    for (auto&& file : filesystem::recursive_directory_iterator(p))
    {
        std::regex fileNamePattern(R"(.*\\(.*)\..*$)");
        std::smatch match;

        std::string pathStr = file.path().string();

        if (std::regex_match(pathStr, match, fileNamePattern))
        {
            if (match[1] == id)
            {
                return true;
            }
        }
    }
#else
    std::cerr
        << "CheckCardImpl skip: apple-clang doesn't support <filesystem>\n";
    exit(EXIT_FAILURE);
#endif

    return false;
}

inline void ExportFile(const std::string& projectPath,
                       CardSet cardSet, std::vector<Card>& cards)
{
    std::ofstream outputFile("result.md");
    if (outputFile)
    {
        size_t allCardNum = 0;
        size_t toImplCardNum = 0;
        size_t impledCardNum = 0;

        for (auto& card : Cards::GetInstance()->FindCardBySet(cardSet))
        {
            if (card.isCollectible)
            {
                allCardNum++;
            }
        }

        // Excludes 9 hero cards from CardSet::CORE
        if (cardSet == +CardSet::CORE)
        {
            allCardNum -= 9;
        }

        outputFile << "Set | ID | Name | Implemented\n";
        outputFile << ":---: | :---: | :---: | :---:\n";

        for (auto& card : cards)
        {
            if (!card.isCollectible)
            {
                continue;
            }

            toImplCardNum++;

            std::string mechanicStr;
            for (auto& mechanic : card.mechanics)
            {
                mechanicStr += mechanic._to_string();
            }

            const bool isImplemented = CheckCardImpl(projectPath, card.id);
            if (isImplemented)
            {
                impledCardNum++;
            }

            outputFile << card.cardSet._to_string() << " | " << card.id << " | "
                       << card.name << " | " << (isImplemented ? 'O' : ' ')
                       << '\n';
        }

        // Adds the number of card that implemented by ability
        impledCardNum += (allCardNum - toImplCardNum);
        const size_t implPercent = static_cast<size_t>(
            static_cast<double>(impledCardNum) / allCardNum * 100);
        outputFile << '\n';
        outputFile << "- Progress: " << implPercent << "% (" << impledCardNum
                   << " of " << allCardNum << " Cards)";

        std::cout << "Export file is completed.\n";
        exit(EXIT_SUCCESS);
    }

    std::cerr << "Failed to write file result.md\n";
    exit(EXIT_FAILURE);
}

int main(int argc, char* argv[])
{
    // Parse command
    bool showHelp = false;
    bool isExportAllCard = false;
    bool implCardOnly = false;
    std::string cardSetName;
    std::string projectPath;

    // Parsing
    auto parser = clara::Help(showHelp) |
                  clara::Opt(isExportAllCard)["-a"]["--all"](
                      "Export a list of all expansion cards") |
                  clara::Opt(cardSetName, "cardSet")["-c"]["--cardset"](
                      "Export a list of specific expansion cards") |
                  clara::Opt(implCardOnly)["-i"]["--implcardonly"](
                      "Export a list of cards that need to be implemented") |
                  clara::Opt(projectPath, "path")["-p"]["--path"](
                      "Specify Hearthstone++ project path");

    auto result = parser.parse(clara::Args(argc, argv));
    if (!result)
    {
        std::cerr << "Error in command line: " << result.errorMessage() << '\n';
        exit(EXIT_FAILURE);
    }

    if (showHelp)
    {
        std::cout << ToString(parser) << '\n';
        exit(EXIT_SUCCESS);
    }

    if (projectPath.empty())
    {
        std::cout << "You should input Hearthstone++ project path\n";
        exit(EXIT_FAILURE);
    }

    CardSet cardSet = CardSet::INVALID;

    if (isExportAllCard)
    {
        cardSet = CardSet::ALL;
    }
    else if (!cardSetName.empty())
    {
        const auto convertedCardSet =
            CardSet::_from_string_nothrow(cardSetName.c_str());
        if (!convertedCardSet)
        {
            std::cerr << "Invalid card set name: " << cardSetName << '\n';
            exit(EXIT_FAILURE);
        }

        cardSet = *convertedCardSet;
    }

    std::vector<Card> cards =
        QueryCardSetList(projectPath, cardSet, implCardOnly);

    if (cards.empty())
    {
        std::cerr << "Your search did not generate any hits.\n";
        exit(EXIT_SUCCESS);
    }

    ExportFile(projectPath, cardSet, cards);

    exit(EXIT_SUCCESS);
}<|endoftext|>


<commit_before>#if !defined(_EDGE_DETECT_DFT_)

#include <Eigen/Core>
#include <Eigen/LU>

using std::complex;
using std::abs;

template <typename T> class edgedetect {
public:
  typedef enum {
    DETECT_X,
    DETECT_Y,
    DETECT_BOTH,
    COLLECT_X,
    COLLECT_Y,
    COLLECT_BOTH } direction_t;
  edgedetect();
  typedef complex<T> U;
  typedef Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> Mat;
  typedef Eigen::Matrix<U, Eigen::Dynamic, Eigen::Dynamic> MatU;
  Mat detect(const Mat& data, const direction_t& dir);
private:
  void initPattern(const int&);
  U    I;
  T    Pi;
  Mat  Dop;
};

template <typename T> edgedetect<T>::edgedetect() {
  I  = sqrt(U(- 1.));
  Pi = atan2(T(1.), T(1.)) * T(4.);
}

template <typename T> Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> edgedetect<T>::detect(const Mat& data, const direction_t& dir) {
  Mat result(data);
  switch(dir) {
  case DETECT_BOTH:
    {
      Mat w(detect(data, DETECT_X));
      Mat h(detect(data, DETECT_Y));
      result = (w + h) / T(2);
    }
    break;
  case DETECT_X:
    result = detect(data.transpose(), DETECT_Y).transpose();
    break;
  case DETECT_Y:
    initPattern(data.rows());
    result = Dop * data;
    break;
  case COLLECT_BOTH:
    {
      Mat w(detect(data, COLLECT_X));
      Mat h(detect(data, COLLECT_Y));
      result = (w + h) / T(2);
    }
    break;
  case COLLECT_X:
    result = detect(data.transpose(), COLLECT_Y).transpose();
    break;
  case COLLECT_Y:
    {
      result = detect(data, DETECT_Y);
#if defined(_OPENMP)
#pragma omp parallel for schedule(static, 1)
#endif
      for(int i = 0; i < result.rows(); i ++)
        for(int j = 0; j < result.cols(); j ++)
          result(i, j) = abs(result(i, j));
    }
    break;
  default:
    ;
  }
  return result;
}

template <typename T> void edgedetect<T>::initPattern(const int& size) {
  MatU Dbuf(size, size), Iop(size, size);
#if defined(_OPENMP)
#pragma omp parallel for schedule(static, 1)
#endif
  for(int i = 0; i < Dbuf.rows(); i ++)
    for(int j = 0; j < Dbuf.cols(); j ++) {
      Dbuf(i, j) = exp(U(- 2.) * Pi * I * U(i * j / T(size)));
      Iop(i, j)  = exp(U(  2.) * Pi * I * U(i * j / T(size)));
    }
#if defined(_OPENMP)
#pragma omp parallel for schedule(static, 1)
#endif
  for(int i = 0; i < Dbuf.rows(); i ++)
    Dbuf.row(i) *= U(- 2.) * Pi * I * U(i / T(size));
  Dop = (Iop * Dbuf).real().template cast<T>();
  return;
}

#define _EDGE_DETECT_DFT_
#endif

<commit_msg>Delete edgedetect.hh<commit_after><|endoftext|>