<commit_before>/**
 * @file lldir_win32.cpp
 * @brief Implementation of directory utilities for windows
 *
 * $LicenseInfo:firstyear=2002&license=viewergpl$
 *
 * Copyright (c) 2002-2007, Linden Research, Inc.
 *
 * Second Life Viewer Source Code
 * The source code in this file ("Source Code") is provided by Linden Lab
 * to you under the terms of the GNU General Public License, version 2.0
 * ("GPL"), unless you have obtained a separate licensing agreement
 * ("Other License"), formally executed by you and Linden Lab.  Terms of
 * the GPL can be found in doc/GPL-license.txt in this distribution, or
 * online at http://secondlife.com/developers/opensource/gplv2
 *
 * There are special exceptions to the terms and conditions of the GPL as
 * it is applied to this Source Code. View the full text of the exception
 * in the file doc/FLOSS-exception.txt in this software distribution, or
 * online at http://secondlife.com/developers/opensource/flossexception
 *
 * By copying, modifying or distributing this software, you acknowledge
 * that you have read and understood your obligations described above,
 * and agree to abide by those obligations.
 *
 * ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO
 * WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY,
 * COMPLETENESS OR PERFORMANCE.
 * $/LicenseInfo$
 */

#if LL_WINDOWS

#include "linden_common.h"

#include "lldir_win32.h"
#include "llerror.h"
#include "llrand.h"		// for gLindenLabRandomNumber
#include "shlobj.h"

#include <direct.h>
#include <sys/types.h>
#include <sys/stat.h>

// Utility stuff to get versions of the sh
#define PACKVERSION(major,minor) MAKELONG(minor,major)
DWORD GetDllVersion(LPCTSTR lpszDllName);

LLDir_Win32::LLDir_Win32()
{
	mDirDelimiter = "\\";

	WCHAR w_str[MAX_PATH];

	// Application Data is where user settings go
	SHGetSpecialFolderPath(NULL, w_str, CSIDL_APPDATA, TRUE);

	mOSUserDir = utf16str_to_utf8str(llutf16string(w_str));

	// Local Settings\Application Data is where cache files should
	// go, they don't get copied to the server if the user moves his
	// profile around on the network. JC
	//
	// TODO: patch the installer to remove old cache files on update, then
	// enable this code.
	//SHGetSpecialFolderPath(NULL, w_str, CSIDL_LOCAL_APPDATA, TRUE);
	//mOSUserCacheDir = utf16str_to_utf8str(llutf16string(w_str));

	if (GetTempPath(MAX_PATH, w_str))
	{
		if (wcslen(w_str))	/* Flawfinder: ignore */
		{
			w_str[wcslen(w_str)-1] = '\0'; /* Flawfinder: ignore */ // remove trailing slash
		}
		mTempDir = utf16str_to_utf8str(llutf16string(w_str));
	}
	else
	{
		mTempDir = mOSUserDir;
	}

//	fprintf(stderr, "mTempDir = <%s>",mTempDir);

#if 1
	// Don't use the real app path for now, as we'll have to add parsing to detect if
	// we're in a developer tree, which has a different structure from the installed product.

	S32 size = GetModuleFileName(NULL, w_str, MAX_PATH);
	if (size)
	{
		w_str[size] = '\0';
		mExecutablePathAndName = utf16str_to_utf8str(llutf16string(w_str));
		S32 path_end = mExecutablePathAndName.find_last_of('\\');
		if (path_end != std::string::npos)
		{
			mExecutableDir = mExecutablePathAndName.substr(0, path_end);
			mExecutableFilename = mExecutablePathAndName.substr(path_end+1, std::string::npos);
		}
		else
		{
			mExecutableFilename = mExecutablePathAndName;
		}
		GetCurrentDirectory(MAX_PATH, w_str);
		mWorkingDir = utf16str_to_utf8str(llutf16string(w_str));

	}
	else
	{
		fprintf(stderr, "Couldn't get APP path, assuming current directory!");
		GetCurrentDirectory(MAX_PATH, w_str);
		mExecutableDir = utf16str_to_utf8str(llutf16string(w_str));
		// Assume it's the current directory
	}
#else
	GetCurrentDirectory(MAX_PATH, w_str);
	mExecutableDir = utf16str_to_utf8str(llutf16string(w_str));
#endif
	if (strstr(mExecutableDir.c_str(), "indra\\newview"))
		mAppRODataDir = getCurPath();
	else
		mAppRODataDir = mExecutableDir;
}

LLDir_Win32::~LLDir_Win32()
{
}

// Implementation

void LLDir_Win32::initAppDirs(const std::string &app_name)
{
	mAppName = app_name;
	mOSUserAppDir = mOSUserDir;
	mOSUserAppDir += "\\";
	mOSUserAppDir += app_name;

	int res = LLFile::mkdir(mOSUserAppDir.c_str());
	if (res == -1)
	{
		if (errno != EEXIST)
		{
			llwarns << "Couldn't create app user dir " << mOSUserAppDir << llendl;
			llwarns << "Default to base dir" << mOSUserDir << llendl;
			mOSUserAppDir = mOSUserDir;
		}
	}
	//dumpCurrentDirectories();

	res = LLFile::mkdir(getExpandedFilename(LL_PATH_LOGS,"").c_str());
	if (res == -1)
	{
		if (errno != EEXIST)
		{
			llwarns << "Couldn't create LL_PATH_LOGS dir " << getExpandedFilename(LL_PATH_LOGS,"") << llendl;
		}
	}

	res = LLFile::mkdir(getExpandedFilename(LL_PATH_USER_SETTINGS,"").c_str());
	if (res == -1)
	{
		if (errno != EEXIST)
		{
			llwarns << "Couldn't create LL_PATH_USER_SETTINGS dir " << getExpandedFilename(LL_PATH_USER_SETTINGS,"") << llendl;
		}
	}

	res = LLFile::mkdir(getExpandedFilename(LL_PATH_CACHE,"").c_str());
	if (res == -1)
	{
		if (errno != EEXIST)
		{
			llwarns << "Couldn't create LL_PATH_CACHE dir " << getExpandedFilename(LL_PATH_CACHE,"") << llendl;
		}
	}

	res = LLFile::mkdir(getExpandedFilename(LL_PATH_MOZILLA_PROFILE,"").c_str());
	if (res == -1)
	{
		if (errno != EEXIST)
		{
			llwarns << "Couldn't create LL_PATH_MOZILLA_PROFILE dir " << getExpandedFilename(LL_PATH_MOZILLA_PROFILE,"") << llendl;
		}
	}

	mCAFile = getExpandedFilename(LL_PATH_APP_SETTINGS, "CA.pem");
}

U32 LLDir_Win32::countFilesInDir(const std::string &dirname, const std::string &mask)
{
	HANDLE count_search_h;
	U32 file_count;

	file_count = 0;

	WIN32_FIND_DATA FileData;

	llutf16string pathname = utf8str_to_utf16str(dirname);
	pathname += utf8str_to_utf16str(mask);

	if ((count_search_h = FindFirstFile(pathname.c_str(), &FileData)) != INVALID_HANDLE_VALUE)
	{
		file_count++;

		while (FindNextFile(count_search_h, &FileData))
		{
			file_count++;
		}

		FindClose(count_search_h);
	}

	return (file_count);
}

// get the next file in the directory
// automatically wrap if we've hit the end
BOOL LLDir_Win32::getNextFileInDir(const std::string &dirname, const std::string &mask, std::string &fname, BOOL wrap)
{
	llutf16string dirnamew = utf8str_to_utf16str(dirname);
	return getNextFileInDir(dirnamew, mask, fname, wrap);

}

BOOL LLDir_Win32::getNextFileInDir(const llutf16string &dirname, const std::string &mask, std::string &fname, BOOL wrap)
{
	WIN32_FIND_DATAW FileData;

	fname = "";
	llutf16string pathname = dirname;
	pathname += utf8str_to_utf16str(mask);

	if (pathname != mCurrentDir)
	{
		// different dir specified, close old search
		if (mCurrentDir[0])
		{
			FindClose(mDirSearch_h);
		}
		mCurrentDir = pathname;

		// and open new one
		// Check error opening Directory structure
		if ((mDirSearch_h = FindFirstFile(pathname.c_str(), &FileData)) == INVALID_HANDLE_VALUE)
		{
//			llinfos << "Unable to locate first file" << llendl;
			return(FALSE);
		}
	}
	else // get next file in list
	{
		// Find next entry
		if (!FindNextFile(mDirSearch_h, &FileData))
		{
			if (GetLastError() == ERROR_NO_MORE_FILES)
			{
                // No more files, so reset to beginning of directory
				FindClose(mDirSearch_h);
				mCurrentDir[0] = NULL;

				if (wrap)
				{
					return(getNextFileInDir(pathname,"",fname,TRUE));
				}
				else
				{
					fname[0] = 0;
					return(FALSE);
				}
			}
			else
			{
				// Error
//				llinfos << "Unable to locate next file" << llendl;
				return(FALSE);
			}
		}
	}

	// convert from TCHAR to char
	fname = utf16str_to_utf8str(FileData.cFileName);

	// fname now first name in list
	return(TRUE);
}

// get a random file in the directory
// automatically wrap if we've hit the end
void LLDir_Win32::getRandomFileInDir(const std::string &dirname, const std::string &mask, std::string &fname)
{
	S32 num_files;
	S32 which_file;
	HANDLE random_search_h;

	fname = "";

	llutf16string pathname = utf8str_to_utf16str(dirname);
	pathname += utf8str_to_utf16str(mask);

	WIN32_FIND_DATA FileData;
	fname[0] = NULL;

	num_files = countFilesInDir(dirname,mask);
	if (!num_files)
	{
		return;
	}

	which_file = ll_rand(num_files);

//	llinfos << "Random select mp3 #" << which_file << llendl;

    // which_file now indicates the (zero-based) index to which file to play

	if ((random_search_h = FindFirstFile(pathname.c_str(), &FileData)) != INVALID_HANDLE_VALUE)
	{
		while (which_file--)
		{
			if (!FindNextFile(random_search_h, &FileData))
			{
				return;
			}
		}
		FindClose(random_search_h);

		fname = utf16str_to_utf8str(llutf16string(FileData.cFileName));
	}
}

std::string LLDir_Win32::getCurPath()
{
	WCHAR w_str[MAX_PATH];
	GetCurrentDirectory(MAX_PATH, w_str);

	return utf16str_to_utf8str(llutf16string(w_str));
}

BOOL LLDir_Win32::fileExists(const std::string &filename)
{
	llstat stat_data;
	// Check the age of the file
	// Now, we see if the files we've gathered are recent...
	int res = LLFile::stat(filename.c_str(), &stat_data);
	if (!res)
	{
		return TRUE;
	}
	else
	{
		return FALSE;
	}
}

#if 0
// Utility function to get version number of a DLL

#define PACKVERSION(major,minor) MAKELONG(minor,major)

