<commit_before>#include "MISC.H"
#include "CONTROL.H"
#include "CAMERA.H"
#include "GPU.H"
#include "LOAD_LEV.H"
#include "SPECIFIC.H"
#include "TEXT_S.H"

#include <EMULATOR.H>
#include <LIBETC.H>

#if PSXPC_VERSION || PSXPC_TEST
	#include <stdint.h>
#endif

#if PSX_VERSION && !PSXPC_TEST
typedef unsigned int uintptr_t;
#endif

void S_MemSet(char* p, int value, int length)
{
	int size;

	if (length != 0)
	{
		if (length > 3)
		{
			value |= value << 8;
			value |= value << 16;

			if (((uintptr_t)p) & 3)
			{
				size = 4 - (((uintptr_t)p) & 3);
				length -= 4 - (((uintptr_t)p) & 3);

				//loc_5E918
				while (size--)
					*p++ = value;

			}
			//loc_5E928
			size = length >> 2;
			if ((length >> 2))
			{
				length &= 3;

				//loc_5E934
				while (size--)
				{
					((int*)p)[0] = value;
					p += 4;
				}
			}
		}
		//loc_5E94C
		while (length-- != 0)
			*p++ = value;
	}
}

void S_LongMemCpy(unsigned long* pDest, unsigned long* pSrc, unsigned long size)//5E964(<), ? (F)
{
	int i;

	if (size > 0)
	{
		for (i = size / sizeof(unsigned long); i > 0; i--, pDest += 4, pSrc += 4)
		{
			//loc_5E974
			pDest[0] = pSrc[0];
			pDest[1] = pSrc[1];
			pDest[2] = pSrc[2];
			pDest[3] = pSrc[3];
		}

		//loc_5E9AC
		for (i = size & 3; i > 0; i--)
		{
			*pDest++ = *pSrc++;
		}
	}
}

void DrawF4(unsigned short x, unsigned short y, unsigned short w, unsigned short h, int unk, int unk2)//5EDF8
{
	UNIMPLEMENTED();
}

void DrawTPage(unsigned char a0, unsigned char a1)//5EE78(<), 5FB58(<)
{
	UNIMPLEMENTED();
}

void DrawLineH(long a0, long a1, long a2, long a3, long a4, long a5)//5EECC(<)
{
	UNIMPLEMENTED();
}

void DrawLineV(long a0, long a1, long a2, long a3, long a4, long a5)//5EF84(<),
{
	UNIMPLEMENTED();
}

void LOAD_VSyncHandler()//5F074(<), 5FD54(<) (F)
{
	int a0, a1, a2;

	if (!LtLoadingBarEnabled)
	{
		return;
	}

	//loc_5F08C
	GPU_BeginScene();

	a0 = 440;//x?
	a1 = 200;//y?
	a2 = 64;//cd width or height?

	if (_first_time_ever)
	{
		a0 += 24;
		a1 += 8;
		a2 = 48;
	}

	//loc_5F0B4
	//PrintString(256, 192, 2, "Load Game", 0x8000);
	draw_rotate_sprite(a0, a1, a2);
	db.current_buffer ^= 1;
	GnLastFrameCount = 0;
	DrawOTagEnv(&db.ot[db.nOTSize - 1], &db.draw[0]);
	return;
}

void LOAD_DrawEnable(unsigned char isEnabled)//5F2C8, 5FFA8
{
	LtLoadingBarEnabled = isEnabled;
}

void GPU_BeginScene()//5F0F0(<), 5FDD0(<)
{
	db.ot = db.order_table[db.current_buffer];
	db.polyptr = (char*)db.poly_buffer[db.current_buffer];
	db.curpolybuf = (char*)db.poly_buffer[db.current_buffer];
	db.polybuf_limit = (char*)(db.poly_buffer[db.current_buffer]) + 26000;
	db.pickup_ot = db.pickup_order_table[db.current_buffer];
	ClearOTagR(db.order_table[db.current_buffer], db.nOTSize);
	Emulator_BeginScene();
}

void draw_rotate_sprite(long a0, long a1, long a2)//5F134, 5FE14 (F)
{
	long t0;
	short* r_cossinptr;
	long t6;
	long t5;
	long t1;
	long t4;

	DelRotAng = (DelRotAng - 52) & 0xFFF;
	r_cossinptr = &rcossin_tbl[DelRotAng * 2];

	t6 = ((-a2 / 2) * r_cossinptr[0]) / 4096;
	t5 = ((-a2 / 2) * r_cossinptr[1]) / 4096;

	*(long*) &db.polyptr[4] = 0x2C808080;
	*(long*) &db.polyptr[12] = 0;
	*(long*) &db.polyptr[20] = 0x1303F00;

	t0 = t6 - t5;
	a2 = -t6;
	t4 = a2 - t5;
	a2 += t5;
	t1 = t6 + t5;

	*(short*) &db.polyptr[8] = t0 + (t0 / 2) + a0;
	*(short*) &db.polyptr[10] = t5 + t6 + a1;

	*(short*) &db.polyptr[16] = t4 + (t4 / 2) + a0;
	*(short*) &db.polyptr[18] = -t5 + t6 + a1;

	*(short*) &db.polyptr[24] = t1 + (t1 / 2) + a0;
	*(short*) &db.polyptr[26] = (t5 - t6) + a1;

	*(short*) &db.polyptr[28] = 0x3F;//width/height of loading cd?
	*(short*) &db.polyptr[36] = 0x3F3F;

	*(short*) &db.polyptr[32] = a2 + (a2 / 2) + a0;
	*(short*) &db.polyptr[34] = a1 + (-t5 - t6);

	*(long*) &db.polyptr[0] = db.ot[0] | 0x09000000;
	db.ot[0] = (unsigned long)&db.polyptr[0];

	db.polyptr += 0x28;//sizeof(POLY_F3); * 2?

	*(long*) &db.polyptr[4] = 0x2C808080;
	*(long*) &db.polyptr[8] = 0x780100;
	*(long*) &db.polyptr[12] = 0x6800;
	*(long*) &db.polyptr[16] = 0x7801FF;

	*(long*) &db.polyptr[20] = 0x13468FF;
	*(long*) &db.polyptr[24] = 0xEF0100;
	*(short*) &db.polyptr[28] = 0xDF00;
	*(long*) &db.polyptr[32] = 0xEF01FF;

	*(short*) &db.polyptr[36] = 0xDFFF;

	*(long*) &db.polyptr[0] = db.ot[0] | 0x9000000;
	db.ot[0] = (unsigned long)db.polyptr;
	//sizeof(POLY_G3);
	db.polyptr += 0x28;
	return;
}

/*   PSX VRAM   (H)
 *  ----------- 1024px
 *  | TL | TR |  |
 *  -----------  v
 *  | BL | BR |
 *  -----------
 *(W)1024px-->
 *
 */
void GPU_ClearVRAM()//5F2D0(<), 5FFB0(<) (F) (D) (ND)
{
	RECT16 r;

	//Clear TL
	r.x = 0;
	r.y = 0;
	r.w = 512;
	r.h = 256;
	clear_a_rect(&r);

	//Clear BL
	r.y = 256;
	clear_a_rect(&r);

	//Clear BR
	r.x = 512;
	clear_a_rect(&r);

	//Clear TR
	r.y = 0;
	clear_a_rect(&r);

	return;
}

void clear_a_rect(RECT16* r)//5F334(<), 60014(<) (F) (D) (ND)
{
	ClearImage(r, 0, 48, 0);
	return;
}

void GPU_GetScreenPosition(short* x, short* y)//5F34C, ? (*) (F) (D) (ND)
{
	*x = db.disp[0].screen.x;
	*y = db.disp[0].screen.y;
	return;
}

void GPU_SetScreenPosition(short x, short y)//5F360(<), 60040(<)
{
	db.disp[0].screen.x = x;
	db.disp[0].screen.y = y;
	db.disp[1].screen.x = x;
	db.disp[1].screen.y = y;

	return;
}

void GPU_SyncBothScreens()//5F374(<), 60054(<)
{
	db.current_buffer ^= 1;
	if (db.current_buffer != 0)
	{
		//MoveImage(&db.disp[1].disp, db.disp[0].disp.x, db.disp[0].disp.y);
		//TODO: Verify ra += 0x10;! prolly else skip loc_5F3A8 (implemented but should be checked).
	}
	else
	{
		//loc_5F3A8
		//MoveImage(&db.disp[0].disp, db.disp[1].disp.x, db.disp[1].disp.y);
	}

	return;
}

///@Gh0stblade - Not sure why this is so unoptimal, we can basically &disp[db.current_buffer]... double check code.
void GPU_FlipToBuffer(int buffer_index)//5F3C8(<), 600A8(<) (F) (D) (ND)
{
	DrawSync(0);
	VSync(0);

	if (buffer_index & 1)
	{
		PutDispEnv(&db.disp[1]);
	}
	else
	{
		PutDispEnv(&db.disp[0]);
	}

	if (buffer_index & 1)
	{
		PutDrawEnv(&db.draw[1]);
	}
	else
	{
		PutDrawEnv(&db.draw[0]);
	}

	db.current_buffer = buffer_index & 1 ^ 1;

	return;
}

void S_AnimateTextures(long nFrames)
{
	UNIMPLEMENTED();
}

void PrintGauge(int x, int y, int length)
{
	UNIMPLEMENTED();
}

long GetRandomControl()//5E9F0, 926F8 (F)
{
	rand_1 = (rand_1 * 0x41C64E6D) + 0x3039;
	return (rand_1 >> 16) & 0x7FFF;
}

void SeedRandomControl(long seed)//(F)
{
	rand_1 = seed;
}

long GetRandomDraw()//5EA18, 5F6F8 (F)
{
	rand_2 = (rand_2 * 0x41C64E6D) + 0x3039;
	return (rand_2 >> 16) * 0x7FFF;
}

void SeedRandomDraw(long seed)//(F)
{
	rand_2 = seed;
}

void S_MemCpy(char* pSrc, char* pDest, int size)
{
	if (size > 0)
	{
		while (size-- > 0)
			*pSrc++ = *pDest++;
	}
}
<commit_msg>Patches for GPU_SyncBothScreens<commit_after>#include "MISC.H"
#include "CONTROL.H"
#include "CAMERA.H"
#include "GPU.H"
#include "LOAD_LEV.H"
#include "SPECIFIC.H"
#include "TEXT_S.H"

#include <EMULATOR.H>
#include <LIBETC.H>

#if PSXPC_VERSION || PSXPC_TEST
	#include <stdint.h>
#endif

#if PSX_VERSION && !PSXPC_TEST
typedef unsigned int uintptr_t;
#endif

void S_MemSet(char* p, int value, int length)
{
	int size;

	if (length != 0)
	{
		if (length > 3)
		{
			value |= value << 8;
			value |= value << 16;

			if (((uintptr_t)p) & 3)
			{
				size = 4 - (((uintptr_t)p) & 3);
				length -= 4 - (((uintptr_t)p) & 3);

				//loc_5E918
				while (size--)
					*p++ = value;

			}
			//loc_5E928
			size = length >> 2;
			if ((length >> 2))
			{
				length &= 3;

				//loc_5E934
				while (size--)
				{
					((int*)p)[0] = value;
					p += 4;
				}
			}
		}
		//loc_5E94C
		while (length-- != 0)
			*p++ = value;
	}
}

void S_LongMemCpy(unsigned long* pDest, unsigned long* pSrc, unsigned long size)//5E964(<), ? (F)
{
	int i;

	if (size > 0)
	{
		for (i = size / sizeof(unsigned long); i > 0; i--, pDest += 4, pSrc += 4)
		{
			//loc_5E974
			pDest[0] = pSrc[0];
			pDest[1] = pSrc[1];
			pDest[2] = pSrc[2];
			pDest[3] = pSrc[3];
		}

		//loc_5E9AC
		for (i = size & 3; i > 0; i--)
		{
			*pDest++ = *pSrc++;
		}
	}
}

void DrawF4(unsigned short x, unsigned short y, unsigned short w, unsigned short h, int unk, int unk2)//5EDF8
{
	UNIMPLEMENTED();
}

void DrawTPage(unsigned char a0, unsigned char a1)//5EE78(<), 5FB58(<)
{
	UNIMPLEMENTED();
}

void DrawLineH(long a0, long a1, long a2, long a3, long a4, long a5)//5EECC(<)
{
	UNIMPLEMENTED();
}

void DrawLineV(long a0, long a1, long a2, long a3, long a4, long a5)//5EF84(<),
{
	UNIMPLEMENTED();
}

void LOAD_VSyncHandler()//5F074(<), 5FD54(<) (F)
{
	int a0, a1, a2;

	if (!LtLoadingBarEnabled)
	{
		return;
	}

	//loc_5F08C
	GPU_BeginScene();

	a0 = 440;//x?
	a1 = 200;//y?
	a2 = 64;//cd width or height?

	if (_first_time_ever)
	{
		a0 += 24;
		a1 += 8;
		a2 = 48;
	}

	//loc_5F0B4
	draw_rotate_sprite(a0, a1, a2);
	db.current_buffer ^= 1;
	GnLastFrameCount = 0;
	DrawOTagEnv(&db.ot[db.nOTSize - 1], &db.draw[0]);
	return;
}

