Exemple #1
0
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)

{
	GDIWorker::Init(); //Initialization gdi+
	MSG msg;
	HWND hwnd;
	RECT rect;
	Game* game = new Game();

	WNDCLASS wc;

	wc.style = 0;
	wc.lpfnWndProc = WndProc;
	wc.cbClsExtra = 0L;
	wc.cbWndExtra = 0L;
	wc.hInstance = hInstance;
	wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
	wc.hCursor = LoadCursor(NULL, IDC_ARROW);
	wc.hbrBackground = GetStockBrush(BLACK_BRUSH);
	wc.lpszMenuName = NULL;//MAKEINTRESOURSE(IDR_MENU1);
	wc.lpszClassName = L"GameWindow";

	RegisterClass(&wc);
//--------------------------------
	GetClientRect(GetDesktopWindow(), &rect);

	hwnd = CreateWindow(
		L"GameWindow",
		L"Puzzle 14.88",
		WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX,
		(rect.right / 2) - 300,	20,	600, 600,
		HWND_DESKTOP,
		NULL,
		GetModuleHandle(0),
		game);

	GetClientRect(hwnd, &rect);
	
	ShowWindow(hwnd, nCmdShow);
//--------------------------------		
	
	game->Initialize();
	game->Render();

	while (GetMessage(&msg, NULL, 0, 0))
	{
		int timeStart = (int)GetTickCount64(); 

		TranslateMessage(&msg);
		DispatchMessage(&msg);
		
		while ((GetTickCount64() - timeStart) < MS_PER_FRAME)
		{
			int pause = (MS_PER_FRAME - (GetTickCount64() - timeStart));
			if (pause < 0)
				break;
			Sleep(pause);
		}
	}
	
	ResourceManager::GetInstance().DestroyTextures();
	GDIWorker::Destroy();
	return 0;
}
Exemple #2
0
//
//  FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM)
//
//  PURPOSE:  Processes messages for the main window.
//
//  WM_COMMAND	- process the application menu
//  WM_PAINT	- Paint the main window
//  WM_DESTROY	- post a quit message and return
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	int wmId, wmEvent;
	PAINTSTRUCT ps;
	HDC hdc;

	switch (message)
	{
	case WM_CREATE:
		SetTimer(hWnd, 0, 1000, NULL);
		Director::getDirector().hWnd = hWnd;
		Director::getDirector().playBackgroundMusic();
		std::srand(GetTickCount64());
		
	case WM_COMMAND:
		wmId    = LOWORD(wParam);
		wmEvent = HIWORD(wParam);
		// Parse the menu selections:
		switch (wmId)
		{
		case IDM_ABOUT:
			DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
			break;
		case IDM_EXIT:
			DestroyWindow(hWnd);
			break;
		default:
			return DefWindowProc(hWnd, message, wParam, lParam);
		}
		break;
	case WM_PAINT:
		hdc = BeginPaint(hWnd, &ps);
		Director::getDirector().update();
		EndPaint(hWnd, &ps); 
		break;
	case WM_DESTROY:
		PostQuitMessage(0);
		break;
	case WM_LBUTTONDOWN:
		Director::getDirector().mouseDownEvent();
		break;
	case WM_LBUTTONUP:
		Director::getDirector().mouseUpEvent();
		break;
	case WM_MOUSEMOVE:
		Director::getDirector().mouseX = GET_X_LPARAM(lParam);
		Director::getDirector().mouseY = GET_Y_LPARAM(lParam);
		Director::getDirector().mouseMove();
		break;
	case WM_KEYDOWN:
		switch (wParam)
		{
		case 0x53://S
			Director::getDirector().startGame();
			break;
		case 0x51://Q
			Director::getDirector().stopGame();
			break;
		}
		break;
	case WM_TIMER:
		
		Director::getDirector().timerEvent();
		
		break;
	default:
		return DefWindowProc(hWnd, message, wParam, lParam);
	}
	return 0;
}
Exemple #3
0
void HandleSysCommand(WPARAM wParam, HWND hwnd)
{
	if (wParam == MOVETOMENU_NEW)
	{
		// abort command, too many commands in a short period of time
		if (nLastCommand > GetTickCount64())
		{
			return;
		}
		Log("Getting RootWindow of %X", hwnd);
		HWND rootHwnd = GetAncestor(hwnd, GA_ROOTOWNER);
		if (rootHwnd != NULL)
		{
			hwnd = rootHwnd;
		}

		Log("Moving %X to new", hwnd);
		IVirtualDesktop *pNewDesktop = nullptr;
		HRESULT hr = pDesktopManagerInternal->CreateDesktopW(&pNewDesktop);
		if (FAILED(hr))
		{
			return;
		}
		GUID id;
		hr = pNewDesktop->GetID(&id);
		if (SUCCEEDED(hr))
		{
			HWND focusHwnd = NULL;
			if (!bSwitchDesktopAfterMove)
			{
				focusHwnd = hwnd;
				do
				{
					focusHwnd = GetNextWindow(focusHwnd, GW_HWNDNEXT);
				} while (focusHwnd && EnumWindowsProc(focusHwnd, NULL));
			}

			Log("pDesktopManager->MoveWindowToDesktop(%X, %X)", hwnd, id);
			hr = pDesktopManager->MoveWindowToDesktop(hwnd, id);
			if (SUCCEEDED(hr))
			{
				if (bSwitchDesktopAfterMove)
				{
					pDesktopManagerInternal->SwitchDesktop(pNewDesktop);
				}
				else if (focusHwnd)
				{
					SetForegroundWindow(focusHwnd);
				}
			}
			else
			{
				Log("Error %d on moving %X to %X", hr, hwnd, id);
			}
		}
		pNewDesktop->Release();
		nLastCommand = GetTickCount64() + COMMAND_TIMEOUT;
	}
	else if (wParam >= MOVETOMENU_START && wParam <= MOVETOMENU_LAST)
	{
		// abort command, too many commands in a short period of time
		if (nLastCommand > GetTickCount64())
		{
			return;
		}
		Log("Getting RootWindow of %X", hwnd);
		HWND rootHwnd = GetAncestor(hwnd, GA_ROOTOWNER);
		if (rootHwnd != NULL)
		{
			hwnd = rootHwnd;
		}

		Log("Moving %X to %X", hwnd, wParam);
		IObjectArray *pObjectArray = nullptr;
		HRESULT hr = pDesktopManagerInternal->GetDesktops(&pObjectArray);
		if (FAILED(hr))
		{
			Log("Failed to get desktops for %X", hwnd);
			return;
		}

		IVirtualDesktop *pDesktop = nullptr;
		if (SUCCEEDED(pObjectArray->GetAt((UINT)wParam - MOVETOMENU_START, __uuidof(IVirtualDesktop), (void**)&pDesktop)))
		{
			GUID id;
			hr = pDesktop->GetID(&id);

			if (SUCCEEDED(hr))
			{
				HWND focusHwnd = NULL;
				if (!bSwitchDesktopAfterMove)
				{
					focusHwnd = hwnd;
					do
					{
						focusHwnd = GetNextWindow(focusHwnd, GW_HWNDNEXT);
					} while (focusHwnd && EnumWindowsProc(focusHwnd, NULL));
				}

				Log("pDesktopManager->MoveWindowToDesktop(%X, %X)", hwnd, id);
				hr = pDesktopManager->MoveWindowToDesktop(hwnd, id);
				if (SUCCEEDED(hr))
				{
					// If there are no windows delete the desktop
					if (bDeleteEmptyDesktops)
					{
						IVirtualDesktop *pCurrentDesktop = nullptr;
						hr = pDesktopManagerInternal->GetCurrentDesktop(&pCurrentDesktop);
						if (SUCCEEDED(hr))
						{
							if (pCurrentDesktop != pDesktop)
							{
								if (EnumWindows((WNDENUMPROC)EnumWindowsProc, NULL) != FALSE)
								{
									Log("Removing Desktop");
									pDesktopManagerInternal->RemoveDesktop(pCurrentDesktop, pDesktop);
								}
							}
							pCurrentDesktop->Release();
						}
					}

					if (bSwitchDesktopAfterMove)
					{
						pDesktopManagerInternal->SwitchDesktop(pDesktop);
					}
					else if (focusHwnd != NULL)
					{
						SetForegroundWindow(focusHwnd);
					}
				}
				else
				{
					Log("Error %X on moving %X to %X", hr, hwnd, id);
				}
			}
			pDesktop->Release();
		}
		pObjectArray->Release();
		nLastCommand = GetTickCount64() + COMMAND_TIMEOUT;
	}
	else if (wParam == MOVETOMENU_LEFT)
	{
		UINT count;
		int index = GetCurrentDesktopIndex(&count);
		Log("Current Index is %d", index);
		Log("Current Count is %d", count);
		if (index == -1)
			return;
		if (index == MOVETOMENU_START)
			return;
		Log("Switch to %d", index - 1);
		HandleSysCommand(--index, hwnd);
	}
	else if (wParam == MOVETOMENU_RIGHT)
	{
		UINT count;
		int index = GetCurrentDesktopIndex(&count);
		Log("Current Index is %d", index);
		Log("Current Count is %d", count);
		if (index == -1)
			return;
		if (index == MOVETOMENU_LAST)
			return;
		if ((++index) <= (int)(count + MOVETOMENU_NEW))
		{
			Log("Switch to %d", index);
			HandleSysCommand(index, hwnd);

		}
		else if (bCreateNewDesktopOnMove)
		{
			Log("Create new desktop");
			HandleSysCommand(MOVETOMENU_NEW, hwnd);
		}
	}
}
bool CDirectoryWatcher::AddPath(const CTGitPath& path, bool bCloseInfoMap)
{
	if (!CGitStatusCache::Instance().IsPathAllowed(path))
		return false;
	if ((!blockedPath.IsEmpty())&&(blockedPath.IsAncestorOf(path)))
	{
		if (GetTickCount64() < blockTickCount)
		{
			CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": Path %s prevented from being watched\n"), path.GetWinPath());
			return false;
		}
	}

	if (path.GetWinPathString().Find(L":\\RECYCLER\\") >= 0)
		return false;
	if (path.GetWinPathString().Find(L":\\$Recycle.Bin\\") >= 0)
		return false;

	AutoLocker lock(m_critSec);
	for (int i=0; i<watchedPaths.GetCount(); ++i)
	{
		if (watchedPaths[i].IsAncestorOf(path))
			return false;		// already watched (recursively)
	}

	// now check if with the new path we might have a new root
	CTGitPath newroot;
	for (int i=0; i<watchedPaths.GetCount(); ++i)
	{
		const CString& watched = watchedPaths[i].GetWinPathString();
		const CString& sPath = path.GetWinPathString();
		int minlen = min(sPath.GetLength(), watched.GetLength());
		int len = 0;
		for (len = 0; len < minlen; ++len)
		{
			if (watched.GetAt(len) != sPath.GetAt(len))
			{
				if ((len > 1)&&(len < minlen))
				{
					if (sPath.GetAt(len)=='\\')
					{
						newroot = CTGitPath(sPath.Left(len));
					}
					else if (watched.GetAt(len)=='\\')
					{
						newroot = CTGitPath(watched.Left(len));
					}
				}
				break;
			}
		}
		if (len == minlen)
		{
			if (sPath.GetLength() == minlen)
			{
				if (watched.GetLength() > minlen)
				{
					if (watched.GetAt(len)=='\\')
					{
						newroot = path;
					}
					else if (sPath.GetLength() == 3 && sPath[1] == ':')
					{
						newroot = path;
					}
				}
			}
			else
			{
				if (sPath.GetLength() > minlen)
				{
					if (sPath.GetAt(len)=='\\')
					{
						newroot = CTGitPath(watched);
					}
					else if (watched.GetLength() == 3 && watched[1] == ':')
					{
						newroot = CTGitPath(watched);
					}
				}
			}
		}
	}
	if (!newroot.IsEmpty())
	{
		CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": add path to watch %s\n"), newroot.GetWinPath());
		watchedPaths.AddPath(newroot);
		watchedPaths.RemoveChildren();
		if (bCloseInfoMap)
			ClearInfoMap();

		return true;
	}
	CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": add path to watch %s\n"), path.GetWinPath());
	watchedPaths.AddPath(path);
	if (bCloseInfoMap)
		ClearInfoMap();

	return true;
}
Exemple #5
0
bool CCacheDlg::GetStatusFromRemoteCache(const CTGitPath& Path, bool bRecursive)
{
	if(!EnsurePipeOpen())
	{
		STARTUPINFO startup = { 0 };
		PROCESS_INFORMATION process = { 0 };
		startup.cb = sizeof(startup);

		CString sCachePath = L"TGitCache.exe";
		if (CreateProcess(sCachePath.GetBuffer(sCachePath.GetLength() + 1), L"", nullptr, nullptr, FALSE, 0, nullptr, nullptr, &startup, &process) == 0)
		{
			// It's not appropriate to do a message box here, because there may be hundreds of calls
			sCachePath.ReleaseBuffer();
			ATLTRACE("Failed to start cache\n");
			return false;
		}
		sCachePath.ReleaseBuffer();

		// Wait for the cache to open
		ULONGLONG endTime = GetTickCount64()+1000;
		while(!EnsurePipeOpen())
		{
			if((GetTickCount64() - endTime) > 0)
			{
				return false;
			}
		}
	}


	DWORD nBytesRead;
	TGITCacheRequest request;
	request.flags = TGITCACHE_FLAGS_NONOTIFICATIONS;
	if(bRecursive)
	{
		request.flags |= TGITCACHE_FLAGS_RECUSIVE_STATUS;
	}
	wcsncpy_s(request.path, Path.GetWinPath(), MAX_PATH);
	SecureZeroMemory(&m_Overlapped, sizeof(OVERLAPPED));
	m_Overlapped.hEvent = m_hEvent;
	// Do the transaction in overlapped mode.
	// That way, if anything happens which might block this call
	// we still can get out of it. We NEVER MUST BLOCK THE SHELL!
	// A blocked shell is a very bad user impression, because users
	// who don't know why it's blocked might find the only solution
	// to such a problem is a reboot and therefore they might loose
	// valuable data.
	// Sure, it would be better to have no situations where the shell
	// even can get blocked, but the timeout of 5 seconds is long enough
	// so that users still recognize that something might be wrong and
	// report back to us so we can investigate further.

	TGITCacheResponse ReturnedStatus;
	BOOL fSuccess = TransactNamedPipe(m_hPipe,
		&request, sizeof(request),
		&ReturnedStatus, sizeof(ReturnedStatus),
		&nBytesRead, &m_Overlapped);

	if (!fSuccess)
	{
		if (GetLastError()!=ERROR_IO_PENDING)
		{
			ClosePipe();
			return false;
		}

		// TransactNamedPipe is working in an overlapped operation.
		// Wait for it to finish
		DWORD dwWait = WaitForSingleObject(m_hEvent, INFINITE);
		if (dwWait == WAIT_OBJECT_0)
		{
			fSuccess = GetOverlappedResult(m_hPipe, &m_Overlapped, &nBytesRead, FALSE);
			return TRUE;
		}
		else
			fSuccess = FALSE;
	}

	ClosePipe();
	return false;
}
Exemple #6
0
void getMenu(char* displayStatsMenu, int size)
{
	if (size < 400)
	{
		return;
	}

	sprintf_s(displayStatsMenu, size, "AC deleted: %6d Requests made: %6d Last deleted: %6lld seconds ago\0", stats.nrOfDeletions, stats.nrOfRequests, stats.lastDeleted == 0 ? 0 : (GetTickCount64() - stats.lastDeleted) / 1000);
	strcpy_s(displayStatsMenu + 74, size-74, "AI Deleter Settings\0");
	sprintf_s(displayStatsMenu + 94, size - 94, "Slow down check rate by 30 seconds (currently every %5d seconds)\0", conf.requestEveryXSec);
	strcpy_s(displayStatsMenu + 161, size - 161, "Speed up check rate by 30 seconds\0");
	sprintf_s(displayStatsMenu + 195, size - 195, "Increase range by 5000m (currently within %6d meters)\0", conf.radius);
	strcpy_s(displayStatsMenu + 252, size - 252, "Reduce range by 5000m\0");
	sprintf_s(displayStatsMenu + 274, size - 274, "Reduce allowed ETD by 1 hour (currently at most %6.2f hours from now)\0", float(conf.maxetd) / 3600.0);
	strcpy_s(displayStatsMenu + 345, size - 345, "Increase allowed ETD by 1 hour\0");
	strcpy_s(displayStatsMenu + 376, size - 376, "Just close window\0");
}
Exemple #7
0
static void set_repeat_time(void)
{
	uint64_t ticks = GetTickCount64();
	next_publish_tv = ticks + cfg.repeat_delay.tv_sec*1000 + cfg.repeat_delay.tv_usec/1000;
}
Exemple #8
0
bool		WinTimer::isUp()
{
	if (this->_t >= GetTickCount64())
		return (true);
	return (false);
}
Exemple #9
0
BOOL ShellCache::IsPathAllowed(LPCTSTR path)
{
	ValidatePathFilter();
	Locker lock(m_critSec);
	tristate_t allowed = pathFilter.IsPathAllowed(path);
	if (allowed != tristate_unknown)
		return allowed == tristate_true ? TRUE : FALSE;

	UINT drivetype = 0;
	int drivenumber = PathGetDriveNumber(path);
	if ((drivenumber >= 0) && (drivenumber < 25))
	{
		drivetype = drivetypecache[drivenumber];
		if ((drivetype == -1) || ((GetTickCount64() - drivetypeticker) > DRIVETYPETIMEOUT))
		{
			if ((DWORD(drivefloppy) == 0) && ((drivenumber == 0) || (drivenumber == 1)))
				drivetypecache[drivenumber] = DRIVE_REMOVABLE;
			else
			{
				drivetypeticker = GetTickCount64();
				TCHAR pathbuf[MAX_PATH + 4] = { 0 };		// MAX_PATH ok here. PathStripToRoot works with partial paths too.
				wcsncpy_s(pathbuf, path, _countof(pathbuf) - 1);
				PathStripToRoot(pathbuf);
				PathAddBackslash(pathbuf);
				CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) L": GetDriveType for %s, Drive %d\n", pathbuf, drivenumber);
				drivetype = GetDriveType(pathbuf);
				drivetypecache[drivenumber] = drivetype;
			}
		}
	}
	else
	{
		TCHAR pathbuf[MAX_PATH + 4] = { 0 };		// MAX_PATH ok here. PathIsUNCServer works with partial paths too.
		wcsncpy_s(pathbuf, path, _countof(pathbuf) - 1);
		if (PathIsUNCServer(pathbuf))
			drivetype = DRIVE_REMOTE;
		else
		{
			PathStripToRoot(pathbuf);
			PathAddBackslash(pathbuf);
			if (wcsncmp(pathbuf, drivetypepathcache, MAX_PATH - 1) == 0) // MAX_PATH ok.
				drivetype = drivetypecache[26];
			else
			{
				CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) L"GetDriveType for %s\n", pathbuf);
				drivetype = GetDriveType(pathbuf);
				drivetypecache[26] = drivetype;
				wcsncpy_s(drivetypepathcache, pathbuf, MAX_PATH - 1); // MAX_PATH ok.
			}
		}
	}
	if ((drivetype == DRIVE_REMOVABLE) && (!IsRemovable()))
		return FALSE;
	if ((drivetype == DRIVE_FIXED) && (!IsFixed()))
		return FALSE;
	if (((drivetype == DRIVE_REMOTE) || (drivetype == DRIVE_NO_ROOT_DIR)) && (!IsRemote()))
		return FALSE;
	if ((drivetype == DRIVE_CDROM) && (!IsCDRom()))
		return FALSE;
	if ((drivetype == DRIVE_RAMDISK) && (!IsRAM()))
		return FALSE;
	if ((drivetype == DRIVE_UNKNOWN) && (IsUnknown()))
		return FALSE;

	return TRUE;
}
Exemple #10
0
/***********************************************************************
 *           GetTickCount       ([email protected])
 *
 * Get the number of milliseconds the system has been running.
 *
 * PARAMS
 *  None.
 *
 * RETURNS
 *  The current tick count.
 *
 * NOTES
 *  The value returned will wrap around every 2^32 milliseconds.
 */