DWORD GetDllVersion(LPCTSTR lpszDllName)
{

    HINSTANCE hinstDll;
    DWORD dwVersion = 0;

    hinstDll = LoadLibrary(lpszDllName);	/* Flawfinder: ignore */

    if(hinstDll)
    {
        DLLGETVERSIONPROC pDllGetVersion;

        pDllGetVersion = (DLLGETVERSIONPROC) GetProcAddress(hinstDll, "DllGetVersion");

/*Because some DLLs might not implement this function, you
  must test for it explicitly. Depending on the particular
  DLL, the lack of a DllGetVersion function can be a useful
  indicator of the version.
*/
        if(pDllGetVersion)
        {
            DLLVERSIONINFO dvi;
            HRESULT hr;

            ZeroMemory(&dvi, sizeof(dvi));
            dvi.cbSize = sizeof(dvi);

            hr = (*pDllGetVersion)(&dvi);

            if(SUCCEEDED(hr))
            {
                dwVersion = PACKVERSION(dvi.dwMajorVersion, dvi.dwMinorVersion);
            }
        }

        FreeLibrary(hinstDll);
    }
    return dwVersion;
}
#endif

#endif

<commit_msg>VC8 Fixes.<commit_after>/**
 * @file lldir_win32.cpp
 * @brief Implementation of directory utilities for windows
 *
 * $LicenseInfo:firstyear=2002&license=viewergpl$
 *
 * Copyright (c) 2002-2007, Linden Research, Inc.
 *
 * Second Life Viewer Source Code
 * The source code in this file ("Source Code") is provided by Linden Lab
 * to you under the terms of the GNU General Public License, version 2.0
 * ("GPL"), unless you have obtained a separate licensing agreement
 * ("Other License"), formally executed by you and Linden Lab.  Terms of
 * the GPL can be found in doc/GPL-license.txt in this distribution, or
 * online at http://secondlife.com/developers/opensource/gplv2
 *
 * There are special exceptions to the terms and conditions of the GPL as
 * it is applied to this Source Code. View the full text of the exception
 * in the file doc/FLOSS-exception.txt in this software distribution, or
 * online at http://secondlife.com/developers/opensource/flossexception
 *
 * By copying, modifying or distributing this software, you acknowledge
 * that you have read and understood your obligations described above,
 * and agree to abide by those obligations.
 *
 * ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO
 * WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY,
 * COMPLETENESS OR PERFORMANCE.
 * $/LicenseInfo$
 */

#if LL_WINDOWS

#include "linden_common.h"

#include "lldir_win32.h"
#include "llerror.h"
#include "llrand.h"		// for gLindenLabRandomNumber
#include "shlobj.h"

#include <direct.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>

// Utility stuff to get versions of the sh
#define PACKVERSION(major,minor) MAKELONG(minor,major)
DWORD GetDllVersion(LPCTSTR lpszDllName);

LLDir_Win32::LLDir_Win32()
{
	mDirDelimiter = "\\";

	WCHAR w_str[MAX_PATH];

	// Application Data is where user settings go
	SHGetSpecialFolderPath(NULL, w_str, CSIDL_APPDATA, TRUE);

	mOSUserDir = utf16str_to_utf8str(llutf16string(w_str));

	// Local Settings\Application Data is where cache files should
	// go, they don't get copied to the server if the user moves his
	// profile around on the network. JC
	//
	// TODO: patch the installer to remove old cache files on update, then
	// enable this code.
	//SHGetSpecialFolderPath(NULL, w_str, CSIDL_LOCAL_APPDATA, TRUE);
	//mOSUserCacheDir = utf16str_to_utf8str(llutf16string(w_str));

	if (GetTempPath(MAX_PATH, w_str))
	{
		if (wcslen(w_str))	/* Flawfinder: ignore */
		{
			w_str[wcslen(w_str)-1] = '\0'; /* Flawfinder: ignore */ // remove trailing slash
		}
		mTempDir = utf16str_to_utf8str(llutf16string(w_str));
	}
	else
	{
		mTempDir = mOSUserDir;
	}

//	fprintf(stderr, "mTempDir = <%s>",mTempDir);

#if 1
	// Don't use the real app path for now, as we'll have to add parsing to detect if
	// we're in a developer tree, which has a different structure from the installed product.

	S32 size = GetModuleFileName(NULL, w_str, MAX_PATH);
	if (size)
	{
		w_str[size] = '\0';
		mExecutablePathAndName = utf16str_to_utf8str(llutf16string(w_str));
		S32 path_end = mExecutablePathAndName.find_last_of('\\');
		if (path_end != std::string::npos)
		{
			mExecutableDir = mExecutablePathAndName.substr(0, path_end);
			mExecutableFilename = mExecutablePathAndName.substr(path_end+1, std::string::npos);
		}
		else
		{
			mExecutableFilename = mExecutablePathAndName;
		}
		GetCurrentDirectory(MAX_PATH, w_str);
		mWorkingDir = utf16str_to_utf8str(llutf16string(w_str));

	}
	else
	{
		fprintf(stderr, "Couldn't get APP path, assuming current directory!");
		GetCurrentDirectory(MAX_PATH, w_str);
		mExecutableDir = utf16str_to_utf8str(llutf16string(w_str));
		// Assume it's the current directory
	}
#else
	GetCurrentDirectory(MAX_PATH, w_str);
	mExecutableDir = utf16str_to_utf8str(llutf16string(w_str));
#endif
	if (strstr(mExecutableDir.c_str(), "indra\\newview"))
		mAppRODataDir = getCurPath();
	else
		mAppRODataDir = mExecutableDir;
}

LLDir_Win32::~LLDir_Win32()
{
}

// Implementation

void LLDir_Win32::initAppDirs(const std::string &app_name)
{
	mAppName = app_name;
	mOSUserAppDir = mOSUserDir;
	mOSUserAppDir += "\\";
	mOSUserAppDir += app_name;

	int res = LLFile::mkdir(mOSUserAppDir.c_str());
	if (res == -1)
	{
		if (errno != EEXIST)
		{
			llwarns << "Couldn't create app user dir " << mOSUserAppDir << llendl;
			llwarns << "Default to base dir" << mOSUserDir << llendl;
			mOSUserAppDir = mOSUserDir;
		}
	}
	//dumpCurrentDirectories();

	res = LLFile::mkdir(getExpandedFilename(LL_PATH_LOGS,"").c_str());
	if (res == -1)
	{
		if (errno != EEXIST)
		{
			llwarns << "Couldn't create LL_PATH_LOGS dir " << getExpandedFilename(LL_PATH_LOGS,"") << llendl;
		}
	}

	res = LLFile::mkdir(getExpandedFilename(LL_PATH_USER_SETTINGS,"").c_str());
	if (res == -1)
	{
		if (errno != EEXIST)
		{
			llwarns << "Couldn't create LL_PATH_USER_SETTINGS dir " << getExpandedFilename(LL_PATH_USER_SETTINGS,"") << llendl;
		}
	}

	res = LLFile::mkdir(getExpandedFilename(LL_PATH_CACHE,"").c_str());
	if (res == -1)
	{
		if (errno != EEXIST)
		{
			llwarns << "Couldn't create LL_PATH_CACHE dir " << getExpandedFilename(LL_PATH_CACHE,"") << llendl;
		}
	}

	res = LLFile::mkdir(getExpandedFilename(LL_PATH_MOZILLA_PROFILE,"").c_str());
	if (res == -1)
	{
		if (errno != EEXIST)
		{
			llwarns << "Couldn't create LL_PATH_MOZILLA_PROFILE dir " << getExpandedFilename(LL_PATH_MOZILLA_PROFILE,"") << llendl;
		}
	}

	mCAFile = getExpandedFilename(LL_PATH_APP_SETTINGS, "CA.pem");
}

U32 LLDir_Win32::countFilesInDir(const std::string &dirname, const std::string &mask)
{
	HANDLE count_search_h;
	U32 file_count;

	file_count = 0;

	WIN32_FIND_DATA FileData;

	llutf16string pathname = utf8str_to_utf16str(dirname);
	pathname += utf8str_to_utf16str(mask);

	if ((count_search_h = FindFirstFile(pathname.c_str(), &FileData)) != INVALID_HANDLE_VALUE)
	{
		file_count++;

		while (FindNextFile(count_search_h, &FileData))
		{
			file_count++;
		}

		FindClose(count_search_h);
	}

	return (file_count);
}

// get the next file in the directory
// automatically wrap if we've hit the end
BOOL LLDir_Win32::getNextFileInDir(const std::string &dirname, const std::string &mask, std::string &fname, BOOL wrap)
{
	llutf16string dirnamew = utf8str_to_utf16str(dirname);
	return getNextFileInDir(dirnamew, mask, fname, wrap);

}

BOOL LLDir_Win32::getNextFileInDir(const llutf16string &dirname, const std::string &mask, std::string &fname, BOOL wrap)
{
	WIN32_FIND_DATAW FileData;

	fname = "";
	llutf16string pathname = dirname;
	pathname += utf8str_to_utf16str(mask);

	if (pathname != mCurrentDir)
	{
		// different dir specified, close old search
		if (mCurrentDir[0])
		{
			FindClose(mDirSearch_h);
		}
		mCurrentDir = pathname;

		// and open new one
		// Check error opening Directory structure
		if ((mDirSearch_h = FindFirstFile(pathname.c_str(), &FileData)) == INVALID_HANDLE_VALUE)
		{
//			llinfos << "Unable to locate first file" << llendl;
			return(FALSE);
		}
	}
	else // get next file in list
	{
		// Find next entry
		if (!FindNextFile(mDirSearch_h, &FileData))
		{
			if (GetLastError() == ERROR_NO_MORE_FILES)
			{
                // No more files, so reset to beginning of directory
				FindClose(mDirSearch_h);
				mCurrentDir[0] = NULL;

				if (wrap)
				{
					return(getNextFileInDir(pathname,"",fname,TRUE));
				}
				else
				{
					fname[0] = 0;
					return(FALSE);
				}
			}
			else
			{
				// Error
//				llinfos << "Unable to locate next file" << llendl;
				return(FALSE);
			}
		}
	}

	// convert from TCHAR to char
	fname = utf16str_to_utf8str(FileData.cFileName);

	// fname now first name in list
	return(TRUE);
}

// get a random file in the directory
// automatically wrap if we've hit the end
void LLDir_Win32::getRandomFileInDir(const std::string &dirname, const std::string &mask, std::string &fname)
{
	S32 num_files;
	S32 which_file;
	HANDLE random_search_h;

	fname = "";

	llutf16string pathname = utf8str_to_utf16str(dirname);
	pathname += utf8str_to_utf16str(mask);

	WIN32_FIND_DATA FileData;
	fname[0] = NULL;

	num_files = countFilesInDir(dirname,mask);
	if (!num_files)
	{
		return;
	}

	which_file = ll_rand(num_files);

//	llinfos << "Random select mp3 #" << which_file << llendl;

    // which_file now indicates the (zero-based) index to which file to play

	if ((random_search_h = FindFirstFile(pathname.c_str(), &FileData)) != INVALID_HANDLE_VALUE)
	{
		while (which_file--)
		{
			if (!FindNextFile(random_search_h, &FileData))
			{
				return;
			}
		}
		FindClose(random_search_h);

		fname = utf16str_to_utf8str(llutf16string(FileData.cFileName));
	}
}

std::string LLDir_Win32::getCurPath()
{
	WCHAR w_str[MAX_PATH];
	GetCurrentDirectory(MAX_PATH, w_str);

	return utf16str_to_utf8str(llutf16string(w_str));
}

