コード例 #1
0
ファイル: Log.cpp プロジェクト: dadamitskiy/Log
void DA::Log::PrintToOutputWindow(const char* File, const char* Function, int LineNumber, const char* LogCategory, Verbosity::Type VerbosityLevel, DetailLevel::Type Detail, const char* Format, va_list Args)
{
	// Ensure we are using Visual Studio to compile the code if we intend to log to its output window.
#if defined(_MSC_VER)
	if (Detail == DetailLevel::High)
	{
		PrintTimeStampToOutputWindow();
	}

	if (Detail != DetailLevel::Low)
	{
		// Output the file, function, and line the LOG statement was called on.
		char detailBuffer[512];
		_snprintf_s(detailBuffer, _TRUNCATE, "[File: %s, Function: %s, Line: %d] - ", File, Function, LineNumber);
		wchar_t wc[512];
		mbstowcs_s(nullptr, wc, detailBuffer, _TRUNCATE);
		OutputDebugStringW(wc);

		//OutputDebugStringW(Printf("[File: %s, Function: %s, Line: %d] - ", File, Function, LineNumber));
	}

	// Output the log category.
	char outputCategory[64];
	_snprintf_s(outputCategory, _TRUNCATE, "Log%s ", LogCategory);
	wchar_t wOutputCategory[64];
	mbstowcs_s(nullptr, wOutputCategory, outputCategory, _TRUNCATE);
	OutputDebugStringW(wOutputCategory);

	// Output the verbosity level.
	if (VerbosityLevel == Verbosity::Info)
	{
		OutputDebugStringW(L"INFO: ");
	}
	else if (VerbosityLevel == Verbosity::Debug)
	{
		OutputDebugStringW(L"DEBUG: ");
	}
	else if (VerbosityLevel == Verbosity::Warning)
	{
		OutputDebugStringW(L"WARNING: ");
	}
	else if (VerbosityLevel == Verbosity::Error)
	{
		OutputDebugStringW(L"ERROR: ");
	}
	else if (VerbosityLevel == Verbosity::Fatal)
	{
		OutputDebugStringW(L"FATAL: ");
	}
	
	// Store the LOG message into the streamBuffer array.
	char streamBuffer[512];
	vsnprintf_s(streamBuffer, _countof(streamBuffer), _TRUNCATE, Format, Args);

	// Output the LOG message to the output window.
	wchar_t wc[512];
	mbstowcs_s(nullptr, wc, streamBuffer, _TRUNCATE);
	OutputDebugStringW(wc);
	OutputDebugStringW(L"\n");
#endif
}
コード例 #2
0
BOOL CSetOverlayIcons::OnInitDialog()
{
	ISettingsPropPage::OnInitDialog();

	m_cIconList.SetExtendedStyle(LVS_EX_FULLROWSELECT | LVS_EX_DOUBLEBUFFER | LVS_EX_INFOTIP | LVS_EX_SUBITEMIMAGES);
	// get the path to our icon sets
	TCHAR buf[MAX_PATH] = {0};
	SHGetSpecialFolderPath(m_hWnd, buf, CSIDL_PROGRAM_FILES_COMMON, true);
	m_sIconPath = buf;
	m_sIconPath += _T("\\TortoiseOverlays\\Icons");
	// list all the icon sets
	CDirFileEnum filefinder(m_sIconPath);
	bool isDir = false;
	CString item;
	while (filefinder.NextFile(item, &isDir))
	{
		if (!isDir)
			continue;
		m_cIconSet.AddString(CPathUtils::GetFileNameFromPath(item));
	}
	CheckRadioButton(IDC_LISTRADIO, IDC_SYMBOLRADIO, IDC_LISTRADIO);
	CString sModifiedIcon = m_regModified;
	if (sModifiedIcon.IsEmpty())
	{
		// no custom icon set, use the default
		sModifiedIcon = m_sIconPath + _T("\\XPStyle\\ModifiedIcon.ico");
	}
	if (sModifiedIcon.Left(m_sIconPath.GetLength()).CompareNoCase(m_sIconPath)!=0)
	{
		// an icon set outside our own installation? We don't support that,
		// so fall back to the default!
		sModifiedIcon = m_sIconPath + _T("\\XPStyle\\ModifiedIcon.ico");
	}
	// the name of the icon set is the folder of the icon location
	m_sOriginalIconSet = sModifiedIcon.Mid(m_sIconPath.GetLength()+1);
	m_sOriginalIconSet = m_sOriginalIconSet.Left(m_sOriginalIconSet.ReverseFind('\\'));
	// now we have the name of the icon set. Set the combobox to show
	// that as selected
	CString ComboItem;
	for (int i=0; i<m_cIconSet.GetCount(); ++i)
	{
		m_cIconSet.GetLBText(i, ComboItem);
		if (ComboItem.CompareNoCase(m_sOriginalIconSet)==0)
			m_cIconSet.SetCurSel(i);
	}

	WORD langID = (WORD)(DWORD)CRegStdDWORD(_T("Software\\TortoiseGit\\LanguageID"), GetUserDefaultLangID());
	TCHAR statustext[MAX_STATUS_STRING_LENGTH] = { 0 };
	GitStatus::GetStatusString(AfxGetResourceHandle(), git_wc_status_normal, statustext, _countof(statustext), langID);
	m_sNormal = statustext;
	GitStatus::GetStatusString(AfxGetResourceHandle(), git_wc_status_modified, statustext, _countof(statustext), langID);
	m_sModified = statustext;
	GitStatus::GetStatusString(AfxGetResourceHandle(), git_wc_status_conflicted, statustext, _countof(statustext), langID);
	m_sConflicted = statustext;
	GitStatus::GetStatusString(AfxGetResourceHandle(), git_wc_status_deleted, statustext, _countof(statustext), langID);
	m_sDeleted = statustext;
	GitStatus::GetStatusString(AfxGetResourceHandle(), git_wc_status_added, statustext, _countof(statustext), langID);
	m_sAdded = statustext;
	GitStatus::GetStatusString(AfxGetResourceHandle(), git_wc_status_ignored, statustext, _countof(statustext), langID);
	m_sIgnored = statustext;
	GitStatus::GetStatusString(AfxGetResourceHandle(), git_wc_status_unversioned, statustext, _countof(statustext), langID);
	m_sUnversioned = statustext;

	m_sReadOnly.LoadString(IDS_SETTINGS_READONLYNAME);
	m_sLocked.LoadString(IDS_SETTINGS_LOCKEDNAME);

	SetWindowTheme(m_hWnd, L"Explorer", NULL);

	ShowIconSet(true);

	return TRUE;
}
コード例 #3
0
ファイル: spherify.cpp プロジェクト: innovatelogic/ilogic-vm
TCHAR *GetString(int id) {
	static TCHAR buf[256];
	if (hInstance)
		return LoadString(hInstance, id, buf, _countof(buf)) ? buf : NULL;
	return NULL;
	}
コード例 #4
0
INT_PTR __cdecl CYahooProto::GetAvatarInfo(WPARAM wParam, LPARAM lParam)
{
	PROTO_AVATAR_INFORMATION* pai = (PROTO_AVATAR_INFORMATION*)lParam;
	DBVARIANT dbv;
	int avtType;

	if (!getString(pai->hContact, YAHOO_LOGINID, &dbv)) {
		debugLogA("[YAHOO_GETAVATARINFO] For: %s", dbv.pszVal);
		db_free(&dbv);
	}
	else {
		debugLogA("[YAHOO_GETAVATARINFO]");
	}

	if (!getByte("ShowAvatars", 1) || !m_bLoggedIn) {
		debugLogA("[YAHOO_GETAVATARINFO] %s", m_bLoggedIn ? "We are not using/showing avatars!" : "We are not logged in. Can't load avatars now!");

		return GAIR_NOAVATAR;
	}

	avtType = getByte(pai->hContact, "AvatarType", 0);
	debugLogA("[YAHOO_GETAVATARINFO] Avatar Type: %d", avtType);

	if (avtType != 2) {
		if (avtType != 0)
			debugLogA("[YAHOO_GETAVATARINFO] Not handling this type yet!");

		return GAIR_NOAVATAR;
	}

	if (getDword(pai->hContact, "PictCK", 0) == 0)
		return GAIR_NOAVATAR;

	GetAvatarFileName(pai->hContact, pai->filename, _countof(pai->filename), getByte(pai->hContact, "AvatarType", 0));
	pai->format = PA_FORMAT_PNG;
	debugLogA("[YAHOO_GETAVATARINFO] filename: %s", pai->filename);

	if (_taccess(pai->filename, 0) == 0)
		return GAIR_SUCCESS;

	if ((wParam & GAIF_FORCE) != 0 && pai->hContact != NULL) {
		/* need to request it again? */
		if (getDword(pai->hContact, "PictLoading", 0) != 0 &&
			(time(NULL) - getDword(pai->hContact, "PictLastCheck", 0) < 500)) {
			debugLogA("[YAHOO_GETAVATARINFO] Waiting for avatar to load!");
			return GAIR_WAITFOR;
		}
		else if (m_bLoggedIn) {
			DBVARIANT dbv;

			if (!getString(pai->hContact, YAHOO_LOGINID, &dbv)) {
				debugLogA("[YAHOO_GETAVATARINFO] Requesting avatar!");

				request_avatar(dbv.pszVal);
				db_free(&dbv);

				return GAIR_WAITFOR;
			}
			else {
				debugLogA("[YAHOO_GETAVATARINFO] Can't retrieve user id?!");
			}
		}
	}

	debugLogA("[YAHOO_GETAVATARINFO] NO AVATAR???");
	return GAIR_NOAVATAR;
}
コード例 #5
0
ファイル: tox_options.cpp プロジェクト: Seldom/miranda-ng
void CToxOptionsNodeList::OnInitDialog()
{
	m_nodes.SetExtendedListViewStyle(LVS_EX_SUBITEMIMAGES | LVS_EX_FULLROWSELECT | LVS_EX_LABELTIP);

	HIMAGELIST hImageList = m_nodes.CreateImageList(LVSIL_SMALL);
	HICON icon = Skin_LoadIcon(SKINICON_OTHER_TYPING);
	ImageList_AddIcon(hImageList, icon); IcoLib_ReleaseIcon(icon);
	icon = Skin_LoadIcon(SKINICON_OTHER_DELETE);
	ImageList_AddIcon(hImageList, icon); IcoLib_ReleaseIcon(icon);

	m_nodes.AddColumn(0, _T("IPv4"), 100);
	m_nodes.AddColumn(1, _T("IPv6"), 100);
	m_nodes.AddColumn(2, TranslateT("Port"), 50);
	m_nodes.AddColumn(3, TranslateT("Public key"), 130);
	m_nodes.AddColumn(4, _T(""), 32 - GetSystemMetrics(SM_CXVSCROLL));
	m_nodes.AddColumn(5, _T(""), 32 - GetSystemMetrics(SM_CXVSCROLL));

	m_nodes.EnableGroupView(TRUE);
	m_nodes.AddGroup(0, TranslateT("Common nodes"));
	m_nodes.AddGroup(1, TranslateT("User nodes"));

	////////////////////////////////////////

	int iItem = -1;

	if (CToxProto::IsFileExists((TCHAR*)VARST(_T(TOX_INI_PATH))))
	{
		char fileName[MAX_PATH];
		mir_strcpy(fileName, VARS(TOX_INI_PATH));

		char *section, sections[MAX_PATH], value[MAX_PATH];
		GetPrivateProfileSectionNamesA(sections, _countof(sections), fileName);
		section = sections;
		while (*section != NULL)
		{
			if (strstr(section, TOX_SETTINGS_NODE_PREFIX) == section)
			{
				GetPrivateProfileStringA(section, "IPv4", NULL, value, _countof(value), fileName);
				iItem = m_nodes.AddItem(mir_a2t(value), -1, NULL, 0);

				GetPrivateProfileStringA(section, "IPv6", NULL, value, _countof(value), fileName);
				m_nodes.SetItem(iItem, 1, mir_a2t(value));

				GetPrivateProfileStringA(section, "Port", NULL, value, _countof(value), fileName);
				m_nodes.SetItem(iItem, 2, mir_a2t(value));

				GetPrivateProfileStringA(section, "PubKey", NULL, value, _countof(value), fileName);
				m_nodes.SetItem(iItem, 3, mir_a2t(value));
			}
			section += mir_strlen(section) + 1;
		}
	}

	char module[MAX_PATH], setting[MAX_PATH];
	mir_snprintf(module, "%s_Nodes", m_proto->m_szModuleName);
	int nodeCount = db_get_w(NULL, module, TOX_SETTINGS_NODE_COUNT, 0);
	for (int i = 0; i < nodeCount; i++)
	{
		mir_snprintf(setting, TOX_SETTINGS_NODE_IPV4, i);
		ptrT value(db_get_tsa(NULL, module, setting));
		iItem = m_nodes.AddItem(value, -1, NULL, 1);

		mir_snprintf(setting, TOX_SETTINGS_NODE_IPV6, i);
		value = db_get_tsa(NULL, module, setting);
		m_nodes.SetItem(iItem, 1, value);

		mir_snprintf(setting, TOX_SETTINGS_NODE_PORT, i);
		int port = db_get_w(NULL, module, setting, 0);
		if (port > 0)
		{
			char portNum[10];
			itoa(port, portNum, 10);
			m_nodes.SetItem(iItem, 2, mir_a2t(portNum));
		}

		mir_snprintf(setting, TOX_SETTINGS_NODE_PKEY, i);
		value = db_get_tsa(NULL, module, setting);
		m_nodes.SetItem(iItem, 3, value);

		m_nodes.SetItem(iItem, 4, _T(""), 0);
		m_nodes.SetItem(iItem, 5, _T(""), 1);
	}
}
コード例 #6
0
QImage QD3D12Window::readbackRGBA8888(ID3D12Resource *rt, D3D12_RESOURCE_STATES rtState, ID3D12GraphicsCommandList *commandList)
{
    ComPtr<ID3D12Resource> readbackBuf;

    D3D12_RESOURCE_DESC rtDesc = rt->GetDesc();
    UINT64 textureByteSize = 0;
    D3D12_PLACED_SUBRESOURCE_FOOTPRINT textureLayout = {};
    device()->GetCopyableFootprints(&rtDesc, 0, 1, 0, &textureLayout, Q_NULLPTR, Q_NULLPTR, &textureByteSize);

    D3D12_HEAP_PROPERTIES heapProp = {};
    heapProp.Type = D3D12_HEAP_TYPE_READBACK;

    D3D12_RESOURCE_DESC bufDesc = {};
    bufDesc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
    bufDesc.Width = textureByteSize;
    bufDesc.Height = 1;
    bufDesc.DepthOrArraySize = 1;
    bufDesc.MipLevels = 1;
    bufDesc.Format = DXGI_FORMAT_UNKNOWN;
    bufDesc.SampleDesc.Count = 1;
    bufDesc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;

    if (FAILED(device()->CreateCommittedResource(&heapProp, D3D12_HEAP_FLAG_NONE, &bufDesc,
                                            D3D12_RESOURCE_STATE_COPY_DEST, Q_NULLPTR, IID_PPV_ARGS(&readbackBuf)))) {
        qWarning("Failed to create committed resource (readback buffer)");
        return QImage();
    }

    D3D12_TEXTURE_COPY_LOCATION dstLoc;
    dstLoc.pResource = readbackBuf.Get();
    dstLoc.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
    dstLoc.PlacedFootprint = textureLayout;
    D3D12_TEXTURE_COPY_LOCATION srcLoc;
    srcLoc.pResource = rt;
    srcLoc.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
    srcLoc.SubresourceIndex = 0;

    transitionResource(rt, commandList, rtState, D3D12_RESOURCE_STATE_COPY_SOURCE);
    commandList->CopyTextureRegion(&dstLoc, 0, 0, 0, &srcLoc, Q_NULLPTR);
    transitionResource(rt, commandList, D3D12_RESOURCE_STATE_COPY_SOURCE, rtState);
    commandList->Close();

    ID3D12CommandList *commandLists[] = { commandList };
    commandQueue()->ExecuteCommandLists(_countof(commandLists), commandLists);
    QScopedPointer<Fence> f(createFence());
    waitForGPU(f.data());

    QImage img(rtDesc.Width, rtDesc.Height, QImage::Format_RGBA8888);
    quint8 *p = Q_NULLPTR;
    D3D12_RANGE readRange = { 0, 0 };
    if (FAILED(readbackBuf->Map(0, &readRange, reinterpret_cast<void **>(&p)))) {
        qWarning("Mapping the readback buffer failed");
        return QImage();
    }
    for (UINT y = 0; y < rtDesc.Height; ++y) {
        quint8 *dst = img.scanLine(y);
        memcpy(dst, p, rtDesc.Width * 4);
        p += textureLayout.Footprint.RowPitch;
    }
    readbackBuf->Unmap(0, Q_NULLPTR);

    return img;
}
コード例 #7
0
ファイル: platform.cpp プロジェクト: gardhi/PM
EXTERN_C DWORD WINAPI
PlatformSetSystemPowerState (LPCTSTR pszName, BOOL fForce, BOOL fInternal)
{
	DWORD dwStatus = ERROR_SUCCESS;
	PSYSTEM_POWER_STATE pNewSystemPowerState = NULL;
	PDEVICE_POWER_RESTRICTION pNewCeilingDx = NULL;
	BOOL fDoTransition = FALSE;
	INT iPreSuspendPriority = 0;
	static BOOL fFirstCall = TRUE;

	SETFNAME (_T ("PlatformSetSystemPowerState"));

	// Read system power state variables and construct new lists:

	if (gfFileSystemsAvailable)
		PmUpdateSystemPowerStatesIfChanged ();
	dwStatus = RegReadSystemPowerState (pszName, &pNewSystemPowerState, &pNewCeilingDx);

	// Did we get registry information about the new power state?

	if (dwStatus == ERROR_SUCCESS)
	{
		BOOL fSuspendSystem = FALSE;
		static BOOL fWantStartupScreen = FALSE;
		DWORD dwNewStateFlags = pNewSystemPowerState->dwFlags;

		// Assume we will update the system power state:
		fDoTransition = TRUE;

		// Are we going to suspend the system as a whole?
		if ((dwNewStateFlags &
			 (POWER_STATE_SUSPEND | POWER_STATE_OFF | POWER_STATE_CRITICAL | POWER_STATE_RESET)) != 0)
		{
			fSuspendSystem = TRUE;
		}

		// A "critical" suspend might mean we have totally lost battery power and need
		// to suspend really quickly.  Depending on the platform, OEMs may be able
		// to bypass driver notification entirely and rely on xxx_PowerDown() notifications
		// to suspend gracefully.  Or they may be able to implement a critical suspend
		// kernel ioctl.  This sample implementation is very generic and simply sets the
		// POWER_FORCE flag, which is not used.

		if (dwNewStateFlags & (POWER_STATE_CRITICAL | POWER_STATE_OFF | POWER_STATE_RESET))
		{
			fForce = TRUE;
		}

		// If everything seems OK, do the set operation:

		if (fDoTransition)
		{
			POWER_BROADCAST_BUFFER pbb;
			PDEVICE_LIST pdl;
			BOOL fResumeSystem = FALSE;

			// Send out system power state change notifications:
			pbb.Message = PBT_TRANSITION;
			pbb.Flags = pNewSystemPowerState->dwFlags;
			pbb.Length = _tcslen (pNewSystemPowerState->pszName) + 1;	// Char count not byte count for now
			if (pbb.Length > MAX_PATH)
			{
				// Truncate the system power state name -- note, we actually have MAX_PATH + 1
				// characters available.
				pbb.Length = MAX_PATH;
			}
			_tcsncpy_s (pbb.SystemPowerState, _countof (pbb.SystemPowerState),
						pNewSystemPowerState->pszName, pbb.Length);
			pbb.Length *= sizeof (pbb.SystemPowerState[0]);	           // Convert to byte count
			GenerateNotifications ((PPOWER_BROADCAST) & pbb);

			// Is GWES ready?
			if (!gfGwesReady)
			{
				if (WaitForAPIReady (SH_GDI, 0) == WAIT_OBJECT_0)
				{
					gfGwesReady = TRUE;
				}
			}

			// Are we suspending?
			if (fSuspendSystem && gpfnGwesPowerDown != NULL)
			{
				// Start the process of suspending GWES:
				if (gfGwesReady)
				{
					fWantStartupScreen = gpfnGwesPowerDown ();
				}
			}

			// Update global system state variables:
			PMLOCK ();
			PSYSTEM_POWER_STATE pOldSystemPowerState = gpSystemPowerState;
			PDEVICE_POWER_RESTRICTION pOldCeilingDx = gpCeilingDx;

			if (gpSystemPowerState != NULL
				&& (gpSystemPowerState->
					dwFlags & (POWER_STATE_SUSPEND | POWER_STATE_OFF | POWER_STATE_CRITICAL)) != 0)
			{
				// We are exiting a suspended state:
				fResumeSystem = TRUE;
			}
			gpSystemPowerState = pNewSystemPowerState;
			gpCeilingDx = pNewCeilingDx;
			PMUNLOCK ();

			// Are we suspending, resuming, or neither?
			if (fSuspendSystem)
			{
				INT iCurrentPriority;

				// We're suspending: update all devices other than block devices,
				// in case any of them need to access the registry or write files.

				PMLOGMSG (ZONE_PLATFORM || ZONE_RESUME,
						  (_T ("%s: suspending - notifying non-block drivers\r\n"), pszFname));
				for (pdl = gpDeviceLists; pdl != NULL; pdl = pdl->pNext)
				{
					if (*pdl->pGuid != idBlockDevices)
					{
						UpdateClassDeviceStates (pdl);
					}
				}

				// Notify the kernel that we are about to suspend.  This gives the
				// kernel an opportunity to clear wake source flags before we initiate
				// the suspend process.  If we don't do this and a wake source interrupt
				// occurs between the time we call PowerOffSystem() and the time
				// OEMPowerOff() is invoked, it is hard for the kernel to know whether or
				// not to suspend.

				PMLOGMSG (ZONE_PLATFORM || ZONE_RESUME,
						  (_T ("%s: calling KernelIoControl(IOCTL_HAL_PRESUSPEND)\r\n"), pszFname));
				KernelIoControl (IOCTL_HAL_PRESUSPEND, NULL, 0, NULL, 0, NULL);
				iCurrentPriority = CeGetThreadPriority (GetCurrentThread ());
				DEBUGCHK (iCurrentPriority != THREAD_PRIORITY_ERROR_RETURN);
				if (iCurrentPriority != THREAD_PRIORITY_ERROR_RETURN)
				{
					CeSetThreadPriority (GetCurrentThread (), giPreSuspendPriority);
					Sleep (0);
					CeSetThreadPriority (GetCurrentThread (), iCurrentPriority);
				}

				// Notify file systems that their block drivers will soon go away.
				// After making this call, this thread is the only one that can access
				// the file system (including registry and device drivers) without
				// blocking.  Unfortunately, this API takes and holds the file system
				// critical section, so other threads attempting to access the registry
				// or files may cause priority inversions.  To avoid priority problem
				// that may starve the Power Manager, we may raise our own priority to a
				// high level.  Do this if giSuspendPriority is non-zero.

				if (giSuspendPriority != 0)
				{
					iPreSuspendPriority = CeGetThreadPriority (GetCurrentThread ());
					DEBUGCHK (iPreSuspendPriority != THREAD_PRIORITY_ERROR_RETURN);
					PMLOGMSG (ZONE_PLATFORM,
							  (_T
							   ("%s: suspending: raising thread priority for 0x%08x from %d to %d\r\n"),
							   pszFname, GetCurrentThreadId (), iPreSuspendPriority,
							   giSuspendPriority));
					CeSetThreadPriority (GetCurrentThread (), giSuspendPriority);
				}

                // Discard code pages from drivers.  This is a diagnostic tool to
                // forcibly expose paging-related bugs that could cause apparently
                // random system crashes or hangs.  Optionally, OEMs can disable this
                // for production systems to speed up resume times.  We have to call
                // PageOutMode before FileSys Shutdown. Otherwise, it cause dead lock
                // between filesystem and loader.

				if (gfPageOutAllModules)
				{
					ForcePageout ();
				}

				if (g_pSysRegistryAccess)
					g_pSysRegistryAccess->EnterLock ();
				gfFileSystemsAvailable = FALSE;

				if ((dwNewStateFlags & POWER_STATE_RESET) != 0)
				{
					// Is this to be a cold boot?
					if (_tcscmp (pszName, _T ("coldreboot")) == 0)
					{
						SetCleanRebootFlag ();
					}
				}

				FileSystemPowerFunction (FSNOTIFY_POWER_OFF);

				// Update block device power states:
				PMLOGMSG (ZONE_PLATFORM || ZONE_RESUME,
						  (_T ("%s: suspending - notifying block drivers\r\n"), pszFname));
				pdl = GetDeviceListFromClass (&idBlockDevices);
				if (pdl != NULL)
				{
					UpdateClassDeviceStates (pdl);
				}

				// Handle resets and shutdowns here, after flushing files.  Since Windows CE does
				// not define a standard mechanism for handling shutdown (via POWER_STATE_OFF),
				// OEMs will need to fill in the appropriate code here.  Similarly, if an OEM does
				// not support IOCTL_HAL_REBOOT, they should not support POWER_STATE_RESET.

				if ((dwNewStateFlags & POWER_STATE_RESET) != 0)
				{
					// Should not return from this call, but if we do just suspend the system:
					KernelLibIoControl ((HANDLE) KMOD_OAL, IOCTL_HAL_REBOOT, NULL, 0, NULL, 0,
										NULL);
					RETAILMSG (TRUE,
							   (_T
								("PM: PlatformSetSystemPowerState: KernelIoControl(IOCTL_HAL_REBOOT) returned!\r\n")));
					DEBUGCHK (FALSE);	// Break into the debugger.
				}
			}
			else if (fResumeSystem)
			{
				// We're waking up from a resume -- update block device power states
				// so we can access the registry and/or files.

				PMLOGMSG (ZONE_PLATFORM || ZONE_RESUME,
						  (_T ("%s: resuming - notifying block drivers\r\n"), pszFname));
				pdl = GetDeviceListFromClass (&idBlockDevices);
				if (pdl != NULL)
				{
					UpdateClassDeviceStates (pdl);
				}

				// Notify file systems that their block drivers are back.

				FileSystemPowerFunction (FSNOTIFY_POWER_ON);
				gfFileSystemsAvailable = TRUE;
				if (g_pSysRegistryAccess)
					g_pSysRegistryAccess->LeaveLock ();

				// Update all devices other than block devices:

				PMLOGMSG (ZONE_PLATFORM || ZONE_RESUME,
						  (_T ("%s: resuming - notifying block drivers\r\n"), pszFname));
				for (pdl = gpDeviceLists; pdl != NULL; pdl = pdl->pNext)
				{
					if (*pdl->pGuid != idBlockDevices)
					{
						UpdateClassDeviceStates (pdl);
					}
				}

				// Tell GWES to wake up:
				if (gpfnGwesPowerUp != NULL && gfGwesReady)
				{
					gpfnGwesPowerUp (fWantStartupScreen);
					fWantStartupScreen = FALSE;
				}

				// Send out resume notification:
				pbb.Message = PBT_RESUME;
				pbb.Flags = 0;
				pbb.Length = 0;
				pbb.SystemPowerState[0] = 0;
				GenerateNotifications ((PPOWER_BROADCAST) & pbb);
			}
			else
			{
				// Update all devices without any particular ordering:
				UpdateAllDeviceStates ();
			}

			// Release the old state information:
			SystemPowerStateDestroy (pOldSystemPowerState);
			while (pOldCeilingDx != NULL)
			{
				PDEVICE_POWER_RESTRICTION pdpr = pOldCeilingDx->pNext;

				PowerRestrictionDestroy (pOldCeilingDx);
				pOldCeilingDx = pdpr;
			}

			// Are we suspending?
			if (fSuspendSystem)
			{
				// Set a flag to notify the resume thread that this was a controlled suspend.
				gfSystemSuspended = TRUE;

				PMLOGMSG (ZONE_PLATFORM
						  || ZONE_RESUME, (_T ("%s: calling PowerOffSystem()\r\n"), pszFname));
				PowerOffSystem ();	    // Sets a flag in the kernel for the scheduler.
				Sleep (0);	            // Force the scheduler to run.
				PMLOGMSG (ZONE_PLATFORM
						  || ZONE_RESUME, (_T ("%s: back from PowerOffSystem()\r\n"), pszFname));

				// Clear the suspend flag:
				gfSystemSuspended = FALSE;
			}
		}
		else
		{
			// Release the unused new state information:
			SystemPowerStateDestroy (pNewSystemPowerState);
			while (pNewCeilingDx != NULL)
			{
				PDEVICE_POWER_RESTRICTION pdpr = pNewCeilingDx->pNext;

				PowerRestrictionDestroy (pNewCeilingDx);
				pNewCeilingDx = pdpr;
			}
		}
	}

	// Restore our priority if we updated it during a suspend transition:
	if (giSuspendPriority != 0 && iPreSuspendPriority != 0)
	{
		PMLOGMSG (ZONE_PLATFORM, (_T ("%s: restoring thread priority to %d\r\n"),
								  pszFname, iPreSuspendPriority));
		CeSetThreadPriority (GetCurrentThread (), iPreSuspendPriority);
	}

	return dwStatus;
}
コード例 #8
0
ファイル: DataCollection.cpp プロジェクト: eaglesky/ARLK
/// <summary>
/// Handle windows messages for the class instance
/// </summary>
/// <param name="hWnd">window message is for</param>
/// <param name="uMsg">message</param>
/// <param name="wParam">message data</param>
/// <param name="lParam">additional message data</param>
/// <returns>result of message processing</returns>
LRESULT CALLBACK CDataCollection::DlgProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	int chour,cmin,csec;
	double dTimeInSeconds;
	WORD wDelayCharNum;
	TCHAR DelayTime[3];
	TCHAR ConstraintBuf[10];
	BROWSEINFO   bf;   
    LPITEMIDLIST   lpitem;   
	WCHAR comboItem[MAX_PATH];