DWORD WINAPI GetTickCount(void)
{
    return GetTickCount64();
}
Exemple #11
0
void		WinTimer::setTimerAt(int time)
{
	this->_t = GetTickCount64();
	this->_t += time;
}
Exemple #12
0
static int
Win32_GetTickCount(Jim_Interp *interp, int objc, Jim_Obj * const *objv)
{
    Jim_SetResult(interp, Jim_NewIntObj(interp, GetTickCount64()));
    return JIM_OK;
}
Exemple #13
0
uint64_t gfwx_GetTime(void)
{
	return (uint64_t) GetTickCount64();
}
Exemple #14
0
int main(int argc, char *argv[])
{
	ERR_VALUE ret = ERR_INTERNAL_ERROR;

	utils_allocator_init(omp_get_num_procs());
	omp_init_lock(&_readCoverageLock);
#ifdef _MSC_VER
	uint64_t startTime = GetTickCount64();
#endif
	ret = options_module_init(37);
	if (ret == ERR_SUCCESS) {
		ret = _init_default_values();
		if (ret == ERR_SUCCESS) {
			ret = options_parse_command_line(argc - 2, argv + 2);
			if (ret == ERR_SUCCESS) {
				PROGRAM_OPTIONS po;
				PROGRAM_STATISTICS st;

				memset(&st, 0, sizeof(st));
				ret = _capture_program_options(&po);
				if (ret == ERR_SUCCESS) {
					omp_set_num_threads(po.OMPThreads);
					const char *cmd = argv[1];
					if (strncmp(cmd, "help", sizeof("help")) == 0) {
						options_print_help();
					} else if (strncmp(cmd, "repair", sizeof("repair")) == 0) {
						size_t refSeqLen = 0;
						FASTA_FILE seqFile;
						char *rsFasta = NULL;

						ret = fasta_load(po.RefSeqFile, &seqFile);
						if (ret == ERR_SUCCESS) {
							ret = fasta_read_seq(&seqFile, &rsFasta, &refSeqLen);
							po.ReferenceSequence = rsFasta;
							if (ret != ERR_SUCCESS)
								fasta_free(&seqFile);
						}

						if (ret == ERR_SUCCESS) {
							ret = utils_calloc(omp_get_num_procs(), sizeof(PUTILS_LOOKASIDE), &_vertexLAs);
							if (ret == ERR_SUCCESS)
								ret = utils_calloc(omp_get_num_procs(), sizeof(PUTILS_LOOKASIDE), &_edgeLAs);

							if (ret == ERR_SUCCESS) {
								ret = utils_calloc(omp_get_num_procs(), sizeof(GEN_ARRAY_ONE_READ), &po.ReadSubArrays);
								if (ret == ERR_SUCCESS) {
									const size_t numThreads = omp_get_num_procs();
									for (size_t i = 0; i < numThreads; ++i) {
										dym_array_init_ONE_READ(po.ReadSubArrays + i, 140);
										_vertexLAs[i] = NULL;
										_edgeLAs[i] = NULL;
									}

									size_t regionCount = 0;
									PACTIVE_REGION regions = NULL;

									ret = input_refseq_to_regions(po.ReferenceSequence, refSeqLen, &regions, &regionCount);
									if (ret == ERR_SUCCESS) {
										const ACTIVE_REGION *pa = NULL;

										pa = regions;
										for (size_t i = 0; i < regionCount; ++i) {
											if (pa->Type == artValid && pa->Length >= po.RegionLength)
												_activeRegionCount += (pa->Length / po.TestStep);

											++pa;
										}

										_activeRegionProcessed = 0;
										pa = regions;
										for (size_t i = 0; i < regionCount; ++i) {
											if (pa->Type == artValid && pa->Length >= po.RegionLength)
												repair_reads_in_parallel(pa, &po);
													
											++pa;
										}

										input_free_regions(regions, regionCount);
									}

									PONE_READ r = po.Reads;
									for (size_t i = 0; i < po.ReadCount; ++i) {
										if (r->NumberOfFixes * 100 / r->ReadSequenceLen <= po.ParseOptions.ReadMaxErrorRate) {
											read_quality_encode(r);
											read_write_sam(stdout, r);
											read_quality_decode(r);
										}

										++r;
									}

									utils_free(rsFasta);
									int i = 0;
#pragma omp parallel for shared (po)
									for (i = 0; i < numThreads; ++i)
										dym_array_finit_ONE_READ(po.ReadSubArrays + i);

									utils_free(po.ReadSubArrays);
								}
							}

							utils_free(_edgeLAs);
							utils_free(_vertexLAs);
							fasta_free(&seqFile);
						}
					} else if (strncmp(cmd, "rfreq", sizeof("rfreq")) == 0) {
						kmer_freq_distribution(&po, po.KMerSize, po.Reads, po.ReadCount);
					} else if (strncmp(cmd, "call", sizeof("call")) == 0) {
						fprintf(stderr, "K-mer size:                 %u\n", po.KMerSize);
						fprintf(stderr, "Active region length:       %u\n", po.RegionLength);
						fprintf(stderr, "Reference:                  %s\n", po.RefSeqFile);
						fprintf(stderr, "Reads:                      %u\n", po.ReadCount);
						fprintf(stderr, "Read coverage threshold:    %u\n", po.Threshold);
						fprintf(stderr, "Min. read position quality: %u\n", po.ReadPosQuality);
						fprintf(stderr, "OpenMP thread count:        %i\n", po.OMPThreads);
						fprintf(stderr, "Output VCF file:            %s\n", po.VCFFile);
						ret = paired_reads_init();
						if (ret == ERR_SUCCESS) {
							if (ret == ERR_SUCCESS) {
								size_t refSeqLen = 0;
								FASTA_FILE seqFile;
								char *rsFasta = NULL;

								ret = fasta_load(po.RefSeqFile, &seqFile);
								if (ret == ERR_SUCCESS) {
									ret = fasta_read_seq(&seqFile, &rsFasta, &refSeqLen);
									po.ReferenceSequence = rsFasta;
									if (ret != ERR_SUCCESS)
										fasta_free(&seqFile);
								}

								if (ret == ERR_SUCCESS) {
									po.VCFFileHandle = NULL;
									if (*po.VCFFile != '\0') {
										ret = utils_fopen(po.VCFFile, FOPEN_MODE_WRITE, &po.VCFFileHandle);
										if (ret == ERR_SUCCESS)
											dym_array_init_VARIANT_CALL(&po.VCArray, 140);
									}

									if (ret == ERR_SUCCESS) {
										ret = utils_calloc(omp_get_num_procs(), sizeof(PUTILS_LOOKASIDE), &_vertexLAs);
										if (ret == ERR_SUCCESS)
											ret = utils_calloc(omp_get_num_procs(), sizeof(PUTILS_LOOKASIDE), &_edgeLAs);
										
										ret = utils_calloc(omp_get_num_procs(), sizeof(GEN_ARRAY_VARIANT_CALL), &po.VCSubArrays);
										if (ret == ERR_SUCCESS) {
											ret = utils_calloc(omp_get_num_procs(), sizeof(GEN_ARRAY_ONE_READ), &po.ReadSubArrays);
											if (ret == ERR_SUCCESS) {
												const size_t numThreads = omp_get_num_procs();
												for (size_t i = 0; i < numThreads; ++i) {
													dym_array_init_VARIANT_CALL(po.VCSubArrays + i, 140);
													dym_array_init_ONE_READ(po.ReadSubArrays + i, 140);
													_vertexLAs[i] = NULL;
													_edgeLAs[i] = NULL;
												}

												size_t regionCount = 0;
												PACTIVE_REGION regions = NULL;

												ret = input_refseq_to_regions(po.ReferenceSequence, refSeqLen, &regions, &regionCount);
												if (ret == ERR_SUCCESS) {
													const ACTIVE_REGION *pa = NULL;

													pa = regions;
													for (size_t i = 0; i < regionCount; ++i) {
														if (pa->Type == artValid && pa->Length >= po.RegionLength)
															_activeRegionCount += (pa->Length / po.TestStep);

														++pa;
													}
														
													_activeRegionProcessed = 0;
													pa = regions;
													for (size_t i = 0; i < regionCount; ++i) {
														if (pa->Type == artValid && pa->Length >= po.RegionLength)
															process_active_region_in_parallel(pa, &po);
														
														++pa;
													}
														
													input_free_regions(regions, regionCount);
												}

												utils_free(rsFasta);
												ret = vc_array_merge(&po.VCArray, po.VCSubArrays, numThreads);
												int i = 0;
#pragma omp parallel for shared(po)
												for (i = 0; i <(int) numThreads; ++i) {
													dym_array_finit_ONE_READ(po.ReadSubArrays + i);
													vc_array_finit(po.VCSubArrays + i);
												}

												utils_free(po.ReadSubArrays);
											}

											utils_free(po.VCSubArrays);
										}

										utils_free(_edgeLAs);
										utils_free(_vertexLAs);

										if (po.VCFFileHandle != NULL) {
											if (ret == ERR_SUCCESS)
												vc_array_print(po.VCFFileHandle, &po.VCArray);

											vc_array_finit(&po.VCArray);
											utils_fclose(po.VCFFileHandle);
										}

									}

									fasta_free(&seqFile);
								}
							} else printf("fix_reads(): %u\n", ret);

							printf("Read coverage: %lf\n", _readBaseCount / _totalRegionLength );
							paired_reads_finit();
						}
					}
				}
			}
		}
	
		options_module_finit();
	}

#ifdef _MSC_VER
	uint64_t endTime = GetTickCount64();
	fprintf(stderr, "Time: %I64u s\n", (endTime - startTime) / 1000);
#endif
	omp_destroy_lock(&_readCoverageLock);

	return ret;
}
  bool Win32Window::Initialize(const char* name, size_t width, size_t height)
  {
	Destroy();
	IsMouseInWindow(false);

	parentClassName = name;
	childClassName = parentClassName + "_Child";

	// Work around compile error from not defining "UNICODE" while Chromium does
	const LPSTR idcArrow = MAKEINTRESOURCEA(32512);

	WNDCLASSEXA parentWindowClass = { 0 };
	parentWindowClass.cbSize = sizeof(WNDCLASSEXA);
	parentWindowClass.style = 0;
	parentWindowClass.lpfnWndProc = WndProc;
	parentWindowClass.cbClsExtra = 0;
	parentWindowClass.cbWndExtra = 0;
	parentWindowClass.hInstance = GetModuleHandle(NULL);
	parentWindowClass.hIcon = NULL;
	parentWindowClass.hCursor = LoadCursorA(NULL, idcArrow);
	parentWindowClass.hbrBackground = 0;
	parentWindowClass.lpszMenuName = NULL;
	parentWindowClass.lpszClassName = parentClassName.c_str();
	if (!RegisterClassExA(&parentWindowClass)) {
	  return false;
	}

	WNDCLASSEXA childWindowClass = { 0 };
	childWindowClass.cbSize = sizeof(WNDCLASSEXA);
	childWindowClass.style = CS_OWNDC;
	childWindowClass.lpfnWndProc = WndProc;
	childWindowClass.cbClsExtra = 0;
	childWindowClass.cbWndExtra = 0;
	childWindowClass.hInstance = GetModuleHandle(NULL);
	childWindowClass.hIcon = NULL;
	childWindowClass.hCursor = LoadCursorA(NULL, idcArrow);
	childWindowClass.hbrBackground = 0;
	childWindowClass.lpszMenuName = NULL;
	childWindowClass.lpszClassName = childClassName.c_str();
	if (!RegisterClassExA(&childWindowClass)) {
	  return false;
	}

	DWORD parentStyle = WS_CAPTION | WS_THICKFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX | WS_SYSMENU;
	DWORD parentExtendedStyle = WS_EX_APPWINDOW;

	RECT sizeRect = { 0, 0, static_cast<LONG>(width), static_cast<LONG>(height) };
	AdjustWindowRectEx(&sizeRect, parentStyle, FALSE, parentExtendedStyle);

	parentWindow = CreateWindowExA(
	  parentExtendedStyle,
	  parentClassName.c_str(),
	  name,
	  parentStyle,
	  CW_USEDEFAULT,
	  CW_USEDEFAULT,
	  sizeRect.right - sizeRect.left,
	  sizeRect.bottom - sizeRect.top,
	  NULL,
	  NULL,
	  GetModuleHandle(NULL),
	  this
	);

	nativeWindow = CreateWindowExA(
	  0,
	  childClassName.c_str(),
	  name,
	  WS_CHILD,
	  0,
	  0,
	  static_cast<int>(width),
	  static_cast<int>(height),
	  parentWindow,
	  NULL,
	  GetModuleHandle(NULL),
	  this
	);

	nativeDisplay = GetDC(nativeWindow);
	if (!nativeDisplay) {
	  Destroy();
	  return false;
	}

	{
	  Event event;
	  event.Type = Event::EVENT_INIT_WINDOW;
	  event.Time = GetTickCount64();
	  PushEvent(event);
	}

	return true;
  }