BOOL LLDir_Win32::fileExists(const std::string &filename)
{
	llstat stat_data;
	// Check the age of the file
	// Now, we see if the files we've gathered are recent...
	int res = LLFile::stat(filename.c_str(), &stat_data);
	if (!res)
	{
		return TRUE;
	}
	else
	{
		return FALSE;
	}
}

#if 0
// Utility function to get version number of a DLL

#define PACKVERSION(major,minor) MAKELONG(minor,major)

DWORD GetDllVersion(LPCTSTR lpszDllName)
{

    HINSTANCE hinstDll;
    DWORD dwVersion = 0;

    hinstDll = LoadLibrary(lpszDllName);	/* Flawfinder: ignore */

    if(hinstDll)
    {
        DLLGETVERSIONPROC pDllGetVersion;

        pDllGetVersion = (DLLGETVERSIONPROC) GetProcAddress(hinstDll, "DllGetVersion");

/*Because some DLLs might not implement this function, you
  must test for it explicitly. Depending on the particular
  DLL, the lack of a DllGetVersion function can be a useful
  indicator of the version.
*/
        if(pDllGetVersion)
        {
            DLLVERSIONINFO dvi;
            HRESULT hr;

            ZeroMemory(&dvi, sizeof(dvi));
            dvi.cbSize = sizeof(dvi);

            hr = (*pDllGetVersion)(&dvi);

            if(SUCCEEDED(hr))
            {
                dwVersion = PACKVERSION(dvi.dwMajorVersion, dvi.dwMinorVersion);
            }
        }

        FreeLibrary(hinstDll);
    }
    return dwVersion;
}
#endif

#endif

<|endoftext|>


<commit_before>
#include <gtest/gtest.h>
#include <qi/messaging.hpp>
#include <qi/perf/dataperftimer.hpp>
#include <string>
#include <alvalue.pb.h>

using namespace qi;

std::string gMasterAddress = "127.0.0.1:5555";
std::string gServerName = "server";
std::string gServerAddress = "127.0.0.1:5556";

Context* c = new Context();
Master gMaster(gMasterAddress, c);
Server gServer(gServerName, c);
Client gClient("client", c);

void ping() {
}

ALCompat::ALValue echo_proto(const ALCompat::ALValue& in) {
  ALCompat::ALValue val = in;
  return val;
}

std::string echo(const std::string& in) {
  return in;
}

TEST(Client, createWithStupidMasterAddress)
{
  Client client("client", c);
  client.connect("blabla");
  bool ex = false;
  try {
    client.callVoid("ognagnuk");
  }
  catch( const std::exception&) {
    ex = true;
  }
  EXPECT_EQ(true, ex);
}

TEST(Server, createWithStupidMasterAddress)
{
  Server server("server", c);
  server.connect("oink");
  bool ex = false;
  try {
    server.advertiseService("ognagnuk", &ping);
  }
  catch( const std::exception&) {
    ex = true;
  }
  EXPECT_EQ(true, ex);
}

TEST(Master, createWithStupidMasterAddress)
{
  Master master("oink2", c);
  // should not blow up, but we should be able to find if it is happy
}

TEST(Messaging, PerformancePing)
{
  gServer.connect();
  gClient.connect();
  gServer.advertiseService("wibble.ping", &ping);
  unsigned int numMessages = 10000;

  qi::perf::DataPerfTimer dt("Node void -> ping -> void");
  dt.start(numMessages);
  for (unsigned int loop = 0; loop < numMessages; loop++) {
    // Serialize
    gClient.callVoid("wibble.ping");
  }
  dt.stop();
}

TEST(Messaging, PerformanceEcho)
{
  gServer.advertiseService("wibble.echo", &echo);
  unsigned int numMessages = 10000;
  unsigned int numPowers = 12;
  qi::perf::DataPerfTimer dt("Node string -> echo -> string");
  char character = 'A';

  // loop message sizes 2^i bytes
  for (unsigned int i = 1; i < numPowers; i++) {
    unsigned int numBytes = (unsigned int)pow(2.0f, (int)i);
    std::string request = std::string(numBytes, character);

    dt.start(numMessages, numBytes);
    for (unsigned int loop = 0; loop < numMessages; loop++) {
      // Serialize
      std::string result = gClient.call<std::string>("wibble.echo", request);
    }
    dt.stop();
  }
}

TEST(Messaging, PerformanceEchoProtobuf)
{
  gServer.advertiseService("wibble.echo", &echo_proto);
  unsigned int numMessages = 10000;
  unsigned int numPowers = 12;
  qi::perf::DataPerfTimer dt("Node string -> echo -> string");
  char character = 'A';

  // loop message sizes 2^i bytes
  for (unsigned int i = 1; i < numPowers; i++) {
    unsigned int numBytes = (unsigned int)pow(2.0f, (int)i);
    std::string requeststr = std::string(numBytes, character);

    ALCompat::ALValue request;
    request.set_type(ALCompat::ALValue::STRING);
    request.set_stringvalue(requeststr);
    dt.start(numMessages, numBytes);
    for (unsigned int loop = 0; loop < numMessages; loop++) {
      // Serialize
      ALCompat::ALValue result = gClient.call<ALCompat::ALValue>("wibble.echo", request);
    }
    dt.stop();
  }
}

//TEST(Messaging, NormalUsage)
//{
//  //std::cout << "TEST: Initialized " << std::endl;
//  //std::cout << "TEST: Calling master.listServices " << std::endl;
//  //ReturnValue result1 = gClient.call("master.listServices");
//
//  std::cout << "TEST: Binding wibble.echo " << std::endl;
//  gServer.addService("wibble.echo", &echo);
//  std::string s = gClient.call<std::string>("wibble.echo", std::string("errr"));
//  //std::cout << "TEST: Calling wibble.echo " << std::endl;
//
//  std::cout << "TEST: Binding wibble.ping " << std::endl;
//  gServer.addService("wibble.ping", &ping);
//  gClient.callVoid("wibble.ping");
//  //std::cout << "TEST: Calling wibble.ping " << std::endl;
//
//  std::cout << "TEST: Calling master.gobledigook " << std::endl;
//  gClient.callVoid("master.gobledigook");
//}
//
<commit_msg>Simple tests for test messaging ... checking more constructors (perf disabled for now)<commit_after>
#include <gtest/gtest.h>
#include <qi/messaging.hpp>
#include <qi/perf/dataperftimer.hpp>
#include <qi/perf/sleep.hpp>
#include <string>
#include <alvalue.pb.h>

using namespace qi;

std::string gMasterAddress = "127.0.0.1:5555";
std::string gServerName = "server";
std::string gServerAddress = "127.0.0.1:5556";

//Context* c = new Context();
//Master gMaster(gMasterAddress);
//Server gServer("server");
//Client gClient("client");

// SERVER
TEST(ServerTest, createWithNoArgs)
{
  Server server;
}

TEST(ServerTest, createWithJustName)
{
  Server server("server");
}

TEST(ServerTest, createWithNameAndContext)
{
  //sleep(10);
  Context * c = new Context();
  Server server("server", c);
  delete(c);
}

// CLIENT
TEST(ClientTest, createWithNoArgs)
{
  Client client;
}

TEST(ClientTest, createWithJustName)
{
  Client client("client");
}

TEST(ClientTest, createWithNameAndContext)
{
  //sleep(10);
  Context * c = new Context();
  Client client("client", c);
  delete(c);
}

// PUBLISHER
TEST(PublisherTest, createWithNoArgs)
{
  Publisher publisher;
}

TEST(PublisherTest, createWithJustName)
{
  Publisher publisher("publisher");
}

TEST(PublisherTest, createWithNameAndContext)
{
  //sleep(10);
  Context * c = new Context();
  Publisher publisher("publisher", c);
  delete(c);
}

// SUBSCRIBER
TEST(SubscriberTest, createWithNoArgs)
{
  Subscriber subscriber;
}

TEST(SubscriberTest, createWithJustName)
{
  Subscriber subscriber("subscriber");
}

TEST(SubscriberTest, createWithNameAndContext)
{
  //sleep(10);
  Context * c = new Context();
  Subscriber subscriber("subscriber", c);
  delete(c);
}

// MASTER
TEST(MasterTest, createWithNoArgs)
{
  Master master;
}

TEST(MasterTest, createWithJustPort)
{
  // TODO int argument
  Master master("5555");
}

TEST(MasterTest, createWithJustIPDEPRECATE)
{
  // TODO deprecate this
  Master master("127.0.0.1");
}

TEST(MasterTest, createWithStupidPortDEPRECATE)
{

  Master master("127.0.0.1:dfjkl");
}

TEST(MasterTest, createWithContext)
{
  //sleep(10);
  // TODO deprecate this
  Context* c = new Context();
  Master master("127.0.0.1:5555", c);
  delete(c);
}

std::string echo(const std::string& in) {
  return in;
}

TEST(ClientServer, explicitAddressPlusContext)
{
  //sleep(10);
  Context* c = new Context();
  std::string address = "127.0.0.1:5555";
  Master master(address, c);
  master.run();
  Server server("server", c);
  server.connect(address);
  server.advertiseService("server.echo", &echo);
  Client client("client", c);
  client.connect(address);
  std::string arg = "hello world";
  std::string ret = client.call<std::string>("server.echo", arg);
  ASSERT_EQ(arg, ret);
  delete(c);
}

TEST(ClientServer, explicitAddressPlusContext2)
{
  //sleep(10);
  Context* c = new Context();
  std::string address = "127.0.0.1:5555";
  Master master(address, c);
  master.run();
  Server server("server", c);
  server.connect(address);
  server.advertiseService("server.echo", &echo);
  Client client("client", c);
  client.connect(address);
  std::string arg = "hello world";
  std::string ret = client.call<std::string>("server.echo", arg);
  ASSERT_EQ(arg, ret);
  delete(c);
}

TEST(ClientServer, defaultArgs)
{
  Master master;
  master.run();
  Server server;
  server.connect();
  server.advertiseService("server.echo", &echo);
  Client client;
  client.connect();
  std::string arg = "hello world";
  std::string ret = client.call<std::string>("server.echo", arg);
  ASSERT_EQ(arg, ret);
}

TEST(ClientServer, explicitAddress)
{
  sleep(10);
  std::string address = "127.0.0.1:5555";
  Master master(address);
  master.run();
  Server server;
  server.connect(address);
  server.advertiseService("server.echo", &echo);
  Client client;
  client.connect(address);
  std::string arg = "hello world";
  std::string ret = client.call<std::string>("server.echo", arg);
  ASSERT_EQ(arg, ret);
}

TEST(ClientServer, explicitAddressPlusOne)
{
  std::string address = "127.0.0.1:5556";
  Master master(address);
  master.run();
  Server server;
  server.connect(address);
  server.advertiseService("server.echo", &echo);
  Client client;
  client.connect(address);
  std::string arg = "hello world";
  std::string ret = client.call<std::string>("server.echo", arg);
  ASSERT_EQ(arg, ret);
}