//	WCHAR fileSavedMessage[50];

    switch (message)
    {
        case WM_INITDIALOG:
        {
			LOGFONT lf;
            // Bind application window handle
            m_hWnd = hWnd;

            // Init Direct2D
            D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, &m_pD2DFactory);

            // Create and initialize a new Direct2D image renderer (take a look at ImageRenderer.h)
            // We'll use this to draw the data we receive from the Kinect to the screen
            m_pDrawColor = new ImageRenderer();
			//m_pDrawDepth = new ImageRenderer();

            HRESULT hr = m_pDrawColor->Initialize(GetDlgItem(m_hWnd, IDC_COLOR), m_pD2DFactory, cColorWidth, cColorHeight, cColorWidth * sizeof(long));
            if (FAILED(hr))
            {
                SetStatusMessage(L"Failed to initialize the Direct2D draw device.");
            }

            // Look for a connected Kinect, and create it if found
            CreateFirstConnected();

			if(!SetCurrentDirectory(L"..\\output"))
				CreateDirectory(L"..\\output",NULL);
			
			//Set the font for recording time display
			GetObject( (HFONT) GetStockObject(DEFAULT_GUI_FONT), sizeof(lf), &lf );
			lf.lfHeight *= 3;
			SendDlgItemMessage( hWnd, IDC_SEC, WM_SETFONT, (WPARAM)CreateFontIndirect(&lf), 0 );
			SendDlgItemMessage( hWnd, IDC_MIN, WM_SETFONT, (WPARAM)CreateFontIndirect(&lf), 0 );
			SendDlgItemMessage( hWnd, IDC_HOUR, WM_SETFONT, (WPARAM)CreateFontIndirect(&lf), 0 );
			SendDlgItemMessage( hWnd, IDC_FRAME_SHOW, WM_SETFONT, (WPARAM)CreateFontIndirect(&lf), 0 );
			SendDlgItemMessage( hWnd, IDC_SEP, WM_SETFONT, (WPARAM)CreateFontIndirect(&lf), 0 );
			SendDlgItemMessage( hWnd, IDC_TIME_COUNT, WM_SETFONT, (WPARAM)CreateFontIndirect(&lf), 0 );

			SetWindowText(GetDlgItem(hWnd,IDC_DELAY),L"0");

			StringCchPrintfW(comboItem, _countof(comboItem), L"No constraints");
			SendDlgItemMessage(hWnd, IDC_MODE, CB_ADDSTRING, 0, reinterpret_cast<LPARAM>(comboItem));
			StringCchPrintfW(comboItem, _countof(comboItem), L"Time length(s)");
			SendDlgItemMessage(hWnd, IDC_MODE, CB_ADDSTRING, 0, reinterpret_cast<LPARAM>(comboItem));
			StringCchPrintfW(comboItem, _countof(comboItem), L"Frame number");
			SendDlgItemMessage(hWnd, IDC_MODE, CB_ADDSTRING, 0, reinterpret_cast<LPARAM>(comboItem));

			SendDlgItemMessage(hWnd, IDC_MODE, CB_SETCURSEL,0, 0);
			m_iRecordingModeIndex=DEFAULT_MODE;
			
		
			lastframetime=GetTickCount();
        }
        break;

        // If the titlebar X is clicked, destroy app
        case WM_CLOSE:
            DestroyWindow(hWnd);
            break;

        case WM_DESTROY:
            // Quit the main message pump
		
		
            PostQuitMessage(0);
            break;

        case WM_TIMER:                      //Handle timer message
			if(m_bSaveSkeStart){
			switch (wParam)  
			{  
			case TIMER_SEC:  
			
				currenttime=GetTickCount();
				dTimeInSeconds=(currenttime-starttime)/1000.0;
				csec=((currenttime-starttime)/1000)%60;
				cmin=((currenttime-starttime)/60000)%60;
				chour=((currenttime-starttime)/3600000)%24;
				::SetDlgItemInt(hWnd, static_cast<int>(IDC_SEC),csec, FALSE );
                ::SetDlgItemInt(hWnd, static_cast<int>(IDC_MIN),cmin, FALSE );
				::SetDlgItemInt(hWnd, static_cast<int>(IDC_HOUR),chour, FALSE );

				
				break ;  
		
			} 
			}
			else if (m_bIsInDelay){
				m_iDelayTime--;
				::SetDlgItemInt(hWnd, static_cast<int>(IDC_TIME_COUNT),m_iDelayTime, FALSE );
				if(m_iDelayTime==0)
				{
					//DEBUG("Start!\n");
					
				    USES_CONVERSION;
				    const char* ascName = T2A(skefname);
					
					m_pSkeData->SaveStart(ascName,m_iFrameConstraint,m_dwTimeConstraint);
					m_bIsInDelay = false;
					m_bSaveSkeStart = true;
					starttime = GetTickCount();
					
				}
				else{
					m_bIsInDelay = true;
				}
			}
			break;

        // Handle button press
        case WM_COMMAND:
            
			

			// If it was for the start control and a button clicked event, start saving the skeleton frame
			if(IDC_START== LOWORD(wParam) && BN_CLICKED == HIWORD(wParam))
			{
                TCHAR timeString[MAX_PATH];
				WORD wSavePathNum;
                
			    m_dwTimeConstraint = 0;
				m_iFrameConstraint = 0;
				
				GetTimeFormatEx(NULL,TIME_FORCE24HOURFORMAT, NULL, L"hh'-'mm'-'ss", timeString, _countof(timeString));
				wSavePathNum=(WORD) SendDlgItemMessage(hWnd,IDC_SAVE_PATH, EM_LINELENGTH, (WPARAM) 0, (LPARAM) 0);
				if(wSavePathNum==0)
				{
                    StringCchPrintfW(skefname, _countof(skefname), L"..\\output\\KinectSkeletonVideo-%s.skd",timeString);
				}
				else{
					StringCchPrintfW(skefname, _countof(skefname), L"%s\\KinectSkeletonVideo-%s.skd",m_SkeFilePath,timeString);
				}

				//hskf=CreateFile(skefname, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
				//SetFilePointer(hskf,sizeof(SKEFILEHEADER)+sizeof(SKEINFORHEADER),NULL,FILE_CURRENT);
				wDelayCharNum=(WORD) SendDlgItemMessage(hWnd,IDC_DELAY, EM_LINELENGTH, (WPARAM) 0, (LPARAM) 0); 
				if (wDelayCharNum >= 3) 
				{ 
					MessageBox(hWnd, L"Too many characters!The number of characters should not be more than 3!", 
						L"Error", 
						MB_OK); 
					break;
				} 
				else if (wDelayCharNum == 0) 
				{ 
					MessageBox(hWnd, L"No characters entered.", 
						L"Error", 
						MB_OK);
					break;
				} 
				SendDlgItemMessage(hWnd,IDC_DELAY,EM_GETLINE, 
					(WPARAM) 0,       // line 0 
					(LPARAM) DelayTime);

				m_iDelayTime=::StrToInt(DelayTime);
				::SetDlgItemInt(hWnd, static_cast<int>(IDC_TIME_COUNT),m_iDelayTime, FALSE );
				

                SendDlgItemMessage(hWnd,IDC_CONSTRAINT,EM_GETLINE, 
						(WPARAM) 0,       // line 0 
						(LPARAM) ConstraintBuf);

				if(m_iRecordingModeIndex==TIME_MODE)
				{
					m_dwTimeConstraint=::StrToInt(ConstraintBuf);
				}
				else if(m_iRecordingModeIndex==FRAME_MODE)
				{
					m_iFrameConstraint=::StrToInt(ConstraintBuf);
				}

				::SetDlgItemInt(hWnd, static_cast<int>(IDC_SEC),0, FALSE );
				::SetDlgItemInt(hWnd, static_cast<int>(IDC_MIN),0, FALSE );
				::SetDlgItemInt(hWnd, static_cast<int>(IDC_HOUR),0, FALSE );
				::SetDlgItemInt(hWnd, static_cast<int>(IDC_FRAME_SHOW),0, FALSE );
				 
				if(m_iDelayTime==0)
				{
					//DEBUG("Start!\n");
					m_pSkeData->SaveStart((const char*)skefname,m_iFrameConstraint,m_dwTimeConstraint);
					m_bSaveSkeStart = true;
					

				} else {
				   
					m_bIsInDelay = true;
				}
				SetTimer (hWnd, TIMER_SEC, 1000, NULL) ;
			}

			// If it was for the stop control and a button clicked event, stop saving the skeleton frame
			if(IDC_STOP== LOWORD(wParam) && BN_CLICKED == HIWORD(wParam))
			{
				if(m_bSaveSkeStart)
				{
					KillTimer (hWnd, TIMER_SEC) ;
					m_bSaveSkeStart=false;
				    m_pSkeData->SaveEnd();
					//DEBUG("Stop!\n");
				}
				else if(m_bIsInDelay){
					KillTimer (hWnd, TIMER_SEC) ;
					::SetDlgItemInt(hWnd, static_cast<int>(IDC_TIME_COUNT),0, FALSE );
                   // CloseHandle(hskf);
					DeleteFile(skefname);
					
				}
				
					
			}

			if(IDC_BROWSE== LOWORD(wParam) && BN_CLICKED == HIWORD(wParam))
			{
				memset(&bf,0,sizeof(BROWSEINFO));   
                bf.hwndOwner=hWnd;   
                bf.lpszTitle=L"Choose the directory";   
                bf.ulFlags=BIF_RETURNONLYFSDIRS;    
                lpitem=SHBrowseForFolder(&bf);
				SHGetPathFromIDList(lpitem,m_SkeFilePath); 
				SetDlgItemText(hWnd,IDC_SAVE_PATH,m_SkeFilePath);
				

			}

			// If it was for the reset time control and a button clicked event, reset the time displayed to 0:0:0
			if(IDC_Reset== LOWORD(wParam) && BN_CLICKED == HIWORD(wParam))
			{
				::SetDlgItemInt(hWnd, static_cast<int>(IDC_SEC),0, FALSE );
				::SetDlgItemInt(hWnd, static_cast<int>(IDC_MIN),0, FALSE );
				::SetDlgItemInt(hWnd, static_cast<int>(IDC_HOUR),0, FALSE );
				::SetDlgItemInt(hWnd, static_cast<int>(IDC_FRAME_SHOW),0, FALSE );
			}

			// If there is a change of selection in the combobox
			if(HIWORD(wParam) == CBN_SELCHANGE)
			{
				 m_iRecordingModeIndex = SendMessage((HWND) lParam, (UINT) CB_GETCURSEL, 
					(WPARAM) 0, (LPARAM) 0);
				// DEBUG("Current mode:%d\n",m_iRecordingModeIndex);
				 if(m_iRecordingModeIndex==TIME_MODE)
				 {
					 SetWindowText(GetDlgItem(hWnd,IDC_CONSTRAINT),L"5");
				 }
				 else if(m_iRecordingModeIndex==FRAME_MODE)
				 {
					 SetWindowText(GetDlgItem(hWnd,IDC_CONSTRAINT),L"100");
				 }
				 else{
					 SetWindowText(GetDlgItem(hWnd,IDC_CONSTRAINT),L"");
				 }
			}
			
            break;
    }

    return FALSE;
}
コード例 #9
0
ファイル: DataCollection.cpp プロジェクト: eaglesky/ARLK
/// <summary>
/// Get the name of the file where screenshot will be stored.
/// </summary>
/// <param name="screenshotName">
/// [out] String buffer that will receive screenshot file name.
/// </param>
/// <param name="screenshotNameSize">
/// [in] Number of characters in screenshotName string buffer.
/// </param>
/// <returns>
/// S_OK on success, otherwise failure code.
/// </returns>
HRESULT GetScreenshotFileName(wchar_t *screenshotName, UINT screenshotNameSize,int shotType)
{
   wchar_t *knownPath = NULL;
    HRESULT hr = SHGetKnownFolderPath(FOLDERID_Pictures, 0, NULL, &knownPath);
	
      knownPath=L"..\\output";
    if (SUCCEEDED(hr))
    {
        // Get the time
        wchar_t timeString[MAX_PATH];
        GetTimeFormatEx(NULL,TIME_FORCE24HOURFORMAT, NULL, L"hh'-'mm'-'ss", timeString, _countof(timeString));

		// File name will be KinectColorShot-HH-MM-SS(shotType==0)
		//                or KinectDepthShot-HH-MM-SS(shotType==1)
        if(shotType==0)
        StringCchPrintfW(screenshotName, screenshotNameSize, L"%s\\KinectColorShot-%s.bmp", knownPath, timeString);
		else if(shotType==1)
        StringCchPrintfW(screenshotName, screenshotNameSize, L"%s\\KinectDepthShot-%s.bmp", knownPath, timeString);
    }

   // CoTaskMemFree(knownPath);
    return hr;
}
コード例 #10
0
 // Returns the number of special non-enumerable properties this type has.
 uint JavascriptStringObject::GetSpecialPropertyCount() const
 {
     return _countof(specialPropertyIds);
 }