void LOAD_DrawEnable(unsigned char isEnabled)//5F2C8, 5FFA8
{
	LtLoadingBarEnabled = isEnabled;
}

void GPU_BeginScene()//5F0F0(<), 5FDD0(<)
{
	db.ot = db.order_table[db.current_buffer];
	db.polyptr = (char*)db.poly_buffer[db.current_buffer];
	db.curpolybuf = (char*)db.poly_buffer[db.current_buffer];
	db.polybuf_limit = (char*)(db.poly_buffer[db.current_buffer] + 26000);
	db.pickup_ot = db.pickup_order_table[db.current_buffer];
	ClearOTagR(db.order_table[db.current_buffer], db.nOTSize);

	Emulator_BeginScene();
}

void draw_rotate_sprite(long a0, long a1, long a2)//5F134, 5FE14 (F)
{
	long t0;
	short* r_cossinptr;
	long t6;
	long t5;
	long t1;
	long t4;

	DelRotAng = (DelRotAng - 52) & 0xFFF;
	r_cossinptr = &rcossin_tbl[DelRotAng * 2];

	t6 = ((-a2 / 2) * r_cossinptr[0]) / 4096;
	t5 = ((-a2 / 2) * r_cossinptr[1]) / 4096;

	*(long*) &db.polyptr[4] = 0x2C808080;
	*(long*) &db.polyptr[12] = 0;
	*(long*) &db.polyptr[20] = 0x1303F00;

	t0 = t6 - t5;
	a2 = -t6;
	t4 = a2 - t5;
	a2 += t5;
	t1 = t6 + t5;

	*(short*) &db.polyptr[8] = t0 + (t0 / 2) + a0;
	*(short*) &db.polyptr[10] = t5 + t6 + a1;

	*(short*) &db.polyptr[16] = t4 + (t4 / 2) + a0;
	*(short*) &db.polyptr[18] = -t5 + t6 + a1;

	*(short*) &db.polyptr[24] = t1 + (t1 / 2) + a0;
	*(short*) &db.polyptr[26] = (t5 - t6) + a1;

	*(short*) &db.polyptr[28] = 0x3F;//width/height of loading cd?
	*(short*) &db.polyptr[36] = 0x3F3F;

	*(short*) &db.polyptr[32] = a2 + (a2 / 2) + a0;
	*(short*) &db.polyptr[34] = a1 + (-t5 - t6);

	*(long*) &db.polyptr[0] = db.ot[0] | 0x09000000;
	db.ot[0] = (unsigned long)&db.polyptr[0];

	db.polyptr += 0x28;//sizeof(POLY_F3); * 2?

	*(long*) &db.polyptr[4] = 0x2C808080;
	*(long*) &db.polyptr[8] = 0x780100;
	*(long*) &db.polyptr[12] = 0x6800;
	*(long*) &db.polyptr[16] = 0x7801FF;

	*(long*) &db.polyptr[20] = 0x13468FF;
	*(long*) &db.polyptr[24] = 0xEF0100;
	*(short*) &db.polyptr[28] = 0xDF00;
	*(long*) &db.polyptr[32] = 0xEF01FF;

	*(short*) &db.polyptr[36] = 0xDFFF;

	*(long*) &db.polyptr[0] = db.ot[0] | 0x9000000;
	db.ot[0] = (unsigned long)db.polyptr;
	//sizeof(POLY_G3);
	db.polyptr += 0x28;
	return;
}

/*   PSX VRAM   (H)
 *  ----------- 1024px
 *  | TL | TR |  |
 *  -----------  v
 *  | BL | BR |
 *  -----------
 *(W)1024px-->
 *
 */
void GPU_ClearVRAM()//5F2D0(<), 5FFB0(<) (F) (D) (ND)
{
	RECT16 r;

	//Clear TL
	r.x = 0;
	r.y = 0;
	r.w = 512;
	r.h = 256;
	clear_a_rect(&r);

	//Clear BL
	r.y = 256;
	clear_a_rect(&r);

	//Clear BR
	r.x = 512;
	clear_a_rect(&r);

	//Clear TR
	r.y = 0;
	clear_a_rect(&r);

	return;
}

void clear_a_rect(RECT16* r)//5F334(<), 60014(<) (F) (D) (ND)
{
	ClearImage(r, 0, 48, 0);
	return;
}

void GPU_GetScreenPosition(short* x, short* y)//5F34C, ? (*) (F) (D) (ND)
{
	*x = db.disp[0].screen.x;
	*y = db.disp[0].screen.y;
	return;
}

void GPU_SetScreenPosition(short x, short y)//5F360(<), 60040(<)
{
	db.disp[0].screen.x = x;
	db.disp[0].screen.y = y;
	db.disp[1].screen.x = x;
	db.disp[1].screen.y = y;

	return;
}

void GPU_SyncBothScreens()//5F374(<), 60054(<)
{
	DrawSync(0);
	db.current_buffer ^= 1;
	if (db.current_buffer != 0)
	{
		MoveImage(&db.disp[1].disp, db.disp[0].disp.x, db.disp[0].disp.y);
	}
	else
	{
		//loc_5F3A8
		MoveImage(&db.disp[0].disp, db.disp[1].disp.x, db.disp[1].disp.y);
	}

	DrawSync(0);

	return;
}

///@Gh0stblade - Not sure why this is so unoptimal, we can basically &disp[db.current_buffer]... double check code.
void GPU_FlipToBuffer(int buffer_index)//5F3C8(<), 600A8(<) (F) (D) (ND)
{
	DrawSync(0);
	VSync(0);

	if (buffer_index & 1)
	{
		PutDispEnv(&db.disp[1]);
	}
	else
	{
		PutDispEnv(&db.disp[0]);
	}

	if (buffer_index & 1)
	{
		PutDrawEnv(&db.draw[1]);
	}
	else
	{
		PutDrawEnv(&db.draw[0]);
	}

	db.current_buffer = buffer_index & 1 ^ 1;

	return;
}

void S_AnimateTextures(long nFrames)
{
	UNIMPLEMENTED();
}

void PrintGauge(int x, int y, int length)
{
	UNIMPLEMENTED();
}

long GetRandomControl()//5E9F0, 926F8 (F)
{
	rand_1 = (rand_1 * 0x41C64E6D) + 0x3039;
	return (rand_1 >> 16) & 0x7FFF;
}

void SeedRandomControl(long seed)//(F)
{
	rand_1 = seed;
}

long GetRandomDraw()//5EA18, 5F6F8 (F)
{
	rand_2 = (rand_2 * 0x41C64E6D) + 0x3039;
	return (rand_2 >> 16) * 0x7FFF;
}

void SeedRandomDraw(long seed)//(F)
{
	rand_2 = seed;
}

void S_MemCpy(char* pSrc, char* pDest, int size)
{
	if (size > 0)
	{
		while (size-- > 0)
			*pSrc++ = *pDest++;
	}
}
<|endoftext|>


<commit_before><commit_msg>(IMU main): fix IMU example by increasing IMU task stack depth<commit_after><|endoftext|>


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

#include "chrome/browser/extensions/api/permissions/permissions_api.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extension_prefs.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/extensions/extension_permission_set.h"
#include "net/base/mock_host_resolver.h"

namespace {

static void AddPattern(URLPatternSet* extent, const std::string& pattern) {
  int schemes = URLPattern::SCHEME_ALL;
  extent->AddPattern(URLPattern(schemes, pattern));
}

}  // namespace

class ExperimentalApiTest : public ExtensionApiTest {
public:
  void SetUpCommandLine(CommandLine* command_line) {
    ExtensionApiTest::SetUpCommandLine(command_line);
    command_line->AppendSwitch(switches::kEnableExperimentalExtensionApis);
  }
};

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, PermissionsFail) {
  ASSERT_TRUE(RunExtensionTest("permissions/disabled")) << message_;

  // Since the experimental APIs require a flag, this will fail even though
  // it's enabled.
  // TODO(erikkay) This test is currently broken because LoadExtension in
  // ExtensionBrowserTest doesn't actually fail, it just times out.  To fix this
  // I'll need to add an EXTENSION_LOAD_ERROR notification, which is probably
  // too much for the branch.  I'll enable this on trunk later.
  //ASSERT_FALSE(RunExtensionTest("permissions/enabled"))) << message_;
}

IN_PROC_BROWSER_TEST_F(ExperimentalApiTest, PermissionsSucceed) {
  ASSERT_TRUE(RunExtensionTest("permissions/enabled")) << message_;
}

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, ExperimentalPermissionsFail) {
  // At the time this test is being created, there is no experimental
  // function that will not be graduating soon, and does not require a
  // tab id as an argument.  So, we need the tab permission to get
  // a tab id.
  ASSERT_TRUE(RunExtensionTest("permissions/experimental_disabled"))
      << message_;
}

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, FaviconPermission) {
  ASSERT_TRUE(RunExtensionTest("permissions/favicon")) << message_;
}

// Test functions and APIs that are always allowed (even if you ask for no
// permissions).
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, AlwaysAllowed) {
  ASSERT_TRUE(RunExtensionTest("permissions/always_allowed")) << message_;
}

// Tests that the optional permissions API works correctly.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, OptionalPermissionsGranted) {
  // Mark all the tested APIs as granted to bypass the confirmation UI.
  ExtensionAPIPermissionSet apis;
  apis.insert(ExtensionAPIPermission::kTab);
  URLPatternSet explicit_hosts;
  AddPattern(&explicit_hosts, "http://*.c.com/*");
  scoped_refptr<ExtensionPermissionSet> granted_permissions =
      new ExtensionPermissionSet(apis, explicit_hosts, URLPatternSet());

  ExtensionPrefs* prefs =
      browser()->profile()->GetExtensionService()->extension_prefs();
  prefs->AddGrantedPermissions("kjmkgkdkpedkejedfhmfcenooemhbpbo",
                               granted_permissions);

  RequestPermissionsFunction::SetIgnoreUserGestureForTests(true);
  host_resolver()->AddRule("*.com", "127.0.0.1");
  ASSERT_TRUE(StartTestServer());
  EXPECT_TRUE(RunExtensionTest("permissions/optional")) << message_;
}

// Tests that the optional permissions API works correctly.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, OptionalPermissionsAutoConfirm) {
  // Rather than setting the granted permissions, set the UI autoconfirm flag
  // and run the same tests.
  RequestPermissionsFunction::SetAutoConfirmForTests(true);
  RequestPermissionsFunction::SetIgnoreUserGestureForTests(true);
  host_resolver()->AddRule("*.com", "127.0.0.1");
  ASSERT_TRUE(StartTestServer());
  EXPECT_TRUE(RunExtensionTest("permissions/optional")) << message_;
}

// Test that denying the optional permissions confirmation dialog works.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, OptionalPermissionsDeny) {
  RequestPermissionsFunction::SetAutoConfirmForTests(false);
  RequestPermissionsFunction::SetIgnoreUserGestureForTests(true);
  host_resolver()->AddRule("*.com", "127.0.0.1");
  ASSERT_TRUE(StartTestServer());
  EXPECT_TRUE(RunExtensionTest("permissions/optional_deny")) << message_;
}

// Tests that the permissions.request function must be called from within a
// user gesture.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, OptionalPermissionsGesture) {
  RequestPermissionsFunction::SetIgnoreUserGestureForTests(false);
  host_resolver()->AddRule("*.com", "127.0.0.1");
  ASSERT_TRUE(StartTestServer());
  EXPECT_TRUE(RunExtensionTest("permissions/optional_gesture")) << message_;
}
<commit_msg>Disable ExtensionApiTest.AlwaysAllowed (crashes on Mac)<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/extensions/api/permissions/permissions_api.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extension_prefs.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/extensions/extension_permission_set.h"
#include "net/base/mock_host_resolver.h"

namespace {

static void AddPattern(URLPatternSet* extent, const std::string& pattern) {
  int schemes = URLPattern::SCHEME_ALL;
  extent->AddPattern(URLPattern(schemes, pattern));
}

}  // namespace

class ExperimentalApiTest : public ExtensionApiTest {
public:
  void SetUpCommandLine(CommandLine* command_line) {
    ExtensionApiTest::SetUpCommandLine(command_line);
    command_line->AppendSwitch(switches::kEnableExperimentalExtensionApis);
  }
};

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, PermissionsFail) {
  ASSERT_TRUE(RunExtensionTest("permissions/disabled")) << message_;

  // Since the experimental APIs require a flag, this will fail even though
  // it's enabled.
  // TODO(erikkay) This test is currently broken because LoadExtension in
  // ExtensionBrowserTest doesn't actually fail, it just times out.  To fix this
  // I'll need to add an EXTENSION_LOAD_ERROR notification, which is probably
  // too much for the branch.  I'll enable this on trunk later.
  //ASSERT_FALSE(RunExtensionTest("permissions/enabled"))) << message_;
}

IN_PROC_BROWSER_TEST_F(ExperimentalApiTest, PermissionsSucceed) {
  ASSERT_TRUE(RunExtensionTest("permissions/enabled")) << message_;
}

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, ExperimentalPermissionsFail) {
  // At the time this test is being created, there is no experimental
  // function that will not be graduating soon, and does not require a
  // tab id as an argument.  So, we need the tab permission to get
  // a tab id.
  ASSERT_TRUE(RunExtensionTest("permissions/experimental_disabled"))
      << message_;
}

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, FaviconPermission) {
  ASSERT_TRUE(RunExtensionTest("permissions/favicon")) << message_;
}