//
//void ping() {
//}
//
//ALCompat::ALValue echo_proto(const ALCompat::ALValue& in) {
//  ALCompat::ALValue val = in;
//  return val;
//}
//
//
//std::string echo(const std::string& in) {
//  return in;
//}
//
//TEST(Client, createWithStupidMasterAddress)
//{
//  Client client("client", c);
//  client.connect("blabla");
//  bool ex = false;
//  try {
//    client.callVoid("ognagnuk");
//  }
//  catch( const std::exception&) {
//    ex = true;
//  }
//  EXPECT_EQ(true, ex);
//}
//
//TEST(Server, createWithStupidMasterAddress)
//{
//  Server server("server", c);
//  server.connect("oink");
//  bool ex = false;
//  try {
//    server.advertiseService("ognagnuk", &ping);
//  }
//  catch( const std::exception&) {
//    ex = true;
//  }
//  EXPECT_EQ(true, ex);
//}
//
//TEST(Master, createWithStupidMasterAddress)
//{
//  Master master("oink2", c);
//  // should not blow up, but we should be able to find if it is happy
//}
//
//TEST(Messaging, PerformancePing)
//{
//  gServer.connect();
//  gClient.connect();
//  gServer.advertiseService("wibble.ping", &ping);
//  unsigned int numMessages = 10000;
//
//  qi::perf::DataPerfTimer dt("Node void -> ping -> void");
//  dt.start(numMessages);
//  for (unsigned int loop = 0; loop < numMessages; loop++) {
//    // Serialize
//    gClient.callVoid("wibble.ping");
//  }
//  dt.stop();
//}
//
//TEST(Messaging, PerformanceEcho)
//{
//  gServer.advertiseService("wibble.echo", &echo);
//  unsigned int numMessages = 10000;
//  unsigned int numPowers = 12;
//  qi::perf::DataPerfTimer dt("Node string -> echo -> string");
//  char character = 'A';
//
//  // loop message sizes 2^i bytes
//  for (unsigned int i = 1; i < numPowers; i++) {
//    unsigned int numBytes = (unsigned int)pow(2.0f, (int)i);
//    std::string request = std::string(numBytes, character);
//
//    dt.start(numMessages, numBytes);
//    for (unsigned int loop = 0; loop < numMessages; loop++) {
//      // Serialize
//      std::string result = gClient.call<std::string>("wibble.echo", request);
//    }
//    dt.stop();
//  }
//}
//
//TEST(Messaging, PerformanceEchoProtobuf)
//{
//  gServer.advertiseService("wibble.echo", &echo_proto);
//  unsigned int numMessages = 10000;
//  unsigned int numPowers = 12;
//  qi::perf::DataPerfTimer dt("Node string -> echo -> string");
//  char character = 'A';
//
//  // loop message sizes 2^i bytes
//  for (unsigned int i = 1; i < numPowers; i++) {
//    unsigned int numBytes = (unsigned int)pow(2.0f, (int)i);
//    std::string requeststr = std::string(numBytes, character);
//
//    ALCompat::ALValue request;
//    request.set_type(ALCompat::ALValue::STRING);
//    request.set_stringvalue(requeststr);
//    dt.start(numMessages, numBytes);
//    for (unsigned int loop = 0; loop < numMessages; loop++) {
//      // Serialize
//      ALCompat::ALValue result = gClient.call<ALCompat::ALValue>("wibble.echo", request);
//    }
//    dt.stop();
//  }
//}

//TEST(Messaging, NormalUsage)
//{
//  //std::cout << "TEST: Initialized " << std::endl;
//  //std::cout << "TEST: Calling master.listServices " << std::endl;
//  //ReturnValue result1 = gClient.call("master.listServices");
//
//  std::cout << "TEST: Binding wibble.echo " << std::endl;
//  gServer.addService("wibble.echo", &echo);
//  std::string s = gClient.call<std::string>("wibble.echo", std::string("errr"));
//  //std::cout << "TEST: Calling wibble.echo " << std::endl;
//
//  std::cout << "TEST: Binding wibble.ping " << std::endl;
//  gServer.addService("wibble.ping", &ping);
//  gClient.callVoid("wibble.ping");
//  //std::cout << "TEST: Calling wibble.ping " << std::endl;
//
//  std::cout << "TEST: Calling master.gobledigook " << std::endl;
//  gClient.callVoid("master.gobledigook");
//}
//
<|endoftext|>


<commit_before>//Copyright (c) 2018 Ultimaker B.V.
//CuraEngine is released under the terms of the AGPLv3 or higher.

#include <google/protobuf/message.h>

#include "MockSocket.h" //To mock out the communication with the front-end.
#include "ArcusCommunicationTest.h"
#include "../src/settings/types/LayerIndex.h"
#include "../src/FffProcessor.h"

namespace cura
{
    CPPUNIT_TEST_SUITE_REGISTRATION(ArcusCommunicationTest);

    void ArcusCommunicationTest::setUp()
    {
        ip = "0.0.0.0";
        port = 12345;
        socket = new MockSocket();
        ac = new ArcusCommunication();
        ac->setSocketMock(socket);

        // from: PolygonConnectorTest
        test_square.emplace_back(0, 0);
        test_square.emplace_back(1000, 0);
        test_square.emplace_back(1000, 1000);
        test_square.emplace_back(0, 1000);
        test_shapes.add(test_square);

        test_square2.emplace_back(1100, 1500);
        test_square2.emplace_back(2000, 1500);
        test_square2.emplace_back(2000, -500);
        test_square2.emplace_back(1100, -500);
        test_shapes.add(test_square2);

        test_triangle.emplace_back(0, 2100);
        test_triangle.emplace_back(500, 1100);
        test_triangle.emplace_back(1500, 2100);
        test_shapes.add(test_triangle);

        for (double a = 0; a < 1.0; a += .05)
        {
            test_circle.add(Point(2050, 2050) + Point(std::cos(a * 2 * M_PI)*500, std::sin(a * 2 * M_PI)*500));
        }
        test_shapes.add(test_circle);

        test_convex_shape.emplace_back(-300, 0);
        test_convex_shape.emplace_back(-100, 500);
        test_convex_shape.emplace_back(-100, 600);
        test_convex_shape.emplace_back(-200, 1000);
        test_convex_shape.emplace_back(-500, 1500);
        test_convex_shape.emplace_back(-1500, 1500);
        test_convex_shape.emplace_back(-1500, 1500);
        test_convex_shape.emplace_back(-1600, 1100);
        test_convex_shape.emplace_back(-700, 200);
        test_shapes.add(test_convex_shape);
    }

    void ArcusCommunicationTest::tearDown()
    {
        delete ac;
        ac = nullptr;
    }

    void ArcusCommunicationTest::flushGCodeTest()
    {
        // socket->setName("flushGCodeTest");
        // ac->flushGCode();
        // // If I don't do anything, no sendMessage calls should be made
        // CPPUNIT_ASSERT(socket->sent_messages.size() == 0);
    }

    void ArcusCommunicationTest::isSequentialTest()
    {
        CPPUNIT_ASSERT(ac->isSequential());
    }

    void ArcusCommunicationTest::hasSliceTest()
    {
        CPPUNIT_ASSERT(ac->hasSlice()); // TODO: Only possible when there's a slice send.
    }

    void ArcusCommunicationTest::sendCurrentPositionTest()
    {
//         ac->sendCurrentPosition(Point(1, 2));
// //        ac->flushGCode();
    }

    void ArcusCommunicationTest::sendGCodePrefixTest()
    {
        const std::string& prefix = "bladibla";

        ac->sendGCodePrefix(prefix);
        ac->flushGCode();
        CPPUNIT_ASSERT(socket->sent_messages.size() > 0);
        bool found_prefix = false;
        for (auto message : socket->sent_messages)
        {
            if (message->DebugString().find(prefix) != std::string::npos)
            {
                found_prefix = true;
                break;
            }
        }
        CPPUNIT_ASSERT(found_prefix);
    }

    void ArcusCommunicationTest::sendFinishedSlicingTest()
    {
        ac->sendFinishedSlicing();
        CPPUNIT_ASSERT(socket->sent_messages.size() > 0);
    }

    void ArcusCommunicationTest::sendLayerCompleteTest()
    {
        ac->sendLayerComplete(10, 20, 30);
        //CPPUNIT_ASSERT(socket->sent_messages.size() > 0);
    }

    void ArcusCommunicationTest::sendLineToTest()
    {
        const PrintFeatureType& type = PrintFeatureType::OuterWall;
        const Point& to = Point(100, 100);
        const coord_t& line_width = 400;
        const coord_t& line_thickness = 200;
        const Velocity& velocity = Velocity(10.0);

        ac->sendLineTo(type, to, line_width, line_thickness, velocity);
        ac->sendLayerComplete(10, 20, 30);
    }

    void ArcusCommunicationTest::sendOptimizedLayerDataTest()
    {
        ac->sendOptimizedLayerData();
    }

    void ArcusCommunicationTest::sendPolygonTest()
    {
        const PrintFeatureType& type = PrintFeatureType::OuterWall;
        const ConstPolygonRef& polygon_ref = test_circle;
        const coord_t& line_width = 400;
        const coord_t& line_thickness = 200;
        const Velocity& velocity = Velocity(10.0);

        ac->sendPolygon(type, polygon_ref, line_width, line_thickness, velocity);
    }

    void ArcusCommunicationTest::sendPolygonsTest()
    {
        const PrintFeatureType& type = PrintFeatureType::OuterWall;
        const Polygons& polygons = test_shapes;
        const coord_t& line_width = 400;
        const coord_t& line_thickness = 200;
        const Velocity& velocity = Velocity(10.0);

        ac->sendPolygons(type, polygons, line_width, line_thickness, velocity);
    }

    void ArcusCommunicationTest::sendPrintTimeMaterialEstimatesTest()
    {
        // Segfault
//        socket->setName("sendPrintTimeMaterialEstimatesTest");
//        std::cout << "sendPrintTimeMaterialEstimatesTest...\n";
//        ac->sendPrintTimeMaterialEstimates();
//        socket->printMessages();
    }

    void ArcusCommunicationTest::sendProgressTest()
    {
        ac->sendProgress(10);;
        ac->sendProgress(50);
    }

    void ArcusCommunicationTest::setLayerForSendTest()
    {
        ac->setLayerForSend(42);
    }

    void ArcusCommunicationTest::setExtruderForSendTest()
    {

    }

    void ArcusCommunicationTest::sliceNextTest()
    {
        ac->sliceNext();
    }
}

<commit_msg>Fix flushGCodeTest<commit_after>//Copyright (c) 2018 Ultimaker B.V.
//CuraEngine is released under the terms of the AGPLv3 or higher.

#include <google/protobuf/message.h>

#include "MockSocket.h" //To mock out the communication with the front-end.
#include "ArcusCommunicationTest.h"
#include "../src/FffProcessor.h"
#include "../src/communication/ArcusCommunicationPrivate.h" //To access the private fields of this communication class.
#include "../src/settings/types/LayerIndex.h"

namespace cura
{
    CPPUNIT_TEST_SUITE_REGISTRATION(ArcusCommunicationTest);