Exemple #16
0
LRESULT CProgressDlg::OnProgressUpdateUI(WPARAM wParam,LPARAM lParam)
{
	if(wParam == MSG_PROGRESSDLG_START)
	{
		m_BufStart = 0 ;
		m_Animate.Play(0, INT_MAX, INT_MAX);
		DialogEnableWindow(IDCANCEL, TRUE);
		if (m_pTaskbarList)
		{
			m_pTaskbarList->SetProgressState(m_hWnd, TBPF_NORMAL);
			m_pTaskbarList->SetProgressValue(m_hWnd, 0, 100);
		}
	}
	if(wParam == MSG_PROGRESSDLG_END || wParam == MSG_PROGRESSDLG_FAILED)
	{
		CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) L": got message: %d\n", wParam);
		ULONGLONG tickSpent = GetTickCount64() - m_startTick;
		CString strEndTime = CLoglistUtils::FormatDateAndTime(CTime::GetCurrentTime(), DATE_SHORTDATE, true, false);

		if(m_bBufferAll)
		{
			m_Databuf.m_critSec.Lock();
			m_Databuf.push_back(0);
			m_Log.SetWindowText(Convert2UnionCode((char*)m_Databuf.data()));
			m_Databuf.m_critSec.Unlock();
		}
		m_BufStart=0;
		m_Databuf.m_critSec.Lock();
		this->m_Databuf.clear();
		m_Databuf.m_critSec.Unlock();

		m_bDone = true;
		m_Animate.Stop();
		m_Progress.SetPos(100);
		this->DialogEnableWindow(IDOK,TRUE);

		m_GitStatus = (DWORD)lParam;
		if (m_GitCmd.IsEmpty() && m_GitCmdList.empty())
			m_GitStatus = (DWORD)-1;

		// detect crashes of perl when performing git svn actions
		if (m_GitStatus == 0 && m_GitCmd.Find(L" svn ") > 1)
		{
			CString log;
			m_Log.GetWindowText(log);
			if (log.GetLength() > 18 && log.Mid(log.GetLength() - 18) == L"perl.exe.stackdump")
				m_GitStatus = (DWORD)-1;
		}

		if (m_PostExecCallback)
		{
			CString extraMsg;
			m_PostExecCallback(m_GitStatus, extraMsg);
			if (!extraMsg.IsEmpty())
			{
				int start = m_Log.GetTextLength();
				m_Log.SetSel(start, start);
				m_Log.ReplaceSel(extraMsg);
			}
		}
		{
			CString text;
			m_Log.GetWindowText(text);
			text.Remove('\r');
			CAppUtils::StyleURLs(text, &m_Log);
		}
		if(this->m_GitStatus)
		{
			if (m_pTaskbarList)
			{
				m_pTaskbarList->SetProgressState(m_hWnd, TBPF_ERROR);
				m_pTaskbarList->SetProgressValue(m_hWnd, 100, 100);
			}
			CString log;
			log.Format(IDS_PROC_PROGRESS_GITUNCLEANEXIT, m_GitStatus);
			CString err;
			if (CRegDWORD(L"Software\\TortoiseGit\\ShowGitexeTimings", TRUE))
				err.Format(L"\r\n\r\n%s (%I64u ms @ %s)\r\n", (LPCTSTR)log, tickSpent, (LPCTSTR)strEndTime);
			else
				err.Format(L"\r\n\r\n%s\r\n", (LPCTSTR)log);
			if (!m_GitCmd.IsEmpty() || !m_GitCmdList.empty())
				InsertColorText(this->m_Log, err, RGB(255,0,0));
			if (CRegDWORD(L"Software\\TortoiseGit\\NoSounds", FALSE) == FALSE)
				PlaySound((LPCTSTR)SND_ALIAS_SYSTEMEXCLAMATION, nullptr, SND_ALIAS_ID | SND_ASYNC);
		}
		else {
			if (m_pTaskbarList)
				m_pTaskbarList->SetProgressState(m_hWnd, TBPF_NOPROGRESS);
			CString temp;
			temp.LoadString(IDS_SUCCESS);
			CString log;
			if (CRegDWORD(L"Software\\TortoiseGit\\ShowGitexeTimings", TRUE))
				log.Format(L"\r\n%s (%I64u ms @ %s)\r\n", (LPCTSTR)temp, tickSpent, (LPCTSTR)strEndTime);
			else
				log.Format(L"\r\n%s\r\n", (LPCTSTR)temp);
			InsertColorText(this->m_Log, log, RGB(0,0,255));
			this->DialogEnableWindow(IDCANCEL,FALSE);
		}

		m_Log.PostMessage(WM_VSCROLL, SB_BOTTOM, 0);

		if (wParam == MSG_PROGRESSDLG_END)
		{
			if (m_PostCmdCallback)	// new handling method using callback
			{
				m_PostCmdCallback(m_GitStatus, m_PostCmdList);

				if (!m_PostCmdList.empty())
				{
					int i = 0;
					for (const auto& entry : m_PostCmdList)
					{
						++i;
						m_ctrlPostCmd.AddEntry(entry.label, entry.icon);
						TCHAR accellerator = CStringUtils::GetAccellerator(entry.label);
						if (accellerator == L'\0')
							continue;
						++m_accellerators[accellerator].cnt;
						if (m_accellerators[accellerator].cnt > 1)
							m_accellerators[accellerator].id = -1;
						else
							m_accellerators[accellerator].id = i - 1;
					}

					if (m_accellerators.size())
					{
						LPACCEL lpaccelNew = (LPACCEL)LocalAlloc(LPTR, m_accellerators.size() * sizeof(ACCEL));
						SCOPE_EXIT { LocalFree(lpaccelNew); };
						i = 0;
						for (auto& entry : m_accellerators)
						{
							lpaccelNew[i].cmd = (WORD)(WM_USER + 1 + entry.second.id);
							lpaccelNew[i].fVirt = FVIRTKEY | FALT;
							lpaccelNew[i].key = entry.first;
							entry.second.wmid = lpaccelNew[i].cmd;
							++i;
						}
						m_hAccel = CreateAcceleratorTable(lpaccelNew, (int)m_accellerators.size());
					}
					GetDlgItem(IDC_PROGRESS_BUTTON1)->ShowWindow(SW_SHOW);
				}
			}
/**
 * Initialise monotonic seconds counter.
 */
void
MHD_monotonic_sec_counter_init (void)
{
#ifdef HAVE_CLOCK_GET_TIME
  mach_timespec_t cur_time;
#endif /* HAVE_CLOCK_GET_TIME */
  enum _MHD_mono_clock_source mono_clock_source = _MHD_CLOCK_NO_SOURCE;
#ifdef HAVE_CLOCK_GETTIME
  struct timespec ts;

  mono_clock_id = _MHD_UNWANTED_CLOCK;
#endif /* HAVE_CLOCK_GETTIME */
#ifdef HAVE_CLOCK_GET_TIME
  mono_clock_service = _MHD_INVALID_CLOCK_SERV;
#endif /* HAVE_CLOCK_GET_TIME */

  /* just a little syntactic trick to get the
     various following ifdef's to work out nicely */
  if (0)
    {
    }
  else
#ifdef HAVE_CLOCK_GETTIME
#ifdef CLOCK_MONOTONIC_COARSE
  /* Linux-specific fast value-getting clock */
  /* Can be affected by frequency adjustment and don't count time in suspend, */
  /* but preferred since it's fast */
  if (0 == clock_gettime (CLOCK_MONOTONIC_COARSE,
                          &ts))
    {
      mono_clock_id = CLOCK_MONOTONIC_COARSE;
      mono_clock_start = ts.tv_sec;
      mono_clock_source = _MHD_CLOCK_GETTIME;
    }
  else
#endif /* CLOCK_MONOTONIC_COARSE */
#ifdef CLOCK_MONOTONIC_FAST
  /* FreeBSD/DragonFly fast value-getting clock */
  /* Can be affected by frequency adjustment, but preferred since it's fast */
  if (0 == clock_gettime (CLOCK_MONOTONIC_FAST,
                          &ts))
    {
      mono_clock_id = CLOCK_MONOTONIC_FAST;
      mono_clock_start = ts.tv_sec;
      mono_clock_source = _MHD_CLOCK_GETTIME;
    }
  else
#endif /* CLOCK_MONOTONIC_COARSE */
#ifdef CLOCK_MONOTONIC_RAW
  /* Linux-specific clock */
  /* Not affected by frequency adjustment, but don't count time in suspend */
  if (0 == clock_gettime (CLOCK_MONOTONIC_RAW,
                          &ts))
    {
      mono_clock_id = CLOCK_MONOTONIC_RAW;
      mono_clock_start = ts.tv_sec;
      mono_clock_source = _MHD_CLOCK_GETTIME;
    }
  else
#endif /* CLOCK_MONOTONIC_RAW */
#ifdef CLOCK_BOOTTIME
  /* Linux-specific clock */
  /* Count time in suspend so it's real monotonic on Linux, */
  /* but can be slower value-getting than other clocks */
  if (0 == clock_gettime (CLOCK_BOOTTIME,
                          &ts))
    {
      mono_clock_id = CLOCK_BOOTTIME;
      mono_clock_start = ts.tv_sec;
      mono_clock_source = _MHD_CLOCK_GETTIME;
    }
  else
#endif /* CLOCK_BOOTTIME */
#ifdef CLOCK_MONOTONIC
  /* Monotonic clock */
  /* Widely supported, may be affected by frequency adjustment */
  /* On Linux it's not truly monotonic as it doesn't count time in suspend */
  if (0 == clock_gettime (CLOCK_MONOTONIC,
                          &ts))
    {
      mono_clock_id = CLOCK_MONOTONIC;
      mono_clock_start = ts.tv_sec;
      mono_clock_source = _MHD_CLOCK_GETTIME;
    }
  else
#endif /* CLOCK_BOOTTIME */
#endif /* HAVE_CLOCK_GETTIME */
#ifdef HAVE_CLOCK_GET_TIME
  /* Darwin-specific monotonic clock */
  /* Should be monotonic as clock_set_time function always unconditionally */
  /* failed on latest kernels */
  if ( (KERN_SUCCESS == host_get_clock_service (mach_host_self(),
                                                SYSTEM_CLOCK,
                                                &mono_clock_service)) &&
       (KERN_SUCCESS == clock_get_time (mono_clock_service,
                                        &cur_time)) )
    {
      mono_clock_start = cur_time.tv_sec;
      mono_clock_source = _MHD_CLOCK_GET_TIME;
    }
  else
#endif /* HAVE_CLOCK_GET_TIME */
#ifdef _WIN32
#if _WIN32_WINNT >= 0x0600
  /* W32 Vista or later specific monotonic clock */
  /* Available since Vista, ~15ms accuracy */
  if (1)
    {
      tick_start = GetTickCount64 ();
      mono_clock_source = _MHD_CLOCK_GETTICKCOUNT64;
    }
  else
#else  /* _WIN32_WINNT < 0x0600 */
  /* W32 specific monotonic clock */
  /* Available on Windows 2000 and later */
  if (1)
    {
      LARGE_INTEGER freq;
      LARGE_INTEGER perf_counter;

      QueryPerformanceFrequency (&freq); /* never fail on XP and later */
      QueryPerformanceCounter (&perf_counter); /* never fail on XP and later */
      perf_freq = freq.QuadPart;
      perf_start = perf_counter.QuadPart;
      mono_clock_source = _MHD_CLOCK_PERFCOUNTER;
    }
  else
#endif /* _WIN32_WINNT < 0x0600 */
#endif /* _WIN32 */
#ifdef HAVE_CLOCK_GETTIME
#ifdef CLOCK_HIGHRES
  /* Solaris-specific monotonic high-resolution clock */
  /* Not preferred due to be potentially resource-hungry */
  if (0 == clock_gettime (CLOCK_HIGHRES,
                          &ts))
    {
      mono_clock_id = CLOCK_HIGHRES;
      mono_clock_start = ts.tv_sec;
      mono_clock_source = _MHD_CLOCK_GETTIME;
    }
  else
#endif /* CLOCK_HIGHRES */
#endif /* HAVE_CLOCK_GETTIME */
#ifdef HAVE_GETHRTIME
  /* HP-UX and Solaris monotonic clock */
  /* Not preferred due to be potentially resource-hungry */
  if (1)
    {
      hrtime_start = gethrtime ();
      mono_clock_source = _MHD_CLOCK_GETHRTIME;
    }
  else
#endif /* HAVE_GETHRTIME */
    {
      /* no suitable clock source was found */
      mono_clock_source = _MHD_CLOCK_NO_SOURCE;
    }

#ifdef HAVE_CLOCK_GET_TIME
  if ( (_MHD_CLOCK_GET_TIME != mono_clock_source) &&
       (_MHD_INVALID_CLOCK_SERV != mono_clock_service) )
    {
      /* clock service was initialised but clock_get_time failed */
      mach_port_deallocate (mach_task_self(),
                            mono_clock_service);
      mono_clock_service = _MHD_INVALID_CLOCK_SERV;
    }
#else
  (void) mono_clock_source; /* avoid compiler warning */
#endif /* HAVE_CLOCK_GET_TIME */

  sys_clock_start = time (NULL);
}
Exemple #18
0
uint64_t _MCFCRT_GetFastMonoClock(void){
	return GetTickCount64() + MONO_CLOCK_OFFSET * 3;
}
Exemple #19
0
void CALLBACK dispatchEvents(SIMCONNECT_RECV*  pData, DWORD  cbData, void *  pContext)
{
	HRESULT hr;

	switch (pData->dwID)
	{
	case SIMCONNECT_RECV_ID_EVENT:
	{
		SIMCONNECT_RECV_EVENT *evt = (SIMCONNECT_RECV_EVENT*)pData;

		switch (evt->uEventID)
		{
		case STARTUP:
			stats.lastDeleted = 0;
			stats.nrOfDeletions = 0;
			stats.nrOfRequests = 0;
			// Now the sim is running, request information on the user aircraft
			hr = SimConnect_RequestDataOnSimObjectType(hSimConnect, R1, AIPARKDATA, conf.radius, SIMCONNECT_SIMOBJECT_TYPE_AIRCRAFT);
			++stats.nrOfRequests;
			break;


		case R2:
			fsecCnt++;

			if (fsecCnt >= (conf.requestEveryXSec/4))
			{
				fsecCnt = 0;
				if (SUCCEEDED(SimConnect_RequestDataOnSimObjectType(hSimConnect, R1, AIPARKDATA, conf.radius, SIMCONNECT_SIMOBJECT_TYPE_AIRCRAFT)))
				{
					++stats.nrOfRequests;
				}
			}
			break;

		case MENU:
			getMenu(menu, sizeof(menu));
			SimConnect_Text(hSimConnect, SIMCONNECT_TEXT_TYPE_MENU, 0, SELECTION, sizeof(menu), (void*)menu);
			break;

		case SELECTION:
			res = (SIMCONNECT_TEXT_RESULT)(evt->dwData);
			switch (res) {
			case SIMCONNECT_TEXT_RESULT_MENU_SELECT_1:
				if (conf.requestEveryXSec < 3600)
				{
					conf.requestEveryXSec += 30;
				}
				getMenu(menu, sizeof(menu));
				SimConnect_Text(hSimConnect, SIMCONNECT_TEXT_TYPE_MENU, 0, SELECTION, sizeof(menu), (void*)menu);
				break;

			case SIMCONNECT_TEXT_RESULT_MENU_SELECT_2:
				if (conf.requestEveryXSec > 45)
				{
					conf.requestEveryXSec -= 30;
				}
				getMenu(menu, sizeof(menu));
				SimConnect_Text(hSimConnect, SIMCONNECT_TEXT_TYPE_MENU, 0, SELECTION, sizeof(menu), (void*)menu);
				break;

			case SIMCONNECT_TEXT_RESULT_MENU_SELECT_3:
				if (conf.radius < 190000)
				{
					conf.radius += 5000;
				}
				getMenu(menu, sizeof(menu));
				SimConnect_Text(hSimConnect, SIMCONNECT_TEXT_TYPE_MENU, 0, SELECTION, sizeof(menu), (void*)menu);
				break;

			case SIMCONNECT_TEXT_RESULT_MENU_SELECT_4:
				if (conf.radius > 5000)
				{
					conf.radius -= 5000;
				}
				getMenu(menu, sizeof(menu));
				SimConnect_Text(hSimConnect, SIMCONNECT_TEXT_TYPE_MENU, 0, SELECTION, sizeof(menu), (void*)menu);
				break;

			case SIMCONNECT_TEXT_RESULT_MENU_SELECT_5:
				if (conf.maxetd > 5400)
				{
					conf.maxetd -= 3600;
				}
				getMenu(menu, sizeof(menu));
				SimConnect_Text(hSimConnect, SIMCONNECT_TEXT_TYPE_MENU, 0, SELECTION, sizeof(menu), (void*)menu);
				break;


			case SIMCONNECT_TEXT_RESULT_MENU_SELECT_6:
				if (conf.maxetd < 7*86400) // must be smaller than a week
				{
					conf.maxetd += 3600;
				}
				getMenu(menu, sizeof(menu));
				SimConnect_Text(hSimConnect, SIMCONNECT_TEXT_TYPE_MENU, 0, SELECTION, sizeof(menu), (void*)menu);
				break;

			case SIMCONNECT_TEXT_RESULT_MENU_SELECT_8:
				SimConnect_Text(hSimConnect, SIMCONNECT_TEXT_TYPE_MENU, 0, SELECTION, sizeof(empty), (void*)empty);
				break;
			default: //default cannot be close as displayed is also an event
				break;
			}
			saveConfig(conf);
			break;
		default:
			break;
		}
		break;
	}


	case SIMCONNECT_RECV_ID_SIMOBJECT_DATA_BYTYPE:
	{
		SIMCONNECT_RECV_SIMOBJECT_DATA_BYTYPE *pObjData = (SIMCONNECT_RECV_SIMOBJECT_DATA_BYTYPE*)pData;

		switch (pObjData->dwRequestID)
		{
		case R1:
		{
			DWORD ObjectID = pObjData->dwObjectID;
			DWORD entry = pObjData->dwentrynumber;
			DWORD outof = pObjData->dwoutof;
			DWORD length = pObjData->dwDefineCount;
			AIData *pS = (AIData*)&pObjData->dwData;
			if (ObjectID != SIMCONNECT_OBJECT_ID_USER)
			{
				if (strcmp(pS->state, "sleep") == 0 && pS->ETD > conf.maxetd)
				{
					if (FS10DeleteAIAircraft != NULL)
					{
						FS10DeleteAIAircraft(ObjectID, 1);
						++stats.nrOfDeletions;
						deletedSome = true;
					}
				}
			}

			if (entry == outof)
			{
				if (deletedSome)
				{
					stats.lastDeleted = GetTickCount64();
				}
				deletedSome = false;
			}


		}

		default:
			break;
		}
		break;
	}

	case SIMCONNECT_RECV_ID_EXCEPTION:
	{
		SIMCONNECT_RECV_EXCEPTION *except = (SIMCONNECT_RECV_EXCEPTION*)pData;
		printf("\n\n***** EXCEPTION=%d  SendID=%d  Index=%d  cbData=%d\n", except->dwException, except->dwSendID, except->dwIndex, cbData);
		break;
	}

	case SIMCONNECT_RECV_ID_QUIT:
	{
		quit = 1;
		break;
	}

	default:
		printf("\nReceived:%d", pData->dwID);
		break;
	}
}
Exemple #20
0
int port_wait(port_state_t* port_state,
              struct epoll_event* events,
              int maxevents,
              int timeout) {
  OVERLAPPED_ENTRY stack_iocp_events[PORT__MAX_ON_STACK_COMPLETIONS];
  OVERLAPPED_ENTRY* iocp_events;
  uint64_t due = 0;
  DWORD gqcs_timeout;
  int result;

  /* Check whether `maxevents` is in range. */
  if (maxevents <= 0)
    return_set_error(-1, ERROR_INVALID_PARAMETER);

  /* Decide whether the IOCP completion list can live on the stack, or allocate
   * memory for it on the heap. */
  if ((size_t) maxevents <= array_count(stack_iocp_events)) {
    iocp_events = stack_iocp_events;
  } else if ((iocp_events =
                  malloc((size_t) maxevents * sizeof *iocp_events)) == NULL) {
    iocp_events = stack_iocp_events;
    maxevents = array_count(stack_iocp_events);
  }

  /* Compute the timeout for GetQueuedCompletionStatus, and the wait end
   * time, if the user specified a timeout other than zero or infinite. */
  if (timeout > 0) {
    due = GetTickCount64() + (uint64_t) timeout;
    gqcs_timeout = (DWORD) timeout;
  } else if (timeout == 0) {
    gqcs_timeout = 0;
  } else {
    gqcs_timeout = INFINITE;
  }

  EnterCriticalSection(&port_state->lock);

  /* Dequeue completion packets until either at least one interesting event
   * has been discovered, or the timeout is reached. */
  for (;;) {
    uint64_t now;

    result = port__poll(
        port_state, events, iocp_events, (DWORD) maxevents, gqcs_timeout);
    if (result < 0 || result > 0)
      break; /* Result, error, or time-out. */

    if (timeout < 0)
      continue; /* When timeout is negative, never time out. */

    /* Update time. */
    now = GetTickCount64();

    /* Do not allow the due time to be in the past. */
    if (now >= due) {
      SetLastError(WAIT_TIMEOUT);
      break;
    }

    /* Recompute time-out argument for GetQueuedCompletionStatus. */
    gqcs_timeout = (DWORD)(due - now);
  }

  port__update_events_if_polling(port_state);

  LeaveCriticalSection(&port_state->lock);

  if (iocp_events != stack_iocp_events)
    free(iocp_events);

  if (result >= 0)
    return result;
  else if (GetLastError() == WAIT_TIMEOUT)
    return 0;
  else
    return -1;
}
Exemple #21
0
static int
pymonotonic(_PyTime_t *tp, _Py_clock_info_t *info, int raise)
{
#if defined(MS_WINDOWS)
    ULONGLONG ticks;
    _PyTime_t t;

    assert(info == NULL || raise);

    ticks = GetTickCount64();
    Py_BUILD_ASSERT(sizeof(ticks) <= sizeof(_PyTime_t));
    t = (_PyTime_t)ticks;

    if (_PyTime_check_mul_overflow(t, MS_TO_NS)) {
        if (raise) {
            _PyTime_overflow();
            return -1;
        }
        /* Hello, time traveler! */
        assert(0);
    }
    *tp = t * MS_TO_NS;

    if (info) {
        DWORD timeAdjustment, timeIncrement;
        BOOL isTimeAdjustmentDisabled, ok;
        info->implementation = "GetTickCount64()";
        info->monotonic = 1;
        ok = GetSystemTimeAdjustment(&timeAdjustment, &timeIncrement,
                                     &isTimeAdjustmentDisabled);
        if (!ok) {
            PyErr_SetFromWindowsErr(0);
            return -1;
        }
        info->resolution = timeIncrement * 1e-7;
        info->adjustable = 0;
    }

#elif defined(__APPLE__)
    static mach_timebase_info_data_t timebase;
    uint64_t time;

    if (timebase.denom == 0) {
        /* According to the Technical Q&A QA1398, mach_timebase_info() cannot
           fail: https://developer.apple.com/library/mac/#qa/qa1398/ */
        (void)mach_timebase_info(&timebase);
    }

    time = mach_absolute_time();

    /* apply timebase factor */
    time *= timebase.numer;
    time /= timebase.denom;

    *tp = time;

    if (info) {
        info->implementation = "mach_absolute_time()";
        info->resolution = (double)timebase.numer / timebase.denom * 1e-9;
        info->monotonic = 1;
        info->adjustable = 0;
    }

#else
    struct timespec ts;
#ifdef CLOCK_HIGHRES
    const clockid_t clk_id = CLOCK_HIGHRES;
    const char *implementation = "clock_gettime(CLOCK_HIGHRES)";
#else
    const clockid_t clk_id = CLOCK_MONOTONIC;
    const char *implementation = "clock_gettime(CLOCK_MONOTONIC)";
#endif

    assert(info == NULL || raise);

    if (clock_gettime(clk_id, &ts) != 0) {
        if (raise) {
            PyErr_SetFromErrno(PyExc_OSError);
            return -1;
        }
        return -1;
    }

    if (info) {
        struct timespec res;
        info->monotonic = 1;
        info->implementation = implementation;
        info->adjustable = 0;
        if (clock_getres(clk_id, &res) != 0) {
            PyErr_SetFromErrno(PyExc_OSError);
            return -1;
        }
        info->resolution = res.tv_sec + res.tv_nsec * 1e-9;
    }
    if (_PyTime_FromTimespec(tp, &ts, raise) < 0)
        return -1;
#endif
    return 0;
}
Exemple #22
0
u32 systemGetClock()
{
	if ( GetTickCount64() > 4294967296 )
		return 0;
	return (u32)GetTickCount64();
}
uint64_t getcurrenttime(void)
{
	return GetTickCount64();
}
HRESULT BtI2cControllerClass::_performContiguousTransfers(I2cTransferClass* & pXfr)
{
    ULONGLONG startWaitTicks = 0;
    ULONGLONG currentTicks = 0;
    I2cTransferClass* cmdXfr = nullptr;
    I2cTransferClass* readXfr = nullptr;
    PUCHAR readPtr = nullptr;
    HRESULT hr = S_OK;
    BOOL restart = FALSE;
    ULONG cmdDat;
    LONG cmdsOutstanding = 0;
    LONG readsOutstanding = 0;
    UCHAR outByte;
    UCHAR inByte;


    if (pXfr == nullptr)
    {
        hr = DMAP_E_DMAP_INTERNAL_ERROR;
    }

    if (SUCCEEDED(hr))
    {
        // Calculate the command and read counts for the current sequence of 
        // contiguous transfers in this transaction.
        hr = calculateCurrentCounts(pXfr, cmdsOutstanding, readsOutstanding);
    }

    // For each transfer in this section of the transaction:
    cmdXfr = pXfr;
    while (SUCCEEDED(hr) && (cmdsOutstanding > 0) && (cmdXfr != nullptr))
    {
        // If this is the first read transfer in this sequence of transfers:
        if ((readXfr == nullptr) && cmdXfr->transferIsRead())
        {
            // Indicate this is the transfer to read into.
            readXfr = cmdXfr;
            readXfr->resetRead();
            readPtr = readXfr->getNextReadLocation();
        }

        // Prepare to access the cmd buffer.
        cmdXfr->resetCmd();

        // Signal a pre-restart if this transfer is marked for one.
        if (cmdXfr->preResart())
        {
            restart = TRUE;
        }

        // For each byte in the transfer:
        while (SUCCEEDED(hr) && (cmdXfr->getNextCmd(outByte)))
        {
            // Wait for at least one empty space in the TX FIFO.
            while (txFifoFull());

            // Issue the command.
            if (cmdXfr->transferIsRead())
            {
                cmdDat = 0x100;             // Build read command (data is ignored)
            }
            else
            {
                cmdDat = outByte;           // Build write command with data byte
            }

            // If restart has been requested, signal a pre-RESTART.
            if (restart)
            {
                cmdDat = cmdDat | (1 << 10);
                restart = FALSE;            // Only want to RESTART on first command of transfer
            }

            // If this is the last command before the end of the transaction or
            // before a callback, signal a STOP.
            if (cmdsOutstanding == 1)
            {
                cmdDat = cmdDat | (1 << 9);
            }

            // Issue the command.
            m_registers->IC_DATA_CMD.ALL_BITS = cmdDat;
            cmdsOutstanding--;

            hr = _handleErrors();

            // Pull any available bytes out of the receive FIFO.
            while (SUCCEEDED(hr) && rxFifoNotEmtpy())
            {
                // Read a byte from the I2C Controller.
                inByte = readByte();
                readsOutstanding--;

                // Store the byte if we have a place for it.
                if (readPtr != nullptr)
                {
                    *readPtr = inByte;

                    // Figure out where the next byte should go.
                    readPtr = readXfr->getNextReadLocation();
                    while ((readPtr == nullptr) && (readXfr->getNextTransfer() != nullptr))
                    {
                        readXfr = readXfr->getNextTransfer();
                        readXfr->resetRead();
                        readPtr = readXfr->getNextReadLocation();
                    }
                }
            }
        }

        if (SUCCEEDED(hr))
        {
            cmdXfr = cmdXfr->getNextTransfer();
        }
    }

    // Complete any outstanding reads and wait for the TX FIFO to empty.
    startWaitTicks = GetTickCount64();
    currentTicks = startWaitTicks;
    while (SUCCEEDED(hr) && ((readsOutstanding > 0) || !txFifoEmpty()) && !errorOccurred())
    {
        // Pull any available bytes out of the receive FIFO.
        while (rxFifoNotEmtpy())
        {
            // Read a byte from the I2C Controller.
            inByte = readByte();
            readsOutstanding--;

            // Store the byte if we have a place for it.
            if (readPtr != nullptr)
            {
                *readPtr = inByte;

                // Figure out where the next byte should go.
                readPtr = readXfr->getNextReadLocation();
                while ((readPtr == nullptr) && (readXfr->getNextTransfer() != nullptr))
                {
                    readXfr = readXfr->getNextTransfer();
                    readXfr->resetRead();
                    readPtr = readXfr->getNextReadLocation();
                }
            }
        }

        // Wait up to to 100 milliseconds for transfers to happen.
        if (readsOutstanding > 0)
        {
            currentTicks = GetTickCount64();
            if (((currentTicks - startWaitTicks) > 100) && rxFifoEmpty())
            {
                hr = DMAP_E_I2C_READ_INCOMPLETE;
            }
        }
    }

    // Determine if an error occured on this transaction.
    if (SUCCEEDED(hr))
    {
        hr = _handleErrors();
    }

    // Pass the next transfer pointer back to the caller.
    pXfr = cmdXfr;

    // Record the read wait count for debugging purposes.
    if ((currentTicks - startWaitTicks) > m_maxWaitTicks)
    {
        m_maxWaitTicks = (ULONG)(currentTicks - startWaitTicks);
    }

    if (SUCCEEDED(hr))
    {
        // Check for some catch-all errors.
        if (cmdsOutstanding > 0)
        {
            hr = DMAP_E_I2C_OPERATION_INCOMPLETE;
        }
        else if (readsOutstanding < 0)
        {
            hr = DMAP_E_I2C_EXTRA_DATA_RECEIVED;
        }
        else if (cmdsOutstanding < 0)
        {
            hr = DMAP_E_DMAP_INTERNAL_ERROR;
        }
    }

    return hr;
}
Exemple #25
0
//this is the thread function which calls the subversion function
UINT CCacheDlg::WatchTestThread()
{
	CDirFileEnum direnum(m_sRootPath);
	m_filelist.RemoveAll();
	CString filepath;
	bool bIsDir = false;
	while (direnum.NextFile(filepath, &bIsDir))
		m_filelist.Add(filepath);

	CTime starttime = CTime::GetCurrentTime();
	GetDlgItem(IDC_STARTTIME)->SetWindowText(starttime.Format(L"%H:%M:%S"));

	ULONGLONG startticks = GetTickCount64();

	CString sNumber;
	std::random_device rd;
	std::mt19937 mt(rd());
	std::uniform_int_distribution<INT_PTR> dist(0, max(0, m_filelist.GetCount() - 1));
	filepath = m_filelist.GetAt(dist(mt));
	GetStatusFromRemoteCache(CTGitPath(m_sRootPath), false);
	for (int i=0; i < 10000; ++i)
	{
		filepath = m_filelist.GetAt(dist(mt));
		GetDlgItem(IDC_FILEPATH)->SetWindowText(filepath);
		TouchFile(filepath);
		CopyRemoveCopy(filepath);
		sNumber.Format(L"%d", i);
		GetDlgItem(IDC_DONE)->SetWindowText(sNumber);
	}

	// create dummy directories and remove them again several times
	for (int outer = 0; outer<100; ++outer)
	{
		for (int i=0; i<10; ++i)
		{
			filepath.Format(L"__MyDummyFolder%d", i);
			CreateDirectory(m_sRootPath + L'\\' + filepath, nullptr);
			HANDLE hFile = CreateFile(m_sRootPath + L'\\' + filepath + L"\\file", GENERIC_READ, FILE_SHARE_READ, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
			CloseHandle(hFile);
			SHChangeNotify(SHCNE_UPDATEITEM, SHCNF_PATH | SHCNF_FLUSHNOWAIT, m_sRootPath + L'\\' + filepath + L"\\file", NULL);
		}
		Sleep(500);
		for (int i=0; i<10; ++i)
		{
			filepath.Format(L"__MyDummyFolder%d", i);
			DeleteFile(m_sRootPath + L'\\' + filepath + L"\\file");
			RemoveDirectory(m_sRootPath + L'\\' + filepath);
		}
		sNumber.Format(L"%d", outer);
		GetDlgItem(IDC_DONE)->SetWindowText(sNumber);
	}

	CTime endtime = CTime::GetCurrentTime();
	CString sEnd = endtime.Format(L"%H:%M:%S");

	ULONGLONG endticks = GetTickCount64();

	CString sEndText;
	sEndText.Format(L"%s  - %I64u ms", (LPCTSTR)sEnd, endticks - startticks);

	GetDlgItem(IDC_ENDTIME)->SetWindowText(sEndText);

	return 0;
}
// Method to initialize the I2C Controller at the start of a transaction.
HRESULT BtI2cControllerClass::_initializeForTransaction(ULONG slaveAddress, BOOL useHighSpeed)
{
    ULONGLONG waitStartTicks = 0;
    BoardPinsClass::BOARD_TYPE board;
    _IC_CON icConReg;

    // If we need to initialize, or re-initialize, the I2C Controller:
    if (!isInitialized() || (m_registers->IC_TAR.IC_TAR != slaveAddress))
    {
        // Disable the I2C controller.  This also clears the FIFOs.
        m_registers->IC_ENABLE.ENABLE = 0;

        // Wait for the controller to go disabled, but only for 100 mS.
        // It can latch in a mode in which it does not go disabled, but appears 
        // to come out of this state when used again.
        waitStartTicks = GetTickCount64();
        while ((m_registers->IC_ENABLE_STATUS.IC_EN == 1) && ((GetTickCount64() - waitStartTicks) < 100))
        {
            Sleep(0);       // Give the CPU to any thread that is waiting
        }

        // Set the desired I2C Clock speed.
        g_pins.getBoardType(board);
        if ((board == BoardPinsClass::BOARD_TYPE::MBM_BARE) ||
            (board == BoardPinsClass::BOARD_TYPE::MBM_IKA_LURE))
        {
            if (useHighSpeed)
            {
                m_registers->IC_FS_SCL_HCNT.IC_FS_SCL_HCNT = 0x3C;
                m_registers->IC_FS_SCL_LCNT.IC_FS_SCL_LCNT = 0x82;
                m_registers->IC_CON.SPEED = 2;
            }
            else
            {
                m_registers->IC_SS_SCL_HCNT.IC_SS_SCL_HCNT = 0x190;
                m_registers->IC_SS_SCL_LCNT.IC_SS_SCL_LCNT = 0x1D6;
                m_registers->IC_CON.SPEED = 1;
            }
        }
        else
        {
            if (useHighSpeed)
            {
                m_registers->IC_FS_SCL_HCNT.IC_FS_SCL_HCNT = 0x14;
                m_registers->IC_FS_SCL_LCNT.IC_FS_SCL_LCNT = 0x2E;
                m_registers->IC_CON.SPEED = 2;
            }
            else
            {
                m_registers->IC_SS_SCL_HCNT.IC_SS_SCL_HCNT = 0x92;
                m_registers->IC_SS_SCL_LCNT.IC_SS_SCL_LCNT = 0xAB;
                m_registers->IC_CON.SPEED = 1;
            }
        }

        // Allow bus restarts.
        m_registers->IC_CON.IC_RESTART_EN = 1;

        // Set 7-bit addressing.
        icConReg.ALL_BITS = m_registers->IC_CON.ALL_BITS;
        icConReg.IC_10BITADDR_MASTER = 0;
        m_registers->IC_CON.ALL_BITS = icConReg.ALL_BITS;

        // Set the address of the slave this tranaction affects.
        // All bits but the 7-bit address are intentionally cleared here.  This is needed
        // for Bay Trail, which supports additional bits (all of which we want clear).
        m_registers->IC_TAR.ALL_BITS = (slaveAddress & 0x7F);

        // Mask all interrupts.
        m_registers->IC_INTR_MASK.ALL_BITS = 0;

        // Clear any outstanding interrupts.
        ULONG dummy = m_registers->IC_CLR_INTR.ALL_BITS;

        // Enable the controller.
        m_registers->IC_ENABLE.ENABLE = 1;

        // Indicate the I2C Controller is now initialized.
        setInitialized();

    } // End - if (!isInitialized() || (getAddress() != m_slaveAddress))

    return S_OK;
}
Exemple #27
0
static double monotonicCurrentTimeInSeconds()
{
	return GetTickCount64() / 1000.0;
}
static int
_win32_create_temp_file(_zip_source_win32_read_file_t *ctx)
{
    zip_uint32_t value;
    /*
    Windows has GetTempFileName(), but it closes the file after
    creation, leaving it open to a horrible race condition. So
    we reinvent the wheel.
    */
    int i;
    HANDLE th = INVALID_HANDLE_VALUE;
    void *temp = NULL;
    PSECURITY_DESCRIPTOR psd = NULL;
    PSECURITY_ATTRIBUTES psa = NULL;


#ifndef WINRT
    DWORD len;
    BOOL success;
    SECURITY_ATTRIBUTES sa;
    SECURITY_INFORMATION si;

    /*
    Read the DACL from the original file, so we can copy it to the temp file.
    If there is no original file, or if we can't read the DACL, we'll use the
    default security descriptor.
    */
    if (ctx->h != INVALID_HANDLE_VALUE && GetFileType(ctx->h) == FILE_TYPE_DISK) {
	si = DACL_SECURITY_INFORMATION | UNPROTECTED_DACL_SECURITY_INFORMATION;
	len = 0;
	success = GetUserObjectSecurity(ctx->h, &si, NULL, len, &len);
	if (!success && GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
	    if ((psd = (PSECURITY_DESCRIPTOR)malloc(len)) == NULL) {
		zip_error_set(&ctx->error, ZIP_ER_MEMORY, 0);
		return -1;
	    }
	    success = GetUserObjectSecurity(ctx->h, &si, psd, len, &len);
	}
	if (success) {
	    sa.nLength = sizeof(SECURITY_ATTRIBUTES);
	    sa.bInheritHandle = FALSE;
	    sa.lpSecurityDescriptor = psd;
	    psa = &sa;
	}
    }

    value = GetTickCount();
#else
    value = (zip_uint32_t)GetTickCount64();
#endif

    for (i = 0; i < 1024 && th == INVALID_HANDLE_VALUE; i++) {
	th = ctx->ops->op_create_temp(ctx, &temp, value + i, psa);
	if (th == INVALID_HANDLE_VALUE && GetLastError() != ERROR_FILE_EXISTS)
	    break;
    }

    if (th == INVALID_HANDLE_VALUE) {
	free(temp);
	free(psd);
	zip_error_set(&ctx->error, ZIP_ER_TMPOPEN, _zip_win32_error_to_errno(GetLastError()));
	return -1;
    }

    free(psd);
    ctx->hout = th;
    ctx->tmpname = temp;

    return 0;
}
Exemple #29
0
double MsgLogger::GetMonotonicTime() {
    return GetTickCount64() / 1000.0;
}
/*******************************************************************************
Main entry point. Here we demonstrate, after some initial housekeeping, how to
initialize the camera, start streaming, grab samples, and process them.
*******************************************************************************/
int main(int argc, char *argv[]) {
	if (!ProcessCmdArgs(argc, argv)) {
		return 1;
	}

	// Check / create file directories
	if (xdmPath != nullptr) {
		if (_mkdir(xdmPath) != 0 && errno != EEXIST){
			fprintf(stderr, "Error: Invalid XDM path. Error %d\n", errno);
			fprintf(stderr, "Terminate? [Y/n]\n");
			char choice = _getch();
			if (choice != 'n' && choice != 'N') {
				return ERROR_FILE;
			}
			xdmPath = nullptr;
		}
		else {
			// Remove any trailing '\' in the path since we'll add it later.
			if (xdmPath[strlen(xdmPath) - 1] == '\\')
				xdmPath[strlen(xdmPath) - 1] = '0';
		}
	}
	if (bufPath != nullptr) {
		if (_mkdir(bufPath) != 0 && errno != EEXIST){
			fprintf(stderr, "Error: Invalid Buffer path. Error %d\n", errno);
			fprintf(stderr, "Terminate? [Y/n]\n");
			char choice = _getch();
			if (choice != 'n' && choice != 'N') {
				return ERROR_FILE;
			}
			bufPath = nullptr;
		}
		else {
			// Remove any trailing '\' in the path since we'll add it later.
			if (bufPath[strlen(bufPath) - 1] == '\\')
				bufPath[strlen(bufPath) - 1] = '0';
		}
	}

	// Start timer for total test execution
	unsigned long long programStart = GetTickCount64();
	
	// Initialize camera and streams
	if (verbose) fprintf_s(stdout, "Initializing camera...\n");
	// The Sense Manager is the root object for interacting with the camera.
	PXCSenseManager *senseManager = nullptr;
	senseManager = PXCSenseManager::CreateInstance();
	if (!senseManager) {
		fprintf_s(stderr, "Unable to create the PXCSenseManager\n");
		return ERROR_CAMERA;
	}

	// When enabling the streams (color and depth), the parameters must match
	// the capabilities of the camera. For example, 60fps for color will fail
	// on the DS4 / R200.
	// Here we're hard-coding the resolution and frame rate
	senseManager->EnableStream(PXCCapture::STREAM_TYPE_COLOR, 320, 240, 30);
	senseManager->EnableStream(PXCCapture::STREAM_TYPE_DEPTH, 320, 240, 30);

	// Initialize the PXCSenseManager
	pxcStatus camStatus;
	camStatus = senseManager->Init();
	if (camStatus != PXC_STATUS_NO_ERROR) {
		fprintf_s(stderr, "Unable to initizlize PXCSenseManager\n");
		senseManager->Release();
		return ERROR_CAMERA;
	}
	
	PXCImage *colorImage;
	PXCImage *depthImage;
	PXCPhoto *xdmPhoto = senseManager->QuerySession()->CreatePhoto();

	// These two objects come from the Intel RealSense SDK helper for rendering
	// camera data. Any rendering technique could be used or omitted if no 
	// visual feedback is desired.
	UtilRender *renderColor = new UtilRender(L"COLOR STREAM");
	UtilRender *renderDepth = new UtilRender(L"DEPTH STREAM");
	
	// Start test
	if (verbose) fprintf_s(stdout, "Running...\n");
	// This section may be wrapped in additional code to automate 
	// repetitive tests. Closure provided just for convenience.
	{ // Beginning of single test block
		unsigned long totalFrames = 0;
		unsigned long long streamStart = GetTickCount64();
		for (unsigned int i = 0; i < framesPerTest; i++) {
			// Passing 'true' to AcquireFrame blocks until all streams are 
			// ready (depth and color).  Passing 'false' will result in 
			// frames unaligned in time.
			camStatus = senseManager->AcquireFrame(true);
			if (camStatus < PXC_STATUS_NO_ERROR) {
				fprintf_s(stderr, "Error acquiring frame: %f\n", camStatus);
				break;
			}
			// Retrieve all available image samples
			PXCCapture::Sample *sample = senseManager->QuerySample();
			if (sample == NULL) {
				fprintf_s(stderr, "Sample unavailable\n");
			}
			else {
				totalFrames++;

				colorImage = sample->color;
				depthImage = sample->depth;
				// Render the frames (not necessary)
				if (!renderColor->RenderFrame(colorImage)) break;
				if (!renderDepth->RenderFrame(depthImage)) break;

				// Save data if requested
				wchar_t filePath[MAXPATH];
				char fileName[18];
				TimeStampString(fileName);
				if (xdmPath != nullptr) { // Save XDM image
					swprintf_s(filePath, MAXPATH, L"%S\\%S%S", 
						xdmPath, 
						fileName,
						xdmExt);
					xdmPhoto->ImportFromPreviewSample(sample);
					pxcStatus saveStatus = xdmPhoto->SaveXDM(filePath);
					if (saveStatus != PXC_STATUS_NO_ERROR)
						fprintf_s(stderr, "Error: SaveXDM\n");
				}
				if (bufPath != NULL) { // Save depth buffer
					swprintf_s(filePath, MAXPATH, L"%S\\%S%S", 
						bufPath, fileName, depBufExt);
					// The WriteDepthBuf function has a lot of detail about
					// accessing image data and should be examined.
					if (!WriteDepthBuf(depthImage, filePath)) {
						fprintf(stderr, "Error: WriteDepthBuf\n");
					}
				}
			}

			// Unlock the current frame to fetch the next one
			senseManager->ReleaseFrame();

		}

		float frameRate = (float)totalFrames /
			((float)(GetTickCount64() - streamStart) / 1000);
		if (verbose) fprintf_s(stdout, "Frame Rate: %.2f\n", frameRate);
	} // End of single test block

	// Wrap up
	if(verbose) fprintf_s(stdout, "Finished in %llu seconds.\n",
		(GetTickCount64() - programStart) / 1000);

	delete renderColor;
	delete renderDepth;
	xdmPhoto->Release();
	if(senseManager != nullptr) senseManager->Release();

	return 0;
}