// Test functions and APIs that are always allowed (even if you ask for no
// permissions).
// Disabled: http://crbug.com/125193
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_AlwaysAllowed) {
  ASSERT_TRUE(RunExtensionTest("permissions/always_allowed")) << message_;
}

// Tests that the optional permissions API works correctly.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, OptionalPermissionsGranted) {
  // Mark all the tested APIs as granted to bypass the confirmation UI.
  ExtensionAPIPermissionSet apis;
  apis.insert(ExtensionAPIPermission::kTab);
  URLPatternSet explicit_hosts;
  AddPattern(&explicit_hosts, "http://*.c.com/*");
  scoped_refptr<ExtensionPermissionSet> granted_permissions =
      new ExtensionPermissionSet(apis, explicit_hosts, URLPatternSet());

  ExtensionPrefs* prefs =
      browser()->profile()->GetExtensionService()->extension_prefs();
  prefs->AddGrantedPermissions("kjmkgkdkpedkejedfhmfcenooemhbpbo",
                               granted_permissions);

  RequestPermissionsFunction::SetIgnoreUserGestureForTests(true);
  host_resolver()->AddRule("*.com", "127.0.0.1");
  ASSERT_TRUE(StartTestServer());
  EXPECT_TRUE(RunExtensionTest("permissions/optional")) << message_;
}

// Tests that the optional permissions API works correctly.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, OptionalPermissionsAutoConfirm) {
  // Rather than setting the granted permissions, set the UI autoconfirm flag
  // and run the same tests.
  RequestPermissionsFunction::SetAutoConfirmForTests(true);
  RequestPermissionsFunction::SetIgnoreUserGestureForTests(true);
  host_resolver()->AddRule("*.com", "127.0.0.1");
  ASSERT_TRUE(StartTestServer());
  EXPECT_TRUE(RunExtensionTest("permissions/optional")) << message_;
}

// Test that denying the optional permissions confirmation dialog works.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, OptionalPermissionsDeny) {
  RequestPermissionsFunction::SetAutoConfirmForTests(false);
  RequestPermissionsFunction::SetIgnoreUserGestureForTests(true);
  host_resolver()->AddRule("*.com", "127.0.0.1");
  ASSERT_TRUE(StartTestServer());
  EXPECT_TRUE(RunExtensionTest("permissions/optional_deny")) << message_;
}

// Tests that the permissions.request function must be called from within a
// user gesture.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, OptionalPermissionsGesture) {
  RequestPermissionsFunction::SetIgnoreUserGestureForTests(false);
  host_resolver()->AddRule("*.com", "127.0.0.1");
  ASSERT_TRUE(StartTestServer());
  EXPECT_TRUE(RunExtensionTest("permissions/optional_gesture")) << message_;
}
<|endoftext|>


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

#ifndef _B3D_B3DENTITY_HXX
#define _B3D_B3DENTITY_HXX

#ifndef _B3D_B3DCOLOR_HXX
#include <goodies/b3dcolor.hxx>
#endif

#ifndef _B3D_BUCKET_HXX
#include <goodies/bucket.hxx>
#endif

#ifndef _BGFX_POINT_B3DPOINT_HXX
#include <basegfx/point/b3dpoint.hxx>
#endif

#ifndef _BGFX_POINT_B2DPOINT_HXX
#include <basegfx/point/b2dpoint.hxx>
#endif

#ifndef _BGFX_VECTOR_B3DVECTOR_HXX
#include <basegfx/vector/b3dvector.hxx>
#endif

/*************************************************************************
|*
|* Merkt sich einen Punkt plus Normale plus Texturkoordinate
|* (in Zukunft noch weitere Attribute, bsp. Farbe, Kante, Linienmodus
|*
\************************************************************************/

// predeclarations
class B3dTransformationSet;
namespace basegfx
{
    class B3DHomMatrix;
} // end of namespace basegfx

class B3dEntity
{
private:
    // Data defining this point, it's normal and texture coordinates
    basegfx::B3DPoint       maPoint;
    basegfx::B3DVector  maNormal;
    basegfx::B3DVector  maPlaneNormal;
    basegfx::B2DPoint       maTexCoor;
    B3dColor                maColor;

    // Ist die diesem Punkt folgende Kante sichtbar ?
    // EdgeFlag bool NOT in bitfield to be able to access it from OpenGL driver
    sal_uInt8               mbEdgeFlag;

    // bitfield
    // Gueltigkeit der geometrischen Daten
    unsigned                mbValid         : 1;

    // Wird eine Normale verwendet ?
    unsigned                mbNormalUsed    : 1;

    // Wird eine Texturkoordinate verwendet ?
    unsigned                mbTexCoorUsed   : 1;

    // Sind die geometrischen Daten schon in DeviceKoordinaten
    // umgerechnet ?
    unsigned                mbDeviceCoor    : 1;

public:
    B3dEntity() { Reset(); }

    sal_Bool IsValid() const { return mbValid; }
    void SetValid(sal_Bool bNew=sal_True) { mbValid = bNew; }

    sal_Bool IsNormalUsed() const { return mbNormalUsed; }
    void SetNormalUsed(sal_Bool bNew=sal_True) { mbNormalUsed = bNew; }

    sal_Bool IsTexCoorUsed() const { return mbTexCoorUsed; }
    void SetTexCoorUsed(sal_Bool bNew=sal_True) { mbTexCoorUsed = bNew; }

    sal_Bool IsDeviceCoor() const { return mbDeviceCoor; }
    void SetDeviceCoor(sal_Bool bNew=sal_True) { mbDeviceCoor = bNew; }

    sal_Bool IsEdgeVisible() const { return mbEdgeFlag; }
    void SetEdgeVisible(sal_Bool bNew=sal_True) { mbEdgeFlag = bNew; }

    basegfx::B3DPoint& Point() { return maPoint; }
    const basegfx::B3DPoint& Point() const { return maPoint; }
    basegfx::B3DVector& Normal() { return maNormal; }
    const basegfx::B3DVector& Normal() const { return maNormal; }
    basegfx::B3DVector& PlaneNormal() { return maPlaneNormal; }
    const basegfx::B3DVector& PlaneNormal() const { return maPlaneNormal; }
    basegfx::B2DPoint& TexCoor() { return maTexCoor; }
    const basegfx::B2DPoint& TexCoor() const { return maTexCoor; }
    B3dColor& Color() { return maColor; }
    const B3dColor& Color() const { return maColor; }
    sal_uInt8& EdgeFlag() { return mbEdgeFlag; }
    const sal_uInt8& EdgeFlag() const { return mbEdgeFlag; }

    double GetX() const { return maPoint.getX(); }
    void SetX(double fNew) { maPoint.setX(fNew); }

    double GetY() const { return maPoint.getY(); }
    void SetY(double fNew) { maPoint.setY(fNew); }

    double GetZ() const { return maPoint.getZ(); }
    void SetZ(double fNew) { maPoint.setZ(fNew); }

    void Reset();

    void Copy(B3dEntity& rEnt);
    void ToDeviceCoor(B3dTransformationSet* pSet)
        { if(!IsDeviceCoor()) ImplToDeviceCoor(pSet); }
    void To3DCoor(B3dTransformationSet* pSet)
        { if(IsDeviceCoor()) ImplTo3DCoor(pSet); }

    void ForceEqualBase(B3dTransformationSet* pSet, B3dEntity& rOld);
    void ForceEqualBase(B3dTransformationSet* pSet, B3dEntity& rOld1,
        B3dEntity& rOld2);
    void CalcInBetween(B3dEntity& rOld1,
        B3dEntity& rOld2, double t);
    void CalcMiddle(B3dEntity& rOld1,
        B3dEntity& rOld2);
    void CalcMiddle(B3dEntity& rOld1,
        B3dEntity& rOld2, B3dEntity& rOld3);

    // Eine beliebige Transformation auf die Geometrie anwenden
    void Transform(const basegfx::B3DHomMatrix& rMat);

protected:
    void ImplToDeviceCoor(B3dTransformationSet* pSet);
    void ImplTo3DCoor(B3dTransformationSet* pSet);
};

/*************************************************************************
|*
|* Bucket fuer geometrische Daten
|*
\************************************************************************/

BASE3D_DECL_BUCKET(B3dEntity, Bucket)

#endif          // _B3D_B3DENTITY_HXX
<commit_msg>INTEGRATION: CWS changefileheader (1.2.86); FILE MERGED 2008/04/01 15:19:26 thb 1.2.86.3: #i85898# Stripping all external header guards 2008/04/01 12:31:02 thb 1.2.86.2: #i85898# Stripping all external header guards 2008/03/31 13:39:30 rt 1.2.86.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: b3dentty.hxx,v $
 * $Revision: 1.3 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef _B3D_B3DENTITY_HXX
#define _B3D_B3DENTITY_HXX

#include <goodies/b3dcolor.hxx>
#include <goodies/bucket.hxx>
#include <basegfx/point/b3dpoint.hxx>
#include <basegfx/point/b2dpoint.hxx>
#include <basegfx/vector/b3dvector.hxx>

/*************************************************************************
|*
|* Merkt sich einen Punkt plus Normale plus Texturkoordinate
|* (in Zukunft noch weitere Attribute, bsp. Farbe, Kante, Linienmodus
|*
\************************************************************************/

// predeclarations
class B3dTransformationSet;
namespace basegfx
{
    class B3DHomMatrix;
} // end of namespace basegfx

class B3dEntity
{
private:
    // Data defining this point, it's normal and texture coordinates
    basegfx::B3DPoint       maPoint;
    basegfx::B3DVector  maNormal;
    basegfx::B3DVector  maPlaneNormal;
    basegfx::B2DPoint       maTexCoor;
    B3dColor                maColor;

    // Ist die diesem Punkt folgende Kante sichtbar ?
    // EdgeFlag bool NOT in bitfield to be able to access it from OpenGL driver
    sal_uInt8               mbEdgeFlag;

    // bitfield
    // Gueltigkeit der geometrischen Daten
    unsigned                mbValid         : 1;

    // Wird eine Normale verwendet ?
    unsigned                mbNormalUsed    : 1;

    // Wird eine Texturkoordinate verwendet ?
    unsigned                mbTexCoorUsed   : 1;

    // Sind die geometrischen Daten schon in DeviceKoordinaten
    // umgerechnet ?
    unsigned                mbDeviceCoor    : 1;

public:
    B3dEntity() { Reset(); }

    sal_Bool IsValid() const { return mbValid; }
    void SetValid(sal_Bool bNew=sal_True) { mbValid = bNew; }

    sal_Bool IsNormalUsed() const { return mbNormalUsed; }
    void SetNormalUsed(sal_Bool bNew=sal_True) { mbNormalUsed = bNew; }

    sal_Bool IsTexCoorUsed() const { return mbTexCoorUsed; }
    void SetTexCoorUsed(sal_Bool bNew=sal_True) { mbTexCoorUsed = bNew; }

    sal_Bool IsDeviceCoor() const { return mbDeviceCoor; }
    void SetDeviceCoor(sal_Bool bNew=sal_True) { mbDeviceCoor = bNew; }

    sal_Bool IsEdgeVisible() const { return mbEdgeFlag; }
    void SetEdgeVisible(sal_Bool bNew=sal_True) { mbEdgeFlag = bNew; }

    basegfx::B3DPoint& Point() { return maPoint; }
    const basegfx::B3DPoint& Point() const { return maPoint; }
    basegfx::B3DVector& Normal() { return maNormal; }
    const basegfx::B3DVector& Normal() const { return maNormal; }
    basegfx::B3DVector& PlaneNormal() { return maPlaneNormal; }
    const basegfx::B3DVector& PlaneNormal() const { return maPlaneNormal; }
    basegfx::B2DPoint& TexCoor() { return maTexCoor; }
    const basegfx::B2DPoint& TexCoor() const { return maTexCoor; }
    B3dColor& Color() { return maColor; }
    const B3dColor& Color() const { return maColor; }
    sal_uInt8& EdgeFlag() { return mbEdgeFlag; }
    const sal_uInt8& EdgeFlag() const { return mbEdgeFlag; }

    double GetX() const { return maPoint.getX(); }
    void SetX(double fNew) { maPoint.setX(fNew); }

    double GetY() const { return maPoint.getY(); }
    void SetY(double fNew) { maPoint.setY(fNew); }

    double GetZ() const { return maPoint.getZ(); }
    void SetZ(double fNew) { maPoint.setZ(fNew); }

    void Reset();

    void Copy(B3dEntity& rEnt);
    void ToDeviceCoor(B3dTransformationSet* pSet)
        { if(!IsDeviceCoor()) ImplToDeviceCoor(pSet); }
    void To3DCoor(B3dTransformationSet* pSet)
        { if(IsDeviceCoor()) ImplTo3DCoor(pSet); }

    void ForceEqualBase(B3dTransformationSet* pSet, B3dEntity& rOld);
    void ForceEqualBase(B3dTransformationSet* pSet, B3dEntity& rOld1,
        B3dEntity& rOld2);
    void CalcInBetween(B3dEntity& rOld1,
        B3dEntity& rOld2, double t);
    void CalcMiddle(B3dEntity& rOld1,
        B3dEntity& rOld2);
    void CalcMiddle(B3dEntity& rOld1,
        B3dEntity& rOld2, B3dEntity& rOld3);