    void ArcusCommunicationTest::setUp()
    {
        ip = "0.0.0.0";
        port = 12345;
        socket = new MockSocket();
        ac = new ArcusCommunication();
        ac->setSocketMock(socket);

        // from: PolygonConnectorTest
        test_square.emplace_back(0, 0);
        test_square.emplace_back(1000, 0);
        test_square.emplace_back(1000, 1000);
        test_square.emplace_back(0, 1000);
        test_shapes.add(test_square);

        test_square2.emplace_back(1100, 1500);
        test_square2.emplace_back(2000, 1500);
        test_square2.emplace_back(2000, -500);
        test_square2.emplace_back(1100, -500);
        test_shapes.add(test_square2);

        test_triangle.emplace_back(0, 2100);
        test_triangle.emplace_back(500, 1100);
        test_triangle.emplace_back(1500, 2100);
        test_shapes.add(test_triangle);

        for (double a = 0; a < 1.0; a += .05)
        {
            test_circle.add(Point(2050, 2050) + Point(std::cos(a * 2 * M_PI)*500, std::sin(a * 2 * M_PI)*500));
        }
        test_shapes.add(test_circle);

        test_convex_shape.emplace_back(-300, 0);
        test_convex_shape.emplace_back(-100, 500);
        test_convex_shape.emplace_back(-100, 600);
        test_convex_shape.emplace_back(-200, 1000);
        test_convex_shape.emplace_back(-500, 1500);
        test_convex_shape.emplace_back(-1500, 1500);
        test_convex_shape.emplace_back(-1500, 1500);
        test_convex_shape.emplace_back(-1600, 1100);
        test_convex_shape.emplace_back(-700, 200);
        test_shapes.add(test_convex_shape);
    }

    void ArcusCommunicationTest::tearDown()
    {
        delete ac;
        ac = nullptr;
    }

    void ArcusCommunicationTest::flushGCodeTest()
    {
        //Before there is g-code, no messages should be sent if we were to flush.
        ac->flushGCode();
        CPPUNIT_ASSERT(socket->sent_messages.empty());

        //Input some 'g-code' to flush.
        const std::string test_gcode = "This Fibonacci joke is as bad as the last two you heard combined.\n"
                                       "It's pretty cool how the Chinese made a language entirely out of tattoos."; //Multi-line to see flushing behaviour.
        ac->private_data->gcode_output_stream.write(test_gcode.c_str(), test_gcode.size());

        //Call the function we're testing. This time it should give us a message.
        ac->flushGCode();

        CPPUNIT_ASSERT_EQUAL(size_t(1), socket->sent_messages.size());
        const proto::GCodeLayer* message = dynamic_cast<proto::GCodeLayer*>(socket->sent_messages.front().get());
        CPPUNIT_ASSERT_EQUAL(test_gcode, message->data());
    }

    void ArcusCommunicationTest::isSequentialTest()
    {
        CPPUNIT_ASSERT(ac->isSequential());
    }

    void ArcusCommunicationTest::hasSliceTest()
    {
        CPPUNIT_ASSERT(ac->hasSlice()); // TODO: Only possible when there's a slice send.
    }

    void ArcusCommunicationTest::sendCurrentPositionTest()
    {
//         ac->sendCurrentPosition(Point(1, 2));
// //        ac->flushGCode();
    }

    void ArcusCommunicationTest::sendGCodePrefixTest()
    {
        const std::string& prefix = "bladibla";

        ac->sendGCodePrefix(prefix);
        ac->flushGCode();
        CPPUNIT_ASSERT(socket->sent_messages.size() > 0);
        bool found_prefix = false;
        for (auto message : socket->sent_messages)
        {
            if (message->DebugString().find(prefix) != std::string::npos)
            {
                found_prefix = true;
                break;
            }
        }
        CPPUNIT_ASSERT(found_prefix);
    }

    void ArcusCommunicationTest::sendFinishedSlicingTest()
    {
        ac->sendFinishedSlicing();
        CPPUNIT_ASSERT(socket->sent_messages.size() > 0);
    }

    void ArcusCommunicationTest::sendLayerCompleteTest()
    {
        ac->sendLayerComplete(10, 20, 30);
        //CPPUNIT_ASSERT(socket->sent_messages.size() > 0);
    }

    void ArcusCommunicationTest::sendLineToTest()
    {
        const PrintFeatureType& type = PrintFeatureType::OuterWall;
        const Point& to = Point(100, 100);
        const coord_t& line_width = 400;
        const coord_t& line_thickness = 200;
        const Velocity& velocity = Velocity(10.0);

        ac->sendLineTo(type, to, line_width, line_thickness, velocity);
        ac->sendLayerComplete(10, 20, 30);
    }

    void ArcusCommunicationTest::sendOptimizedLayerDataTest()
    {
        ac->sendOptimizedLayerData();
    }

    void ArcusCommunicationTest::sendPolygonTest()
    {
        const PrintFeatureType& type = PrintFeatureType::OuterWall;
        const ConstPolygonRef& polygon_ref = test_circle;
        const coord_t& line_width = 400;
        const coord_t& line_thickness = 200;
        const Velocity& velocity = Velocity(10.0);

        ac->sendPolygon(type, polygon_ref, line_width, line_thickness, velocity);
    }

    void ArcusCommunicationTest::sendPolygonsTest()
    {
        const PrintFeatureType& type = PrintFeatureType::OuterWall;
        const Polygons& polygons = test_shapes;
        const coord_t& line_width = 400;
        const coord_t& line_thickness = 200;
        const Velocity& velocity = Velocity(10.0);

        ac->sendPolygons(type, polygons, line_width, line_thickness, velocity);
    }

    void ArcusCommunicationTest::sendPrintTimeMaterialEstimatesTest()
    {
        // Segfault
//        socket->setName("sendPrintTimeMaterialEstimatesTest");
//        std::cout << "sendPrintTimeMaterialEstimatesTest...\n";
//        ac->sendPrintTimeMaterialEstimates();
//        socket->printMessages();
    }

    void ArcusCommunicationTest::sendProgressTest()
    {
        ac->sendProgress(10);;
        ac->sendProgress(50);
    }

    void ArcusCommunicationTest::setLayerForSendTest()
    {
        ac->setLayerForSend(42);
    }

    void ArcusCommunicationTest::setExtruderForSendTest()
    {

    }

    void ArcusCommunicationTest::sliceNextTest()
    {
        ac->sliceNext();
    }
}

<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the test suite 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 Technology Preview License Agreement accompanying
** this package.
**
** 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.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QApplication>
#include <QProcess>

#include <qtest.h>

class tst_qapplication : public QObject
{
    Q_OBJECT
private slots:
    void ctor();
};

/*
    Test the performance of the QApplication constructor.

    This test creates a new process and thus includes process creation overhead.
    Callgrind results are meaningless since the child process is not traced.
*/
void tst_qapplication::ctor()
{
    QProcess proc;
    const QString program       = QCoreApplication::applicationFilePath();
    const QStringList arguments = QStringList() << QLatin1String("--exit-now");

    QBENCHMARK {
        proc.start(program, arguments);
        QVERIFY(proc.waitForStarted());
        QVERIFY(proc.waitForFinished());
        QCOMPARE(proc.exitStatus(), QProcess::NormalExit);
        QCOMPARE(proc.exitCode(), 0);
    }
}

int main(int argc, char** argv)
{
    QApplication app(argc, argv);

    if (argc == 2 && QLatin1String("--exit-now") == QLatin1String(argv[1])) {
        return 0;
    }

    tst_qapplication test;
    return QTest::qExec(&test, argc, argv);
}

#include "main.moc"
<commit_msg>make the qapplication constructor test more meaningful<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the test suite 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 Technology Preview License Agreement accompanying
** this package.
**
** 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.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QApplication>

#include <qtest.h>

class tst_qapplication : public QObject
{
    Q_OBJECT
private slots:
    void ctor();
};

/*
    Test the performance of the QApplication constructor.

    Note: results from the second start on can be misleading,
    since all global statics are already initialized.
*/
void tst_qapplication::ctor()
{
    // simulate reasonable argc, argv
    int argc = 1;
    char *argv[] = { "tst_qapplication" };
    QBENCHMARK {
        QApplication app(argc, argv);
    }
}

QTEST_APPLESS_MAIN(tst_qapplication)

#include "main.moc"
<|endoftext|>


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

#include <stddef.h>
#include <string.h>

#include "native_client/src/include/nacl_assert.h"

// This test checks the representation of C++ method pointers used by
// the C++ front end.

// Define example classes where a method pointer's this-offset and
// vtable-offset are both non-zero.

class TestBaseClass1 {
 public:
  virtual ~TestBaseClass1() {}
  virtual void some_virtual() {}
  char data[1000];
};

class TestBaseClass2 {
 public:
  virtual ~TestBaseClass2() {}
  int nonvirtual_method() { return 123; }
  virtual void other_method1() {}
  virtual void other_method2() {}
  virtual int virtual_method() { return 456; }
};

class TestClass : public TestBaseClass1, public TestBaseClass2 {
};

// Offset of virtual_method() in vtable: it comes after
// ~TestBaseClass1(), ~TestBaseClass2(), other_method1() and
// other_method2().
const int kVtableOffset = sizeof(void *) * 4;
const int kThisOffset = sizeof(TestBaseClass1);

// Mangled name for TestBaseClass2::method()
#define NONVIRTUAL_METHOD _ZN14TestBaseClass217nonvirtual_methodEv
extern "C" void NONVIRTUAL_METHOD();

typedef int (TestClass::*method_ptr)();

struct method_ptr_repr {
  ptrdiff_t ptr;
  ptrdiff_t adj;
};