コード例 #11
0
static void SetValue(CIcqProto* ppro, HWND hwndDlg, int idCtrl, MCONTACT hContact, char* szModule, char* szSetting, int special)
{
	DBVARIANT dbv = { 0 };
	char str[MAX_PATH];
	char* pstr = NULL;
	int unspecified = 0;
	int bUtf = 0, bDbv = 0, bAlloc = 0;

	dbv.type = DBVT_DELETED;

	if ((hContact == NULL) && ((int)szModule < 0x100)) {
		dbv.type = (BYTE)szModule;

		switch ((int)szModule) {
		case DBVT_BYTE:
			dbv.cVal = (BYTE)szSetting;
			break;
		case DBVT_WORD:
			dbv.wVal = (WORD)szSetting;
			break;
		case DBVT_DWORD:
			dbv.dVal = (DWORD)szSetting;
			break;
		case DBVT_ASCIIZ:
			dbv.pszVal = pstr = szSetting;
			break;
		default:
			unspecified = 1;
			dbv.type = DBVT_DELETED;
		}
	}
	else {
		if (szModule == NULL)
			unspecified = 1;
		else {
			unspecified = db_get(hContact, szModule, szSetting, &dbv);
			bDbv = 1;
		}
	}

	if (!unspecified) {
		switch (dbv.type) {
		case DBVT_BYTE:
			unspecified = (special == SVS_ZEROISUNSPEC && dbv.bVal == 0);
			pstr = _itoa(special == SVS_SIGNED ? dbv.cVal : dbv.bVal, str, 10);
			break;

		case DBVT_WORD:
			if (special == SVS_ICQVERSION) {
				if (dbv.wVal != 0) {
					char szExtra[80];

					mir_snprintf(str, "%d", dbv.wVal);
					pstr = str;

					if (hContact && ppro->IsDirectConnectionOpen(hContact, DIRECTCONN_STANDARD, 1)) {
						ICQTranslateUtfStatic(LPGEN(" (DC Established)"), szExtra, _countof(szExtra));
						mir_strcat(str, (char*)szExtra);
						bUtf = 1;
					}
				}
				else
					unspecified = 1;
			}
			else if (special == SVS_STATUSID) {
				char *pszStatus = MirandaStatusToStringUtf(dbv.wVal);
				BYTE bXStatus = ppro->getContactXStatus(hContact);

				if (bXStatus) {
					char *pXName = ppro->getSettingStringUtf(hContact, DBSETTING_XSTATUS_NAME, NULL);
					if (pXName == NULL) // give default name
						pXName = ICQTranslateUtf(nameXStatus[bXStatus - 1]);

					mir_snprintf(str, "%s (%s)", pszStatus, pXName);
					SAFE_FREE((void**)&pXName);
				}
				else strncpy_s(str, pszStatus, _TRUNCATE);

				bUtf = 1;
				SAFE_FREE(&pszStatus);
				pstr = str;
				unspecified = 0;
			}
			else {
				unspecified = (special == SVS_ZEROISUNSPEC && dbv.wVal == 0);
				pstr = _itoa(special == SVS_SIGNED ? dbv.sVal : dbv.wVal, str, 10);
			}
			break;

		case DBVT_DWORD:
			unspecified = (special == SVS_ZEROISUNSPEC && dbv.dVal == 0);
			if (special == SVS_IP) {
				struct in_addr ia;
				ia.S_un.S_addr = htonl(dbv.dVal);
				pstr = inet_ntoa(ia);
				if (dbv.dVal == 0)
					unspecified = 1;
			}
			else if (special == SVS_TIMESTAMP) {
				if (dbv.dVal == 0)
					unspecified = 1;
				else
					pstr = time2text(dbv.dVal);
			}
			else
				pstr = _itoa(special == SVS_SIGNED ? dbv.lVal : dbv.dVal, str, 10);
			break;

		case DBVT_ASCIIZ:
		case DBVT_WCHAR:
			unspecified = (special == SVS_ZEROISUNSPEC && dbv.pszVal[0] == '\0');
			if (!unspecified && pstr != szSetting) {
				pstr = ppro->getSettingStringUtf(hContact, szModule, szSetting, NULL);
				bUtf = 1;
				bAlloc = 1;
			}
			if (idCtrl == IDC_UIN)
				SetDlgItemText(hwndDlg, IDC_UINSTATIC, TranslateT("ScreenName:"));
			break;

		default:
			pstr = str;
			mir_strcpy(str, "???");
			break;
		}
	}

	EnableDlgItem(hwndDlg, idCtrl, !unspecified);
	if (unspecified)
		SetDlgItemText(hwndDlg, idCtrl, TranslateT("<not specified>"));
	else if (bUtf)
		SetDlgItemTextUtf(hwndDlg, idCtrl, pstr);
	else
		SetDlgItemTextA(hwndDlg, idCtrl, pstr);

	if (bDbv)
		db_free(&dbv);

	if (bAlloc)
		SAFE_FREE(&pstr);
}
コード例 #12
0
ファイル: ch.cpp プロジェクト: EdMaurer/ChakraCore
HRESULT ExecuteTest(const char* fileName)
{
    HRESULT hr = S_OK;
    LPCWSTR fileContents = nullptr;
    JsRuntimeHandle runtime = JS_INVALID_RUNTIME_HANDLE;

    if(strlen(fileName) >= 14 && strcmp(fileName + strlen(fileName) - 14, "ttdSentinal.js") == 0)
    {
#if !ENABLE_TTD
        wprintf(_u("Sential js file is only ok when in TTDebug mode!!!\n"));
        return E_FAIL;
#else
        if(!doTTDebug)
        {
            wprintf(_u("Sential js file is only ok when in TTDebug mode!!!\n"));
            return E_FAIL;
        }

        jsrtAttributes = static_cast<JsRuntimeAttributes>(jsrtAttributes | JsRuntimeAttributeEnableExperimentalFeatures);

        IfJsErrorFailLog(ChakraRTInterface::JsTTDCreateDebugRuntime(jsrtAttributes, ttUri, nullptr, &runtime));
        chRuntime = runtime;

        ChakraRTInterface::JsTTDSetIOCallbacks(runtime, &Helpers::GetTTDDirectory, &Helpers::TTInitializeForWriteLogStreamCallback, &Helpers::TTGetLogStreamCallback, &Helpers::TTGetSnapshotStreamCallback, &Helpers::TTGetSrcCodeStreamCallback, &Helpers::TTReadBytesFromStreamCallback, &Helpers::TTWriteBytesToStreamCallback, &Helpers::TTFlushAndCloseStreamCallback);

        JsContextRef context = JS_INVALID_REFERENCE;
        IfJsErrorFailLog(ChakraRTInterface::JsTTDCreateContext(runtime, &context));
        IfJsErrorFailLog(ChakraRTInterface::JsSetCurrentContext(context));

        IfFailGo(RunScript(fileName, fileContents, nullptr, nullptr));
#endif
    }
    else
    {
        bool isUtf8 = false;
        LPCOLESTR contentsRaw = nullptr;
        UINT lengthBytes = 0;

        char fullPath[_MAX_PATH];
        size_t len = 0;

        hr = Helpers::LoadScriptFromFile(fileName, fileContents, &isUtf8, &contentsRaw, &lengthBytes);
        contentsRaw; lengthBytes; // Unused for now.

        IfFailGo(hr);
        if(HostConfigFlags::flags.GenerateLibraryByteCodeHeaderIsEnabled)
        {
            jsrtAttributes = (JsRuntimeAttributes)(jsrtAttributes | JsRuntimeAttributeSerializeLibraryByteCode);
        }

#if ENABLE_TTD
        if(doTTRecord)
        {
            //Ensure we run with experimental features (as that is what Node does right now).
            jsrtAttributes = static_cast<JsRuntimeAttributes>(jsrtAttributes | JsRuntimeAttributeEnableExperimentalFeatures);

            IfJsErrorFailLog(ChakraRTInterface::JsTTDCreateRecordRuntime(jsrtAttributes, ttUri, snapInterval, snapHistoryLength, nullptr, &runtime));
            chRuntime = runtime;

            ChakraRTInterface::JsTTDSetIOCallbacks(runtime, &Helpers::GetTTDDirectory, &Helpers::TTInitializeForWriteLogStreamCallback, &Helpers::TTGetLogStreamCallback, &Helpers::TTGetSnapshotStreamCallback, &Helpers::TTGetSrcCodeStreamCallback, &Helpers::TTReadBytesFromStreamCallback, &Helpers::TTWriteBytesToStreamCallback, &Helpers::TTFlushAndCloseStreamCallback);

            JsContextRef context = JS_INVALID_REFERENCE;
            IfJsErrorFailLog(ChakraRTInterface::JsTTDCreateContext(runtime, &context));
            IfJsErrorFailLog(ChakraRTInterface::JsSetCurrentContext(context));
        }
        else
        {
            AssertMsg(!doTTDebug, "Should be handled in the else case above!!!");

            IfJsErrorFailLog(ChakraRTInterface::JsCreateRuntime(jsrtAttributes, nullptr, &runtime));
            chRuntime = runtime;

            if(HostConfigFlags::flags.DebugLaunch)
            {
                Debugger* debugger = Debugger::GetDebugger(runtime);
                debugger->StartDebugging(runtime);
            }

            JsContextRef context = JS_INVALID_REFERENCE;
            IfJsErrorFailLog(ChakraRTInterface::JsCreateContext(runtime, &context));
            IfJsErrorFailLog(ChakraRTInterface::JsSetCurrentContext(context));
        }
#else
        IfJsErrorFailLog(ChakraRTInterface::JsCreateRuntime(jsrtAttributes, nullptr, &runtime));
        chRuntime = runtime;

        if(HostConfigFlags::flags.DebugLaunch)
        {
            Debugger* debugger = Debugger::GetDebugger(runtime);
            debugger->StartDebugging(runtime);
        }

        JsContextRef context = JS_INVALID_REFERENCE;
        IfJsErrorFailLog(ChakraRTInterface::JsCreateContext(runtime, &context));
        IfJsErrorFailLog(ChakraRTInterface::JsSetCurrentContext(context));
#endif

#ifdef DEBUG
        ChakraRTInterface::SetCheckOpHelpersFlag(true);
#endif

        if(!WScriptJsrt::Initialize())
        {
            IfFailGo(E_FAIL);
        }

    if (_fullpath(fullPath, fileName, _MAX_PATH) == nullptr)
    {
        IfFailGo(E_FAIL);
    }

    // canonicalize that path name to lower case for the profile storage
    // REVIEW: Assuming no utf8 characters here
    len = strlen(fullPath);
    for (size_t i = 0; i < len; i++)
    {
        fullPath[i] = (char) tolower(fullPath[i]);
    }

    if (HostConfigFlags::flags.GenerateLibraryByteCodeHeaderIsEnabled)
    {
        if (isUtf8)
        {
            if (HostConfigFlags::flags.GenerateLibraryByteCodeHeader != nullptr && *HostConfigFlags::flags.GenerateLibraryByteCodeHeader != _u('\0'))
            {
                CHAR libraryName[_MAX_PATH];
                CHAR ext[_MAX_EXT];
                _splitpath_s(fullPath, NULL, 0, NULL, 0, libraryName, _countof(libraryName), ext, _countof(ext));

                    IfFailGo(CreateLibraryByteCodeHeader(fileContents, (BYTE*)contentsRaw, lengthBytes, HostConfigFlags::flags.GenerateLibraryByteCodeHeader, libraryName));
                }
                else
                {
                    fwprintf(stderr, _u("FATAL ERROR: -GenerateLibraryByteCodeHeader must provide the file name, i.e., -GenerateLibraryByteCodeHeader:<bytecode file name>, exiting\n"));
                    IfFailGo(E_FAIL);
                }
            }
            else
            {
                fwprintf(stderr, _u("FATAL ERROR: GenerateLibraryByteCodeHeader flag can only be used on UTF8 file, exiting\n"));
                IfFailGo(E_FAIL);
            }
        }
        else if(HostConfigFlags::flags.SerializedIsEnabled)
        {
            if(isUtf8)
            {
                CreateAndRunSerializedScript(fileName, fileContents, fullPath);
            }
            else
            {
                fwprintf(stderr, _u("FATAL ERROR: Serialized flag can only be used on UTF8 file, exiting\n"));
                IfFailGo(E_FAIL);
            }
        }
        else
        {
            IfFailGo(RunScript(fileName, fileContents, nullptr, fullPath));
        }
    }

Error:
    if (Debugger::debugger != nullptr)
    {
        Debugger::debugger->CompareOrWriteBaselineFile(fileName);
        Debugger::CloseDebugger();
    }

    ChakraRTInterface::JsSetCurrentContext(nullptr);

    if (runtime != JS_INVALID_RUNTIME_HANDLE)
    {
        ChakraRTInterface::JsDisposeRuntime(runtime);
    }

    _flushall();

    return hr;
}
コード例 #13
0
ファイル: ch.cpp プロジェクト: EdMaurer/ChakraCore
HRESULT CreateLibraryByteCodeHeader(LPCOLESTR fileContents, BYTE * contentsRaw, DWORD lengthBytes, LPCWSTR bcFullPath, LPCSTR libraryNameNarrow)
{
    HANDLE bcFileHandle = nullptr;
    BYTE *bcBuffer = nullptr;
    DWORD bcBufferSize = 0;
    HRESULT hr = GetSerializedBuffer(fileContents, &bcBuffer, &bcBufferSize);

    if (FAILED(hr)) return hr;

    bcFileHandle = CreateFile(bcFullPath, GENERIC_WRITE, FILE_SHARE_DELETE, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
    if (bcFileHandle == INVALID_HANDLE_VALUE)
    {
        return E_FAIL;
    }

    DWORD written;

    // For validating the header file against the library file
    auto outputStr =
        "//-------------------------------------------------------------------------------------------------------\r\n"
        "// Copyright (C) Microsoft. All rights reserved.\r\n"
        "// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.\r\n"
        "//-------------------------------------------------------------------------------------------------------\r\n"
        "#if 0\r\n";
    IfFalseGo(WriteFile(bcFileHandle, outputStr, (DWORD)strlen(outputStr), &written, nullptr));
    IfFalseGo(WriteFile(bcFileHandle, contentsRaw, lengthBytes, &written, nullptr));
    if (lengthBytes < 2 || contentsRaw[lengthBytes - 2] != '\r' || contentsRaw[lengthBytes - 1] != '\n')
    {
        outputStr = "\r\n#endif\r\n";
    }
    else
    {
        outputStr = "#endif\r\n";
    }
    IfFalseGo(WriteFile(bcFileHandle, outputStr, (DWORD)strlen(outputStr), &written, nullptr));

    // Write out the bytecode
    outputStr = "namespace Js\r\n{\r\n    const char Library_Bytecode_";
    IfFalseGo(WriteFile(bcFileHandle, outputStr, (DWORD)strlen(outputStr), &written, nullptr));
    IfFalseGo(WriteFile(bcFileHandle, libraryNameNarrow, (DWORD)strlen(libraryNameNarrow), &written, nullptr));
    outputStr = "[] = {\r\n/* 00000000 */";
    IfFalseGo(WriteFile(bcFileHandle, outputStr, (DWORD)strlen(outputStr), &written, nullptr));

    for (unsigned int i = 0; i < bcBufferSize; i++)
    {
        char scratch[6];
        auto scratchLen = sizeof(scratch);
        int num = _snprintf_s(scratch, scratchLen, _countof(scratch), " 0x%02X", bcBuffer[i]);
        Assert(num == 5);
        IfFalseGo(WriteFile(bcFileHandle, scratch, (DWORD)(scratchLen - 1), &written, nullptr));

        // Add a comma and a space if this is not the last item
        if (i < bcBufferSize - 1)
        {
            char commaSpace[2];
            _snprintf_s(commaSpace, sizeof(commaSpace), _countof(commaSpace), ",");  // close quote, new line, offset and open quote
            IfFalseGo(WriteFile(bcFileHandle, commaSpace, (DWORD)strlen(commaSpace), &written, nullptr));
        }

        // Add a line break every 16 scratches, primarily so the compiler doesn't complain about the string being too long.
        // Also, won't add for the last scratch
        if (i % 16 == 15 && i < bcBufferSize - 1)
        {
            char offset[17];
            _snprintf_s(offset, sizeof(offset), _countof(offset), "\r\n/* %08X */", i + 1);  // close quote, new line, offset and open quote
            IfFalseGo(WriteFile(bcFileHandle, offset, (DWORD)strlen(offset), &written, nullptr));
        }
    }
    outputStr = "};\r\n\r\n";
    IfFalseGo(WriteFile(bcFileHandle, outputStr, (DWORD)strlen(outputStr), &written, nullptr));

    outputStr = "}\r\n";
    IfFalseGo(WriteFile(bcFileHandle, outputStr, (DWORD)strlen(outputStr), &written, nullptr));

Error:
    if (bcFileHandle != nullptr)
    {
        CloseHandle(bcFileHandle);
    }
    if (bcBuffer != nullptr)
    {
        delete[] bcBuffer;
    }

    return hr;
}
コード例 #14
0
ファイル: Log.cpp プロジェクト: dadamitskiy/Log
void DA::Log::PrintToTextFile(const char* File, const char* Function, int LineNumber, const char* LogCategory, Verbosity::Type VerbosityLevel, DetailLevel::Type Detail, const char* Format, va_list Args)
{
	// If an OutputLogs folder does not exist, create one.
	DWORD filetype = GetFileAttributes(L"OutputLogs");
	if (filetype == INVALID_FILE_ATTRIBUTES && (filetype & FILE_ATTRIBUTE_DIRECTORY))
	{
		_mkdir("OutputLogs");
	}

	// Setup the text file name and path based off of the category name.
	std::string filename = "OutputLogs/";
	filename += LogCategory;
	filename += ".txt";

	// Store the LOG message into streamBuffer.
	char streamBuffer[512];
	vsnprintf_s(streamBuffer, _countof(streamBuffer), _TRUNCATE, Format, Args);

	// Append the data to a text file.
	std::ofstream fout;
	fout.open(filename.c_str(), std::ios_base::out | std::ios_base::app);
	if (fout.is_open())
	{
		if (Detail == DetailLevel::High)
		{
			PrintTimeStampToTextFile(fout);
		}

		if (Detail != DetailLevel::Low)
		{
			// Print the file, function, and line the LOG statement was called on.
			char detailBuffer[128];
			_snprintf_s(detailBuffer, _TRUNCATE, "[File: %s, Function: %s, Line: %d] - ", File, Function, LineNumber);
			fout << detailBuffer;
		}

		// Print out the verbosity level.
		if (VerbosityLevel == Verbosity::Info)
		{
			fout << "INFO: ";
		}
		else if (VerbosityLevel == Verbosity::Debug)
		{
			fout << "DEBUG: ";
		}
		else if (VerbosityLevel == Verbosity::Warning)
		{
			fout << "WARNING: ";
		}
		else if (VerbosityLevel == Verbosity::Error)
		{
			fout << "ERROR: ";
		}
		else if (VerbosityLevel == Verbosity::Fatal)
		{
			fout << "FATAL: ";
		}

		fout << streamBuffer << std::endl;
		fout.close();
	}
}
コード例 #15
0
void CShellUpdater::WorkerThread()
{
	HANDLE hWaitHandles[2];
	hWaitHandles[0] = m_hTerminationEvent;
	hWaitHandles[1] = m_hWakeEvent;

	for(;;)
	{
		DWORD waitResult = WaitForMultipleObjects(_countof(hWaitHandles), hWaitHandles, FALSE, INFINITE);

		// exit event/working loop if the first event (m_hTerminationEvent)
		// has been signaled or if one of the events has been abandoned
		// (i.e. ~CShellUpdater() is being executed)
		if(waitResult == WAIT_OBJECT_0 || waitResult == WAIT_ABANDONED_0 || waitResult == WAIT_ABANDONED_0+1)
		{
			// Termination event
			break;
		}
		// wait some time before we notify the shell
		Sleep(50);
		for(;;)
		{
			CTGitPath workingPath;
			if (!m_bRunning)
				return;
			Sleep(0);
			{
				AutoLocker lock(m_critSec);
				if(m_pathsToUpdate.empty())
				{
					// Nothing left to do
					break;
				}

				if(m_bItemsAddedSinceLastUpdate)
				{
					m_pathsToUpdate.erase(std::unique(m_pathsToUpdate.begin(), m_pathsToUpdate.end(), &CTGitPath::PredLeftEquivalentToRight), m_pathsToUpdate.end());
					m_bItemsAddedSinceLastUpdate = false;
				}

				workingPath = m_pathsToUpdate.front();
				m_pathsToUpdate.pop_front();
			}
			if (workingPath.IsEmpty())
				continue;
			ATLTRACE(_T("Update notifications for: %s\n"), workingPath.GetWinPath());
			if (workingPath.IsDirectory())
			{
				// check if the path is monitored by the watcher. If it isn't, then we have to invalidate the cache
				// for that path and add it to the watcher.
				if (!CGitStatusCache::Instance().IsPathWatched(workingPath))
				{
					if (workingPath.HasAdminDir())
						CGitStatusCache::Instance().AddPathToWatch(workingPath);
				}
				// first send a notification about a sub folder change, so explorer doesn't discard
				// the folder notification. Since we only know for sure that the subversion admin
				// dir is present, we send a notification for that folder.
				CString admindir = workingPath.GetWinPathString() + _T("\\") + g_GitAdminDir.GetAdminDirName();
				if(::PathFileExists(admindir))
					SHChangeNotify(SHCNE_UPDATEITEM, SHCNF_PATH | SHCNF_FLUSHNOWAIT, (LPCTSTR)admindir, NULL);

				SHChangeNotify(SHCNE_UPDATEITEM, SHCNF_PATH | SHCNF_FLUSHNOWAIT, workingPath.GetWinPath(), NULL);
				// Sending an UPDATEDIR notification somehow overwrites/deletes the UPDATEITEM message. And without
				// that message, the folder overlays in the current view don't get updated without hitting F5.
				// Drawback is, without UPDATEDIR, the left tree view isn't always updated...

				SHChangeNotify(SHCNE_UPDATEDIR, SHCNF_PATH | SHCNF_FLUSHNOWAIT, workingPath.GetWinPath(), NULL);
			}
			else
				SHChangeNotify(SHCNE_UPDATEITEM, SHCNF_PATH | SHCNF_FLUSHNOWAIT, workingPath.GetWinPath(), NULL);
		}
	}
	_endthread();
}
コード例 #16
0
void CTextObject::_OnTextSelectChangeNotify(SELCHANGE* pSelChange)
{
	DRAWOBJBASEINFO stDrawObjectInfo(CStringResouceMgr::Instance()->GetEditFontName().c_str());
	stDrawObjectInfo.dwDrawMask = 0;
	const int _cchStyleName = 64;
	TCHAR szFontName[_cchStyleName] = {0};
	int nFontSize = 0;

	HRESULT hr = E_FAIL;
	long nStart = pSelChange->chrg.cpMin;
	long nEnd = pSelChange->chrg.cpMax;

	COM_VERIFY_EXCEPT1(m_pShareEditPtr->GetTextFontName(nStart, nEnd,
		szFontName, _countof(szFontName)), S_FALSE);
	if (S_FALSE == hr)
	{
		stDrawObjectInfo.strFontName = _T("");
		stDrawObjectInfo.dwDrawMask |= DRAWOBJECT_BASE_FONTNAME;
	}
	else
	{
		stDrawObjectInfo.dwDrawMask |= DRAWOBJECT_BASE_FONTNAME;
	}
	if (szFontName[0] == _T('\0'))
	{
		stDrawObjectInfo.strFontName = _T("");
	}
	else
	{
		stDrawObjectInfo.strFontName = szFontName;
	}
	
	COM_VERIFY_EXCEPT1(m_pShareEditPtr->GetTextFontSize(nStart, nEnd, &nFontSize), S_FALSE)
	if (S_FALSE == hr)
	{
		//multi select , nFontSize is -1
		stDrawObjectInfo.nFontSize = -1;
		stDrawObjectInfo.dwDrawMask |= DRAWOBJECT_BASE_FONTSIZE;
	}
	else
	{
		stDrawObjectInfo.dwDrawMask |= DRAWOBJECT_BASE_FONTSIZE;
		stDrawObjectInfo.nFontSize = nFontSize;
	}

	COLORREF clrText = RGB(0, 0, 0);
	COM_VERIFY_EXCEPT1(m_pShareEditPtr->GetTextForeColor(nStart, nEnd, &clrText), S_FALSE);
	if (S_FALSE == hr)
	{
		stDrawObjectInfo.clrFontFore = clrText;

	}
	else
	{
		stDrawObjectInfo.clrFontFore = clrText;
		stDrawObjectInfo.dwDrawMask |= DRAWOBJECT_BASE_FONTCLR;
	}
	
	m_pDrawCanvas->NotifyDrawObjectBaseInfo(stDrawObjectInfo);
	//m_pDrawCanvas->SetDrawObjectBaseInfo(stDrawObjectInfo, FALSE);
}
コード例 #17
0
// Load the sample assets.
void D3D12Bundles::LoadAssets()
{
    // Note: ComPtr's are CPU objects but these resources need to stay in scope until
    // the command list that references them has finished executing on the GPU.
    // We will flush the GPU at the end of this method to ensure the resources are not
    // prematurely destroyed.
    ComPtr<ID3D12Resource> vertexBufferUploadHeap;
    ComPtr<ID3D12Resource> indexBufferUploadHeap;
    ComPtr<ID3D12Resource> textureUploadHeap;

    // Create the root signature.
    {
        D3D12_FEATURE_DATA_ROOT_SIGNATURE featureData = {};

        // This is the highest version the sample supports. If CheckFeatureSupport succeeds, the HighestVersion returned will not be greater than this.
        featureData.HighestVersion = D3D_ROOT_SIGNATURE_VERSION_1_1;

        if (FAILED(m_device->CheckFeatureSupport(D3D12_FEATURE_ROOT_SIGNATURE, &featureData, sizeof(featureData))))
        {
            featureData.HighestVersion = D3D_ROOT_SIGNATURE_VERSION_1_0;
        }

        CD3DX12_DESCRIPTOR_RANGE1 ranges[3];
        ranges[0].Init(D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0, 0, D3D12_DESCRIPTOR_RANGE_FLAG_DATA_STATIC);
        ranges[1].Init(D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER, 1, 0);
        ranges[2].Init(D3D12_DESCRIPTOR_RANGE_TYPE_CBV, 1, 0, 0, D3D12_DESCRIPTOR_RANGE_FLAG_DATA_STATIC);

        CD3DX12_ROOT_PARAMETER1 rootParameters[3];
        rootParameters[0].InitAsDescriptorTable(1, &ranges[0], D3D12_SHADER_VISIBILITY_PIXEL);
        rootParameters[1].InitAsDescriptorTable(1, &ranges[1], D3D12_SHADER_VISIBILITY_PIXEL);
        rootParameters[2].InitAsDescriptorTable(1, &ranges[2], D3D12_SHADER_VISIBILITY_ALL);

        CD3DX12_VERSIONED_ROOT_SIGNATURE_DESC rootSignatureDesc;
        rootSignatureDesc.Init_1_1(_countof(rootParameters), rootParameters, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT);

        ComPtr<ID3DBlob> signature;
        ComPtr<ID3DBlob> error;
        ThrowIfFailed(D3DX12SerializeVersionedRootSignature(&rootSignatureDesc, featureData.HighestVersion, &signature, &error));
        ThrowIfFailed(m_device->CreateRootSignature(0, signature->GetBufferPointer(), signature->GetBufferSize(), IID_PPV_ARGS(&m_rootSignature)));
        NAME_D3D12_OBJECT(m_rootSignature);
    }

    // Create the pipeline state, which includes loading shaders.
    {
        UINT8* pVertexShaderData;
        UINT8* pPixelShaderData1;
        UINT8* pPixelShaderData2;
        UINT vertexShaderDataLength;
        UINT pixelShaderDataLength1;
        UINT pixelShaderDataLength2;

        // Load pre-compiled shaders.
        ThrowIfFailed(ReadDataFromFile(GetAssetFullPath(L"shader_mesh_simple_vert.cso").c_str(), &pVertexShaderData, &vertexShaderDataLength));
        ThrowIfFailed(ReadDataFromFile(GetAssetFullPath(L"shader_mesh_simple_pixel.cso").c_str(), &pPixelShaderData1, &pixelShaderDataLength1));
        ThrowIfFailed(ReadDataFromFile(GetAssetFullPath(L"shader_mesh_alt_pixel.cso").c_str(), &pPixelShaderData2, &pixelShaderDataLength2));

        CD3DX12_RASTERIZER_DESC rasterizerStateDesc(D3D12_DEFAULT);
        rasterizerStateDesc.CullMode = D3D12_CULL_MODE_NONE;

        // Describe and create the graphics pipeline state objects (PSO).
        D3D12_GRAPHICS_PIPELINE_STATE_DESC psoDesc = {};
        psoDesc.InputLayout = { SampleAssets::StandardVertexDescription, SampleAssets::StandardVertexDescriptionNumElements };
        psoDesc.pRootSignature = m_rootSignature.Get();
        psoDesc.VS = CD3DX12_SHADER_BYTECODE(pVertexShaderData, vertexShaderDataLength);
        psoDesc.PS = CD3DX12_SHADER_BYTECODE(pPixelShaderData1, pixelShaderDataLength1);
        psoDesc.RasterizerState = rasterizerStateDesc;
        psoDesc.BlendState = CD3DX12_BLEND_DESC(D3D12_DEFAULT);
        psoDesc.DepthStencilState = CD3DX12_DEPTH_STENCIL_DESC(D3D12_DEFAULT);
        psoDesc.SampleMask = UINT_MAX;
        psoDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
        psoDesc.NumRenderTargets = 1;
        psoDesc.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM;
        psoDesc.DSVFormat = DXGI_FORMAT_D32_FLOAT;
        psoDesc.SampleDesc.Count = 1;

        ThrowIfFailed(m_device->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&m_pipelineState1)));
        NAME_D3D12_OBJECT(m_pipelineState1);

        // Modify the description to use an alternate pixel shader and create
        // a second PSO.
        psoDesc.PS = CD3DX12_SHADER_BYTECODE(pPixelShaderData2, pixelShaderDataLength2);

        ThrowIfFailed(m_device->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&m_pipelineState2)));
        NAME_D3D12_OBJECT(m_pipelineState2);

        delete pVertexShaderData;
        delete pPixelShaderData1;
        delete pPixelShaderData2;
    }

    ThrowIfFailed(m_device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, m_commandAllocator.Get(), nullptr, IID_PPV_ARGS(&m_commandList)));
    NAME_D3D12_OBJECT(m_commandList);

    // Create render target views (RTVs).
    CD3DX12_CPU_DESCRIPTOR_HANDLE rtvHandle(m_rtvHeap->GetCPUDescriptorHandleForHeapStart());
    for (UINT i = 0; i < FrameCount; i++)
    {
        ThrowIfFailed(m_swapChain->GetBuffer(i, IID_PPV_ARGS(&m_renderTargets[i])));
        m_device->CreateRenderTargetView(m_renderTargets[i].Get(), nullptr, rtvHandle);
        rtvHandle.Offset(1, m_rtvDescriptorSize);

        NAME_D3D12_OBJECT_INDEXED(m_renderTargets, i);
    }

    // Read in mesh data for vertex/index buffers.
    UINT8* pMeshData;
    UINT meshDataLength;
    ThrowIfFailed(ReadDataFromFile(GetAssetFullPath(SampleAssets::DataFileName).c_str(), &pMeshData, &meshDataLength));

    // Create the vertex buffer.
    {
        ThrowIfFailed(m_device->CreateCommittedResource(
            &CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_DEFAULT),
            D3D12_HEAP_FLAG_NONE,
            &CD3DX12_RESOURCE_DESC::Buffer(SampleAssets::VertexDataSize),
            D3D12_RESOURCE_STATE_COPY_DEST,
            nullptr,
            IID_PPV_ARGS(&m_vertexBuffer)));

        ThrowIfFailed(m_device->CreateCommittedResource(
            &CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD),
            D3D12_HEAP_FLAG_NONE,
            &CD3DX12_RESOURCE_DESC::Buffer(SampleAssets::VertexDataSize),
            D3D12_RESOURCE_STATE_GENERIC_READ,
            nullptr,
            IID_PPV_ARGS(&vertexBufferUploadHeap)));

        NAME_D3D12_OBJECT(m_vertexBuffer);

        // Copy data to the intermediate upload heap and then schedule a copy 
        // from the upload heap to the vertex buffer.
        D3D12_SUBRESOURCE_DATA vertexData = {};
        vertexData.pData = pMeshData + SampleAssets::VertexDataOffset;
        vertexData.RowPitch = SampleAssets::VertexDataSize;
        vertexData.SlicePitch = vertexData.RowPitch;

        UpdateSubresources<1>(m_commandList.Get(), m_vertexBuffer.Get(), vertexBufferUploadHeap.Get(), 0, 0, 1, &vertexData);
        m_commandList->ResourceBarrier(1, &CD3DX12_RESOURCE_BARRIER::Transition(m_vertexBuffer.Get(), D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER));

        // Initialize the vertex buffer view.
        m_vertexBufferView.BufferLocation = m_vertexBuffer->GetGPUVirtualAddress();
        m_vertexBufferView.StrideInBytes = SampleAssets::StandardVertexStride;
        m_vertexBufferView.SizeInBytes = SampleAssets::VertexDataSize;
    }

    // Create the index buffer.
    {
        ThrowIfFailed(m_device->CreateCommittedResource(
            &CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_DEFAULT),
            D3D12_HEAP_FLAG_NONE,
            &CD3DX12_RESOURCE_DESC::Buffer(SampleAssets::IndexDataSize),
            D3D12_RESOURCE_STATE_COPY_DEST,
            nullptr,
            IID_PPV_ARGS(&m_indexBuffer)));

        ThrowIfFailed(m_device->CreateCommittedResource(
            &CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD),
            D3D12_HEAP_FLAG_NONE,
            &CD3DX12_RESOURCE_DESC::Buffer(SampleAssets::IndexDataSize),
            D3D12_RESOURCE_STATE_GENERIC_READ,
            nullptr,
            IID_PPV_ARGS(&indexBufferUploadHeap)));

        NAME_D3D12_OBJECT(m_indexBuffer);

        // Copy data to the intermediate upload heap and then schedule a copy 
        // from the upload heap to the index buffer.
        D3D12_SUBRESOURCE_DATA indexData = {};
        indexData.pData = pMeshData + SampleAssets::IndexDataOffset;
        indexData.RowPitch = SampleAssets::IndexDataSize;
        indexData.SlicePitch = indexData.RowPitch;

        UpdateSubresources<1>(m_commandList.Get(), m_indexBuffer.Get(), indexBufferUploadHeap.Get(), 0, 0, 1, &indexData);
        m_commandList->ResourceBarrier(1, &CD3DX12_RESOURCE_BARRIER::Transition(m_indexBuffer.Get(), D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_INDEX_BUFFER));

        // Describe the index buffer view.
        m_indexBufferView.BufferLocation = m_indexBuffer->GetGPUVirtualAddress();
        m_indexBufferView.Format = SampleAssets::StandardIndexFormat;
        m_indexBufferView.SizeInBytes = SampleAssets::IndexDataSize;

        m_numIndices = SampleAssets::IndexDataSize / 4;    // R32_UINT (SampleAssets::StandardIndexFormat) = 4 bytes each.
    }

    // Create the texture and sampler.
    {
        // Describe and create a Texture2D.
        D3D12_RESOURCE_DESC textureDesc = {};
        textureDesc.MipLevels = SampleAssets::Textures[0].MipLevels;
        textureDesc.Format = SampleAssets::Textures[0].Format;
        textureDesc.Width = SampleAssets::Textures[0].Width;
        textureDesc.Height = SampleAssets::Textures[0].Height;
        textureDesc.Flags = D3D12_RESOURCE_FLAG_NONE;
        textureDesc.DepthOrArraySize = 1;
        textureDesc.SampleDesc.Count = 1;
        textureDesc.SampleDesc.Quality = 0;
        textureDesc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;

        ThrowIfFailed(m_device->CreateCommittedResource(
            &CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_DEFAULT),
            D3D12_HEAP_FLAG_NONE,
            &textureDesc,
            D3D12_RESOURCE_STATE_COPY_DEST,
            nullptr,
            IID_PPV_ARGS(&m_texture)));

        NAME_D3D12_OBJECT(m_texture);

        const UINT subresourceCount = textureDesc.DepthOrArraySize * textureDesc.MipLevels;
        const UINT64 uploadBufferSize = GetRequiredIntermediateSize(m_texture.Get(), 0, subresourceCount);

        ThrowIfFailed(m_device->CreateCommittedResource(
            &CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD),
            D3D12_HEAP_FLAG_NONE,
            &CD3DX12_RESOURCE_DESC::Buffer(uploadBufferSize),
            D3D12_RESOURCE_STATE_GENERIC_READ,
            nullptr,
            IID_PPV_ARGS(&textureUploadHeap)));

        // Copy data to the intermediate upload heap and then schedule a copy 
        // from the upload heap to the Texture2D.
        D3D12_SUBRESOURCE_DATA textureData = {};
        textureData.pData = pMeshData + SampleAssets::Textures[0].Data[0].Offset;
        textureData.RowPitch = SampleAssets::Textures[0].Data[0].Pitch;
        textureData.SlicePitch = SampleAssets::Textures[0].Data[0].Size;

        UpdateSubresources(m_commandList.Get(), m_texture.Get(), textureUploadHeap.Get(), 0, 0, subresourceCount, &textureData);
        m_commandList->ResourceBarrier(1, &CD3DX12_RESOURCE_BARRIER::Transition(m_texture.Get(), D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE));

        // Describe and create a sampler.
        D3D12_SAMPLER_DESC samplerDesc = {};
        samplerDesc.Filter = D3D12_FILTER_MIN_MAG_MIP_LINEAR;
        samplerDesc.AddressU = D3D12_TEXTURE_ADDRESS_MODE_WRAP;
        samplerDesc.AddressV = D3D12_TEXTURE_ADDRESS_MODE_WRAP;
        samplerDesc.AddressW = D3D12_TEXTURE_ADDRESS_MODE_WRAP;
        samplerDesc.MinLOD = 0;
        samplerDesc.MaxLOD = D3D12_FLOAT32_MAX;
        samplerDesc.MipLODBias = 0.0f;
        samplerDesc.MaxAnisotropy = 1;
        samplerDesc.ComparisonFunc = D3D12_COMPARISON_FUNC_ALWAYS;
        m_device->CreateSampler(&samplerDesc, m_samplerHeap->GetCPUDescriptorHandleForHeapStart());

        // Describe and create a SRV for the texture.
        D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc = {};
        srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
        srvDesc.Format = SampleAssets::Textures->Format;
        srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D;
        srvDesc.Texture2D.MipLevels = 1;
        m_device->CreateShaderResourceView(m_texture.Get(), &srvDesc, m_cbvSrvHeap->GetCPUDescriptorHandleForHeapStart());
    }

    delete pMeshData;

    // Create the depth stencil view.
    {
        D3D12_DEPTH_STENCIL_VIEW_DESC depthStencilDesc = {};
        depthStencilDesc.Format = DXGI_FORMAT_D32_FLOAT;
        depthStencilDesc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2D;
        depthStencilDesc.Flags = D3D12_DSV_FLAG_NONE;

        D3D12_CLEAR_VALUE depthOptimizedClearValue = {};
        depthOptimizedClearValue.Format = DXGI_FORMAT_D32_FLOAT;
        depthOptimizedClearValue.DepthStencil.Depth = 1.0f;
        depthOptimizedClearValue.DepthStencil.Stencil = 0;

        ThrowIfFailed(m_device->CreateCommittedResource(
            &CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_DEFAULT),
            D3D12_HEAP_FLAG_NONE,
            &CD3DX12_RESOURCE_DESC::Tex2D(DXGI_FORMAT_D32_FLOAT, m_width, m_height, 1, 0, 1, 0, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL),
            D3D12_RESOURCE_STATE_DEPTH_WRITE,
            &depthOptimizedClearValue,
            IID_PPV_ARGS(&m_depthStencil)
            ));

        NAME_D3D12_OBJECT(m_depthStencil);

        m_device->CreateDepthStencilView(m_depthStencil.Get(), &depthStencilDesc, m_dsvHeap->GetCPUDescriptorHandleForHeapStart());
    }

    // Close the command list and execute it to begin the initial GPU setup.
    ThrowIfFailed(m_commandList->Close());
    ID3D12CommandList* ppCommandLists[] = { m_commandList.Get() };
    m_commandQueue->ExecuteCommandLists(_countof(ppCommandLists), ppCommandLists);

    // Create synchronization objects and wait until assets have been uploaded to the GPU.
    {
        ThrowIfFailed(m_device->CreateFence(m_fenceValue, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&m_fence)));
        m_fenceValue++;

        // Create an event handle to use for frame synchronization.
        m_fenceEvent = CreateEvent(nullptr, FALSE, FALSE, nullptr);
        if (m_fenceEvent == nullptr)
        {
            ThrowIfFailed(HRESULT_FROM_WIN32(GetLastError()));
        }

        // Wait for the command list to execute; we are reusing the same command 
        // list in our main loop but for now, we just want to wait for setup to 
        // complete before continuing.

        // Signal and increment the fence value.
        const UINT64 fenceToWaitFor = m_fenceValue;
        ThrowIfFailed(m_commandQueue->Signal(m_fence.Get(), fenceToWaitFor));
        m_fenceValue++;

        // Wait until the fence is completed.
        ThrowIfFailed(m_fence->SetEventOnCompletion(fenceToWaitFor, m_fenceEvent));
        WaitForSingleObject(m_fenceEvent, INFINITE);
    }

    CreateFrameResources();
}
コード例 #18
0
//-------------------------------------------------------------------------------------------------
HRESULT ImageShader2D::Init(ApplicationContext *pApplicationContext, ALVRComputeContext *pComputeContext)
{
    m_pApplicationContext = pApplicationContext;
    m_pComputeContext = pComputeContext;

    if (!m_bShaderReady)
    {
        if (m_uiShaderID == 0)
        {
            m_pApplicationContext->m_ShaderCache.AddShader(NULL,
                AMD::ShaderCache::SHADER_TYPE_COMPUTE, L"cs_5_0", m_pNameMain,
                m_pFileNameSource, 0, NULL, NULL, NULL, 0,
                0, -1, -1, true, &m_uiShaderID, ShaderReadyCallback, this);

            m_pApplicationContext->m_ShaderCache.GetShaderBinaryFileName(m_uiShaderID, m_pFileNameBin, (UINT)_countof(m_pFileNameBin));

        }
    }
    return S_OK;
}
コード例 #19
0
ファイル: interactive.c プロジェクト: Ashion/openvpn
/*
 * Validate options against a white list. Also check the config_file is
 * inside the config_dir. The white list is defined in validate.c
 * Returns true on success
 */