    // Eine beliebige Transformation auf die Geometrie anwenden
    void Transform(const basegfx::B3DHomMatrix& rMat);

protected:
    void ImplToDeviceCoor(B3dTransformationSet* pSet);
    void ImplTo3DCoor(B3dTransformationSet* pSet);
};

/*************************************************************************
|*
|* Bucket fuer geometrische Daten
|*
\************************************************************************/

BASE3D_DECL_BUCKET(B3dEntity, Bucket)

#endif          // _B3D_B3DENTITY_HXX
<|endoftext|>


<commit_before><commit_msg>A few more helgrind cleanups (https://stroika.atlassian.net/browse/STK-471_<commit_after><|endoftext|>


<commit_before>#pragma ident "$Id$"

//============================================================================
//
//  This file is part of GPSTk, the GPS Toolkit.
//
//  The GPSTk is free software; you can redistribute it and/or modify
//  it under the terms of the GNU Lesser General Public License as published
//  by the Free Software Foundation; either version 2.1 of the License, or
//  any later version.
//
//  The GPSTk is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with GPSTk; if not, write to the Free Software Foundation,
//  Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
//  Copyright 2004, The University of Texas at Austin
//
//============================================================================

//============================================================================
//
//This software developed by Applied Research Laboratories at the University of
//Texas at Austin, under contract to an agency or agencies within the U.S.
//Department of Defense. The U.S. Government retains all rights to use,
//duplicate, distribute, disclose, or release this software.
//
//Pursuant to DoD Directive 523024
//
// DISTRIBUTION STATEMENT A: This software has been approved for public
//                           release, distribution is unlimited.
//
//=============================================================================

/**
 * @file TabularEphemerisStore.hpp
 * Store a tabular list of Xvt data (such as a table of precise ephemeris data
 * in an SP3 file) and compute Xvt from this table. A Lagrange interpolation
 * is used to compute the Xvt for times that are not in the table but do have
 * sufficient data.
 */

#ifndef GPSTK_TABULAR_EPHEMERIS_STORE_HPP
#define GPSTK_TABULAR_EPHEMERIS_STORE_HPP

#include <iostream>

#include "SatID.hpp"
#include "DayTime.hpp"
#include "XvtStore.hpp"
#include "SP3Data.hpp"

namespace gpstk
{

      /** @addtogroup ephemstore */
      //@{

      /// Store a tabular list of Xvt data (such as a table of precise
      /// ephemeris data in an SP3 file) and compute Xvt from this table.
      /// A Lagrange interpolation is used to compute the Xvt for times that
      /// are not in the table but do have sufficient data.
   class TabularEphemerisStore : public XvtStore<SatID>
   {
   public:

         /// Default constructor
      TabularEphemerisStore()
         throw()
         : haveVelocity(true), initialTime(DayTime::END_OF_TIME),
           finalTime(DayTime::BEGINNING_OF_TIME), checkDataGap(false),
           gapInterval(901.0), checkInterval(false), maxInterval(8105.0)
      {};

         /// Destructor
      virtual ~TabularEphemerisStore() {};

         /** Returns the position, velocity, and clock offset of the indicated
          *  object in ECEF coordinates (meters) at the indicated time.
          *
          * @param[in] id the object's identifier
          * @param[in] t the time to look up
          *
          * @return the Xvt of the object at the indicated time
          *
          * @throw InvalidRequest If the request can not be completed for any
          *    reason, this is thrown. The text may have additional
          *    information as to why the request failed.
          */
      virtual Xvt getXvt( const SatID id,
                          const DayTime& t )
         const throw(InvalidRequest);

         /** Returns the acceleration of the indicated object in ECEF
          *  coordinates (meters) at the indicated time.
          *
          * @param[in] id the object's identifier
          * @param[in] t the time to look up
          *
          * @return the Triple holding the acceleration of the object at the
          * indicated time
          *
          * @throw InvalidRequest If the request can not be completed for any
          *    reason, this is thrown. The text may have additional
          *    information as to why the request failed.
          */
      virtual Triple getAccel( const SatID id,
                               const DayTime& t )
         const throw(InvalidRequest);

         /** A debugging function that outputs in human readable form,
          *  all data stored in this object.
          *
          * @param[in] s the stream to receive the output; defaults to cout
          * @param[in] detail the level of detail to provide
          */
      virtual void dump( std::ostream& s = std::cout,
                         short detail = 0 )
         const throw();

         /** Edit the dataset, removing data outside the indicated time
          *  interval.
          *
          * @param[in] tmin defines the beginning of the time interval
          * @param[in] tmax defines the end of the time interval
          */
      virtual void edit( const DayTime& tmin,
                         const DayTime& tmax = DayTime(DayTime::END_OF_TIME) )
         throw();

         /** Determine the earliest time for which this object can successfully
          *  determine the Xvt for any object.
          *
          * @return The initial time
          *
          * @throw InvalidRequest This is thrown if the object has no data.
          */
      virtual DayTime getInitialTime()
         const throw(InvalidRequest)
      { return initialTime; };

         /** Determine the latest time for which this object can successfully
          *  determine the Xvt for any object.
          *
          * @return The final time
          *
          * @throw InvalidRequest This is thrown if the object has no data.
          */
      virtual DayTime getFinalTime()
         const throw(InvalidRequest)
      { return finalTime; };

         /// Check if this ephemeris contains velocity information in all
         /// datasets loaded.
      virtual bool velocityIsPresent()
         const throw()
      { return haveVelocity; }

         /// Check if this ephemeris contains clock information.
      virtual bool clockIsPresent()
         const throw()
      { return true; };

         /// Get number of satellite maps
      int nsats(void) throw() { return pe.size(); }

         /// Get total number of ephemerides, all sats
      int neph(void) throw() {
         int n(0);
         std::map<SatID, SvEphMap>::const_iterator it(pe.begin());
         while(it != pe.end()) {
            n += it->second.size();
            ++it;
         }
         return n;
      }

      //---------------------------------------------------------------
      // Below are interfaces that are unique to this class (i.e. not
      // in the parent class)
      //---------------------------------------------------------------

         /// Insert a new SP3Data object into the store
      void addEphemeris(const SP3Data& data)
         throw();

         /// Remove all data
      void clear() throw();

         /// Enable checking of data gaps.
      void enableDataGapCheck(void)
      { checkDataGap = true; };

         /// Disable checking of data gaps.
      void disableDataGapCheck(void)
      { checkDataGap = false; };

         /// Get current gap interval.
      double getGapInterval(void)
      { return gapInterval; };

         /// Set gap interval.
      void setGapInterval(double interval)
      { gapInterval = interval; return; };

         /// Enable checking of maximum interval.
      void enableIntervalCheck(void)
      { checkInterval = true; };

         /// Disable checking of maximum interval.
      void disableIntervalCheck(void)
      { checkInterval = false; };

         /// Get current maximum interval.
      double getMaxInterval(void)
      { return maxInterval; };

         /// Set maximum interval.
      void setMaxInterval(double interval)
      { maxInterval = interval; return; };

   protected:

         /// Flag indicating that velocity data present in all datasets loaded.
      bool haveVelocity;

   private:

         /// The key to this map is the time
      typedef std::map<DayTime, Xvt> SvEphMap;

         /// The key to this map is the svid of the satellite (usually the prn)
      typedef std::map<SatID, SvEphMap> EphMap;

         /// the map of SVs and XVTs
      EphMap pe;

         /** These give the overall span of time for which this object
          *  contains data.
          *
          * NB there may be gaps in the data, i.e. the data may not be
          * continuous.
          */
      DayTime initialTime, finalTime;

         /** Flag to check for data gaps.
          *
          * If this flag is enabled, data gaps wider than "gapInterval" will
          * generate an "InvalidRequest" exception when using method "getXvt()".
          *
          * This flag is disabled by default.
          */
      bool checkDataGap;

         /** Maximum interval of time (in seconds) to declare a data gap.
          *
          * Recommended value is (SP3 sample period) + 1, in seconds, which
          * means 900 s + 1 s = 901 s for a typical 15-minutes-per-sample
          * SP3 file.
          *
          * This field is useful only if "checkDataGap" is enabled. Use method
          * "enableDataGapCheck()" for this.
          */
      double gapInterval;

         /** Flag to check for interpolation interval.
          *
          * If this flag is enabled, interpolation intervals wider than
          * "maxInterval" will generate an "InvalidRequest" exception when
          * using method "getXvt()".
          *
          * This flag is disabled by default.
          */
      bool checkInterval;

         /** Maximum interval of time (in seconds) allowed to carry out the
          *  interpolation process.
          *
          * Recommended value is (10 - 1) * (SP3 sample period) + 5, in
          * seconds, which means 8100 s + 5 s = 8105 s for a typical
          * 15-minutes-per-sample SP3 file (please note that the order of the
          * Lagrange interpolation is usually 10).
          *
          * This field is useful only if "checkInterval" is enabled. Use method
          * "enableIntervalCheck()" for this.
          */
      double maxInterval;

   };

      //@}

}  // End of namespace gpstk

#endif   // GPSTK_TABULAR_EPHEMERIS_STORE_HPP
<commit_msg>change the class members to 'protected' from 'private' to make inherited classes to access these members. a new class 'IGSEphemerisStore' to process igs sp3 and clk files will be implemented, and the getXvt() function can be rewritten to process daily data with daily ephemeris but not three days ephemeris<commit_after>#pragma ident "$Id$"

//============================================================================
//
//  This file is part of GPSTk, the GPS Toolkit.
//
//  The GPSTk is free software; you can redistribute it and/or modify
//  it under the terms of the GNU Lesser General Public License as published
//  by the Free Software Foundation; either version 2.1 of the License, or
//  any later version.
//
//  The GPSTk is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with GPSTk; if not, write to the Free Software Foundation,
//  Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
//  Copyright 2004, The University of Texas at Austin
//
//============================================================================

//============================================================================
//
//This software developed by Applied Research Laboratories at the University of
//Texas at Austin, under contract to an agency or agencies within the U.S.
//Department of Defense. The U.S. Government retains all rights to use,
//duplicate, distribute, disclose, or release this software.
//
//Pursuant to DoD Directive 523024
//
// DISTRIBUTION STATEMENT A: This software has been approved for public
//                           release, distribution is unlimited.
//
//=============================================================================

/**
 * @file TabularEphemerisStore.hpp
 * Store a tabular list of Xvt data (such as a table of precise ephemeris data
 * in an SP3 file) and compute Xvt from this table. A Lagrange interpolation
 * is used to compute the Xvt for times that are not in the table but do have
 * sufficient data.
 */

#ifndef GPSTK_TABULAR_EPHEMERIS_STORE_HPP
#define GPSTK_TABULAR_EPHEMERIS_STORE_HPP

#include <iostream>

#include "SatID.hpp"
#include "DayTime.hpp"
#include "XvtStore.hpp"
#include "SP3Data.hpp"

namespace gpstk
{

      /** @addtogroup ephemstore */
      //@{

      /// Store a tabular list of Xvt data (such as a table of precise
      /// ephemeris data in an SP3 file) and compute Xvt from this table.
      /// A Lagrange interpolation is used to compute the Xvt for times that
      /// are not in the table but do have sufficient data.
   class TabularEphemerisStore : public XvtStore<SatID>
   {
   public:

         /// Default constructor
      TabularEphemerisStore()
         throw()
         : haveVelocity(true), initialTime(DayTime::END_OF_TIME),
           finalTime(DayTime::BEGINNING_OF_TIME), checkDataGap(false),
           gapInterval(901.0), checkInterval(false), maxInterval(8105.0)
      {};

         /// Destructor
      virtual ~TabularEphemerisStore() {};

         /** Returns the position, velocity, and clock offset of the indicated
          *  object in ECEF coordinates (meters) at the indicated time.
          *
          * @param[in] id the object's identifier
          * @param[in] t the time to look up
          *
          * @return the Xvt of the object at the indicated time
          *
          * @throw InvalidRequest If the request can not be completed for any
          *    reason, this is thrown. The text may have additional
          *    information as to why the request failed.
          */
      virtual Xvt getXvt( const SatID id,
                          const DayTime& t )
         const throw(InvalidRequest);

         /** Returns the acceleration of the indicated object in ECEF
          *  coordinates (meters) at the indicated time.
          *
          * @param[in] id the object's identifier
          * @param[in] t the time to look up
          *
          * @return the Triple holding the acceleration of the object at the
          * indicated time
          *
          * @throw InvalidRequest If the request can not be completed for any
          *    reason, this is thrown. The text may have additional
          *    information as to why the request failed.
          */
      virtual Triple getAccel( const SatID id,
                               const DayTime& t )
         const throw(InvalidRequest);

         /** A debugging function that outputs in human readable form,
          *  all data stored in this object.
          *
          * @param[in] s the stream to receive the output; defaults to cout
          * @param[in] detail the level of detail to provide
          */
      virtual void dump( std::ostream& s = std::cout,
                         short detail = 0 )
         const throw();

         /** Edit the dataset, removing data outside the indicated time
          *  interval.
          *
          * @param[in] tmin defines the beginning of the time interval
          * @param[in] tmax defines the end of the time interval
          */
      virtual void edit( const DayTime& tmin,
                         const DayTime& tmax = DayTime(DayTime::END_OF_TIME) )
         throw();

         /** Determine the earliest time for which this object can successfully
          *  determine the Xvt for any object.
          *
          * @return The initial time
          *
          * @throw InvalidRequest This is thrown if the object has no data.
          */
      virtual DayTime getInitialTime()
         const throw(InvalidRequest)
      { return initialTime; };

         /** Determine the latest time for which this object can successfully
          *  determine the Xvt for any object.
          *
          * @return The final time
          *
          * @throw InvalidRequest This is thrown if the object has no data.
          */
      virtual DayTime getFinalTime()
         const throw(InvalidRequest)
      { return finalTime; };

         /// Check if this ephemeris contains velocity information in all
         /// datasets loaded.
      virtual bool velocityIsPresent()
         const throw()
      { return haveVelocity; }

         /// Check if this ephemeris contains clock information.
      virtual bool clockIsPresent()
         const throw()
      { return true; };

         /// Get number of satellite maps
      int nsats(void) throw() { return pe.size(); }

         /// Get total number of ephemerides, all sats
      int neph(void) throw() {
         int n(0);
         std::map<SatID, SvEphMap>::const_iterator it(pe.begin());
         while(it != pe.end()) {
            n += it->second.size();
            ++it;
         }
         return n;
      }

      //---------------------------------------------------------------
      // Below are interfaces that are unique to this class (i.e. not
      // in the parent class)
      //---------------------------------------------------------------

         /// Insert a new SP3Data object into the store
      void addEphemeris(const SP3Data& data)
         throw();

         /// Remove all data
      void clear() throw();

         /// Enable checking of data gaps.
      void enableDataGapCheck(void)
      { checkDataGap = true; };

         /// Disable checking of data gaps.
      void disableDataGapCheck(void)
      { checkDataGap = false; };

         /// Get current gap interval.
      double getGapInterval(void)
      { return gapInterval; };

         /// Set gap interval.
      void setGapInterval(double interval)
      { gapInterval = interval; return; };

         /// Enable checking of maximum interval.
      void enableIntervalCheck(void)
      { checkInterval = true; };

         /// Disable checking of maximum interval.
      void disableIntervalCheck(void)
      { checkInterval = false; };

         /// Get current maximum interval.
      double getMaxInterval(void)
      { return maxInterval; };

         /// Set maximum interval.
      void setMaxInterval(double interval)
      { maxInterval = interval; return; };

   protected:

         /// Flag indicating that velocity data present in all datasets loaded.
      bool haveVelocity;

   protected:

         /// The key to this map is the time
      typedef std::map<DayTime, Xvt> SvEphMap;

         /// The key to this map is the svid of the satellite (usually the prn)
      typedef std::map<SatID, SvEphMap> EphMap;

         /// the map of SVs and XVTs
      EphMap pe;

         /** These give the overall span of time for which this object
          *  contains data.
          *
          * NB there may be gaps in the data, i.e. the data may not be
          * continuous.
          */
      DayTime initialTime, finalTime;

         /** Flag to check for data gaps.
          *
          * If this flag is enabled, data gaps wider than "gapInterval" will
          * generate an "InvalidRequest" exception when using method "getXvt()".
          *
          * This flag is disabled by default.
          */
      bool checkDataGap;

         /** Maximum interval of time (in seconds) to declare a data gap.
          *
          * Recommended value is (SP3 sample period) + 1, in seconds, which
          * means 900 s + 1 s = 901 s for a typical 15-minutes-per-sample
          * SP3 file.
          *
          * This field is useful only if "checkDataGap" is enabled. Use method
          * "enableDataGapCheck()" for this.
          */
      double gapInterval;

         /** Flag to check for interpolation interval.
          *
          * If this flag is enabled, interpolation intervals wider than
          * "maxInterval" will generate an "InvalidRequest" exception when
          * using method "getXvt()".
          *
          * This flag is disabled by default.
          */
      bool checkInterval;

         /** Maximum interval of time (in seconds) allowed to carry out the
          *  interpolation process.
          *
          * Recommended value is (10 - 1) * (SP3 sample period) + 5, in
          * seconds, which means 8100 s + 5 s = 8105 s for a typical
          * 15-minutes-per-sample SP3 file (please note that the order of the
          * Lagrange interpolation is usually 10).
          *
          * This field is useful only if "checkInterval" is enabled. Use method
          * "enableIntervalCheck()" for this.
          */
      double maxInterval;

   };

      //@}

}  // End of namespace gpstk

#endif   // GPSTK_TABULAR_EPHEMERIS_STORE_HPP
<|endoftext|>


<commit_before>//
//
// Description: This file is part of FET
//
//
// Author: Lalescu Liviu <Please see https://lalescu.ro/liviu/ for details about contacting Liviu Lalescu (in particular, you can find here the e-mail address)>
// Copyright (C) 2005 Liviu Lalescu <https://lalescu.ro/liviu/>
//
/***************************************************************************
 *                                                                         *
 *   This program is free software: you can redistribute it and/or modify  *
 *   it under the terms of the GNU Affero General Public License as        *
 *   published by the Free Software Foundation, either version 3 of the    *
 *   License, or (at your option) any later version.                       *
 *                                                                         *
 ***************************************************************************/

#include "timetable_defs.h"
#include "timetable.h"
#include "fet.h"
#include "activitytagsform.h"
#include "studentsset.h"
#include "teacher.h"
#include "subject.h"
#include "activitytag.h"

#include <QInputDialog>

#include <QMessageBox>

#include <QListWidget>
#include <QAbstractItemView>

#include <QSplitter>
#include <QSettings>
#include <QObject>
#include <QMetaObject>

extern const QString COMPANY;
extern const QString PROGRAM;

ActivityTagsForm::ActivityTagsForm(QWidget* parent): QDialog(parent)
{
	setupUi(this);

	currentActivityTagTextEdit->setReadOnly(true);

	renameActivityTagPushButton->setDefault(true);

	activityTagsListWidget->setSelectionMode(QAbstractItemView::SingleSelection);

	connect(closePushButton, SIGNAL(clicked()), this, SLOT(close()));
	connect(addActivityTagPushButton, SIGNAL(clicked()), this, SLOT(addActivityTag()));
	connect(removeActivityTagPushButton, SIGNAL(clicked()), this, SLOT(removeActivityTag()));
	connect(renameActivityTagPushButton, SIGNAL(clicked()), this, SLOT(renameActivityTag()));

	connect(moveActivityTagUpPushButton, SIGNAL(clicked()), this, SLOT(moveActivityTagUp()));
	connect(moveActivityTagDownPushButton, SIGNAL(clicked()), this, SLOT(moveActivityTagDown()));

	connect(sortActivityTagsPushButton, SIGNAL(clicked()), this, SLOT(sortActivityTags()));
	connect(activityTagsListWidget, SIGNAL(currentRowChanged(int)), this, SLOT(activityTagChanged(int)));
	connect(activateActivityTagPushButton, SIGNAL(clicked()), this, SLOT(activateActivityTag()));
	connect(deactivateActivityTagPushButton, SIGNAL(clicked()), this, SLOT(deactivateActivityTag()));
	connect(activityTagsListWidget, SIGNAL(itemDoubleClicked(QListWidgetItem*)), this, SLOT(renameActivityTag()));
	connect(helpPushButton, SIGNAL(clicked()), this, SLOT(help()));

	connect(printablePushButton, SIGNAL(clicked()), this, SLOT(printableActivityTag()));
	connect(notPrintablePushButton, SIGNAL(clicked()), this, SLOT(notPrintableActivityTag()));

	connect(commentsPushButton, SIGNAL(clicked()), this, SLOT(comments()));

	centerWidgetOnScreen(this);
	restoreFETDialogGeometry(this);
	//restore splitter state
	QSettings settings(COMPANY, PROGRAM);
	if(settings.contains(this->metaObject()->className()+QString("/splitter-state")))
		splitter->restoreState(settings.value(this->metaObject()->className()+QString("/splitter-state")).toByteArray());

	activityTagsListWidget->clear();
	for(int i=0; i<gt.rules.activityTagsList.size(); i++){
		ActivityTag* sbt=gt.rules.activityTagsList[i];
		activityTagsListWidget->addItem(sbt->name);
	}

	if(activityTagsListWidget->count()>0)
		activityTagsListWidget->setCurrentRow(0);
}

ActivityTagsForm::~ActivityTagsForm()
{
	saveFETDialogGeometry(this);
	//save splitter state
	QSettings settings(COMPANY, PROGRAM);
	settings.setValue(this->metaObject()->className()+QString("/splitter-state"), splitter->saveState());
}

void ActivityTagsForm::addActivityTag()
{
	bool ok = false;
	ActivityTag* sbt=new ActivityTag();
	sbt->name = QInputDialog::getText( this, tr("Add activity tag"), tr("Please enter activity tag's name") ,
	 QLineEdit::Normal, QString(), &ok );

	if ( ok && !((sbt->name).isEmpty()) ){
		// user entered something and pressed OK
		if(!gt.rules.addActivityTag(sbt)){
			QMessageBox::information( this, tr("Activity tag insertion dialog"),
				tr("Could not insert item. Must be a duplicate"));
			delete sbt;
		}
		else{
			activityTagsListWidget->addItem(sbt->name);
			activityTagsListWidget->setCurrentRow(activityTagsListWidget->count()-1);
		}
	}
	else{
		if(ok){ //the user entered nothing
			QMessageBox::information(this, tr("FET information"), tr("Incorrect name"));
		}
		delete sbt;// user entered nothing or pressed Cancel
	}
}

void ActivityTagsForm::removeActivityTag()
{
	int i=activityTagsListWidget->currentRow();
	if(activityTagsListWidget->currentRow()<0){
		QMessageBox::information(this, tr("FET information"), tr("Invalid selected activity tag"));
		return;
	}

	QString text=activityTagsListWidget->currentItem()->text();
	int activity_tag_ID=gt.rules.searchActivityTag(text);
	if(activity_tag_ID<0){
		QMessageBox::information(this, tr("FET information"), tr("Invalid selected activity tag"));
		return;
	}

	if(QMessageBox::warning( this, tr("FET"),
		tr("Are you sure you want to delete this activity tag?"),
		tr("Yes"), tr("No"), 0, 0, 1 ) == 1)
		return;

	int tmp=gt.rules.removeActivityTag(text);
	if(tmp){
		activityTagsListWidget->setCurrentRow(-1);
		QListWidgetItem* item;
		item=activityTagsListWidget->takeItem(i);
		delete item;

		if(i>=activityTagsListWidget->count())
			i=activityTagsListWidget->count()-1;
		if(i>=0)
			activityTagsListWidget->setCurrentRow(i);
		else
			currentActivityTagTextEdit->setPlainText(QString(""));
	}
}

void ActivityTagsForm::renameActivityTag()
{
	int i=activityTagsListWidget->currentRow();
	if(activityTagsListWidget->currentRow()<0){
		QMessageBox::information(this, tr("FET information"), tr("Invalid selected activity tag"));
		return;
	}

	QString initialActivityTagName=activityTagsListWidget->currentItem()->text();

	int activity_tag_ID=gt.rules.searchActivityTag(initialActivityTagName);
	if(activity_tag_ID<0){
		QMessageBox::information(this, tr("FET information"), tr("Invalid selected activity tag"));
		return;
	}

	bool ok = false;
	QString finalActivityTagName;
	finalActivityTagName = QInputDialog::getText( this, tr("Rename activity tag"), tr("Please enter new activity tag's name") ,
	 QLineEdit::Normal, initialActivityTagName, &ok );

	if ( ok && !(finalActivityTagName.isEmpty()) ){
		// user entered something and pressed OK
		if(gt.rules.searchActivityTag(finalActivityTagName)>=0){
			QMessageBox::information( this, tr("Activity tag insertion dialog"),
				tr("Could not modify item. New name must be a duplicate"));
		}
		else{
			gt.rules.modifyActivityTag(initialActivityTagName, finalActivityTagName);
			activityTagsListWidget->item(i)->setText(finalActivityTagName);
			activityTagChanged(activityTagsListWidget->currentRow());
		}
	}
}

void ActivityTagsForm::moveActivityTagUp()
{
	if(activityTagsListWidget->count()<=1)
		return;
	int i=activityTagsListWidget->currentRow();
	if(i<0 || i>=activityTagsListWidget->count())
		return;
	if(i==0)
		return;

	QString s1=activityTagsListWidget->item(i)->text();
	QString s2=activityTagsListWidget->item(i-1)->text();

	ActivityTag* at1=gt.rules.activityTagsList.at(i);
	ActivityTag* at2=gt.rules.activityTagsList.at(i-1);

	gt.rules.internalStructureComputed=false;
	setRulesModifiedAndOtherThings(&gt.rules);

	activityTagsListWidget->item(i)->setText(s2);
	activityTagsListWidget->item(i-1)->setText(s1);

	gt.rules.activityTagsList[i]=at2;
	gt.rules.activityTagsList[i-1]=at1;

	activityTagsListWidget->setCurrentRow(i-1);
	activityTagChanged(i-1);
}

void ActivityTagsForm::moveActivityTagDown()
{
	if(activityTagsListWidget->count()<=1)
		return;
	int i=activityTagsListWidget->currentRow();
	if(i<0 || i>=activityTagsListWidget->count())
		return;
	if(i==activityTagsListWidget->count()-1)
		return;

	QString s1=activityTagsListWidget->item(i)->text();
	QString s2=activityTagsListWidget->item(i+1)->text();

	ActivityTag* at1=gt.rules.activityTagsList.at(i);
	ActivityTag* at2=gt.rules.activityTagsList.at(i+1);

	gt.rules.internalStructureComputed=false;
	setRulesModifiedAndOtherThings(&gt.rules);

	activityTagsListWidget->item(i)->setText(s2);
	activityTagsListWidget->item(i+1)->setText(s1);

	gt.rules.activityTagsList[i]=at2;
	gt.rules.activityTagsList[i+1]=at1;

	activityTagsListWidget->setCurrentRow(i+1);
	activityTagChanged(i+1);
}

void ActivityTagsForm::sortActivityTags()
{
	gt.rules.sortActivityTagsAlphabetically();

	activityTagsListWidget->clear();
	for(int i=0; i<gt.rules.activityTagsList.size(); i++){
		ActivityTag* sbt=gt.rules.activityTagsList[i];
		activityTagsListWidget->addItem(sbt->name);
	}

	if(activityTagsListWidget->count()>0)
		activityTagsListWidget->setCurrentRow(0);
}

void ActivityTagsForm::activityTagChanged(int index)
{
	if(index<0){
		currentActivityTagTextEdit->setPlainText(QString(""));
		return;
	}

	ActivityTag* st=gt.rules.activityTagsList.at(index);
	assert(st);
	QString s=st->getDetailedDescriptionWithConstraints(gt.rules);
	currentActivityTagTextEdit->setPlainText(s);
}

void ActivityTagsForm::activateActivityTag()
{
	if(activityTagsListWidget->currentRow()<0){
		QMessageBox::information(this, tr("FET information"), tr("Invalid selected activity tag"));
		return;
	}

	QString text=activityTagsListWidget->currentItem()->text();
	int count=gt.rules.activateActivityTag(text);
	QMessageBox::information(this, tr("FET information"), tr("Activated a number of %1 activities").arg(count));
}

void ActivityTagsForm::deactivateActivityTag()
{
	if(activityTagsListWidget->currentRow()<0){
		QMessageBox::information(this, tr("FET information"), tr("Invalid selected activity tag"));
		return;
	}

	QString text=activityTagsListWidget->currentItem()->text();
	int count=gt.rules.deactivateActivityTag(text);
	QMessageBox::information(this, tr("FET information"), tr("De-activated a number of %1 activities").arg(count));
}

void ActivityTagsForm::printableActivityTag()
{
	if(activityTagsListWidget->currentRow()<0){
		QMessageBox::information(this, tr("FET information"), tr("Invalid selected activity tag"));
		return;
	}

	QString text=activityTagsListWidget->currentItem()->text();

	gt.rules.makeActivityTagPrintable(text);

	activityTagChanged(activityTagsListWidget->currentRow());
}

void ActivityTagsForm::notPrintableActivityTag()
{
	if(activityTagsListWidget->currentRow()<0){
		QMessageBox::information(this, tr("FET information"), tr("Invalid selected activity tag"));
		return;
	}

	QString text=activityTagsListWidget->currentItem()->text();

	gt.rules.makeActivityTagNotPrintable(text);

	activityTagChanged(activityTagsListWidget->currentRow());
}

void ActivityTagsForm::help()
{
	QMessageBox::information(this, tr("FET help on activity tags"),
	 tr("Activity tag is a field which can be used or not, depending on your wish (optional field)."
	 " It is designed to help you with some constraints. Each activity has a possible empty list of activity tags"
	 " (if you don't use activity tags, the list will be empty)"));
}

void ActivityTagsForm::comments()
{
	int ind=activityTagsListWidget->currentRow();
	if(ind<0){
		QMessageBox::information(this, tr("FET information"), tr("Invalid selected activity tag"));
		return;
	}

	ActivityTag* at=gt.rules.activityTagsList[ind];
	assert(at!=NULL);

	QDialog getCommentsDialog(this);

	getCommentsDialog.setWindowTitle(tr("Activity tag comments"));

	QPushButton* okPB=new QPushButton(tr("OK"));
	okPB->setDefault(true);
	QPushButton* cancelPB=new QPushButton(tr("Cancel"));

	connect(okPB, SIGNAL(clicked()), &getCommentsDialog, SLOT(accept()));
	connect(cancelPB, SIGNAL(clicked()), &getCommentsDialog, SLOT(reject()));

	QHBoxLayout* hl=new QHBoxLayout();
	hl->addStretch();
	hl->addWidget(okPB);
	hl->addWidget(cancelPB);

	QVBoxLayout* vl=new QVBoxLayout();

	QPlainTextEdit* commentsPT=new QPlainTextEdit();
	commentsPT->setPlainText(at->comments);
	commentsPT->selectAll();
	commentsPT->setFocus();

	vl->addWidget(commentsPT);
	vl->addLayout(hl);

	getCommentsDialog.setLayout(vl);

	const QString settingsName=QString("ActivityTagCommentsDialog");

	getCommentsDialog.resize(500, 320);
	centerWidgetOnScreen(&getCommentsDialog);
	restoreFETDialogGeometry(&getCommentsDialog, settingsName);

	int t=getCommentsDialog.exec();
	saveFETDialogGeometry(&getCommentsDialog, settingsName);

	if(t==QDialog::Accepted){
		at->comments=commentsPT->toPlainText();

		gt.rules.internalStructureComputed=false;
		setRulesModifiedAndOtherThings(&gt.rules);

		activityTagChanged(ind);
	}
}
<commit_msg>activity tag help string clarification<commit_after>//
//
// Description: This file is part of FET
//
//
// Author: Lalescu Liviu <Please see https://lalescu.ro/liviu/ for details about contacting Liviu Lalescu (in particular, you can find here the e-mail address)>
// Copyright (C) 2005 Liviu Lalescu <https://lalescu.ro/liviu/>
//
/***************************************************************************
 *                                                                         *
 *   This program is free software: you can redistribute it and/or modify  *
 *   it under the terms of the GNU Affero General Public License as        *
 *   published by the Free Software Foundation, either version 3 of the    *
 *   License, or (at your option) any later version.                       *
 *                                                                         *
 ***************************************************************************/

#include "timetable_defs.h"
#include "timetable.h"
#include "fet.h"
#include "activitytagsform.h"
#include "studentsset.h"
#include "teacher.h"
#include "subject.h"
#include "activitytag.h"

#include <QInputDialog>

#include <QMessageBox>

#include <QListWidget>
#include <QAbstractItemView>

#include <QSplitter>
#include <QSettings>
#include <QObject>
#include <QMetaObject>

extern const QString COMPANY;
extern const QString PROGRAM;

ActivityTagsForm::ActivityTagsForm(QWidget* parent): QDialog(parent)
{
	setupUi(this);

	currentActivityTagTextEdit->setReadOnly(true);

	renameActivityTagPushButton->setDefault(true);

	activityTagsListWidget->setSelectionMode(QAbstractItemView::SingleSelection);

	connect(closePushButton, SIGNAL(clicked()), this, SLOT(close()));
	connect(addActivityTagPushButton, SIGNAL(clicked()), this, SLOT(addActivityTag()));
	connect(removeActivityTagPushButton, SIGNAL(clicked()), this, SLOT(removeActivityTag()));
	connect(renameActivityTagPushButton, SIGNAL(clicked()), this, SLOT(renameActivityTag()));

	connect(moveActivityTagUpPushButton, SIGNAL(clicked()), this, SLOT(moveActivityTagUp()));
	connect(moveActivityTagDownPushButton, SIGNAL(clicked()), this, SLOT(moveActivityTagDown()));

	connect(sortActivityTagsPushButton, SIGNAL(clicked()), this, SLOT(sortActivityTags()));
	connect(activityTagsListWidget, SIGNAL(currentRowChanged(int)), this, SLOT(activityTagChanged(int)));
	connect(activateActivityTagPushButton, SIGNAL(clicked()), this, SLOT(activateActivityTag()));
	connect(deactivateActivityTagPushButton, SIGNAL(clicked()), this, SLOT(deactivateActivityTag()));
	connect(activityTagsListWidget, SIGNAL(itemDoubleClicked(QListWidgetItem*)), this, SLOT(renameActivityTag()));
	connect(helpPushButton, SIGNAL(clicked()), this, SLOT(help()));

	connect(printablePushButton, SIGNAL(clicked()), this, SLOT(printableActivityTag()));
	connect(notPrintablePushButton, SIGNAL(clicked()), this, SLOT(notPrintableActivityTag()));

	connect(commentsPushButton, SIGNAL(clicked()), this, SLOT(comments()));

	centerWidgetOnScreen(this);
	restoreFETDialogGeometry(this);
	//restore splitter state
	QSettings settings(COMPANY, PROGRAM);
	if(settings.contains(this->metaObject()->className()+QString("/splitter-state")))
		splitter->restoreState(settings.value(this->metaObject()->className()+QString("/splitter-state")).toByteArray());

	activityTagsListWidget->clear();
	for(int i=0; i<gt.rules.activityTagsList.size(); i++){
		ActivityTag* sbt=gt.rules.activityTagsList[i];
		activityTagsListWidget->addItem(sbt->name);
	}

	if(activityTagsListWidget->count()>0)
		activityTagsListWidget->setCurrentRow(0);
}

ActivityTagsForm::~ActivityTagsForm()
{
	saveFETDialogGeometry(this);
	//save splitter state
	QSettings settings(COMPANY, PROGRAM);
	settings.setValue(this->metaObject()->className()+QString("/splitter-state"), splitter->saveState());
}

void ActivityTagsForm::addActivityTag()
{
	bool ok = false;
	ActivityTag* sbt=new ActivityTag();
	sbt->name = QInputDialog::getText( this, tr("Add activity tag"), tr("Please enter activity tag's name") ,
	 QLineEdit::Normal, QString(), &ok );

	if ( ok && !((sbt->name).isEmpty()) ){
		// user entered something and pressed OK
		if(!gt.rules.addActivityTag(sbt)){
			QMessageBox::information( this, tr("Activity tag insertion dialog"),
				tr("Could not insert item. Must be a duplicate"));
			delete sbt;
		}
		else{
			activityTagsListWidget->addItem(sbt->name);
			activityTagsListWidget->setCurrentRow(activityTagsListWidget->count()-1);
		}
	}
	else{
		if(ok){ //the user entered nothing
			QMessageBox::information(this, tr("FET information"), tr("Incorrect name"));
		}
		delete sbt;// user entered nothing or pressed Cancel
	}
}

void ActivityTagsForm::removeActivityTag()
{
	int i=activityTagsListWidget->currentRow();
	if(activityTagsListWidget->currentRow()<0){
		QMessageBox::information(this, tr("FET information"), tr("Invalid selected activity tag"));
		return;
	}

	QString text=activityTagsListWidget->currentItem()->text();
	int activity_tag_ID=gt.rules.searchActivityTag(text);
	if(activity_tag_ID<0){
		QMessageBox::information(this, tr("FET information"), tr("Invalid selected activity tag"));
		return;
	}

	if(QMessageBox::warning( this, tr("FET"),
		tr("Are you sure you want to delete this activity tag?"),
		tr("Yes"), tr("No"), 0, 0, 1 ) == 1)
		return;

	int tmp=gt.rules.removeActivityTag(text);
	if(tmp){
		activityTagsListWidget->setCurrentRow(-1);
		QListWidgetItem* item;
		item=activityTagsListWidget->takeItem(i);
		delete item;

		if(i>=activityTagsListWidget->count())
			i=activityTagsListWidget->count()-1;
		if(i>=0)
			activityTagsListWidget->setCurrentRow(i);
		else
			currentActivityTagTextEdit->setPlainText(QString(""));
	}
}

void ActivityTagsForm::renameActivityTag()
{
	int i=activityTagsListWidget->currentRow();
	if(activityTagsListWidget->currentRow()<0){
		QMessageBox::information(this, tr("FET information"), tr("Invalid selected activity tag"));
		return;
	}

	QString initialActivityTagName=activityTagsListWidget->currentItem()->text();

	int activity_tag_ID=gt.rules.searchActivityTag(initialActivityTagName);
	if(activity_tag_ID<0){
		QMessageBox::information(this, tr("FET information"), tr("Invalid selected activity tag"));
		return;
	}

	bool ok = false;
	QString finalActivityTagName;
	finalActivityTagName = QInputDialog::getText( this, tr("Rename activity tag"), tr("Please enter new activity tag's name") ,
	 QLineEdit::Normal, initialActivityTagName, &ok );

	if ( ok && !(finalActivityTagName.isEmpty()) ){
		// user entered something and pressed OK
		if(gt.rules.searchActivityTag(finalActivityTagName)>=0){
			QMessageBox::information( this, tr("Activity tag insertion dialog"),
				tr("Could not modify item. New name must be a duplicate"));
		}
		else{
			gt.rules.modifyActivityTag(initialActivityTagName, finalActivityTagName);
			activityTagsListWidget->item(i)->setText(finalActivityTagName);
			activityTagChanged(activityTagsListWidget->currentRow());
		}
	}
}

void ActivityTagsForm::moveActivityTagUp()
{
	if(activityTagsListWidget->count()<=1)
		return;
	int i=activityTagsListWidget->currentRow();
	if(i<0 || i>=activityTagsListWidget->count())
		return;
	if(i==0)
		return;

	QString s1=activityTagsListWidget->item(i)->text();
	QString s2=activityTagsListWidget->item(i-1)->text();

	ActivityTag* at1=gt.rules.activityTagsList.at(i);
	ActivityTag* at2=gt.rules.activityTagsList.at(i-1);

	gt.rules.internalStructureComputed=false;
	setRulesModifiedAndOtherThings(&gt.rules);

	activityTagsListWidget->item(i)->setText(s2);
	activityTagsListWidget->item(i-1)->setText(s1);

	gt.rules.activityTagsList[i]=at2;
	gt.rules.activityTagsList[i-1]=at1;

	activityTagsListWidget->setCurrentRow(i-1);
	activityTagChanged(i-1);
}

void ActivityTagsForm::moveActivityTagDown()
{
	if(activityTagsListWidget->count()<=1)
		return;
	int i=activityTagsListWidget->currentRow();
	if(i<0 || i>=activityTagsListWidget->count())
		return;
	if(i==activityTagsListWidget->count()-1)
		return;

	QString s1=activityTagsListWidget->item(i)->text();
	QString s2=activityTagsListWidget->item(i+1)->text();

	ActivityTag* at1=gt.rules.activityTagsList.at(i);
	ActivityTag* at2=gt.rules.activityTagsList.at(i+1);

	gt.rules.internalStructureComputed=false;
	setRulesModifiedAndOtherThings(&gt.rules);

	activityTagsListWidget->item(i)->setText(s2);
	activityTagsListWidget->item(i+1)->setText(s1);

	gt.rules.activityTagsList[i]=at2;
	gt.rules.activityTagsList[i+1]=at1;

	activityTagsListWidget->setCurrentRow(i+1);
	activityTagChanged(i+1);
}

void ActivityTagsForm::sortActivityTags()
{
	gt.rules.sortActivityTagsAlphabetically();

	activityTagsListWidget->clear();
	for(int i=0; i<gt.rules.activityTagsList.size(); i++){
		ActivityTag* sbt=gt.rules.activityTagsList[i];
		activityTagsListWidget->addItem(sbt->name);
	}

	if(activityTagsListWidget->count()>0)
		activityTagsListWidget->setCurrentRow(0);
}

void ActivityTagsForm::activityTagChanged(int index)
{
	if(index<0){
		currentActivityTagTextEdit->setPlainText(QString(""));
		return;
	}

	ActivityTag* st=gt.rules.activityTagsList.at(index);
	assert(st);
	QString s=st->getDetailedDescriptionWithConstraints(gt.rules);
	currentActivityTagTextEdit->setPlainText(s);
}

void ActivityTagsForm::activateActivityTag()
{
	if(activityTagsListWidget->currentRow()<0){
		QMessageBox::information(this, tr("FET information"), tr("Invalid selected activity tag"));
		return;
	}

	QString text=activityTagsListWidget->currentItem()->text();
	int count=gt.rules.activateActivityTag(text);
	QMessageBox::information(this, tr("FET information"), tr("Activated a number of %1 activities").arg(count));
}

void ActivityTagsForm::deactivateActivityTag()
{
	if(activityTagsListWidget->currentRow()<0){
		QMessageBox::information(this, tr("FET information"), tr("Invalid selected activity tag"));
		return;
	}

	QString text=activityTagsListWidget->currentItem()->text();
	int count=gt.rules.deactivateActivityTag(text);
	QMessageBox::information(this, tr("FET information"), tr("De-activated a number of %1 activities").arg(count));
}

void ActivityTagsForm::printableActivityTag()
{
	if(activityTagsListWidget->currentRow()<0){
		QMessageBox::information(this, tr("FET information"), tr("Invalid selected activity tag"));
		return;
	}

	QString text=activityTagsListWidget->currentItem()->text();

	gt.rules.makeActivityTagPrintable(text);

	activityTagChanged(activityTagsListWidget->currentRow());
}

void ActivityTagsForm::notPrintableActivityTag()
{
	if(activityTagsListWidget->currentRow()<0){
		QMessageBox::information(this, tr("FET information"), tr("Invalid selected activity tag"));
		return;
	}

	QString text=activityTagsListWidget->currentItem()->text();

	gt.rules.makeActivityTagNotPrintable(text);

	activityTagChanged(activityTagsListWidget->currentRow());
}

void ActivityTagsForm::help()
{
	QMessageBox::information(this, tr("FET help on activity tags"),
	 tr("Activity tag is a field which can be used or not, depending on your wish (optional field)."
	 " It is designed to help you with some constraints. Each activity has a list of activity tags"
	 " (which may be empty)."));
}

void ActivityTagsForm::comments()
{
	int ind=activityTagsListWidget->currentRow();
	if(ind<0){
		QMessageBox::information(this, tr("FET information"), tr("Invalid selected activity tag"));
		return;
	}

	ActivityTag* at=gt.rules.activityTagsList[ind];
	assert(at!=NULL);

	QDialog getCommentsDialog(this);

	getCommentsDialog.setWindowTitle(tr("Activity tag comments"));

	QPushButton* okPB=new QPushButton(tr("OK"));
	okPB->setDefault(true);
	QPushButton* cancelPB=new QPushButton(tr("Cancel"));

	connect(okPB, SIGNAL(clicked()), &getCommentsDialog, SLOT(accept()));
	connect(cancelPB, SIGNAL(clicked()), &getCommentsDialog, SLOT(reject()));

	QHBoxLayout* hl=new QHBoxLayout();
	hl->addStretch();
	hl->addWidget(okPB);
	hl->addWidget(cancelPB);

	QVBoxLayout* vl=new QVBoxLayout();

	QPlainTextEdit* commentsPT=new QPlainTextEdit();
	commentsPT->setPlainText(at->comments);
	commentsPT->selectAll();
	commentsPT->setFocus();

	vl->addWidget(commentsPT);
	vl->addLayout(hl);

	getCommentsDialog.setLayout(vl);

	const QString settingsName=QString("ActivityTagCommentsDialog");

	getCommentsDialog.resize(500, 320);
	centerWidgetOnScreen(&getCommentsDialog);
	restoreFETDialogGeometry(&getCommentsDialog, settingsName);

	int t=getCommentsDialog.exec();
	saveFETDialogGeometry(&getCommentsDialog, settingsName);

	if(t==QDialog::Accepted){
		at->comments=commentsPT->toPlainText();

		gt.rules.internalStructureComputed=false;
		setRulesModifiedAndOtherThings(&gt.rules);

		activityTagChanged(ind);
	}
}
<|endoftext|>


<commit_before>// MaterialTests.cpp
#include <gtest/gtest.h>
#include "MaterialTests.h"
#include <cmath>

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MaterialTest, Constructors){
  EXPECT_EQ(test_mat_->units(), "kg");
  EXPECT_EQ(test_mat_->type(), MATERIAL_RES);
  EXPECT_GE(test_mat_->ID(),0);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MaterialTest, Clone) {
  rsrc_ptr clone_mat;
  ASSERT_NO_THROW(clone_mat = test_mat_->clone());

  // in order to acommodate discrete material tracking, all ID's mush be unique
  EXPECT_NE(test_mat_->ID(), clone_mat->ID());

  EXPECT_EQ(test_mat_->quantity(), clone_mat->quantity());
  EXPECT_EQ(test_mat_->type(), clone_mat->type());
  EXPECT_TRUE(test_mat_->checkQuality(clone_mat));
  EXPECT_DOUBLE_EQ(test_mat_->quantity(), clone_mat->quantity());
  EXPECT_TRUE(clone_mat->checkQuality(test_mat_));
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MaterialTest, CheckQuality) {
  rsrc_ptr test(test_mat_);
  rsrc_ptr diff(diff_mat_);
  rsrc_ptr gen(new GenericResource("kg", "foo", 10));

  EXPECT_TRUE(test->checkQuality(diff));
  EXPECT_TRUE(diff->checkQuality(test));
  EXPECT_FALSE(test->checkQuality(gen));
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MaterialTest, CheckIsoMass) {
  // check total mass, you'll use it later.
  EXPECT_FLOAT_EQ(test_mat_->quantity(),test_size_);

  // you should be able to get the mass per isotope
  EXPECT_NO_THROW(test_mat_->mass(u235_));

  // if the material has only one isotope, it should be the same as the total
  // the u235 mass should be (mol/mat)(1kg/1000g)(235g/mol)
  ASSERT_FLOAT_EQ(test_mat_->mass(u235_) , test_mat_->moles(u235_)*0.235);

  // if the mat has many isotopes, their individual masses should scale with
  // their atomic numbers.
  double test_total = 0;
  CompMap::iterator comp;
  int i;
  for( comp = (*test_comp_).begin(); comp != (*test_comp_).end(); ++comp){
    i = (*comp).first;
    test_total += test_mat_->mass(i);
  }
  ASSERT_FLOAT_EQ(test_mat_->quantity(), test_total);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MaterialTest, CheckIsoAtoms){

  // you should be able to get to the atoms of a certain iso in your material
  EXPECT_NO_THROW(test_mat_->moles(u235_));
  EXPECT_FLOAT_EQ(one_mol_,test_mat_->moles(u235_));

  // a mat's total atoms should be the total of all the contained isotopes.
  double test_total = 0;
  CompMap::iterator comp;
  int i;
  for( comp = (*test_comp_).begin(); comp != (*test_comp_).end(); ++comp){
    i = (*comp).first;
    total_atoms += test_mat_->moles(i);
  }
  ASSERT_FLOAT_EQ(test_mat_->moles(), test_total);

  // you should be able to get to the total atoms in your material
  total_atoms = test_mat_->moles();

}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MaterialTest, CheckConvertFromKg){
  // check total mass, you'll use it later.
  EXPECT_FLOAT_EQ(test_mat_->quantity(),test_size_);
  // you should be able to get the mass per isotope
  EXPECT_NO_THROW(test_mat_->mass(u235_));
  ASSERT_FLOAT_EQ(test_mat_->mass(u235_), test_mat_->mass(u235_,KG));
  ASSERT_FLOAT_EQ(1000.0*test_mat_->mass(u235_), test_mat_->mass(u235_,G));
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MaterialTest, CheckConvertToKg){
  // check total mass, you'll use it later.
  EXPECT_FLOAT_EQ(test_mat_->quantity(),test_size_);
  ASSERT_FLOAT_EQ(test_size_, test_mat_->mass(KG));
  EXPECT_NO_THROW(test_mat_->setQuantity(test_size_*1000.0,G));
  ASSERT_FLOAT_EQ(test_size_, test_mat_->mass(KG));
  EXPECT_NO_THROW(test_mat_->setQuantity(test_size_,G));
  ASSERT_FLOAT_EQ(test_size_, test_mat_->mass(KG)/1000.0);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MaterialTest, AbsorbLikeMaterial) {
  mat_rsrc_ptr one_test_mat;
  mat_rsrc_ptr two_test_mat;
  mat_rsrc_ptr ten_test_mat;
  one_test_mat = mat_rsrc_ptr(new Material(test_comp_));
  int one = 1;
  one_test_mat->setQuantity(one*test_size_);
  two_test_mat = mat_rsrc_ptr(new Material(test_comp_));
  int two = 2;
  two_test_mat->setQuantity(two*test_size_);
  ten_test_mat = mat_rsrc_ptr(new Material(test_comp_));
  int ten = 10;
  ten_test_mat->setQuantity(ten*test_size_);

  // see that two materials with the same composition do the right thing
  double orig = test_mat_->quantity();
  int factor = 1+one;
  ASSERT_NO_THROW(test_mat_->absorb(one_test_mat));
  EXPECT_FLOAT_EQ(test_mat_->quantity(), factor * orig );

  factor += two;
  ASSERT_NO_THROW(test_mat_->absorb(two_test_mat));
  EXPECT_FLOAT_EQ(test_mat_->quantity(), factor * orig );

  factor += ten;
  ASSERT_NO_THROW(test_mat_->absorb(ten_test_mat));
  EXPECT_FLOAT_EQ(test_mat_->quantity(), factor * orig );
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MaterialTest, AbsorbUnLikeMaterial) {
  // make a number of materials masses 1, 2, and 10
  mat_rsrc_ptr same_as_orig_test_mat = mat_rsrc_ptr(new Material(test_comp_));

  CompMapPtr diff_test_comp = CompMapPtr(new CompMap(MASS));
  (*diff_test_comp)[pb208_] = 1.0;
  (*diff_test_comp)[am241_] = 1.0;
  (*diff_test_comp)[th228_] = 1.0;
  mat_rsrc_ptr diff_test_mat = mat_rsrc_ptr(new Material(diff_test_comp));
  diff_test_mat->setQuantity(test_size_/2);

  double orig = test_mat_->quantity();
  double origdiff = diff_test_mat->quantity();

  // see that materials with different compositions do the right thing
  ASSERT_NO_THROW(test_mat_->absorb(diff_test_mat));
  EXPECT_FLOAT_EQ(orig + origdiff, test_mat_->quantity() );
  EXPECT_TRUE(std::abs(same_as_orig_test_mat->quantity() -
              test_mat_->quantity()) > EPS_KG);
  EXPECT_TRUE(same_as_orig_test_mat->checkQuality(test_mat_));
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MaterialTest, ExtractMass) {
  double amt = test_size_ / 3;
  double diff = test_size_ - amt;
  mat_rsrc_ptr extracted;
  EXPECT_FLOAT_EQ(test_mat_->quantity(),test_size_); // we expect this amt
  EXPECT_NO_THROW(extracted = test_mat_->extract(amt)); // extract an amt
  EXPECT_FLOAT_EQ(extracted->quantity(),amt); // check correctness
  EXPECT_FLOAT_EQ(test_mat_->quantity(),diff); // check correctness
  EXPECT_EQ(test_mat_->isoVector(),extracted->isoVector());
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MaterialTest, Extract) {
  mat_rsrc_ptr m1;
  ASSERT_NO_THROW(m1 = test_mat_->extract(test_comp_));
  EXPECT_FLOAT_EQ(test_mat_->quantity(), 0 );
  EXPECT_FLOAT_EQ(m1->quantity(), test_size_ );

  mat_rsrc_ptr m2;
  ASSERT_NO_THROW(m2 = diff_mat_->extract(test_comp_));
  EXPECT_FLOAT_EQ(diff_mat_->quantity(), test_size_*fraction );
  EXPECT_FLOAT_EQ(m2->quantity(), test_size_*(1-fraction) );

  // ASSERT_THROW(two_test_mat->extract(ten_test_comp), CycException);
}
<commit_msg>all tests compile<commit_after>// MaterialTests.cpp
#include <gtest/gtest.h>
#include "MaterialTests.h"
#include <cmath>

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MaterialTest, Constructors){
  EXPECT_EQ(test_mat_->units(), "kg");
  EXPECT_EQ(test_mat_->type(), MATERIAL_RES);
  EXPECT_GE(test_mat_->ID(),0);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MaterialTest, Clone) {
  rsrc_ptr clone_mat;
  ASSERT_NO_THROW(clone_mat = test_mat_->clone());

  // in order to acommodate discrete material tracking, all ID's mush be unique
  EXPECT_NE(test_mat_->ID(), clone_mat->ID());

  EXPECT_EQ(test_mat_->quantity(), clone_mat->quantity());
  EXPECT_EQ(test_mat_->type(), clone_mat->type());
  EXPECT_TRUE(test_mat_->checkQuality(clone_mat));
  EXPECT_DOUBLE_EQ(test_mat_->quantity(), clone_mat->quantity());
  EXPECT_TRUE(clone_mat->checkQuality(test_mat_));
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MaterialTest, CheckQuality) {
  rsrc_ptr test(test_mat_);
  rsrc_ptr diff(diff_mat_);
  rsrc_ptr gen(new GenericResource("kg", "foo", 10));

  EXPECT_TRUE(test->checkQuality(diff));
  EXPECT_TRUE(diff->checkQuality(test));
  EXPECT_FALSE(test->checkQuality(gen));
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MaterialTest, CheckIsoMass) {
  // check total mass, you'll use it later.
  EXPECT_FLOAT_EQ(test_mat_->quantity(),test_size_);

  // you should be able to get the mass per isotope
  EXPECT_NO_THROW(test_mat_->mass(u235_));

  // if the material has only one isotope, it should be the same as the total
  // the u235 mass should be (mol/mat)(1kg/1000g)(235g/mol)
  ASSERT_FLOAT_EQ(test_mat_->mass(u235_) , test_mat_->moles(u235_)*0.235);

  // if the mat has many isotopes, their individual masses should scale with
  // their atomic numbers.
  double test_total = 0;
  CompMap::iterator comp;
  int i;
  for( comp = (*test_comp_).begin(); comp != (*test_comp_).end(); ++comp){
    i = (*comp).first;
    test_total += test_mat_->mass(i);
  }
  ASSERT_FLOAT_EQ(test_mat_->quantity(), test_total);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MaterialTest, CheckIsoAtoms){

  // you should be able to get to the atoms of a certain iso in your material
  EXPECT_NO_THROW(test_mat_->moles(u235_));
  EXPECT_FLOAT_EQ(one_mol_,test_mat_->moles(u235_));

  // a mat's total atoms should be the total of all the contained isotopes.
  double total_atoms = 0;
  CompMap::iterator comp;
  int i;
  for( comp = (*test_comp_).begin(); comp != (*test_comp_).end(); ++comp){
    i = (*comp).first;
    total_atoms += test_mat_->moles(i);
  }
  // you should be able to get to the total atoms in your material
  ASSERT_FLOAT_EQ(test_mat_->moles(), total_atoms);

}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MaterialTest, CheckConvertFromKg){
  // check total mass, you'll use it later.
  EXPECT_FLOAT_EQ(test_mat_->quantity(),test_size_);
  // you should be able to get the mass per isotope
  EXPECT_NO_THROW(test_mat_->mass(u235_));
  ASSERT_FLOAT_EQ(test_mat_->mass(u235_), test_mat_->mass(u235_,KG));
  ASSERT_FLOAT_EQ(1000.0*test_mat_->mass(u235_), test_mat_->mass(u235_,G));
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MaterialTest, CheckConvertToKg){
  // check total mass, you'll use it later.
  EXPECT_FLOAT_EQ(test_mat_->quantity(),test_size_);
  ASSERT_FLOAT_EQ(test_size_, test_mat_->mass(KG));
  EXPECT_NO_THROW(test_mat_->setQuantity(test_size_*1000.0,G));
  ASSERT_FLOAT_EQ(test_size_, test_mat_->mass(KG));
  EXPECT_NO_THROW(test_mat_->setQuantity(test_size_,G));
  ASSERT_FLOAT_EQ(test_size_, test_mat_->mass(KG)/1000.0);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MaterialTest, AbsorbLikeMaterial) {
  mat_rsrc_ptr one_test_mat;
  mat_rsrc_ptr two_test_mat;
  mat_rsrc_ptr ten_test_mat;
  one_test_mat = mat_rsrc_ptr(new Material(test_comp_));
  int one = 1;
  one_test_mat->setQuantity(one*test_size_);
  two_test_mat = mat_rsrc_ptr(new Material(test_comp_));
  int two = 2;
  two_test_mat->setQuantity(two*test_size_);
  ten_test_mat = mat_rsrc_ptr(new Material(test_comp_));
  int ten = 10;
  ten_test_mat->setQuantity(ten*test_size_);

  // see that two materials with the same composition do the right thing
  double orig = test_mat_->quantity();
  int factor = 1+one;
  ASSERT_NO_THROW(test_mat_->absorb(one_test_mat));
  EXPECT_FLOAT_EQ(test_mat_->quantity(), factor * orig );

  factor += two;
  ASSERT_NO_THROW(test_mat_->absorb(two_test_mat));
  EXPECT_FLOAT_EQ(test_mat_->quantity(), factor * orig );

  factor += ten;
  ASSERT_NO_THROW(test_mat_->absorb(ten_test_mat));
  EXPECT_FLOAT_EQ(test_mat_->quantity(), factor * orig );
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MaterialTest, AbsorbUnLikeMaterial) {
  // make a number of materials masses 1, 2, and 10
  mat_rsrc_ptr same_as_orig_test_mat = mat_rsrc_ptr(new Material(test_comp_));

  CompMapPtr diff_test_comp = CompMapPtr(new CompMap(MASS));
  (*diff_test_comp)[pb208_] = 1.0;
  (*diff_test_comp)[am241_] = 1.0;
  (*diff_test_comp)[th228_] = 1.0;
  mat_rsrc_ptr diff_test_mat = mat_rsrc_ptr(new Material(diff_test_comp));
  diff_test_mat->setQuantity(test_size_/2);

  double orig = test_mat_->quantity();
  double origdiff = diff_test_mat->quantity();

  // see that materials with different compositions do the right thing
  ASSERT_NO_THROW(test_mat_->absorb(diff_test_mat));
  EXPECT_FLOAT_EQ(orig + origdiff, test_mat_->quantity() );
  EXPECT_TRUE(std::abs(same_as_orig_test_mat->quantity() -
              test_mat_->quantity()) > EPS_KG);
  EXPECT_TRUE(same_as_orig_test_mat->checkQuality(test_mat_));
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MaterialTest, ExtractMass) {
  double amt = test_size_ / 3;
  double diff = test_size_ - amt;
  mat_rsrc_ptr extracted;
  EXPECT_FLOAT_EQ(test_mat_->quantity(),test_size_); // we expect this amt
  EXPECT_NO_THROW(extracted = test_mat_->extract(amt)); // extract an amt
  EXPECT_FLOAT_EQ(extracted->quantity(),amt); // check correctness
  EXPECT_FLOAT_EQ(test_mat_->quantity(),diff); // check correctness
  EXPECT_EQ(test_mat_->isoVector(),extracted->isoVector());
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MaterialTest, Extract) {
  mat_rsrc_ptr m1;
  ASSERT_NO_THROW(m1 = test_mat_->extract(test_comp_));
  EXPECT_FLOAT_EQ(test_mat_->quantity(), 0 );
  EXPECT_FLOAT_EQ(m1->quantity(), test_size_ );

  mat_rsrc_ptr m2;
  ASSERT_NO_THROW(m2 = diff_mat_->extract(test_comp_));
  EXPECT_FLOAT_EQ(diff_mat_->quantity(), test_size_*fraction );
  EXPECT_FLOAT_EQ(m2->quantity(), test_size_*(1-fraction) );

  // ASSERT_THROW(two_test_mat->extract(ten_test_comp), CycException);
}
<|endoftext|>