int main() {
  ASSERT_EQ(sizeof(method_ptr), 8);
  ASSERT_EQ(kThisOffset, 1004);

  method_ptr nonvirtual_mp = &TestClass::nonvirtual_method;
  method_ptr virtual_mp = &TestClass::virtual_method;

  // Check that method pointers work.
  TestClass instance;
  ASSERT_EQ((instance.*nonvirtual_mp)(), 123);
  ASSERT_EQ((instance.*virtual_mp)(), 456);

  method_ptr_repr nonvirtual_mpr;
  method_ptr_repr virtual_mpr;
  // Copy to avoid strict-aliasing problems.
  memcpy(&nonvirtual_mpr, &nonvirtual_mp, sizeof(method_ptr));
  memcpy(&virtual_mpr, &virtual_mp, sizeof(method_ptr));

#if defined(__pnacl__)
  // TODO(mseaborn): pnacl-clang is currently using the Itanium/x86
  // scheme, but we want to switch it to use the ARM scheme.
  // See https://code.google.com/p/nativeclient/issues/detail?id=3450
#elif defined(__arm__)
  // In the ARM scheme, adj & 1 indicates whether the method is
  // virtual.  This makes no assumption about the alignment of
  // function pointers.

  ASSERT_EQ(nonvirtual_mpr.ptr, (ptrdiff_t) NONVIRTUAL_METHOD);
  ASSERT_EQ(nonvirtual_mpr.adj, kThisOffset << 1);

  ASSERT_EQ(virtual_mpr.ptr, kVtableOffset);
  ASSERT_EQ(virtual_mpr.adj, (kThisOffset << 1) + 1);
#else
  // In the Itanium scheme (used for x86), ptr & 1 indicates whether
  // the method is virtual.  This assumes that function pointers are 0
  // mod 2, so we do not want to use this scheme for PNaCl.

  ASSERT_EQ(nonvirtual_mpr.ptr, (ptrdiff_t) NONVIRTUAL_METHOD);
  ASSERT_EQ(nonvirtual_mpr.adj, kThisOffset);

  ASSERT_EQ(virtual_mpr.ptr, kVtableOffset + 1);
  ASSERT_EQ(virtual_mpr.adj, kThisOffset);
#endif

  return 0;
}
<commit_msg>Enable test for C++ method pointer representation under PNaCl<commit_after>/*
 * Copyright (c) 2013 The Native Client Authors. All rights reserved.
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include <stddef.h>
#include <string.h>

#include "native_client/src/include/nacl_assert.h"

// This test checks the representation of C++ method pointers used by
// the C++ front end.

// Define example classes where a method pointer's this-offset and
// vtable-offset are both non-zero.

class TestBaseClass1 {
 public:
  virtual ~TestBaseClass1() {}
  virtual void some_virtual() {}
  char data[1000];
};

class TestBaseClass2 {
 public:
  virtual ~TestBaseClass2() {}
  int nonvirtual_method() { return 123; }
  virtual void other_method1() {}
  virtual void other_method2() {}
  virtual int virtual_method() { return 456; }
};

class TestClass : public TestBaseClass1, public TestBaseClass2 {
};

// Offset of virtual_method() in vtable: it comes after
// ~TestBaseClass1(), ~TestBaseClass2(), other_method1() and
// other_method2().
const int kVtableOffset = sizeof(void *) * 4;
const int kThisOffset = sizeof(TestBaseClass1);

// Mangled name for TestBaseClass2::method()
#define NONVIRTUAL_METHOD _ZN14TestBaseClass217nonvirtual_methodEv
extern "C" void NONVIRTUAL_METHOD();

typedef int (TestClass::*method_ptr)();

struct method_ptr_repr {
  ptrdiff_t ptr;
  ptrdiff_t adj;
};

int main() {
  ASSERT_EQ(sizeof(method_ptr), 8);
  ASSERT_EQ(kThisOffset, 1004);

  method_ptr nonvirtual_mp = &TestClass::nonvirtual_method;
  method_ptr virtual_mp = &TestClass::virtual_method;

  // Check that method pointers work.
  TestClass instance;
  ASSERT_EQ((instance.*nonvirtual_mp)(), 123);
  ASSERT_EQ((instance.*virtual_mp)(), 456);

  method_ptr_repr nonvirtual_mpr;
  method_ptr_repr virtual_mpr;
  // Copy to avoid strict-aliasing problems.
  memcpy(&nonvirtual_mpr, &nonvirtual_mp, sizeof(method_ptr));
  memcpy(&virtual_mpr, &virtual_mp, sizeof(method_ptr));

#if defined(__arm__) || defined(__pnacl__)
  // In the ARM scheme, adj & 1 indicates whether the method is
  // virtual.  This makes no assumption about the alignment of
  // function pointers.  PNaCl uses the same scheme (see
  // https://code.google.com/p/nativeclient/issues/detail?id=3450).

  ASSERT_EQ(nonvirtual_mpr.ptr, (ptrdiff_t) NONVIRTUAL_METHOD);
  ASSERT_EQ(nonvirtual_mpr.adj, kThisOffset << 1);

  ASSERT_EQ(virtual_mpr.ptr, kVtableOffset);
  ASSERT_EQ(virtual_mpr.adj, (kThisOffset << 1) + 1);
#else
  // In the Itanium scheme (used for x86), ptr & 1 indicates whether
  // the method is virtual.  This assumes that function pointers are 0
  // mod 2, so we do not want to use this scheme for PNaCl.

  ASSERT_EQ(nonvirtual_mpr.ptr, (ptrdiff_t) NONVIRTUAL_METHOD);
  ASSERT_EQ(nonvirtual_mpr.adj, kThisOffset);

  ASSERT_EQ(virtual_mpr.ptr, kVtableOffset + 1);
  ASSERT_EQ(virtual_mpr.adj, kThisOffset);
#endif

  return 0;
}
<|endoftext|>


<commit_before>// Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.

#include "mfem.hpp"
#include "catch.hpp"
#include <stdio.h>

#ifndef _WIN32
#include <unistd.h> // rmdir
#else
#include <direct.h> // _rmdir
#define rmdir(dir) _rmdir(dir)
#endif

using namespace mfem;

TEST_CASE("Save and load from collections", "[DataCollection]")
{
   SECTION("VisIt data files")
   {
       std::cout<<"Testing VisIt data files"<<std::endl;
      //Set up a small mesh and a couple of grid function on that mesh
      Mesh *mesh = new Mesh(2, 3, Element::QUADRILATERAL, 0, 2.0, 3.0);
      FiniteElementCollection *fec = new LinearFECollection;
      FiniteElementSpace *fespace = new FiniteElementSpace(mesh, fec);
      GridFunction *u = new GridFunction(fespace);
      GridFunction *v = new GridFunction(fespace);

      int N = u->Size();
      for (int i = 0; i < N; ++i)
      {
         (*u)(i) = double(i);
         (*v)(i) = double(N - i - 1);
      }

      int intOrder = 3;

      QuadratureSpace *qspace = new QuadratureSpace(mesh, intOrder);
      QuadratureFunction *qs = new QuadratureFunction(qspace, 1);
      QuadratureFunction *qv = new QuadratureFunction(qspace, 2);

      int Nq = qs->Size();
      for (int i = 0; i < Nq; ++i)
      {
         (*qs)(i) = double(i);
         (*qv)(2*i+0) = double(i);
         (*qv)(2*i+1) = double(Nq - i - 1);
      }

      SECTION("Uncompressed MFEM format")
      {
         std::cout<<"Testing uncompressed MFEM format"<<std::endl;

         //Collect the mesh and grid functions into a DataCollection and test that they got in there
         VisItDataCollection dc("base", mesh);
         dc.RegisterField("u", u);
         dc.RegisterField("v", v);
         dc.RegisterQField("qs",qs);
         dc.RegisterQField("qv",qv);
         dc.SetCycle(5);
         dc.SetTime(8.0);
         REQUIRE(dc.GetMesh() == mesh );
         REQUIRE(dc.HasField("u"));
         REQUIRE(dc.HasField("v"));
         REQUIRE(dc.HasQField("qs"));
         REQUIRE(dc.HasQField("qv"));
         REQUIRE(dc.GetCycle() == 5);
         REQUIRE(dc.GetTime() == 8.0);

         //Save the DataCollection and load it into a new DataCollection for comparison
         dc.SetPadDigits(5);
         dc.Save();

         VisItDataCollection dc_new("base");
         dc_new.SetPadDigits(5);
         dc_new.Load(dc.GetCycle());
         Mesh* mesh_new = dc_new.GetMesh();
         GridFunction *u_new = dc_new.GetField("u");
         GridFunction *v_new = dc_new.GetField("v");
         QuadratureFunction *qs_new = dc_new.GetQField("qs");
         QuadratureFunction *qv_new = dc_new.GetQField("qv");
         REQUIRE(mesh_new);
         REQUIRE(u_new);
         REQUIRE(v_new);
         REQUIRE(qs_new);
         REQUIRE(qv_new);

         //Compare some collection parameters for old and new
         std::string name, name_new;
         name = dc.GetCollectionName();
         name_new = dc_new.GetCollectionName();
         REQUIRE(name == name_new);
         REQUIRE(dc.GetCycle() == dc_new.GetCycle());
         REQUIRE(dc.GetTime() == dc_new.GetTime());

         //Compare the new new mesh with the old mesh
         //(Just a basic comparison here, a full comparison should be done in Mesh unit testing)
         REQUIRE(mesh->Dimension() == mesh_new->Dimension());
         REQUIRE(mesh->SpaceDimension() == mesh_new->SpaceDimension());

         Vector vert, vert_diff;
         mesh->GetVertices(vert);
         mesh_new->GetVertices(vert_diff);
         vert_diff -= vert;
         REQUIRE(vert_diff.Normlinf() < 1e-10);

         //Compare the old and new grid functions
         //(Just a basic comparison here, a full comparison should be done in GridFunction unit testing)
         Vector u_diff(*u_new), v_diff(*v_new);
         u_diff -= *u;
         v_diff -= *v;
         REQUIRE(u_diff.Normlinf() < 1e-10);
         REQUIRE(v_diff.Normlinf() < 1e-10);

         //Compare the old and new quadrature functions
         //(Just a basic comparison here, a full comparison should be done in GridFunction unit testing)
         Vector qs_diff(*qs_new), qv_diff(*qv_new);
         qs_diff -= *qs;
         qv_diff -= *qv;
         REQUIRE(qs_diff.Normlinf() < 1e-10);
         REQUIRE(qv_diff.Normlinf() < 1e-10);

         //Cleanup all the files
         REQUIRE(remove("base_00005.mfem_root") == 0);
         REQUIRE(remove("base_00005/mesh.00000") == 0);
         REQUIRE(remove("base_00005/u.00000") == 0);
         REQUIRE(remove("base_00005/v.00000") == 0);
         REQUIRE(remove("base_00005/qs.00000") == 0);
         REQUIRE(remove("base_00005/qv.00000") == 0);
         REQUIRE(rmdir("base_00005") == 0);
      }

#ifdef MFEM_USE_ZLIB
      SECTION("Compressed MFEM format")
      {
         std::cout<<"Testing compressed MFEM format"<<std::endl;

         //Collect the mesh and grid functions into a DataCollection and test that they got in there
         VisItDataCollection dc("base", mesh);
         dc.RegisterField("u", u);
         dc.RegisterField("v", v);
         dc.RegisterQField("qs",qs);
         dc.RegisterQField("qv",qv);
         dc.SetCycle(5);
         dc.SetTime(8.0);
         REQUIRE(dc.GetMesh() == mesh );
         REQUIRE(dc.HasField("u"));
         REQUIRE(dc.HasField("v"));
         REQUIRE(dc.HasQField("qs"));
         REQUIRE(dc.HasQField("qv"));
         REQUIRE(dc.GetCycle() == 5);
         REQUIRE(dc.GetTime() == 8.0);

         //Save the DataCollection and load it into a new DataCollection for comparison
         dc.SetPadDigits(5);
         dc.SetCompression(true);
         dc.Save();

         VisItDataCollection dc_new("base");
         dc_new.SetPadDigits(5);
         dc_new.Load(dc.GetCycle());
         Mesh* mesh_new = dc_new.GetMesh();
         GridFunction *u_new = dc_new.GetField("u");
         GridFunction *v_new = dc_new.GetField("v");
         QuadratureFunction *qs_new = dc_new.GetQField("qs");
         QuadratureFunction *qv_new = dc_new.GetQField("qv");
         REQUIRE(mesh_new);
         REQUIRE(u_new);
         REQUIRE(v_new);
         REQUIRE(qs_new);
         REQUIRE(qv_new);

         //Compare some collection parameters for old and new
         std::string name, name_new;
         name = dc.GetCollectionName();
         name_new = dc_new.GetCollectionName();
         REQUIRE(name == name_new);
         REQUIRE(dc.GetCycle() == dc_new.GetCycle());
         REQUIRE(dc.GetTime() == dc_new.GetTime());

         //Compare the new new mesh with the old mesh
         //(Just a basic comparison here, a full comparison should be done in Mesh unit testing)
         REQUIRE(mesh->Dimension() == mesh_new->Dimension());
         REQUIRE(mesh->SpaceDimension() == mesh_new->SpaceDimension());

         Vector vert, vert_diff;
         mesh->GetVertices(vert);
         mesh_new->GetVertices(vert_diff);
         vert_diff -= vert;
         REQUIRE(vert_diff.Normlinf() < 1e-10);

         //Compare the old and new grid functions
         //(Just a basic comparison here, a full comparison should be done in GridFunction unit testing)
         Vector u_diff(*u_new), v_diff(*v_new);
         u_diff -= *u;
         v_diff -= *v;
         REQUIRE(u_diff.Normlinf() < 1e-10);
         REQUIRE(v_diff.Normlinf() < 1e-10);

         //Compare the old and new quadrature functions
         //(Just a basic comparison here, a full comparison should be done in GridFunction unit testing)
         Vector qs_diff(*qs_new), qv_diff(*qv_new);
         qs_diff -= *qs;
         qv_diff -= *qv;
         REQUIRE(qs_diff.Normlinf() < 1e-10);
         REQUIRE(qv_diff.Normlinf() < 1e-10);

         //Cleanup all the files
         REQUIRE(remove("base_00005.mfem_root") == 0);
         REQUIRE(remove("base_00005/mesh.00000") == 0);
         REQUIRE(remove("base_00005/u.00000") == 0);
         REQUIRE(remove("base_00005/v.00000") == 0);
         REQUIRE(remove("base_00005/qs.00000") == 0);
         REQUIRE(remove("base_00005/qv.00000") == 0);
         REQUIRE(rmdir("base_00005") == 0);
      }
#endif
   }

}
<commit_msg>Make style<commit_after>// Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.

#include "mfem.hpp"
#include "catch.hpp"
#include <stdio.h>

#ifndef _WIN32
#include <unistd.h> // rmdir
#else
#include <direct.h> // _rmdir
#define rmdir(dir) _rmdir(dir)
#endif

using namespace mfem;

TEST_CASE("Save and load from collections", "[DataCollection]")
{
   SECTION("VisIt data files")
   {
      std::cout<<"Testing VisIt data files"<<std::endl;
      //Set up a small mesh and a couple of grid function on that mesh
      Mesh *mesh = new Mesh(2, 3, Element::QUADRILATERAL, 0, 2.0, 3.0);
      FiniteElementCollection *fec = new LinearFECollection;
      FiniteElementSpace *fespace = new FiniteElementSpace(mesh, fec);
      GridFunction *u = new GridFunction(fespace);
      GridFunction *v = new GridFunction(fespace);

      int N = u->Size();
      for (int i = 0; i < N; ++i)
      {
         (*u)(i) = double(i);
         (*v)(i) = double(N - i - 1);
      }

      int intOrder = 3;

      QuadratureSpace *qspace = new QuadratureSpace(mesh, intOrder);
      QuadratureFunction *qs = new QuadratureFunction(qspace, 1);
      QuadratureFunction *qv = new QuadratureFunction(qspace, 2);

      int Nq = qs->Size();
      for (int i = 0; i < Nq; ++i)
      {
         (*qs)(i) = double(i);
         (*qv)(2*i+0) = double(i);
         (*qv)(2*i+1) = double(Nq - i - 1);
      }

      SECTION("Uncompressed MFEM format")
      {
         std::cout<<"Testing uncompressed MFEM format"<<std::endl;

         //Collect the mesh and grid functions into a DataCollection and test that they got in there
         VisItDataCollection dc("base", mesh);
         dc.RegisterField("u", u);
         dc.RegisterField("v", v);
         dc.RegisterQField("qs",qs);
         dc.RegisterQField("qv",qv);
         dc.SetCycle(5);
         dc.SetTime(8.0);
         REQUIRE(dc.GetMesh() == mesh );
         REQUIRE(dc.HasField("u"));
         REQUIRE(dc.HasField("v"));
         REQUIRE(dc.HasQField("qs"));
         REQUIRE(dc.HasQField("qv"));
         REQUIRE(dc.GetCycle() == 5);
         REQUIRE(dc.GetTime() == 8.0);

         //Save the DataCollection and load it into a new DataCollection for comparison
         dc.SetPadDigits(5);
         dc.Save();

         VisItDataCollection dc_new("base");
         dc_new.SetPadDigits(5);
         dc_new.Load(dc.GetCycle());
         Mesh* mesh_new = dc_new.GetMesh();
         GridFunction *u_new = dc_new.GetField("u");
         GridFunction *v_new = dc_new.GetField("v");
         QuadratureFunction *qs_new = dc_new.GetQField("qs");
         QuadratureFunction *qv_new = dc_new.GetQField("qv");
         REQUIRE(mesh_new);
         REQUIRE(u_new);
         REQUIRE(v_new);
         REQUIRE(qs_new);
         REQUIRE(qv_new);

         //Compare some collection parameters for old and new
         std::string name, name_new;
         name = dc.GetCollectionName();
         name_new = dc_new.GetCollectionName();
         REQUIRE(name == name_new);
         REQUIRE(dc.GetCycle() == dc_new.GetCycle());
         REQUIRE(dc.GetTime() == dc_new.GetTime());

         //Compare the new new mesh with the old mesh
         //(Just a basic comparison here, a full comparison should be done in Mesh unit testing)
         REQUIRE(mesh->Dimension() == mesh_new->Dimension());
         REQUIRE(mesh->SpaceDimension() == mesh_new->SpaceDimension());

         Vector vert, vert_diff;
         mesh->GetVertices(vert);
         mesh_new->GetVertices(vert_diff);
         vert_diff -= vert;
         REQUIRE(vert_diff.Normlinf() < 1e-10);

         //Compare the old and new grid functions
         //(Just a basic comparison here, a full comparison should be done in GridFunction unit testing)
         Vector u_diff(*u_new), v_diff(*v_new);
         u_diff -= *u;
         v_diff -= *v;
         REQUIRE(u_diff.Normlinf() < 1e-10);
         REQUIRE(v_diff.Normlinf() < 1e-10);

         //Compare the old and new quadrature functions
         //(Just a basic comparison here, a full comparison should be done in GridFunction unit testing)
         Vector qs_diff(*qs_new), qv_diff(*qv_new);
         qs_diff -= *qs;
         qv_diff -= *qv;
         REQUIRE(qs_diff.Normlinf() < 1e-10);
         REQUIRE(qv_diff.Normlinf() < 1e-10);

         //Cleanup all the files
         REQUIRE(remove("base_00005.mfem_root") == 0);
         REQUIRE(remove("base_00005/mesh.00000") == 0);
         REQUIRE(remove("base_00005/u.00000") == 0);
         REQUIRE(remove("base_00005/v.00000") == 0);
         REQUIRE(remove("base_00005/qs.00000") == 0);
         REQUIRE(remove("base_00005/qv.00000") == 0);
         REQUIRE(rmdir("base_00005") == 0);
      }

#ifdef MFEM_USE_ZLIB
      SECTION("Compressed MFEM format")
      {
         std::cout<<"Testing compressed MFEM format"<<std::endl;

         //Collect the mesh and grid functions into a DataCollection and test that they got in there
         VisItDataCollection dc("base", mesh);
         dc.RegisterField("u", u);
         dc.RegisterField("v", v);
         dc.RegisterQField("qs",qs);
         dc.RegisterQField("qv",qv);
         dc.SetCycle(5);
         dc.SetTime(8.0);
         REQUIRE(dc.GetMesh() == mesh );
         REQUIRE(dc.HasField("u"));
         REQUIRE(dc.HasField("v"));
         REQUIRE(dc.HasQField("qs"));
         REQUIRE(dc.HasQField("qv"));
         REQUIRE(dc.GetCycle() == 5);
         REQUIRE(dc.GetTime() == 8.0);

         //Save the DataCollection and load it into a new DataCollection for comparison
         dc.SetPadDigits(5);
         dc.SetCompression(true);
         dc.Save();

         VisItDataCollection dc_new("base");
         dc_new.SetPadDigits(5);
         dc_new.Load(dc.GetCycle());
         Mesh* mesh_new = dc_new.GetMesh();
         GridFunction *u_new = dc_new.GetField("u");
         GridFunction *v_new = dc_new.GetField("v");
         QuadratureFunction *qs_new = dc_new.GetQField("qs");
         QuadratureFunction *qv_new = dc_new.GetQField("qv");
         REQUIRE(mesh_new);
         REQUIRE(u_new);
         REQUIRE(v_new);
         REQUIRE(qs_new);
         REQUIRE(qv_new);

         //Compare some collection parameters for old and new
         std::string name, name_new;
         name = dc.GetCollectionName();
         name_new = dc_new.GetCollectionName();
         REQUIRE(name == name_new);
         REQUIRE(dc.GetCycle() == dc_new.GetCycle());
         REQUIRE(dc.GetTime() == dc_new.GetTime());

         //Compare the new new mesh with the old mesh
         //(Just a basic comparison here, a full comparison should be done in Mesh unit testing)
         REQUIRE(mesh->Dimension() == mesh_new->Dimension());
         REQUIRE(mesh->SpaceDimension() == mesh_new->SpaceDimension());

         Vector vert, vert_diff;
         mesh->GetVertices(vert);
         mesh_new->GetVertices(vert_diff);
         vert_diff -= vert;
         REQUIRE(vert_diff.Normlinf() < 1e-10);

         //Compare the old and new grid functions
         //(Just a basic comparison here, a full comparison should be done in GridFunction unit testing)
         Vector u_diff(*u_new), v_diff(*v_new);
         u_diff -= *u;
         v_diff -= *v;
         REQUIRE(u_diff.Normlinf() < 1e-10);
         REQUIRE(v_diff.Normlinf() < 1e-10);

         //Compare the old and new quadrature functions
         //(Just a basic comparison here, a full comparison should be done in GridFunction unit testing)
         Vector qs_diff(*qs_new), qv_diff(*qv_new);
         qs_diff -= *qs;
         qv_diff -= *qv;
         REQUIRE(qs_diff.Normlinf() < 1e-10);
         REQUIRE(qv_diff.Normlinf() < 1e-10);

         //Cleanup all the files
         REQUIRE(remove("base_00005.mfem_root") == 0);
         REQUIRE(remove("base_00005/mesh.00000") == 0);
         REQUIRE(remove("base_00005/u.00000") == 0);
         REQUIRE(remove("base_00005/v.00000") == 0);
         REQUIRE(remove("base_00005/qs.00000") == 0);
         REQUIRE(remove("base_00005/qv.00000") == 0);
         REQUIRE(rmdir("base_00005") == 0);
      }
#endif
   }

}
<|endoftext|>


<commit_before>#include <stdio.h>
#include <fcntl.h>
#include <assert.h>
#include <time.h>
#include <sys/time.h>
#include <sys/shm.h>

#include <stdlib.h>
#include <string.h>
#include <termios.h>

#include <curl/curl.h>

#include "context.h"
#include "tangram.h"
#include "platform.h"
#include "platform_rpi.h"

#include <iostream>
#include "glm/trigonometric.hpp"

#define KEY_ESC      113    // q
#define KEY_ZOOM_IN  45     // -
#define KEY_ZOOM_OUT 61     // =
#define KEY_UP       119    // w
#define KEY_LEFT     97     // a
#define KEY_RIGHT    115    // s
#define KEY_DOWN     122    // z

struct timeval tv;
unsigned long long timePrev, timeStart;

static bool bUpdate = true;

//==============================================================================
void setup(int argc, char **argv);
void newFrame();

int main(int argc, char **argv){

    // Start OpenGL context
    initGL(argc, argv);

    /* Do Curl Init */
    curl_global_init(CURL_GLOBAL_DEFAULT);

    // Set background color and clear buffers
    setup(argc, argv);

    // Start clock
    gettimeofday(&tv, NULL);
    timeStart = timePrev = (unsigned long long)(tv.tv_sec) * 1000 + (unsigned long long)(tv.tv_usec) / 1000;

    while (bUpdate) {
        updateGL();

        processNetworkQueue();

        if (getRenderRequest()) {
            setRenderRequest(false);
            newFrame();
        }
    }

    curl_global_cleanup();
    closeGL();
    return 0;
}