static BOOL
ValidateOptions (HANDLE pipe, const WCHAR *workdir, const WCHAR *options)
{
    WCHAR **argv;
    int argc;
    WCHAR buf[256];
    BOOL ret = FALSE;
    int i;
    const WCHAR *msg1 = L"You have specified a config file location (%s relative to %s)"
                        " that requires admin approval. This error may be avoided"
                        " by adding your account to the \"%s\" group";

    const WCHAR *msg2 = L"You have specified an option (%s) that may be used"
                         " only with admin approval. This error may be avoided"
                         " by adding your account to the \"%s\" group";

    argv = CommandLineToArgvW (options, &argc);

    if (!argv)
    {
        ReturnLastError (pipe, L"CommandLineToArgvW");
        ReturnError (pipe, ERROR_STARTUP_DATA, L"Cannot validate options", 1, &exit_event);
        goto out;
    }

    /* Note: argv[0] is the first option */
    if (argc < 1)  /* no options */
    {
        ret = TRUE;
        goto out;
    }

    /*
     * If only one argument, it is the config file
     */
    if (argc == 1)
    {
        WCHAR *argv_tmp[2] = { L"--config", argv[0] };

        if (!CheckOption (workdir, 2, argv_tmp, &settings))
        {
            snwprintf (buf, _countof(buf), msg1, argv[0], workdir,
                       settings.ovpn_admin_group);
            buf[_countof(buf) - 1] = L'\0';
            ReturnError (pipe, ERROR_STARTUP_DATA, buf, 1, &exit_event);
        }
        goto out;
    }

    for (i = 0; i < argc; ++i)
    {
        if (!IsOption(argv[i]))
            continue;

        if (!CheckOption (workdir, argc-i, &argv[i], &settings))
        {
            if (wcscmp(L"--config", argv[i]) == 0 && argc-i > 1)
            {
                snwprintf (buf, _countof(buf), msg1, argv[i+1], workdir,
                            settings.ovpn_admin_group);
                buf[_countof(buf) - 1] = L'\0';
                ReturnError (pipe, ERROR_STARTUP_DATA, buf, 1, &exit_event);
            }
            else
            {
                snwprintf (buf, _countof(buf), msg2, argv[i],
                           settings.ovpn_admin_group);
                buf[_countof(buf) - 1] = L'\0';
                ReturnError (pipe, ERROR_STARTUP_DATA, buf, 1, &exit_event);
            }
            goto out;
        }
    }

    /* all options passed */
    ret = TRUE;

out:
    if (argv)
        LocalFree (argv);
    return ret;
}
コード例 #20
0
ファイル: Utils.cpp プロジェクト: kmdtukl/miranda-ng
static void CheckUpdates(void *)
{
	TCHAR tszBuff[2048] = { 0 }, tszFileInfo[30] = { 0 }, tszTmpIni[MAX_PATH] = { 0 };
	char szKey[64] = { 0 };
	vector<FILEINFO> UpdateFiles;

	if (!Exists(tszRoot))
		CreateDirectory(tszRoot, NULL);
	Files.clear();
	Reminder = db_get_b(NULL, MODNAME, "Reminder", DEFAULT_REMINDER);
	FileCount = db_get_dw(NULL, MODNAME, "FileCount", DEFAULT_FILECOUNT);

	// Load files info
	ptrT tszDownloadURL(db_get_tsa(NULL, MODNAME, "File_VersionURL"));
	if (!tszDownloadURL) { // URL is not set
		Title = TranslateT("Pack Updater");
		Text = TranslateT("URL for checking updates not found.");
		if (ServiceExists(MS_POPUP_ADDPOPUPT) && db_get_b(NULL, "Popup", "ModuleIsEnabled", 1) && db_get_b(NULL, MODNAME, "Popups1", DEFAULT_POPUP_ENABLED)) {
			Number = 1;
			show_popup(0, Title, Text, Number, 0);
		}
		else if (db_get_b(NULL, MODNAME, "Popups1M", DEFAULT_MESSAGE_ENABLED))
			MessageBox(NULL, Text, Title, MB_ICONSTOP);
		hCheckThread = NULL;
		return;
	}
	// Download version info
	pFileUrl = (FILEURL *)mir_alloc(sizeof(*pFileUrl));
	mir_tstrncpy(pFileUrl->tszDownloadURL, tszDownloadURL, _countof(pFileUrl->tszDownloadURL));
	mir_sntprintf(tszBuff, _countof(tszBuff), _T("%s\\tmp.ini"), tszRoot);
	mir_tstrncpy(pFileUrl->tszDiskPath, tszBuff, _countof(pFileUrl->tszDiskPath));
	mir_tstrncpy(tszTmpIni, tszBuff, _countof(tszTmpIni));
	Title = TranslateT("Pack Updater");
	Text = TranslateT("Downloading version info...");
	DlgDownloadProc();
	mir_free(pFileUrl);
	if (!DlgDld) {
		hCheckThread = NULL;
		return;
	}

	for (CurrentFile = 0; CurrentFile < FileCount; CurrentFile++) {
		FILEINFO FileInfo = { _T(""), _T(""), _T(""), _T(""), _T(""), _T(""), _T(""), { _T(""), _T("") } };

		mir_snprintf(szKey, _countof(szKey), "File_%d_CurrentVersion", CurrentFile + 1);
		ptrT tszCurVer(db_get_tsa(NULL, MODNAME, szKey));
		if (tszCurVer)
			mir_tstrncpy(FileInfo.tszCurVer, tszCurVer, _countof(FileInfo.tszCurVer));
		else 
			mir_tstrncpy(FileInfo.tszCurVer, _T(""), _countof(FileInfo.tszCurVer));

		mir_snprintf(szKey, _countof(szKey), "File_%d_LastVersion", CurrentFile + 1);
		ptrT tszLastVer(db_get_tsa(NULL, MODNAME, szKey));
		if (tszLastVer)
			mir_tstrncpy(FileInfo.tszLastVer, tszLastVer, _countof(FileInfo.tszLastVer));
		else
			mir_tstrncpy(FileInfo.tszLastVer, _T(""), _countof(FileInfo.tszLastVer));

		Files.push_back(FileInfo);

		// Read version info
		mir_sntprintf(tszFileInfo, _countof(tszFileInfo), _T("FileInfo_%d"), CurrentFile + 1);
		GetPrivateProfileString(tszFileInfo, _T("FileVersion"), _T(""), Files[CurrentFile].tszNewVer, _countof(Files[CurrentFile].tszNewVer), tszTmpIni);
		GetPrivateProfileString(tszFileInfo, _T("Message"), _T(""), Files[CurrentFile].tszMessage, _countof(Files[CurrentFile].tszMessage), tszTmpIni);
		GetPrivateProfileString(tszFileInfo, _T("DownloadURL"), _T(""), Files[CurrentFile].File.tszDownloadURL, _countof(Files[CurrentFile].File.tszDownloadURL), tszTmpIni);
		GetPrivateProfileString(tszFileInfo, _T("AdvFolder"), _T(""), Files[CurrentFile].tszAdvFolder, _countof(Files[CurrentFile].tszAdvFolder), tszTmpIni);
		GetPrivateProfileString(tszFileInfo, _T("Descr"), _T(""), Files[CurrentFile].tszDescr, _countof(Files[CurrentFile].tszDescr), tszTmpIni);
		GetPrivateProfileString(tszFileInfo, _T("DiskFileName"), _T(""), tszBuff, MAX_PATH, tszTmpIni);

		if (_tcsstr(tszBuff, _T("\\"))) { //check update name
			Title = TranslateT("Pack Updater");
			Text = TranslateT("Name of Update's file is not supported.");
			if (ServiceExists(MS_POPUP_ADDPOPUPT) && db_get_b(NULL, "Popup", "ModuleIsEnabled", 1) && db_get_b(NULL, MODNAME, "Popups1", DEFAULT_POPUP_ENABLED)) {
				Number = 1;
				show_popup(0, Title, Text, Number, 0);
			}
			else if (db_get_b(NULL, MODNAME, "Popups1M", DEFAULT_MESSAGE_ENABLED))
				MessageBox(NULL, Text, Title, MB_ICONINFORMATION);
			continue;
		} // end check update name
		mir_tstrncpy(Files[CurrentFile].File.tszDiskPath, tszBuff, _countof(Files[CurrentFile].File.tszDiskPath));
		GetPrivateProfileString(tszFileInfo, _T("InfoURL"), _T(""), Files[CurrentFile].tszInfoURL, _countof(Files[CurrentFile].tszInfoURL), tszTmpIni);
		Files[CurrentFile].FileType = GetPrivateProfileInt(tszFileInfo, _T("FileType"), 0, tszTmpIni);
		Files[CurrentFile].Force = GetPrivateProfileInt(tszFileInfo, _T("Force"), 0, tszTmpIni);
		Files[CurrentFile].FileNum = CurrentFile + 1;

		if (Files[CurrentFile].FileType == 2) {
			if (mir_tstrcmp(Files[CurrentFile].tszAdvFolder, _T("")) == 0)
				mir_sntprintf(tszBuff, _countof(tszBuff), _T("Plugins\\%s"), Files[CurrentFile].File.tszDiskPath);
			else
				mir_sntprintf(tszBuff, _countof(tszBuff), _T("Plugins\\%s\\%s"), Files[CurrentFile].tszAdvFolder, Files[CurrentFile].File.tszDiskPath);
			TCHAR pluginFolderName[MAX_PATH];
			PathToAbsoluteT(tszBuff, pluginFolderName);
			if (!Files[CurrentFile].Force && (IsPluginDisabled(Files[CurrentFile].File.tszDiskPath) || !Exists(pluginFolderName))) //check if plugin disabled or not exists
				continue;
		}
		// Compare versions
		if (getVer(Files[CurrentFile].tszCurVer) < getVer(Files[CurrentFile].tszNewVer)) { // Yeah, we've got new version.
			VARST tszSysRoot(_T("%SystemRoot%"));
			VARST tszProgFiles(_T("%ProgramFiles%"));

			if (Files[CurrentFile].FileType != 1 && !IsUserAnAdmin() && (_tcsstr(tszRoot, tszSysRoot) || _tcsstr(tszRoot, tszProgFiles))) {
				MessageBox(NULL, TranslateT("Update is not possible!\nYou have no Administrator's rights.\nPlease run Miranda NG with Administrator's rights."), Title, MB_ICONINFORMATION);
				DeleteFile(tszTmpIni);
				hCheckThread = NULL;
				return;
			} // user have not admin's rights

			//добавить проверку на существование файла
			TCHAR tszFilePathDest[MAX_PATH] = { 0 };
			switch (Files[CurrentFile].FileType) {
			case 0:
			case 1:
				break;
			case 2: {
				VARST tszUtilRootPlug(_T("%miranda_path%\\Plugins"));
				if (mir_tstrcmp(Files[CurrentFile].tszAdvFolder, _T("")) == 0)
					mir_sntprintf(tszFilePathDest, _countof(tszFilePathDest), _T("%s\\%s"), tszUtilRootPlug, Files[CurrentFile].File.tszDiskPath);
				else
					mir_sntprintf(tszFilePathDest, _countof(tszFilePathDest), _T("%s\\%s\\%s"), tszUtilRootPlug, Files[CurrentFile].tszAdvFolder, Files[CurrentFile].File.tszDiskPath);
				}
				break;
			case 3: {
				VARST tszUtilRootIco(_T("%miranda_path%\\Icons"));
				if (mir_tstrcmp(Files[CurrentFile].tszAdvFolder, _T("")) == 0)
					mir_sntprintf(tszFilePathDest, _countof(tszFilePathDest), _T("%s\\%s"), tszUtilRootIco, Files[CurrentFile].File.tszDiskPath);
				else
					mir_sntprintf(tszFilePathDest, _countof(tszFilePathDest), _T("%s\\%s\\%s"), tszUtilRootIco, Files[CurrentFile].tszAdvFolder, Files[CurrentFile].File.tszDiskPath);
				}
				break;
			case 4:
			case 5: {
				VARST tszUtilRoot = Utils_ReplaceVarsT(_T("%miranda_path%"));
				if (mir_tstrcmp(Files[CurrentFile].tszAdvFolder, _T("")) == 0)
					mir_sntprintf(tszFilePathDest, _countof(tszFilePathDest), _T("%s\\%s"), tszUtilRoot, Files[CurrentFile].File.tszDiskPath);
				else
					mir_sntprintf(tszFilePathDest, _countof(tszFilePathDest), _T("%s\\%s\\%s"), tszUtilRoot, Files[CurrentFile].tszAdvFolder, Files[CurrentFile].File.tszDiskPath);
				}
				break;
			}//end* switch (Files[CurrentFile].FileType)

			if (Files[CurrentFile].Force || Exists(tszFilePathDest))
				UpdateFiles.push_back(Files[CurrentFile]);
			// Save last version
			mir_tstrncpy(Files[CurrentFile].tszLastVer, Files[CurrentFile].tszNewVer, _countof(Files[CurrentFile].tszLastVer));
			mir_snprintf(szKey, _countof(szKey), "File_%d_LastVersion", CurrentFile + 1);
			db_set_ts(NULL, MODNAME, szKey, Files[CurrentFile].tszLastVer);
		} // end compare versions
	} //end checking all files in for ()

	// Show dialog
	INT upd_ret = 0;
	if (UpdateFiles.size() > 0)
		upd_ret = DialogBoxParam(hInst, MAKEINTRESOURCE(IDD_UPDATE), GetDesktopWindow(), DlgUpdate, (LPARAM)&UpdateFiles);
	DeleteFile(tszTmpIni);
	if (upd_ret == IDCANCEL) {
		hCheckThread = NULL;
		return;
	}

	if (!UpdatesCount && !Silent) {
		Title = TranslateT("Pack Updater");
		Text = TranslateT("No updates found.");
		if (ServiceExists(MS_POPUP_ADDPOPUPT) && db_get_b(NULL, "Popup", "ModuleIsEnabled", 1) && db_get_b(NULL, MODNAME, "Popups2", DEFAULT_POPUP_ENABLED)) {
			Number = 2;
			show_popup(0, Title, Text, Number, 0);
		}
		else if (db_get_b(NULL, MODNAME, "Popups2M", DEFAULT_MESSAGE_ENABLED))
			MessageBox(NULL, Text, Title, MB_ICONINFORMATION);
	}

	if (!FileCount) {
		Title = TranslateT("Pack Updater");
		Text = TranslateT("No files for update.");
		if (ServiceExists(MS_POPUP_ADDPOPUPT) && db_get_b(NULL, "Popup", "ModuleIsEnabled", 1) && db_get_b(NULL, MODNAME, "Popups2", DEFAULT_POPUP_ENABLED)) {
			Number = 2;
			show_popup(0, Title, Text, Number, 0);
		}
		else if (db_get_b(NULL, MODNAME, "Popups2M", DEFAULT_MESSAGE_ENABLED))
			MessageBox(NULL, Text, Title, MB_ICONINFORMATION);
	}
	hCheckThread = NULL;
}
コード例 #21
0
void WindowsHttpDownloader::InternalConnect(char* append_headers)
{
	WCHAR host_name[1024] = {};
	if (wcslen(_url.lpszHostName) > 1024) {
		SetEvent(_events[EventErr]);
		return;
	}
	wcscpy(host_name, _url.lpszHostName);
	if (wcsstr(host_name, L"/") != NULL)
		*wcsstr(host_name, L"/") = 0;
	if (wcsstr(host_name, L":") != NULL)
		*wcsstr(host_name, L":") = 0;

	_http.connect = WinHttpConnect(_http.session, host_name, _url.nPort, 0);
	if (_http.connect == NULL) {
		SetEvent(_events[EventErr]);
		return;
	}
	SetEvent(_events[EventConnect]);
	if (_abort_download)
		return;

	_http.request = WinHttpOpenRequest(_http.connect, L"GET",
		_url.dwUrlPathLength > 0 ? _url.lpszUrlPath : NULL,
		NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, 0);
	if (_http.connect == NULL) {
		SetEvent(_events[EventErr]);
		return;
	}
	if (_abort_download)
		return;

	DWORD temp = WINHTTP_DISABLE_AUTHENTICATION;
	WinHttpSetOption(_http.request, WINHTTP_OPTION_DISABLE_FEATURE, &temp, sizeof(temp));

	int hcount = _user_heads.size();
	for (int i = 0; i < hcount; i++) {
		WCHAR header[MAX_PATH], hvalue[1024];
		header[0] = hvalue[0] = 0;
		auto h = _user_heads.front();
		_user_heads.pop();
		AnsiToUnicode(h.name, header);
		AnsiToUnicode(h.value, hvalue, _countof(hvalue));
		h.Free();
		auto str = (LPWSTR)malloc(4096);
		RtlZeroMemory(str, 4096);
		wcscpy(str, header);
		wcscat(str, L": ");
		wcscat(str, hvalue);
		WinHttpAddRequestHeaders(_http.request, str, -1, WINHTTP_ADDREQ_FLAG_ADD);
		free(str);
	}

	LPWSTR add_headers = NULL;
	if (append_headers) {
		int add_head_len = MultiByteToWideChar(CP_ACP, 0, append_headers, -1, NULL, 0);
		if (add_head_len > 1) {
			add_headers = (LPWSTR)calloc(2, add_head_len);
			if (add_headers)
				MultiByteToWideChar(CP_ACP, 0, append_headers, -1, add_headers, add_head_len + 1);
		}
	}
	if (!WinHttpSendRequest(_http.request,
		add_headers, -1,
		WINHTTP_NO_REQUEST_DATA, 0, 0, 0)) {
		if (add_headers)
			free(add_headers);
		_http.Close();
		SetEvent(_events[EventErr]);
		return;
	}
	if (add_headers)
		free(add_headers);
	SetEvent(_events[EventSendRequest]);
	if (_abort_download)
		return;

	if (!WinHttpReceiveResponse(_http.request, NULL)) {
		_http.Close();
		SetEvent(_events[EventErr]);
		return;
	}

	//status code...
	temp = MAX_PATH;
	WCHAR scode[MAX_PATH] = {};
	WinHttpQueryHeaders(_http.request, WINHTTP_QUERY_STATUS_CODE,
		WINHTTP_HEADER_NAME_BY_INDEX, &scode, &temp, WINHTTP_NO_HEADER_INDEX);
	_http.status_code = wcstol(scode, NULL, 10);

	//headers...
	WinHttpQueryHeaders(_http.request, WINHTTP_QUERY_RAW_HEADERS_CRLF,
		WINHTTP_HEADER_NAME_BY_INDEX, NULL, (LPDWORD)&_recv_headers_zero_size, WINHTTP_NO_HEADER_INDEX);
	_recv_headers = (wchar_t*)calloc(_recv_headers_zero_size, 2);
	if (_recv_headers)
		WinHttpQueryHeaders(_http.request, WINHTTP_QUERY_RAW_HEADERS_CRLF,
		WINHTTP_HEADER_NAME_BY_INDEX, _recv_headers, (LPDWORD)&_recv_headers_zero_size, WINHTTP_NO_HEADER_INDEX);

	WinHttpQueryHeaders(_http.request, WINHTTP_QUERY_RAW_HEADERS,
		WINHTTP_HEADER_NAME_BY_INDEX, NULL, (LPDWORD)&_recv_headers_zero_size, WINHTTP_NO_HEADER_INDEX);
	_recv_headers_zero = (unsigned char*)calloc(_recv_headers_zero_size, 2);
	if (_recv_headers_zero)
		WinHttpQueryHeaders(_http.request, WINHTTP_QUERY_RAW_HEADERS,
		WINHTTP_HEADER_NAME_BY_INDEX, _recv_headers_zero, (LPDWORD)&_recv_headers_zero_size, WINHTTP_NO_HEADER_INDEX);

	SetEvent(_events[EventReceiveResponse]);
	if (_abort_download)
		return;

	if (_http.status_code >= 400)
		SetEvent(_events[EventStatusCode400]);
	else
		InternalDownload();
}
コード例 #22
0
ファイル: Utils.cpp プロジェクト: kmdtukl/miranda-ng
VOID IcoLibInit()
{
	Icon_Register(hInst, MODULEA, iconList, _countof(iconList));
}
コード例 #23
0
ファイル: history.cpp プロジェクト: ybznek/miranda-ng
static INT_PTR CALLBACK DlgProcHistory(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam)
{
	MCONTACT hContact = (MCONTACT)GetWindowLongPtr(hwndDlg, GWLP_USERDATA);
	switch (msg) {
	case WM_INITDIALOG:
		TranslateDialogDefault(hwndDlg);
		SetWindowLongPtr(hwndDlg, GWLP_USERDATA, (LONG_PTR)lParam);
		hContact = lParam;
		WindowList_Add(hWindowList, hwndDlg, hContact);
		Utils_RestoreWindowPosition(hwndDlg, hContact, "History", "");
		{
			TCHAR* contactName, str[200];
			contactName = pcli->pfnGetContactDisplayName(hContact, 0);
			mir_sntprintf(str, TranslateT("History for %s"), contactName);
			SetWindowText(hwndDlg, str);
		}
		Window_SetSkinIcon_IcoLib(hwndDlg, SKINICON_OTHER_HISTORY);
		SendMessage(hwndDlg, DM_HREBUILD, 0, 0);
		return TRUE;

	case DM_HREBUILD:
		{
			THistoryThread* hInfo = (THistoryThread*)mir_alloc(sizeof(THistoryThread));
			EnableWindow(GetDlgItem(hwndDlg, IDC_LIST), FALSE);
			hInfo->hContact = hContact;
			hInfo->hwnd = hwndDlg;
			mir_forkthread(FillHistoryThread, hInfo);
		}
		return TRUE;

	case WM_DESTROY:
		Window_FreeIcon_IcoLib(hwndDlg);
		Utils_SaveWindowPosition(hwndDlg, hContact, "History", "");
		WindowList_Remove(hWindowList, hwndDlg);
		return TRUE;

	case WM_GETMINMAXINFO:
		((MINMAXINFO*)lParam)->ptMinTrackSize.x = 300;
		((MINMAXINFO*)lParam)->ptMinTrackSize.y = 230;
		break;

	case WM_SIZE:
		Utils_ResizeDialog(hwndDlg, hInst, MAKEINTRESOURCEA(IDD_HISTORY), HistoryDlgResizer);
		return TRUE;

	case WM_COMMAND:
		switch (LOWORD(wParam)) {
		case IDOK:
		case IDCANCEL:
			DestroyWindow(hwndDlg);
			return TRUE;

		case IDC_FIND:
			ShowWindow(CreateDialogParam(hInst, MAKEINTRESOURCE(IDD_HISTORY_FIND), hwndDlg, DlgProcHistoryFind, (LPARAM)hwndDlg), SW_SHOW);
			return TRUE;

		case IDC_DELETEHISTORY:
			MEVENT hDbevent;
			{
				int index = SendDlgItemMessage(hwndDlg, IDC_LIST, LB_GETCURSEL, 0, 0);
				if (index == LB_ERR)
					break;

				if (MessageBox(hwndDlg, TranslateT("Are you sure you want to delete this history item?"), TranslateT("Delete history"), MB_YESNO | MB_ICONQUESTION) == IDYES) {
					hDbevent = SendDlgItemMessage(hwndDlg, IDC_LIST, LB_GETITEMDATA, index, 0);
					db_event_delete(hContact, hDbevent);
					SendMessage(hwndDlg, DM_HREBUILD, 0, 0);
				}
			}
			return TRUE;

		case IDC_LIST:
			if (HIWORD(wParam) == LBN_SELCHANGE) {
				int sel = SendDlgItemMessage(hwndDlg, IDC_LIST, LB_GETCURSEL, 0, 0);
				if (sel == LB_ERR) { EnableWindow(GetDlgItem(hwndDlg, IDC_DELETEHISTORY), FALSE); break; }
				EnableWindow(GetDlgItem(hwndDlg, IDC_DELETEHISTORY), TRUE);
				MEVENT hDbEvent = SendDlgItemMessage(hwndDlg, IDC_LIST, LB_GETITEMDATA, sel, 0);

				DBEVENTINFO dbei = { sizeof(dbei) };
				dbei.cbBlob = db_event_getBlobSize(hDbEvent);
				if ((int)dbei.cbBlob != -1) {
					dbei.pBlob = (PBYTE)mir_alloc(dbei.cbBlob);
					if (db_event_get(hDbEvent, &dbei) == 0) {
						TCHAR str[8192];
						GetObjectDescription(&dbei, str, _countof(str));
						if (str[0])
							SetDlgItemText(hwndDlg, IDC_EDIT, str);
					}
					mir_free(dbei.pBlob);
				}
			}
			return TRUE;
		}
		break;

	case DM_FINDNEXT:
		int index = SendDlgItemMessage(hwndDlg, IDC_LIST, LB_GETCURSEL, 0, 0);
		if (index == LB_ERR)
			break;

		DBEVENTINFO dbei = { sizeof(dbei) };
		int oldBlobSize = 0;
		MEVENT hDbEventStart = SendDlgItemMessage(hwndDlg, IDC_LIST, LB_GETITEMDATA, index, 0);

		for (;;) {
			MEVENT hDbEvent = SendDlgItemMessage(hwndDlg, IDC_LIST, LB_GETITEMDATA, ++index, 0);
			if (hDbEvent == LB_ERR) {
				index = -1;
				continue;
			}
			if (hDbEvent == hDbEventStart)
				break;

			int newBlobSize = db_event_getBlobSize(hDbEvent);
			if (newBlobSize > oldBlobSize) {
				dbei.pBlob = (PBYTE)mir_realloc(dbei.pBlob, newBlobSize);
				oldBlobSize = newBlobSize;
			}
			dbei.cbBlob = oldBlobSize;
			db_event_get(hDbEvent, &dbei);

			TCHAR str[1024];
			GetObjectDescription(&dbei, str, _countof(str));
			if (str[0]) {
				CharUpperBuff(str, (int)mir_tstrlen(str));
				if (_tcsstr(str, (const TCHAR*)lParam) != NULL) {
					SendDlgItemMessage(hwndDlg, IDC_LIST, LB_SETCURSEL, index, 0);
					SendMessage(hwndDlg, WM_COMMAND, MAKEWPARAM(IDC_LIST, LBN_SELCHANGE), 0);
					break;
				}
			}
		}

		mir_free(dbei.pBlob);
		break;
	}
	return FALSE;
}
コード例 #24
0
static void DoAutoExec(void)
{
	TCHAR szUse[7], szIniPath[MAX_PATH], szFindPath[MAX_PATH];
	TCHAR buf[2048], szSecurity[11], szOverrideSecurityFilename[MAX_PATH], szOnCreateFilename[MAX_PATH];

	GetPrivateProfileString(_T("AutoExec"), _T("Use"), _T("prompt"), szUse, _countof(szUse), mirandabootini);
	if (!mir_tstrcmpi(szUse, _T("no"))) return;
	GetPrivateProfileString(_T("AutoExec"), _T("Safe"), _T("CLC Icons CLUI CList SkinSounds"), buf, _countof(buf), mirandabootini);
	ptrA szSafeSections(mir_t2a(buf));
	GetPrivateProfileString(_T("AutoExec"), _T("Unsafe"), _T("AIM Facebook GG ICQ IRC JABBER MRA MSN SKYPE Tlen TWITTER VKontakte XFire"), buf, _countof(buf), mirandabootini);
	ptrA szUnsafeSections(mir_t2a(buf));
	GetPrivateProfileString(_T("AutoExec"), _T("Warn"), _T("notsafe"), szSecurity, _countof(szSecurity), mirandabootini);

	int secur = 0;
	if (!mir_tstrcmpi(szSecurity, _T("none"))) secur = 0;
	else if (!mir_tstrcmpi(szSecurity, _T("notsafe"))) secur = 1;
	else if (!mir_tstrcmpi(szSecurity, _T("onlyunsafe"))) secur = 2;

	GetPrivateProfileString(_T("AutoExec"), _T("OverrideSecurityFilename"), _T(""), szOverrideSecurityFilename, _countof(szOverrideSecurityFilename), mirandabootini);
	GetPrivateProfileString(_T("AutoExec"), _T("OnCreateFilename"), _T(""), szOnCreateFilename, _countof(szOnCreateFilename), mirandabootini);
	GetPrivateProfileString(_T("AutoExec"), _T("Glob"), _T("autoexec_*.ini"), szFindPath, _countof(szFindPath), mirandabootini);

	if (g_bDbCreated && szOnCreateFilename[0]) {
		PathToAbsoluteT(VARST(szOnCreateFilename), szIniPath);
		ProcessIniFile(szIniPath, szSafeSections, szUnsafeSections, 0, 1);
	}

	PathToAbsoluteT(VARST(szFindPath), szFindPath);

	WIN32_FIND_DATA fd;
	HANDLE hFind = FindFirstFile(szFindPath, &fd);
	if (hFind == INVALID_HANDLE_VALUE)
		return;

	TCHAR *str2 = _tcsrchr(szFindPath, '\\');
	if (str2 == NULL)
		szFindPath[0] = 0;
	else
		str2[1] = 0;

	do {
		bool secFN = mir_tstrcmpi(fd.cFileName, szOverrideSecurityFilename) == 0;

		mir_sntprintf(szIniPath, _countof(szIniPath), _T("%s%s"), szFindPath, fd.cFileName);
		if (!mir_tstrcmpi(szUse, _T("prompt")) && !secFN) {
			int result = DialogBoxParam(g_hInst, MAKEINTRESOURCE(IDD_INSTALLINI), NULL, InstallIniDlgProc, (LPARAM)szIniPath);
			if (result == IDC_NOTOALL) break;
			if (result == IDCANCEL) continue;
		}

		ProcessIniFile(szIniPath, szSafeSections, szUnsafeSections, secur, secFN);

		if (secFN)
			DeleteFile(szIniPath);
		else {
			TCHAR szOnCompletion[8];
			GetPrivateProfileString(_T("AutoExec"), _T("OnCompletion"), _T("recycle"), szOnCompletion, _countof(szOnCompletion), mirandabootini);
			if (!mir_tstrcmpi(szOnCompletion, _T("delete")))
				DeleteFile(szIniPath);
			else if (!mir_tstrcmpi(szOnCompletion, _T("recycle"))) {
				SHFILEOPSTRUCT shfo = { 0 };
				shfo.wFunc = FO_DELETE;
				shfo.pFrom = szIniPath;
				szIniPath[mir_tstrlen(szIniPath) + 1] = 0;
				shfo.fFlags = FOF_NOCONFIRMATION | FOF_NOERRORUI | FOF_SILENT | FOF_ALLOWUNDO;
				SHFileOperation(&shfo);
			}
			else if (!mir_tstrcmpi(szOnCompletion, _T("rename"))) {
				TCHAR szRenamePrefix[MAX_PATH], szNewPath[MAX_PATH];
				GetPrivateProfileString(_T("AutoExec"), _T("RenamePrefix"), _T("done_"), szRenamePrefix, _countof(szRenamePrefix), mirandabootini);
				mir_tstrcpy(szNewPath, szFindPath);
				mir_tstrcat(szNewPath, szRenamePrefix);
				mir_tstrcat(szNewPath, fd.cFileName);
				MoveFile(szIniPath, szNewPath);
			}
			else if (!mir_tstrcmpi(szOnCompletion, _T("ask")))
				DialogBoxParam(g_hInst, MAKEINTRESOURCE(IDD_INIIMPORTDONE), NULL, IniImportDoneDlgProc, (LPARAM)szIniPath);
		}
	}
		while (FindNextFile(hFind, &fd));

	FindClose(hFind);
}
コード例 #25
0
//******************************************************************************************
int32_t MasterComponent::saveEXCEL(FilePtr componentFile, uint8_t masterId, float baseSensorRange)
{
	char dataLine[512];
	char piece[512];
	char comma[2] = ",";
	if(masterID == -1)
	{
		//---------------------------------------
		// Blank undefined line in compbas here.
		sprintf_s(dataLine, _countof(dataline), "0,undefined,undefined,0,0,0,0,0,0,0,0,0,0,0,0,No,No,0,No,0,0,0,0,na,na,na,na,na,na,na,na,na,,,,,");
		componentFile->writeLine(dataLine);
		return(0);
	}
	//----------------------------------------------------------
	// Build the dataline piece by piece
	sprintf_s(piece, _countof(piece), "%d", masterId);
	strcpy(dataLine, piece);
	strcat(dataLine, comma);
	cLoadString(COMPONENT_NAME_START + masterID, name, MAXLEN_COMPONENT_NAME);
	strcat(dataLine, name);
	strcat(dataLine, comma);
	cLoadString(COMPONENT_ABBR_START + masterID, abbreviation, MAXLEN_COMPONENT_ABBREV);
	strcat(dataLine, abbreviation);
	strcat(dataLine, comma);
	strcat(dataLine, ComponentFormString[form]);
	strcat(dataLine, comma);
	sprintf_s(piece, _countof(piece), "%d", size);
	strcat(dataLine, piece);
	strcat(dataLine, comma);
	sprintf_s(piece, _countof(piece), "1");
	strcat(dataLine, piece);
	strcat(dataLine, comma);
	sprintf_s(piece, _countof(piece), "%3.1f", tonnage);
	strcat(dataLine, piece);
	strcat(dataLine, comma);
	sprintf_s(piece, _countof(piece), "%d", resourcePoints);
	strcat(dataLine, piece);
	strcat(dataLine, comma);
	for(size_t location = 0; location < NUM_BODY_LOCATIONS; location++)
	{
		if(criticalSpacesReq[location] == -1)
			sprintf_s(piece, _countof(piece), "No");
		else if(criticalSpacesReq[location] == 0)
			sprintf_s(piece, _countof(piece), "Yes");
		else
			Fatal(criticalSpacesReq[location], "Bad Data");
		strcat(dataLine, piece);
		strcat(dataLine, comma);
	}
	if(getCanVehicleUse())
		sprintf_s(piece, _countof(piece), "Yes");
	else
		sprintf_s(piece, _countof(piece), "No");
	strcat(dataLine, piece);
	strcat(dataLine, comma);
	if(getCanMechUse())
		sprintf_s(piece, _countof(piece), "Yes");
	else
		sprintf_s(piece, _countof(piece), "No");
	strcat(dataLine, piece);
	strcat(dataLine, comma);
	if(getClanTechBase() && getISTechBase())
	{
		sprintf_s(piece, _countof(piece), "Both");
	}
	else if(getClanTechBase())
	{
		sprintf_s(piece, _countof(piece), "Clan");
	}
	else if(getISTechBase())
	{
		sprintf_s(piece, _countof(piece), "IS");
	}
	else
	{
		sprintf_s(piece, _countof(piece), "0");
	}
	strcat(dataLine, piece);
	strcat(dataLine, comma);
	if(getCanISUse())
		sprintf_s(piece, _countof(piece), "Yes");
	else
		sprintf_s(piece, _countof(piece), "No");
	strcat(dataLine, piece);
	strcat(dataLine, comma);
	sprintf_s(piece, _countof(piece), "0");
	strcat(dataLine, piece);
	strcat(dataLine, comma);
	sprintf_s(piece, _countof(piece), "1");
	strcat(dataLine, piece);
	strcat(dataLine, comma);
	sprintf_s(piece, _countof(piece), "%8.1f", CV);
	strcat(dataLine, piece);
	strcat(dataLine, comma);
	switch(form)
	{
		case COMPONENT_FORM_COCKPIT:
		case COMPONENT_FORM_ACTUATOR:
		case COMPONENT_FORM_SIMPLE:
		case COMPONENT_FORM_CASE:
		case COMPONENT_FORM_POWER_AMPLIFIER:
		case COMPONENT_FORM_GYROSCOPE:
		case COMPONENT_FORM_LIFESUPPORT:
		case COMPONENT_FORM_BULK:
		default:
			//----------------------
			// No additional data...
			sprintf_s(piece, _countof(piece), "na,na,na,na,na,na,na,na,na,,,,,");
			strcat(dataLine, piece);
			strcat(dataLine, comma);
			break;
		case COMPONENT_FORM_SENSOR:
			sprintf_s(piece, _countof(piece), "%4.1f", float(stats.sensor.range / baseSensorRange));
			strcat(dataLine, piece);
			strcat(dataLine, comma);
			sprintf_s(piece, _countof(piece), "na,na,na,na,na,na,na,na,,,,,");
			strcat(dataLine, piece);
			strcat(dataLine, comma);
			break;
		case COMPONENT_FORM_ECM:
			sprintf_s(piece, _countof(piece), "%4.1f", stats.ecm.effect);
			strcat(dataLine, piece);
			strcat(dataLine, comma);
			sprintf_s(piece, _countof(piece), "%4.1f", stats.ecm.range);
			strcat(dataLine, piece);
			strcat(dataLine, comma);
			sprintf_s(piece, _countof(piece), "na,na,na,na,na,na,na,,,,,");
			strcat(dataLine, piece);
			strcat(dataLine, comma);
			break;
		case COMPONENT_FORM_JAMMER:
			sprintf_s(piece, _countof(piece), "%4.1f", stats.jammer.effect);
			strcat(dataLine, piece);
			strcat(dataLine, comma);
			sprintf_s(piece, _countof(piece), "na,na,na,na,na,na,na,na,,,,,");
			strcat(dataLine, piece);
			strcat(dataLine, comma);
			break;
		case COMPONENT_FORM_PROBE:
			sprintf_s(piece, _countof(piece), "%4.1f", stats.probe.effect);
			strcat(dataLine, piece);
			strcat(dataLine, comma);
			sprintf_s(piece, _countof(piece), "na,na,na,na,na,na,na,na,,,,,");
			strcat(dataLine, piece);
			strcat(dataLine, comma);
			break;
		case COMPONENT_FORM_ENGINE:
			sprintf_s(piece, _countof(piece), "%d", 0);
			strcat(dataLine, piece);
			strcat(dataLine, comma);
			sprintf_s(piece, _countof(piece), "na,na,na,na,na,na,na,na,,,,,");
			strcat(dataLine, piece);
			strcat(dataLine, comma);
			break;
		case COMPONENT_FORM_HEATSINK:
			sprintf_s(piece, _countof(piece), "%4.1f", stats.heatsink.dissipation);
			strcat(dataLine, piece);
			strcat(dataLine, comma);
			sprintf_s(piece, _countof(piece), "na,na,na,na,na,na,na,na,,,,,");
			strcat(dataLine, piece);
			strcat(dataLine, comma);
			break;
		case COMPONENT_FORM_WEAPON_ENERGY:
			sprintf_s(piece, _countof(piece), "%4.1f", stats.weapon.damage);
			strcat(dataLine, piece);
			strcat(dataLine, comma);
			sprintf_s(piece, _countof(piece), "%4.2f", stats.weapon.recycleTime);
			strcat(dataLine, piece);
			strcat(dataLine, comma);
			sprintf_s(piece, _countof(piece), "%4.1f", stats.weapon.heat);
			strcat(dataLine, piece);
			strcat(dataLine, comma);
			sprintf_s(piece, _countof(piece), "%d", 0);
			strcat(dataLine, piece);
			strcat(dataLine, comma);
			sprintf_s(piece, _countof(piece), "%d", WEAPON_AMMO_NONE);
			strcat(dataLine, piece);
			strcat(dataLine, comma);
			sprintf_s(piece, _countof(piece), "%s", WeaponRangeString[stats.weapon.range]);
			strcat(dataLine, piece);
			strcat(dataLine, comma);
			//sprintf_s(piece,_countof(piece),"%d",stats.weapon.type);
			//strcat(dataLine,piece);
			//strcat(dataLine,comma);
			sprintf_s(piece, _countof(piece), "%d", stats.weapon.specialEffect);
			strcat(dataLine, piece);
			strcat(dataLine, comma);
			sprintf_s(piece, _countof(piece), "%d", 0);
			strcat(dataLine, piece);
			strcat(dataLine, comma);
			sprintf_s(piece, _countof(piece), "%d", stats.weapon.flags);
			strcat(dataLine, piece);
			strcat(dataLine, comma);
			break;
		case COMPONENT_FORM_WEAPON_BALLISTIC:
			sprintf_s(piece, _countof(piece), "%4.1f", stats.weapon.damage);
			strcat(dataLine, piece);
			strcat(dataLine, comma);
			sprintf_s(piece, _countof(piece), "%4.2f", stats.weapon.recycleTime);
			strcat(dataLine, piece);
			strcat(dataLine, comma);
			sprintf_s(piece, _countof(piece), "%4.1f", stats.weapon.heat);
			strcat(dataLine, piece);
			strcat(dataLine, comma);
			sprintf_s(piece, _countof(piece), "%d", stats.weapon.ammoAmount);
			strcat(dataLine, piece);
			strcat(dataLine, comma);
			sprintf_s(piece, _countof(piece), "%d", stats.weapon.ammoType);
			strcat(dataLine, piece);
			strcat(dataLine, comma);
			sprintf_s(piece, _countof(piece), "%s", WeaponRangeString[stats.weapon.range]);
			strcat(dataLine, piece);
			strcat(dataLine, comma);
//			sprintf_s(piece,_countof(piece),"%d",stats.weapon.type);
//			strcat(dataLine,piece);
//			strcat(dataLine,comma);
			sprintf_s(piece, _countof(piece), "%d", stats.weapon.specialEffect);
			strcat(dataLine, piece);
			strcat(dataLine, comma);
			sprintf_s(piece, _countof(piece), "%d", stats.weapon.flags);
			strcat(dataLine, piece);
			strcat(dataLine, comma);
			break;
		case COMPONENT_FORM_WEAPON_MISSILE:
			sprintf_s(piece, _countof(piece), "%4.1f", stats.weapon.damage);
			strcat(dataLine, piece);
			strcat(dataLine, comma);
			sprintf_s(piece, _countof(piece), "%4.2f", stats.weapon.recycleTime);
			strcat(dataLine, piece);
			strcat(dataLine, comma);
			sprintf_s(piece, _countof(piece), "%4.1f", stats.weapon.heat);
			strcat(dataLine, piece);
			strcat(dataLine, comma);
			sprintf_s(piece, _countof(piece), "%d", stats.weapon.ammoAmount);
			strcat(dataLine, piece);
			strcat(dataLine, comma);
			sprintf_s(piece, _countof(piece), "%d", stats.weapon.ammoType);
			strcat(dataLine, piece);
			strcat(dataLine, comma);
			sprintf_s(piece, _countof(piece), "%s", WeaponRangeString[stats.weapon.range]);
			strcat(dataLine, piece);
			strcat(dataLine, comma);
//			sprintf_s(piece,_countof(piece),"%d",stats.weapon.type);
//			strcat(dataLine,piece);
//			strcat(dataLine,comma);
			sprintf_s(piece, _countof(piece), "%d", stats.weapon.specialEffect);
			strcat(dataLine, piece);
			strcat(dataLine, comma);
			sprintf_s(piece, _countof(piece), "%d", stats.weapon.flags);
			strcat(dataLine, piece);
			strcat(dataLine, comma);
			break;
		case COMPONENT_FORM_AMMO:
			sprintf_s(piece, _countof(piece), "%d", stats.ammo.ammoPerTon);
			strcat(dataLine, piece);
			strcat(dataLine, comma);
			sprintf_s(piece, _countof(piece), "%6.1f", stats.ammo.explosiveDamage);
			strcat(dataLine, piece);
			strcat(dataLine, comma);
			sprintf_s(piece, _countof(piece), "na,na,na,na,na,na,na,,,,,");
			strcat(dataLine, piece);
			strcat(dataLine, comma);
			break;
		case COMPONENT_FORM_JUMPJET:
			sprintf_s(piece, _countof(piece), "%6.2f", stats.jumpjet.rangeMod);
			strcat(dataLine, piece);
			strcat(dataLine, comma);
			sprintf_s(piece, _countof(piece), "na,na,na,na,na,na,na,na,,,,,");
			strcat(dataLine, piece);
			strcat(dataLine, comma);
			break;
	}
	return(NO_ERROR);
}
コード例 #26
0
int CHttpDownloader::TransferDataPost()
{
	CUrlCrack url;
	if (!url.Crack(m_strUrl.c_str()))
		return ERR_URLCRACKERROR;

	NEED_STOP;

	//LPCTSTR lpszUserAgent = _T("Mozilla/5.0 (compatible; MSIE 6.0; Windows NT 5.1)");
	//m_hInetSession = ::InternetOpen(lpszUserAgent, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
	m_hInetSession = ::InternetOpen(MONEYHUB_USERAGENT, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
	if (m_hInetSession == NULL)
		return ERR_NETWORKERROR;

	NEED_STOP;

	DWORD dwTimeOut = 60000;
	InternetSetOptionEx(m_hInetSession, INTERNET_OPTION_CONTROL_RECEIVE_TIMEOUT, &dwTimeOut, sizeof(DWORD), 0);
	InternetSetOptionEx(m_hInetSession, INTERNET_OPTION_CONTROL_SEND_TIMEOUT, &dwTimeOut, sizeof(DWORD), 0);
	InternetSetOptionEx(m_hInetSession, INTERNET_OPTION_SEND_TIMEOUT, &dwTimeOut, sizeof(DWORD), 0);
	InternetSetOptionEx(m_hInetSession, INTERNET_OPTION_RECEIVE_TIMEOUT, &dwTimeOut, sizeof(DWORD), 0);
	InternetSetOptionEx(m_hInetSession, INTERNET_OPTION_CONNECT_TIMEOUT, &dwTimeOut, sizeof(DWORD), 0);

	m_hInetConnection = ::InternetConnect(m_hInetSession, url.GetHostName(), url.GetPort(), NULL, NULL, INTERNET_SERVICE_HTTP, 0, (DWORD)this);
	if (m_hInetConnection == NULL)
	{
		//服务器连接错误,反馈 
		CRecordProgram::GetInstance()->FeedbackError(MY_ERROR_PRO_NAME, MY_ERROR_ID_SERVICE, MY_ERROR_DESCRIPT_SERVICE);
		CloseHandles();
		return ERR_NETWORKERROR;
	}

	NEED_STOP;

	LPCTSTR ppszAcceptTypes[2];
	ppszAcceptTypes[0] = _T("*/*"); 
	ppszAcceptTypes[1] = NULL;

	m_hInetFile = HttpOpenRequest(m_hInetConnection, _T("POST"), url.GetPath(), NULL, NULL, ppszAcceptTypes, INTERNET_FLAG_RELOAD | INTERNET_FLAG_DONT_CACHE | INTERNET_FLAG_KEEP_CONNECTION, (DWORD)this);
	if (m_hInetFile == NULL)
	{
		CloseHandles();
		return ERR_NETWORKERROR;
	}

	NEED_STOP;

	HttpAddRequestHeaders(m_hInetFile, _T("Content-Type: application/x-www-form-urlencoded\r\n"), -1, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE); 

	TCHAR szHeaders[1024];
	//_stprintf_s(szHeaders, _countof(szHeaders), _T("MoneyhubUID: %08X%08X%08X%08X\r\n"), m_hwid.dw1, m_hwid.dw2, m_hwid.dw3, m_hwid.dw4);
	_stprintf_s(szHeaders, _countof(szHeaders), _T("MoneyhubUID: %s\r\n"), m_strHWID.c_str());
	HttpAddRequestHeaders(m_hInetFile, szHeaders, -1, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE); 

	BOOL bSend = ::HttpSendRequest(m_hInetFile, NULL, 0, m_lpPostData, m_dwPostDataLength);
	if (!bSend)
	{
		CloseHandles();
		return ERR_NETWORKERROR;
	}

	NEED_STOP;

	TCHAR szStatusCode[32];
	DWORD dwInfoSize = sizeof(szStatusCode);
	if (!HttpQueryInfo(m_hInetFile, HTTP_QUERY_STATUS_CODE, szStatusCode, &dwInfoSize, NULL))
	{
		CloseHandles();
		return ERR_FILENOTFOUND;
	}
	else
	{
		long nStatusCode = _ttol(szStatusCode);
		if (nStatusCode != HTTP_STATUS_OK)
		{
			CloseHandles();
			return ERR_FILENOTFOUND;
		}
	}

	NEED_STOP;
	
	m_hSaveFile = CreateFile(m_strSaveFile.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
	if (m_hSaveFile == INVALID_HANDLE_VALUE)
	{
		//xml文件创建失败
		CRecordProgram::GetInstance()->FeedbackError(MY_ERROR_PRO_NAME, MY_ERROR_ID_FILE, MY_ERROR_DESCRIPT_FILE);
		CloseHandles();
		return ERR_DISKERROR;
	}
	
	NEED_STOP;

	LPBYTE lpszData = NULL;
	DWORD dwSize = 0;

	while (true)   
	{   
		NEED_STOP;

		if (!InternetQueryDataAvailable(m_hInetFile, &dwSize, 0, 0))   
			break;   

		lpszData = new BYTE[dwSize];   
		DWORD dwDownloaded = 0;

		if (!InternetReadFile(m_hInetFile, (LPVOID)lpszData, dwSize, &dwDownloaded))   
		{   
			delete []lpszData;
			CloseHandles();
			return ERR_FILENOTFOUND;  
		}   
		else   
		{   
			DWORD dwBytesWritten = 0;
			if (!WriteFile(m_hSaveFile, lpszData, dwDownloaded, &dwBytesWritten, NULL))
			{
				//xml文件写入失败
				CRecordProgram::GetInstance()->FeedbackError(MY_ERROR_PRO_NAME, MY_EEEOR_ID_FILER, MY_ERROR_DESCRIPT_FILER);

				CloseHandles();
				return ERR_DISKERROR;
			}

			delete []lpszData;   

			if (dwDownloaded == 0)   
				break;   
		}   
	}

	CloseHandles();

	return ERR_SUCCESS;
}
コード例 #27
0
ファイル: filest.cpp プロジェクト: CyberShadow/Far-NetBox
BOOL CFile::GetStatus(CFileStatus& rStatus) const
{
	ASSERT_VALID(this);

	memset(&rStatus, 0, sizeof(CFileStatus));

	// copy file name from cached m_strFileName
	Checked::tcsncpy_s(rStatus.m_szFullName, _countof(rStatus.m_szFullName), m_strFileName, _TRUNCATE);

	if (m_hFile != hFileNull)
	{
		// get time current file size
		FILETIME ftCreate, ftAccess, ftModify;
		if (!::GetFileTime(m_hFile, &ftCreate, &ftAccess, &ftModify))
			return FALSE;


		LARGE_INTEGER li;

		if (::GetFileSizeEx(m_hFile, &li) == 0)
			return FALSE;

		rStatus.m_size = li.QuadPart;


		if (m_strFileName.IsEmpty())
			rStatus.m_attribute = 0;
		else
		{
			DWORD dwAttribute = ::GetFileAttributes(m_strFileName);

			// don't return an error for this because previous versions of MFC didn't
			if (dwAttribute == 0xFFFFFFFF)
				rStatus.m_attribute = 0;
			else
			{
				rStatus.m_attribute = (BYTE) dwAttribute;
			}
		}

		// convert times as appropriate
		// some file systems may not record file creation time, file access time etc
		if (CTime::IsValidFILETIME(ftCreate))
		{
			rStatus.m_ctime = CTime(ftCreate);
		}
		else
		{
			rStatus.m_ctime = CTime();
		}

		if (CTime::IsValidFILETIME(ftAccess))
		{
			rStatus.m_atime = CTime(ftAccess);
		}
		else
		{
			rStatus.m_atime = CTime();
		}
		
		if (CTime::IsValidFILETIME(ftModify))
		{
			rStatus.m_mtime = CTime(ftModify);
		}
		else
		{
			rStatus.m_mtime = CTime();
		}

		if (rStatus.m_ctime.GetTime() == 0)
			rStatus.m_ctime = rStatus.m_mtime;

		if (rStatus.m_atime.GetTime() == 0)
			rStatus.m_atime = rStatus.m_mtime;
	}
	return TRUE;
}
コード例 #28
0
int CHttpDownloader::TransferDataGet()
{
	CUrlCrack url;
	if (!url.Crack(m_strUrl.c_str()))
		return ERR_URLCRACKERROR;

	NEED_STOP;

	//LPCTSTR lpszUserAgent = _T("Mozilla/5.0 (compatible; MSIE 6.0; Windows NT 5.1)");
	//m_hInetSession = ::InternetOpen(lpszUserAgent, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
	m_hInetSession = ::InternetOpen(MONEYHUB_USERAGENT, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
	if (m_hInetSession == NULL)
		return ERR_NETWORKERROR;

	NEED_STOP;

	DWORD dwTimeOut = 60000;
	InternetSetOptionEx(m_hInetSession, INTERNET_OPTION_CONTROL_RECEIVE_TIMEOUT, &dwTimeOut, sizeof(DWORD), 0);
	InternetSetOptionEx(m_hInetSession, INTERNET_OPTION_CONTROL_SEND_TIMEOUT, &dwTimeOut, sizeof(DWORD), 0);
	InternetSetOptionEx(m_hInetSession, INTERNET_OPTION_SEND_TIMEOUT, &dwTimeOut, sizeof(DWORD), 0);
	InternetSetOptionEx(m_hInetSession, INTERNET_OPTION_RECEIVE_TIMEOUT, &dwTimeOut, sizeof(DWORD), 0);
	InternetSetOptionEx(m_hInetSession, INTERNET_OPTION_CONNECT_TIMEOUT, &dwTimeOut, sizeof(DWORD), 0);

	m_hInetConnection = ::InternetConnect(m_hInetSession, url.GetHostName(), url.GetPort(), NULL, NULL, INTERNET_SERVICE_HTTP, 0, (DWORD)this);
	if (m_hInetConnection == NULL)
	{
		//服务器连接错误,反馈 
		CRecordProgram::GetInstance()->FeedbackError(MY_ERROR_PRO_NAME, MY_ERROR_ID_SERVICE, MY_ERROR_DESCRIPT_SERVICE);

		CloseHandles();
		return ERR_NETWORKERROR;
	}

	NEED_STOP;

	LPCTSTR ppszAcceptTypes[2];
	ppszAcceptTypes[0] = _T("*/*"); 
	ppszAcceptTypes[1] = NULL;

	m_hInetFile = HttpOpenRequest(m_hInetConnection, NULL, url.GetPath(), NULL, NULL, ppszAcceptTypes, INTERNET_FLAG_RELOAD /*| INTERNET_FLAG_DONT_CACHE*/ | INTERNET_FLAG_KEEP_CONNECTION, (DWORD)this);
	if (m_hInetFile == NULL)
	{
		CloseHandles();
		return ERR_NETWORKERROR;
	}

	NEED_STOP;

	getBreakDownloadName();

	TCHAR szHeaders[100];
	//_stprintf_s(szHeaders, _countof(szHeaders), _T("MoneyhubUID: %08X%08X%08X%08X\r\n"), m_hwid.dw1, m_hwid.dw2, m_hwid.dw3, m_hwid.dw4);
	_stprintf_s(szHeaders, _countof(szHeaders), _T("MoneyhubUID: %s\r\n"), m_strHWID.c_str());
	HttpAddRequestHeaders(m_hInetFile, szHeaders, -1, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE); 

	_stprintf_s(szHeaders,_countof(szHeaders),_T("Range: bytes=%d-"), isBreakPointFile(m_strSaveFile.c_str()) );
  	HttpAddRequestHeaders(m_hInetFile, szHeaders, -1, HTTP_ADDREQ_FLAG_ADD_IF_NEW ) ;

	BOOL bSend = ::HttpSendRequest(m_hInetFile, NULL, 0, NULL, 0);
	if (!bSend)
	{
		CloseHandles();
		return ERR_NETWORKERROR;
	}

	NEED_STOP;

	TCHAR szStatusCode[32];
	DWORD dwInfoSize = sizeof(szStatusCode);
	if (!HttpQueryInfo(m_hInetFile, HTTP_QUERY_STATUS_CODE, szStatusCode, &dwInfoSize, NULL))
	{
		CloseHandles();
		return ERR_FILENOTFOUND;
	}
	else
	{
		long nStatusCode = _ttol(szStatusCode);
		if (nStatusCode != HTTP_STATUS_PARTIAL_CONTENT && nStatusCode != HTTP_STATUS_OK)
		{
			CloseHandles();
			return ERR_FILENOTFOUND;
		}
	}


	TCHAR szContentLength[32];
	dwInfoSize = sizeof(szContentLength);
	if (::HttpQueryInfo(m_hInetFile, HTTP_QUERY_CONTENT_LENGTH, szContentLength, &dwInfoSize, NULL))
	{
		m_ui64FileSize = (UINT64)_ttoi64(szContentLength) + isBreakPointFile(m_strSaveFile.c_str());
		if (m_pUpdateMgr)
			m_pUpdateMgr->SetProgressVal(m_ui64FileSize, 0);
	}
	else 
	{
		CloseHandles();
		return ERR_FILENOTFOUND;
	}

	NEED_STOP;

	return this->downLoadBreakpointFile();
}
コード例 #29
0
ファイル: ssl_openssl.cpp プロジェクト: gloria8023/miranda-ng
static void ReportSslError(SECURITY_STATUS scRet, int line, bool = false)
{
    TCHAR szMsgBuf[256];
    switch (scRet) {
    case 0:
    case ERROR_NOT_READY:
        return;

    case SEC_E_INVALID_TOKEN:
        _tcsncpy_s(szMsgBuf, TranslateT("Client cannot decode host message. Possible causes: host does not support SSL or requires not existing security package"), _TRUNCATE);
        break;

    case CERT_E_CN_NO_MATCH:
    case SEC_E_WRONG_PRINCIPAL:
        _tcsncpy_s(szMsgBuf, TranslateT("Host we are connecting to is not the one certificate was issued for"), _TRUNCATE);
        break;

    default:
        FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, scRet, LANG_USER_DEFAULT, szMsgBuf, _countof(szMsgBuf), NULL);
    }

    TCHAR szMsgBuf2[512];
    mir_sntprintf(szMsgBuf2, _T("SSL connection failure (%x %u): %s"), scRet, line, szMsgBuf);

    char* szMsg = Utf8EncodeT(szMsgBuf2);
    SslLog(szMsg);
    mir_free(szMsg);

    SetLastError(scRet);
    PUShowMessageT(szMsgBuf2, SM_WARNING);
}
コード例 #30
0
ファイル: Notifications.cpp プロジェクト: Seldom/miranda-ng
INT_PTR CALLBACK DlgUpdate(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
	HWND hwndList = GetDlgItem(hDlg, IDC_LIST_UPDATES);

	switch (message) {
	case WM_INITDIALOG:
		TranslateDialogDefault(hDlg);
		SetWindowLongPtr(hDlg, GWLP_USERDATA, 0);
		SendMessage(hwndList, LVM_SETEXTENDEDLISTVIEWSTYLE, 0, LVS_EX_FULLROWSELECT | LVS_EX_CHECKBOXES);
		{
			LVCOLUMN lvc = { 0 };
			// Initialize the LVCOLUMN structure.
			// The mask specifies that the format, width, text, and
			// subitem members of the structure are valid.
			lvc.mask = LVCF_FMT | LVCF_WIDTH | LVCF_TEXT | LVCF_SUBITEM;
			lvc.fmt = LVCFMT_LEFT;

			lvc.iSubItem = 0;
			lvc.pszText = TranslateT("Component Name");
			lvc.cx = 145; // width of column in pixels
			ListView_InsertColumn(hwndList, 0, &lvc);

			lvc.iSubItem = 1;
			lvc.pszText = TranslateT("Current Version");
			lvc.cx = 95; // width of column in pixels
			ListView_InsertColumn(hwndList, 1, &lvc);

			lvc.iSubItem = 2;
			lvc.pszText = TranslateT("New Version");
			lvc.cx = 82; // width of column in pixels
			ListView_InsertColumn(hwndList, 2, &lvc);

			//enumerate plugins, fill in list
			//bool one_enabled = false;
			ListView_DeleteAllItems(hwndList);

			LVITEM lvI = { 0 };

			// Some code to create the list-view control.
			// Initialize LVITEM members that are common to all
			// items.
			lvI.mask = LVIF_TEXT | LVIF_PARAM | LVIF_NORECOMPUTE;// | LVIF_IMAGE;

			vector<FILEINFO> &todo = *(vector<FILEINFO> *)lParam;
			for (int i = 0; i < (int)todo.size(); ++i) {
				lvI.mask = LVIF_TEXT | LVIF_PARAM;// | LVIF_IMAGE;
				lvI.iSubItem = 0;
				lvI.lParam = (LPARAM)&todo[i];
				lvI.pszText = todo[i].tszDescr;
				lvI.iItem = i;
				ListView_InsertItem(hwndList, &lvI);

				lvI.mask = LVIF_TEXT;// | LVIF_IMAGE;

				lvI.iSubItem = 1;
				lvI.pszText = todo[i].tszCurVer;
				ListView_SetItem(hwndList, &lvI);

				lvI.iSubItem = 2;
				lvI.pszText = todo[i].tszNewVer;
				ListView_SetItem(hwndList, &lvI);

				ListView_SetCheckState(hwndList, lvI.iItem, true);
				todo[i].enabled = true;
			}
			HWND hwOk = GetDlgItem(hDlg, IDOK);
			EnableWindow(hwOk, true/*one_enabled ? TRUE : FALSE*/);
			// do this after filling list - enables 'ITEMCHANGED' below
			SetWindowLongPtr(hDlg, GWLP_USERDATA, lParam);
			Utils_RestoreWindowPositionNoSize(hDlg, 0, MODNAME, "ConfirmWindow");
		}
		return TRUE;

	case WM_NOTIFY:
		if (((LPNMHDR)lParam)->hwndFrom == hwndList) {
			switch (((LPNMHDR)lParam)->code) {
			case LVN_ITEMCHANGED:
				if (GetWindowLongPtr(hDlg, GWLP_USERDATA)) {
					NMLISTVIEW *nmlv = (NMLISTVIEW *)lParam;

					LVITEM lvI = { 0 };

					lvI.iItem = nmlv->iItem;
					lvI.iSubItem = 0;
					lvI.mask = LVIF_PARAM;
					ListView_GetItem(hwndList, &lvI);

					vector<FILEINFO> &todo = *(vector<FILEINFO> *)GetWindowLongPtr(hDlg, GWLP_USERDATA);
					if ((nmlv->uNewState ^ nmlv->uOldState) & LVIS_STATEIMAGEMASK) {
						todo[lvI.iItem].enabled = ListView_GetCheckState(hwndList, nmlv->iItem);

						bool enableOk = false;
						for (int i = 0; i < (int)todo.size(); ++i) {
							if (todo[i].enabled) {
								enableOk = true;
								break;
							}
						}
						HWND hwOk = GetDlgItem(hDlg, IDOK);
						EnableWindow(hwOk, enableOk ? TRUE : FALSE);
					}
					if (nmlv->uNewState & LVIS_SELECTED) {
						if (mir_tstrcmp(todo[lvI.iItem].tszInfoURL, _T("")))
							EnableWindow(GetDlgItem(hDlg, IDC_INFO), TRUE);
						else
							EnableWindow(GetDlgItem(hDlg, IDC_INFO), FALSE);
						SetDlgItemText(hDlg, IDC_MESSAGE, TranslateTS(todo[lvI.iItem].tszMessage));
					}
				}
				break;
			}
		}
		break;

	case WM_COMMAND:
		if (HIWORD(wParam) == BN_CLICKED) {
			switch (LOWORD(wParam)) {
			case IDOK:
			{
				vector<FILEINFO> &todo = *(vector<FILEINFO> *)GetWindowLongPtr(hDlg, GWLP_USERDATA);
				ShowWindow(hDlg, SW_HIDE);
				TCHAR tszBuff[2048] = { 0 }, tszFileDest[MAX_PATH] = { 0 }, tszFilePathDest[MAX_PATH] = { 0 }, tszFilePathBack[MAX_PATH] = { 0 }, tszFileName[MAX_PATH] = { 0 };
				TCHAR* tszExt = NULL;
				char szKey[64] = { 0 };
				vector<int> arFileType;
				vector<tString> arFilePath;
				vector<tString> arFileName;
				vector<tString> arAdvFolder;
				vector<tString> arExt;
				STARTUPINFO si;
				PROCESS_INFORMATION pi;

				SetWindowLongPtr(hDlg, GWLP_USERDATA, 0);
				Utils_SaveWindowPosition(hDlg, NULL, MODNAME, "ConfirmWindow");

				arFileType.clear();
				arFilePath.clear();
				arFileName.clear();
				arAdvFolder.clear();
				arExt.clear();
				for (int i = 0; i < (int)todo.size(); ++i) {
					if (todo[i].enabled) {
						switch (todo[i].FileType) {
						case 1:
							mir_sntprintf(tszFileDest, _T("%s\\Pack"), tszRoot);
							CreateDirectory(tszFileDest, NULL);
							break;
						case 2:
							mir_sntprintf(tszFileDest, _T("%s\\Plugins"), tszRoot);
							CreateDirectory(tszFileDest, NULL);
							break;
						case 3:
							mir_sntprintf(tszFileDest, _T("%s\\Icons"), tszRoot);
							CreateDirectory(tszFileDest, NULL);
							break;
						case 4:
							mir_sntprintf(tszFileDest, _T("%s\\Others"), tszRoot);
							CreateDirectory(tszFileDest, NULL);
							break;
						case 5:
							mir_sntprintf(tszFileDest, _T("%s\\Others"), tszRoot);
							CreateDirectory(tszFileDest, NULL);
							break;
						default:
							mir_tstrncpy(tszFileDest, tszRoot, _countof(tszFileDest));
							break;
						}
						mir_sntprintf(tszBuff, _T("%s\\Backups"), tszRoot);
						CreateDirectory(tszBuff, NULL);
						mir_tstrncpy(tszFileName, todo[i].File.tszDiskPath, _countof(tszFileName));
						mir_sntprintf(todo[i].File.tszDiskPath, _T("%s\\%s"), tszFileDest, tszFileName);
						UpdatesCount++;

						tszExt = &todo[i].File.tszDownloadURL[mir_tstrlen(todo[i].File.tszDownloadURL) - 5];
						if (mir_tstrcmp(tszExt, _T(".html")) == 0) {
							char* szUrl = mir_t2a(todo[i].File.tszDownloadURL);
							Utils_OpenUrl(szUrl);
							mir_free(szUrl);
						}
						else {
							// download update
							pFileUrl = &todo[i].File;
							Title = TranslateT("Pack Updater");
							if (todo[i].FileType == 1)
								Text = TranslateT("Downloading pack updates...");
							else
								Text = TranslateT("Downloading update...");
							DlgDownloadProc();
							if (!DlgDld) {
								if (UpdatesCount)
									UpdatesCount--;
								continue;
							}
						}
						mir_tstrncpy(todo[i].tszCurVer, todo[i].tszNewVer, _countof(todo[i].tszCurVer));
						mir_snprintf(szKey, "File_%d_CurrentVersion", todo[i].FileNum);
						db_set_ts(NULL, MODNAME, szKey, todo[i].tszCurVer);
						arFileType.push_back(todo[i].FileType);
						arFilePath.push_back(todo[i].File.tszDiskPath);
						arFileName.push_back(tszFileName);
						arAdvFolder.push_back(todo[i].tszAdvFolder);
						arExt.push_back(tszExt);
						if (todo[i].FileType == 1)
							i = (int)todo.size();
					}
				}

				if (UpdatesCount > 1 && mir_tstrcmp(arExt[0].c_str(), _T(".html")) != 0)
					mir_tstrncpy(tszBuff, TranslateT("Downloads complete. Start updating? All your data will be saved and Miranda NG will be closed."), _countof(tszBuff));
				else if (UpdatesCount == 1 && mir_tstrcmp(arExt[0].c_str(), _T(".html")) != 0)
					mir_tstrncpy(tszBuff, TranslateT("Download complete. Start updating? All your data will be saved and Miranda NG will be closed."), _countof(tszBuff));
				if (UpdatesCount > 0 && mir_tstrcmp(arExt[0].c_str(), _T(".html")) != 0) {
					INT rc = -1;
					Title = TranslateT("Pack Updater");
					Text = tszBuff;
					if (ServiceExists(MS_POPUP_ADDPOPUPT) && ServiceExists(MS_POPUP_REGISTERACTIONS) && db_get_b(NULL, "Popup", "ModuleIsEnabled", 1) && db_get_b(NULL, MODNAME, "Popups0", DEFAULT_POPUP_ENABLED) && (db_get_dw(NULL, "Popup", "Actions", 0) & 1))
						rc = DialogBox(hInst, MAKEINTRESOURCE(IDD_POPUPDUMMI), NULL, DlgMsgPop);
					else
						rc = MessageBox(NULL, tszBuff, Title, MB_YESNO | MB_ICONQUESTION);
					if (rc == IDYES) {
						for (int i = 0; i < UpdatesCount; i++) {
							TCHAR* tszUtilRootPlug = NULL;
							TCHAR* tszUtilRootIco = NULL;
							TCHAR* tszUtilRoot = NULL;
							TCHAR  tszCurrentDir[MAX_PATH];

							switch (arFileType[i]) {
							case 0:
								break;
							case 1:
								if (Reminder == 2)
									db_set_b(NULL, MODNAME, "Reminder", 1);
								memset(&si, 0, sizeof(STARTUPINFO));
								memset(&pi, 0, sizeof(PROCESS_INFORMATION));
								si.cb = sizeof(STARTUPINFO);
								{
									_tcsncpy_s(tszCurrentDir, arFilePath[i].c_str(), _TRUNCATE);
									TCHAR *p = _tcsrchr(tszCurrentDir, '\\');
									if (p) *p = 0;
								}
								CreateProcess(arFilePath[i].c_str(), _T(""), NULL, NULL, FALSE, NULL, NULL, tszCurrentDir, &si, &pi);
								i = UpdatesCount;
								CallFunctionAsync(ExitMe, 0);
								break;
							case 2:
								tszUtilRootPlug = Utils_ReplaceVarsT(_T("%miranda_path%\\Plugins"));
								if (mir_tstrcmp(arAdvFolder[i].c_str(), _T("")) == 0)
									mir_sntprintf(tszFilePathDest, _T("%s\\%s"), tszUtilRootPlug, arFileName[i].c_str());
								else
									mir_sntprintf(tszFilePathDest, _T("%s\\%s\\%s"), tszUtilRootPlug, arAdvFolder[i].c_str(), arFileName[i].c_str());
								mir_sntprintf(tszFilePathBack, _T("%s\\Backups\\%s"), tszRoot, arFileName[i].c_str());
								MoveFile(tszFilePathDest, tszFilePathBack);
								MoveFile(arFilePath[i].c_str(), tszFilePathDest);
								mir_free(tszUtilRootPlug);
								if (i == UpdatesCount - 1)
									CallFunctionAsync(RestartMe, 0);
								break;
							case 3:
								tszUtilRootIco = Utils_ReplaceVarsT(_T("%miranda_path%\\Icons"));
								if (mir_tstrcmp(arAdvFolder[i].c_str(), _T("")) == 0)
									mir_sntprintf(tszFilePathDest, _T("%s\\%s"), tszUtilRootIco, arFileName[i].c_str());
								else
									mir_sntprintf(tszFilePathDest, _T("%s\\%s\\%s"), tszUtilRootIco, arAdvFolder[i].c_str(), arFileName[i].c_str());
								mir_sntprintf(tszFilePathBack, _T("%s\\Backups\\%s"), tszRoot, arFileName[i].c_str());
								MoveFile(tszFilePathDest, tszFilePathBack);
								MoveFile(arFilePath[i].c_str(), tszFilePathDest);
								mir_free(tszUtilRootIco);
								if (i == UpdatesCount - 1)
									CallFunctionAsync(RestartMe, 0);
								break;
							case 4:
								tszUtilRoot = Utils_ReplaceVarsT(_T("%miranda_path%"));
								if (mir_tstrcmp(arAdvFolder[i].c_str(), _T("")) == 0)
									mir_sntprintf(tszFilePathDest, _T("%s\\%s"), tszUtilRoot, arFileName[i].c_str());
								else
									mir_sntprintf(tszFilePathDest, _T("%s\\%s\\%s"), tszUtilRoot, arAdvFolder[i].c_str(), arFileName[i].c_str());
								mir_sntprintf(tszFilePathBack, _T("%s\\Backups\\%s"), tszRoot, arFileName[i].c_str());
								MoveFile(tszFilePathDest, tszFilePathBack);
								MoveFile(arFilePath[i].c_str(), tszFilePathDest);
								mir_free(tszUtilRoot);
								if (i == UpdatesCount - 1)
									CallFunctionAsync(RestartMe, 0);
								break;
							case 5:
								tszUtilRoot = Utils_ReplaceVarsT(_T("%miranda_path%"));
								if (mir_tstrcmp(arAdvFolder[i].c_str(), _T("")) == 0)
									mir_sntprintf(tszFilePathDest, _T("%s\\%s"), tszUtilRoot, arFileName[i].c_str());
								else
									mir_sntprintf(tszFilePathDest, _T("%s\\%s\\%s"), tszUtilRoot, arAdvFolder[i].c_str(), arFileName[i].c_str());
								mir_sntprintf(tszFilePathBack, _T("%s\\Backups\\%s"), tszRoot, arFileName[i].c_str());
								MoveFile(tszFilePathDest, tszFilePathBack);
								MoveFile(arFilePath[i].c_str(), tszFilePathDest);
								mir_free(tszUtilRoot);
								break;
							}
						}
					}
					else { //reminder for not installed pack update
						if (Reminder && (UpdatesCount == 1) && (arFileType[0] == 1))
							db_set_b(NULL, MODNAME, "Reminder", 2);
						mir_sntprintf(tszBuff, TranslateT("You have chosen not to install the pack update immediately.\nYou can install it manually from this location:\n\n%s"), arFilePath[0].c_str());
						Title = TranslateT("Pack Updater");
						Text = tszBuff;
						if (ServiceExists(MS_POPUP_ADDPOPUPT) && db_get_b(NULL, "Popup", "ModuleIsEnabled", 1) && db_get_b(NULL, MODNAME, "Popups2", DEFAULT_POPUP_ENABLED)) {
							Number = 2;
							show_popup(0, Title, Text, Number, 0);
						}
						else if (db_get_b(NULL, MODNAME, "Popups2M", DEFAULT_MESSAGE_ENABLED))
							MessageBox(NULL, Text, Title, MB_ICONINFORMATION);
					}
				}
			}
			EndDialog(hDlg, IDOK);
			return TRUE;

			case IDCANCEL:
				SetWindowLongPtr(hDlg, GWLP_USERDATA, 0);
				Utils_SaveWindowPosition(hDlg, NULL, MODNAME, "ConfirmWindow");
				EndDialog(hDlg, IDCANCEL);
				return TRUE;

			case IDC_INFO:
				int sel = ListView_GetSelectionMark(hwndList);
				vector<FILEINFO> &todo = *(vector<FILEINFO> *)GetWindowLongPtr(hDlg, GWLP_USERDATA);
				Utils_OpenUrlT(todo[sel].tszInfoURL);
			}
			break;
		}
	}
	return FALSE;
}