<commit_before>#include "Support/IRPrettyPrinter.h"
#include "IR/Type.h"
#include "IR/Value.h"
#include "IR/Instruction.h"
#include "IR/BasicBlock.h"
#include "IR/Constants.h"

IRPrettyPrinter::IRPrettyPrinter(BasicBlock const* bb, std::ostream& out) :
    bb_(bb), out_(out)
{
}

IRPrettyPrinter::~IRPrettyPrinter() {
}

void IRPrettyPrinter::prettyPrint() {
    printBasicBlock(bb_);
}

void IRPrettyPrinter::printValue(Value const* v) {
    switch (v->getValueType()) {
    case Value::BasicBlockV:
        printBasicBlock(dynamic_cast<BasicBlock const*>(v));
        break;

    case Value::InstructionV:
        printInstruction(dynamic_cast<Instruction const*>(v));
        break;

    default:
        out_ << "<unknown value>\n";
        break;
    }
}

void IRPrettyPrinter::printBasicBlock(BasicBlock const* bb) {
    out_ << bb->getName() << ":\n";
    for (Value const* v : *bb) {
        printValue(v);
    }
}

void IRPrettyPrinter::printInstruction(Instruction const* inst) {
    if (inst->isBinaryOp()) {
        BinaryOperator const* binst = dynamic_cast<BinaryOperator const*>(inst);
        out_ << "    "
             << binst->getName() << " = "
             << binst->getOpcodeName() << ' '
             //<< typeToString(binst->getType()) << ' '
             << binst->getLHS()->getName() << ", "
             << binst->getRHS()->getName() << '\n';
    }
}