void setup(int argc, char **argv) {
    int width = getWindowWidth();
    int height = getWindowHeight();
    float rot = 0.0f;
    float zoom = 0.0f;
    float tilt = 0.0f;
    double lat = 0.0f;
    double lon = 0.0f;
    std::string scene = "scene.yaml";

    for (int i = 1; i < argc - 1; i++) {
        std::string argName(argv[i]), argValue(argv[i + 1]);
        if (argName == "-s" || argName == "--scene") {
            scene = argValue;
        } else if (argName == "-lat" ) {
            lat = std::stod(argValue);
        } else if (argName == "-lon" ) {
            lon = std::stod(argValue);
        } else if (argName == "-z" || argName == "--zoom" ) {
            zoom = std::stof(argValue);
        } else if (argName == "-w" || argName == "--width") {
            width = std::stoi(argValue);
        } else if (argName == "-h" || argName == "--height") {
            height = std::stoi(argValue);
        } else if (argName == "-t" || argName == "--tilt") {
            tilt = std::stof(argValue);
        } else if (argName == "-r" || argName == "--rotation") {
            rot = std::stof(argValue);
        }
    }

    Tangram::initialize(scene.c_str());
    Tangram::loadSceneAsync(scene.c_str());
    Tangram::setupGL();
    Tangram::resize(width, height);
    if (lon != 0.0f && lat != 0.0f) {
        Tangram::setPosition(lon,lat);
    }
    if (zoom != 0.0f) {
        Tangram::setZoom(zoom);
    }
    if (tilt != 0.0f) {
        Tangram::setTilt(glm::radians(tilt));
    }
    if (rot != 0.0f) {
        Tangram::setRotation(glm::radians(rot));
    }
}

void newFrame() {

    // Update
    gettimeofday( &tv, NULL);
    unsigned long long timeNow = (unsigned long long)(tv.tv_sec) * 1000 + (unsigned long long)(tv.tv_usec) / 1000;
    double delta = ((double)timeNow - (double)timePrev)*0.001;

    //logMsg("New frame (delta %d msec)\n",delta);

    Tangram::update(delta);
    timePrev = timeNow;

    // Render
    Tangram::render();

    renderGL();
}

//======================================================================= EVENTS

void onKeyPress(int _key) {
    switch (_key) {
        case KEY_ZOOM_IN:
            Tangram::handlePinchGesture(0.0,0.0,0.5,0.0);
            break;
        case KEY_ZOOM_OUT:
            Tangram::handlePinchGesture(0.0,0.0,2.0,0.0);
            break;
        case KEY_UP:
            Tangram::handlePanGesture(0.0,0.0,0.0,100.0);
            break;
        case KEY_DOWN:
            Tangram::handlePanGesture(0.0,0.0,0.0,-100.0);
            break;
        case KEY_LEFT:
            Tangram::handlePanGesture(0.0,0.0,100.0,0.0);
            break;
        case KEY_RIGHT:
            Tangram::handlePanGesture(0.0,0.0,-100.0,0.0);
            break;
        case KEY_ESC:
            bUpdate = false;
            break;
        default:
            logMsg(" -> %i\n",_key);
    }
    requestRender();
}

void onMouseMove(float _x, float _y) {
    requestRender();
}

void onMouseClick(float _x, float _y, int _button) {
    requestRender();
}

void onMouseDrag(float _x, float _y, int _button) {
    if( _button == 1 ){

        Tangram::handlePanGesture(  _x-getMouseVelX()*1.0,
                                    _y+getMouseVelY()*1.0,
                                    _x,
                                    _y);

    } else if( _button == 2 ){
        if ( getKeyPressed() == 'r') {
            float scale = -0.05;
            float rot = atan2(getMouseVelY(),getMouseVelX());
            if( _x < getWindowWidth()/2.0 ) {
                scale *= -1.0;
            }
            Tangram::handleRotateGesture(getWindowWidth()/2.0, getWindowHeight()/2.0, rot*scale);
        } else if ( getKeyPressed() == 't') {
            Tangram::handleShoveGesture(getMouseVelY()*0.005);
        } else {
            Tangram::handlePinchGesture(getWindowWidth()/2.0, getWindowHeight()/2.0, 1.0 + getMouseVelY()*0.001, 0.f);
        }

    }
    requestRender();
}

void onMouseRelease(float _x, float _y) {
    requestRender();
}

void onViewportResize(int _newWidth, int _newHeight) {
    requestRender();
}
<commit_msg>Update RPi demo to use Map class<commit_after>#include <stdio.h>
#include <fcntl.h>
#include <assert.h>
#include <time.h>
#include <sys/time.h>
#include <sys/shm.h>

#include <stdlib.h>
#include <string.h>
#include <termios.h>

#include <curl/curl.h>

#include "context.h"
#include "tangram.h"
#include "platform.h"
#include "platform_rpi.h"

#include <iostream>
#include "glm/trigonometric.hpp"

#define KEY_ESC      113    // q
#define KEY_ZOOM_IN  45     // -
#define KEY_ZOOM_OUT 61     // =
#define KEY_UP       119    // w
#define KEY_LEFT     97     // a
#define KEY_RIGHT    115    // s
#define KEY_DOWN     122    // z

struct timeval tv;
unsigned long long timePrev, timeStart;

Tangram::Map* map = nullptr;

static bool bUpdate = true;

//==============================================================================
void setup(int argc, char **argv);
void newFrame();

int main(int argc, char **argv){

    // Start OpenGL context
    initGL(argc, argv);

    /* Do Curl Init */
    curl_global_init(CURL_GLOBAL_DEFAULT);

    // Set background color and clear buffers
    setup(argc, argv);

    // Start clock
    gettimeofday(&tv, NULL);
    timeStart = timePrev = (unsigned long long)(tv.tv_sec) * 1000 + (unsigned long long)(tv.tv_usec) / 1000;

    while (bUpdate) {
        updateGL();

        processNetworkQueue();

        if (getRenderRequest()) {
            setRenderRequest(false);
            newFrame();
        }
    }

    curl_global_cleanup();
    closeGL();
    return 0;
}

void setup(int argc, char **argv) {
    int width = getWindowWidth();
    int height = getWindowHeight();
    float rot = 0.0f;
    float zoom = 0.0f;
    float tilt = 0.0f;
    double lat = 0.0f;
    double lon = 0.0f;
    std::string scene = "scene.yaml";

    for (int i = 1; i < argc - 1; i++) {
        std::string argName(argv[i]), argValue(argv[i + 1]);
        if (argName == "-s" || argName == "--scene") {
            scene = argValue;
        } else if (argName == "-lat" ) {
            lat = std::stod(argValue);
        } else if (argName == "-lon" ) {
            lon = std::stod(argValue);
        } else if (argName == "-z" || argName == "--zoom" ) {
            zoom = std::stof(argValue);
        } else if (argName == "-w" || argName == "--width") {
            width = std::stoi(argValue);
        } else if (argName == "-h" || argName == "--height") {
            height = std::stoi(argValue);
        } else if (argName == "-t" || argName == "--tilt") {
            tilt = std::stof(argValue);
        } else if (argName == "-r" || argName == "--rotation") {
            rot = std::stof(argValue);
        }
    }

    map = new Tangram::Map();
    map->loadSceneAsync(scene.c_str());
    map->setupGL();
    map->resize(width, height);
    if (lon != 0.0f && lat != 0.0f) {
        map->setPosition(lon,lat);
    }
    if (zoom != 0.0f) {
        map->setZoom(zoom);
    }
    if (tilt != 0.0f) {
        map->setTilt(glm::radians(tilt));
    }
    if (rot != 0.0f) {
        map->setRotation(glm::radians(rot));
    }
}

void newFrame() {

    // Update
    gettimeofday( &tv, NULL);
    unsigned long long timeNow = (unsigned long long)(tv.tv_sec) * 1000 + (unsigned long long)(tv.tv_usec) / 1000;
    double delta = ((double)timeNow - (double)timePrev)*0.001;

    //logMsg("New frame (delta %d msec)\n",delta);

    map->update(delta);
    timePrev = timeNow;

    // Render
    map->render();

    renderGL();
}

//======================================================================= EVENTS

void onKeyPress(int _key) {
    switch (_key) {
        case KEY_ZOOM_IN:
            map->handlePinchGesture(0.0,0.0,0.5,0.0);
            break;
        case KEY_ZOOM_OUT:
            map->handlePinchGesture(0.0,0.0,2.0,0.0);
            break;
        case KEY_UP:
            map->handlePanGesture(0.0,0.0,0.0,100.0);
            break;
        case KEY_DOWN:
            map->handlePanGesture(0.0,0.0,0.0,-100.0);
            break;
        case KEY_LEFT:
            map->handlePanGesture(0.0,0.0,100.0,0.0);
            break;
        case KEY_RIGHT:
            map->handlePanGesture(0.0,0.0,-100.0,0.0);
            break;
        case KEY_ESC:
            bUpdate = false;
            break;
        default:
            logMsg(" -> %i\n",_key);
    }
    requestRender();
}

void onMouseMove(float _x, float _y) {
    requestRender();
}

void onMouseClick(float _x, float _y, int _button) {
    requestRender();
}

void onMouseDrag(float _x, float _y, int _button) {
    if( _button == 1 ){

        map->handlePanGesture(_x - getMouseVelX(), _y + getMouseVelY(), _x, _y);

    } else if( _button == 2 ){
        if ( getKeyPressed() == 'r') {
            float scale = -0.05;
            float rot = atan2(getMouseVelY(),getMouseVelX());
            if( _x < getWindowWidth()/2.0 ) {
                scale *= -1.0;
            }
            map->handleRotateGesture(getWindowWidth()/2.0, getWindowHeight()/2.0, rot*scale);
        } else if ( getKeyPressed() == 't') {
            map->handleShoveGesture(getMouseVelY()*0.005);
        } else {
            map->handlePinchGesture(getWindowWidth()/2.0, getWindowHeight()/2.0, 1.0 + getMouseVelY()*0.001, 0.f);
        }

    }
    requestRender();
}

void onMouseRelease(float _x, float _y) {
    requestRender();
}

void onViewportResize(int _newWidth, int _newHeight) {
    requestRender();
}
<|endoftext|>