std::string IRPrettyPrinter::typeToString(Type const* type) {
    if (type == Type::getInt64Ty())
        return "i64";
    return "utype";
}
<commit_msg>Fix IRPrettyPrinter<commit_after>#include "Support/IRPrettyPrinter.h"
#include "IR/Type.h"
#include "IR/Value.h"
#include "IR/Instruction.h"
#include "IR/BasicBlock.h"
#include "IR/Constants.h"

IRPrettyPrinter::IRPrettyPrinter(BasicBlock const* bb, std::ostream& out) :
    bb_(bb), out_(out)
{
}

IRPrettyPrinter::~IRPrettyPrinter() {
}

void IRPrettyPrinter::prettyPrint() {
    printBasicBlock(bb_);
}

void IRPrettyPrinter::printValue(Value const* v) {
    switch (v->getValueType()) {
    case Value::BasicBlockV:
        printBasicBlock(dynamic_cast<BasicBlock const*>(v));
        break;

    case Value::InstructionV:
        printInstruction(dynamic_cast<Instruction const*>(v));
        break;

    default:
        out_ << "<unknown value>\n";
        break;
    }
}

void IRPrettyPrinter::printBasicBlock(BasicBlock const* bb) {
    out_ << bb->getName() << ":\n";
    for (Value const* v : *bb) {
        printValue(v);
    }
}

void IRPrettyPrinter::printInstruction(Instruction const* inst) {
    if (inst->isBinaryOp()) {
        BinaryOperator const* binst = dynamic_cast<BinaryOperator const*>(inst);
        out_ << "    "
             << binst->getName() << " = "
             << binst->getOpcodeName() << ' '
             << typeToString(binst->getType()) << ' '
             << binst->getLHS()->getName() << ", "
             << binst->getRHS()->getName() << '\n';
    }
}

std::string IRPrettyPrinter::typeToString(Type const* type) {
    if (type == Type::getInt64Ty())
        return "i64";
    return "utype";
}
<|endoftext|>