예제 #1
0
END_TEST

START_TEST(test_syllable_iterator)
{
    ucschar str[] = {
	// L L V V T T
	0x1107, 0x1107, 0x116e, 0x1166, 0x11af, 0x11a8,          // 0
	// L V T
	0x1108, 0x1170, 0x11b0,                                  // 6
	// L L V V T T M
	0x1107, 0x1107, 0x116e, 0x1166, 0x11af, 0x11a8, 0x302E,  // 9
	// L V T M
	0x1108, 0x1170, 0x11b0, 0x302F,                          // 16
	// Lf V
	0x115f, 0x1161,                                          // 20
	// L Vf
	0x110c, 0x1160,                                          // 22
	// L LVT T
	0x1107, 0xbc14, 0x11a8,                                  // 24
	// L LV T
	0x1100, 0xac00, 0x11a8,                                  // 27
	// LVT
	0xc00d,                                                  // 30 
	// other
	'a',                                                     // 31
	0                                                        // 32
    };

    const ucschar* begin = str;
    const ucschar* end = str + countof(str) - 1;
    const ucschar* s = str;

    s = hangul_syllable_iterator_next(s, end);
    fail_unless(s - str == 6,
		"error: next syllable: L L V V T T");

    s = hangul_syllable_iterator_next(s, end);
    fail_unless(s - str == 9,
		"error: next syllable: L V T");

    s = hangul_syllable_iterator_next(s, end);
    fail_unless(s - str == 16,
		"error: next syllable: L L V V T T M");

    s = hangul_syllable_iterator_next(s, end);
    fail_unless(s - str == 20,
		"error: next syllable: L V T M");

    s = hangul_syllable_iterator_next(s, end);
    fail_unless(s - str == 22,
		"error: next syllable: Lf V");

    s = hangul_syllable_iterator_next(s, end);
    fail_unless(s - str == 24,
		"error: next syllable: L Vf");

    s = hangul_syllable_iterator_next(s, end);
    fail_unless(s - str == 27,
		"error: next syllable: L LVT T");

    s = hangul_syllable_iterator_next(s, end);
    fail_unless(s - str == 30,
		"error: next syllable: L LV T");

    s = hangul_syllable_iterator_next(s, end);
    fail_unless(s - str == 31,
		"error: next syllable: LVT");

    s = hangul_syllable_iterator_next(s, end);
    fail_unless(s - str == 32,
		"error: next syllable: other");

    s = end;
    s = hangul_syllable_iterator_prev(s, begin);
    fail_unless(s - str == 31,
		"error: prev syllable: other");

    s = hangul_syllable_iterator_prev(s, begin);
    fail_unless(s - str == 30,
		"error: prev syllable: LVT");

    s = hangul_syllable_iterator_prev(s, begin);
    fail_unless(s - str == 27,
		"error: prev syllable: L LV T");

    s = hangul_syllable_iterator_prev(s, begin);
    fail_unless(s - str == 24,
		"error: prev syllable: L LVT T");

    s = hangul_syllable_iterator_prev(s, begin);
    fail_unless(s - str == 22,
		"error: prev syllable: L Vf");

    s = hangul_syllable_iterator_prev(s, begin);
    fail_unless(s - str == 20,
		"error: prev syllable: Lf V");

    s = hangul_syllable_iterator_prev(s, begin);
    fail_unless(s - str == 16,
		"error: prev syllable: L V T M");

    s = hangul_syllable_iterator_prev(s, begin);
    fail_unless(s - str == 9,
		"error: prev syllable: L L V V T T M");

    s = hangul_syllable_iterator_prev(s, begin);
    fail_unless(s - str == 6,
		"error: prev syllable: L V T");

    s = hangul_syllable_iterator_prev(s, begin);
    fail_unless(s - str == 0,
		"error: prev syllable: L L V V T T");
}
예제 #2
0
BOOL g_RegisterCrossSvScript()
{
	return g_cScriptManager.RegisterTableFuncs("KCrossSv", KCrossSvScript::arFunction, countof(KCrossSvScript::arFunction));
}
예제 #3
0
HRESULT CpiSubscriptionsVerifyInstall(
    CPI_SUBSCRIPTION_LIST* pList
    )
{
    HRESULT hr = S_OK;
    UINT er = ERROR_SUCCESS;

    ICatalogObject* piSubsObj = NULL;

    for (CPI_SUBSCRIPTION* pItm = pList->pFirst; pItm; pItm = pItm->pNext)
    {
        // subscriptions that are being installed
        if (!WcaIsInstalling(pItm->isInstalled, pItm->isAction))
            continue;

        // subscription is supposed to exist
        if (CpiIsInstalled(pItm->isInstalled))
        {
            // if we don't have an id
            if (!*pItm->wzID)
            {
                // find subscriptions with conflicting name
                hr = FindObjectForSubscription(pItm, FALSE, TRUE, &piSubsObj);
                ExitOnFailure(hr, "Failed to find collection object for subscription");

                // if the subscription was found
                if (S_OK == hr)
                {
                    // get id from subscription object
                    hr = CpiGetKeyForObject(piSubsObj, pItm->wzID, countof(pItm->wzID));
                    ExitOnFailure(hr, "Failed to get id");
                }

                // if the subscription was not found
                else
                {
                    // create a new id
                    hr = CpiCreateId(pItm->wzID, countof(pItm->wzID));
                    ExitOnFailure(hr, "Failed to create id");
                }
            }
        }

        // subscription is supposed to be created
        else
        {
            // check for conflicts
            do {
                if (*pItm->wzID)
                {
                    // find subscriptions with conflicting id
                    hr = FindObjectForSubscription(pItm, TRUE, FALSE, &piSubsObj);
                    ExitOnFailure(hr, "Failed to find collection object for subscription");

                    if (S_FALSE == hr)
                    {
                        // find subscriptions with conflicting name
                        hr = FindObjectForSubscription(pItm, FALSE, TRUE, &piSubsObj);
                        ExitOnFailure(hr, "Failed to find collection object for subscription");

                        if (S_OK == hr)
                            // "A subscription with a conflictiong name exists. retry cancel"
                            er = WcaErrorMessage(msierrComPlusSubscriptionNameConflict, hr, INSTALLMESSAGE_ERROR | MB_RETRYCANCEL, 0);
                        else
                            break; // no conflicting entry found, break loop
                    }
                    else
                        // "A subscription with a conflicting id exists. abort retry ignore"
                        er = WcaErrorMessage(msierrComPlusSubscriptionIdConflict, hr, INSTALLMESSAGE_ERROR | MB_ABORTRETRYIGNORE, 0);
                }
                else
                {
                    // find subscriptions with conflicting name
                    hr = FindObjectForSubscription(pItm, FALSE, TRUE, &piSubsObj);
                    ExitOnFailure(hr, "Failed to find collection object for subscription");

                    if (S_OK == hr)
                        // "A subscription with a conflictiong name exists. abort retry ignore"
                        er = WcaErrorMessage(msierrComPlusSubscriptionNameConflict, hr, INSTALLMESSAGE_ERROR | MB_ABORTRETRYIGNORE, 0);
                    else
                        break; // no conflicting entry found, break loop
                }

                switch (er)
                {
                case IDCANCEL:
                case IDABORT:
                    ExitOnFailure1(hr = E_FAIL, "A subscription with a conflictiong name or id exists, key: %S", pItm->wzKey);
                    break;
                case IDRETRY:
                    break;
                case IDIGNORE:
                default:
                    // if we don't have an id, copy id from object
                    if (!*pItm->wzID)
                    {
                        hr = CpiGetKeyForObject(piSubsObj, pItm->wzID, countof(pItm->wzID));
                        ExitOnFailure(hr, "Failed to get id");
                    }
                    hr = S_FALSE; // indicate that this is not a conflict
                }
            } while (S_OK == hr); // hr = S_FALSE if we don't have any conflicts

            // create a new id if one is missing
            if (!*pItm->wzID)
            {
                hr = CpiCreateId(pItm->wzID, countof(pItm->wzID));
                ExitOnFailure(hr, "Failed to create id");
            }
        }

        // clean up
        ReleaseNullObject(piSubsObj);
    }

    hr = S_OK;

LExit:
    // clean up
    ReleaseObject(piSubsObj);

    return hr;
}
예제 #4
0
MConHandle::operator const HANDLE()
{
	if (mpp_OutBuffer && *mpp_OutBuffer && (*mpp_OutBuffer != INVALID_HANDLE_VALUE))
	{
		LogHandle(Event::e_GetHandlePtr, *mpp_OutBuffer);
		return *mpp_OutBuffer;
	}

	if (mh_Handle == INVALID_HANDLE_VALUE)
	{
		if (mn_StdMode)
		{
			mh_Handle = GetStdHandle(mn_StdMode);
			LogHandle(Event::e_CreateHandleStd, mh_Handle);
		}
		else
		{
			// Чтобы случайно не открыть хэндл несколько раз в разных потоках
			MSectionLock CS; CS.Lock(&mcs_Handle, TRUE);

			// Во время ожидания хэндл мог быт открыт в другом потоке
			if (mh_Handle == INVALID_HANDLE_VALUE)
			{
				mh_Handle = CreateFileW(ms_Name, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE,
										0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);

				if (mh_Handle != INVALID_HANDLE_VALUE)
				{
					mb_OpenFailed = FALSE;
				}
				else
				{
					mn_LastError = GetLastError();

					if (!mb_OpenFailed)
					{
						mb_OpenFailed = TRUE; // чтобы ошибка вываливалась только один раз!
						char szErrMsg[512], szNameA[10], szSelfFull[MAX_PATH];
						const char *pszSelf;
						char *pszDot;

						if (!GetModuleFileNameA(0,szSelfFull,MAX_PATH))
						{
							pszSelf = "???";
						}
						else
						{
							pszSelf = strrchr(szSelfFull, '\\');
							if (pszSelf) pszSelf++; else pszSelf = szSelfFull;

							pszDot = strrchr((char*)pszSelf, '.');

							if (pszDot) *pszDot = 0;
						}

						WideCharToMultiByte(CP_OEMCP, 0, ms_Name, -1, szNameA, sizeof(szNameA), 0,0);
						_wsprintfA(szErrMsg, SKIPLEN(countof(szErrMsg)) "%s: CreateFile(%s) failed, ErrCode=0x%08X\n", pszSelf, szNameA, mn_LastError);
						HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);

						if (h && h!=INVALID_HANDLE_VALUE)
						{
							DWORD dwWritten = 0;
							WriteFile(h, szErrMsg, lstrlenA(szErrMsg), &dwWritten, 0);
						}
					}
				}

				LogHandle(Event::e_CreateHandle, mh_Handle);
			}
		}
	}

	LogHandle(Event::e_GetHandle, mh_Handle);
	return mh_Handle;
};
예제 #5
0
파일: Actions.cpp 프로젝트: ForNeVeR/ConEmu
int DoInjectHooks(LPWSTR asCmdArg)
{
	gbInShutdown = TRUE; // чтобы не возникло вопросов при выходе
	gnRunMode = RM_SETHOOK64;
	LPWSTR pszNext = asCmdArg;
	LPWSTR pszEnd = NULL;
	BOOL lbForceGui = FALSE;
	PROCESS_INFORMATION pi = {NULL};


	pi.hProcess = (HANDLE)wcstoul(pszNext, &pszEnd, 16);

	if (pi.hProcess && pszEnd && *pszEnd)
	{
		pszNext = pszEnd+1;
		pi.dwProcessId = wcstoul(pszNext, &pszEnd, 10);
	}

	if (pi.dwProcessId && pszEnd && *pszEnd)
	{
		pszNext = pszEnd+1;
		pi.hThread = (HANDLE)wcstoul(pszNext, &pszEnd, 16);
	}

	if (pi.hThread && pszEnd && *pszEnd)
	{
		pszNext = pszEnd+1;
		pi.dwThreadId = wcstoul(pszNext, &pszEnd, 10);
	}

	if (pi.dwThreadId && pszEnd && *pszEnd)
	{
		pszNext = pszEnd+1;
		lbForceGui = wcstoul(pszNext, &pszEnd, 10);
	}


	#ifdef SHOW_INJECT_MSGBOX
	wchar_t szDbgMsg[512], szTitle[128];
	PROCESSENTRY32 pinf;
	GetProcessInfo(pi.dwProcessId, &pinf);
	_wsprintf(szTitle, SKIPLEN(countof(szTitle)) L"ConEmuCD PID=%u", GetCurrentProcessId());
	_wsprintf(szDbgMsg, SKIPLEN(countof(szDbgMsg)) L"InjectsTo PID=%s {%s}\nConEmuCD PID=%u", asCmdArg ? asCmdArg : L"", pinf.szExeFile, GetCurrentProcessId());
	MessageBoxW(NULL, szDbgMsg, szTitle, MB_SYSTEMMODAL);
	#endif


	if (pi.hProcess && pi.hThread && pi.dwProcessId && pi.dwThreadId)
	{
		// Аргумент abForceGui не использовался
		CINJECTHK_EXIT_CODES iHookRc = InjectHooks(pi, /*lbForceGui,*/ gbLogProcess);

		if (iHookRc == CIH_OK/*0*/)
		{
			return CERR_HOOKS_WAS_SET;
		}

		// Ошибку (пока во всяком случае) лучше показать, для отлова возможных проблем
		DWORD nErrCode = GetLastError();
		//_ASSERTE(iHookRc == 0); -- ассерт не нужен, есть MsgBox
		wchar_t szDbgMsg[255], szTitle[128];
		_wsprintf(szTitle, SKIPLEN(countof(szTitle)) L"ConEmuC[%u], PID=%u", WIN3264TEST(32,64), GetCurrentProcessId());
		_wsprintf(szDbgMsg, SKIPLEN(countof(szDbgMsg)) L"ConEmuC.X, PID=%u\nInjecting hooks into PID=%u\nFAILED, code=%i:0x%08X", GetCurrentProcessId(), pi.dwProcessId, iHookRc, nErrCode);
		MessageBoxW(NULL, szDbgMsg, szTitle, MB_SYSTEMMODAL);
	}
	else
	{
		//_ASSERTE(pi.hProcess && pi.hThread && pi.dwProcessId && pi.dwThreadId);
		wchar_t szDbgMsg[512], szTitle[128];
		_wsprintf(szTitle, SKIPLEN(countof(szTitle)) L"ConEmuC, PID=%u", GetCurrentProcessId());
		_wsprintf(szDbgMsg, SKIPLEN(countof(szDbgMsg)) L"ConEmuC.X, PID=%u\nCmdLine parsing FAILED (%u,%u,%u,%u,%u)!\n%s",
			GetCurrentProcessId(), LODWORD(pi.hProcess), LODWORD(pi.hThread), pi.dwProcessId, pi.dwThreadId, lbForceGui, //-V205
			asCmdArg);
		MessageBoxW(NULL, szDbgMsg, szTitle, MB_SYSTEMMODAL);
	}

	return CERR_HOOKS_FAILED;
}
예제 #6
0
#include "mui.h"

#include "printer.h"
#include "uiprinter.h"
#include "intl.h"
#include "translate.h"

static video_canvas_t *printer_canvas;

static int ui_printer_enable_translate[] = {
    IDMS_DISABLED,
    IDS_ENABLED,
    0
};

static char *ui_printer_enable[countof(ui_printer_enable_translate)];

static const int ui_printer_enable_values[] = {
    0,
    1,
    -1
};

static int ui_printer_emulation_translate[] = {
    IDS_NONE,
    IDS_FILESYSTEM,
    0
};

static char *ui_printer_emulation[countof(ui_printer_emulation_translate)];
예제 #7
0
bool GSDevice11::Create(GSWnd* wnd)
{
	if(!__super::Create(wnd))
	{
		return false;
	}

	HRESULT hr = E_FAIL;

	DXGI_SWAP_CHAIN_DESC scd;
	D3D11_BUFFER_DESC bd;
	D3D11_SAMPLER_DESC sd;
	D3D11_DEPTH_STENCIL_DESC dsd;
	D3D11_RASTERIZER_DESC rd;
	D3D11_BLEND_DESC bsd;

	CComPtr<IDXGIAdapter1> adapter;
	D3D_DRIVER_TYPE driver_type = D3D_DRIVER_TYPE_HARDWARE;

	std::string adapter_id = theApp.GetConfig("Adapter", "default");

	if (adapter_id == "default")
		;
	else if (adapter_id == "ref")
	{
		driver_type = D3D_DRIVER_TYPE_REFERENCE;
	}
	else
	{
		CComPtr<IDXGIFactory1> dxgi_factory;
		CreateDXGIFactory1(__uuidof(IDXGIFactory1), (void**)&dxgi_factory);
		if (dxgi_factory)
			for (int i = 0;; i++)
			{
				CComPtr<IDXGIAdapter1> enum_adapter;
				if (S_OK != dxgi_factory->EnumAdapters1(i, &enum_adapter))
					break;
				DXGI_ADAPTER_DESC1 desc;
				hr = enum_adapter->GetDesc1(&desc);
				if (S_OK == hr && GSAdapter(desc) == adapter_id)
				{
					adapter = enum_adapter;
					driver_type = D3D_DRIVER_TYPE_UNKNOWN;
					break;
				}
			}
	}

	memset(&scd, 0, sizeof(scd));

	scd.BufferCount = 2;
	scd.BufferDesc.Width = 1;
	scd.BufferDesc.Height = 1;
	scd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
	//scd.BufferDesc.RefreshRate.Numerator = 60;
	//scd.BufferDesc.RefreshRate.Denominator = 1;
	scd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
	scd.OutputWindow = (HWND)m_wnd->GetHandle();
	scd.SampleDesc.Count = 1;
	scd.SampleDesc.Quality = 0;

	// Always start in Windowed mode.  According to MS, DXGI just "prefers" this, and it's more or less
	// required if we want to add support for dual displays later on.  The fullscreen/exclusive flip
	// will be issued after all other initializations are complete.

	scd.Windowed = TRUE;

	spritehack = !!theApp.GetConfig("UserHacks", 0) ? theApp.GetConfig("UserHacks_SpriteHack", 0) : 0;
	// NOTE : D3D11_CREATE_DEVICE_SINGLETHREADED
	//   This flag is safe as long as the DXGI's internal message pump is disabled or is on the
	//   same thread as the GS window (which the emulator makes sure of, if it utilizes a
	//   multithreaded GS).  Setting the flag is a nice and easy 5% speedup on GS-intensive scenes.

	uint32 flags = D3D11_CREATE_DEVICE_SINGLETHREADED;

#ifdef DEBUG
	flags |= D3D11_CREATE_DEVICE_DEBUG;
#endif

	D3D_FEATURE_LEVEL level;

	const D3D_FEATURE_LEVEL levels[] =
	{
		D3D_FEATURE_LEVEL_11_0,
		D3D_FEATURE_LEVEL_10_1,
		D3D_FEATURE_LEVEL_10_0,
	};

	hr = D3D11CreateDeviceAndSwapChain(adapter, driver_type, NULL, flags, levels, countof(levels), D3D11_SDK_VERSION, &scd, &m_swapchain, &m_dev, &level, &m_ctx);

	if(FAILED(hr)) return false;

	if(!SetFeatureLevel(level, true))
	{
		return false;
	}

	D3D11_FEATURE_DATA_D3D10_X_HARDWARE_OPTIONS options;

	hr = m_dev->CheckFeatureSupport(D3D11_FEATURE_D3D10_X_HARDWARE_OPTIONS, &options, sizeof(D3D11_FEATURE_D3D10_X_HARDWARE_OPTIONS));

	// msaa

	for(uint32 i = 2; i <= D3D11_MAX_MULTISAMPLE_SAMPLE_COUNT; i++)
	{
		uint32 quality[2] = {0, 0};

		if(SUCCEEDED(m_dev->CheckMultisampleQualityLevels(DXGI_FORMAT_R8G8B8A8_UNORM, i, &quality[0])) && quality[0] > 0
		&& SUCCEEDED(m_dev->CheckMultisampleQualityLevels(DXGI_FORMAT_D32_FLOAT_S8X24_UINT, i, &quality[1])) && quality[1] > 0)
		{
			m_msaa_desc.Count = i;
			m_msaa_desc.Quality = std::min<uint32>(quality[0] - 1, quality[1] - 1);

			if(i >= m_msaa) break;
		}
	}

	if(m_msaa_desc.Count == 1)
	{
		m_msaa = 0;
	}

	// convert

	D3D11_INPUT_ELEMENT_DESC il_convert[] =
	{
		{"POSITION", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0},
		{"TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 16, D3D11_INPUT_PER_VERTEX_DATA, 0},
	};

	vector<unsigned char> shader;
	theApp.LoadResource(IDR_CONVERT_FX, shader);
	CompileShader((const char *)shader.data(), shader.size(), "convert.fx", nullptr, "vs_main", nullptr, &m_convert.vs, il_convert, countof(il_convert), &m_convert.il);

	for(size_t i = 0; i < countof(m_convert.ps); i++)
	{
		CompileShader((const char *)shader.data(), shader.size(), "convert.fx", nullptr, format("ps_main%d", i).c_str(), nullptr, &m_convert.ps[i]);
	}

	memset(&dsd, 0, sizeof(dsd));

	dsd.DepthEnable = false;
	dsd.StencilEnable = false;

	hr = m_dev->CreateDepthStencilState(&dsd, &m_convert.dss);

	memset(&bsd, 0, sizeof(bsd));

	bsd.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;

	hr = m_dev->CreateBlendState(&bsd, &m_convert.bs);

	// merge

	memset(&bd, 0, sizeof(bd));

	bd.ByteWidth = sizeof(MergeConstantBuffer);
	bd.Usage = D3D11_USAGE_DEFAULT;
	bd.BindFlags = D3D11_BIND_CONSTANT_BUFFER;

	hr = m_dev->CreateBuffer(&bd, NULL, &m_merge.cb);

	theApp.LoadResource(IDR_MERGE_FX, shader);
	for(size_t i = 0; i < countof(m_merge.ps); i++)
	{
		CompileShader((const char *)shader.data(), shader.size(), "merge.fx", nullptr, format("ps_main%d", i).c_str(), nullptr, &m_merge.ps[i]);
	}

	memset(&bsd, 0, sizeof(bsd));

	bsd.RenderTarget[0].BlendEnable = true;
	bsd.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;
	bsd.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA;
	bsd.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA;
	bsd.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;
	bsd.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE;
	bsd.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO;
	bsd.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;

	hr = m_dev->CreateBlendState(&bsd, &m_merge.bs);

	// interlace

	memset(&bd, 0, sizeof(bd));

	bd.ByteWidth = sizeof(InterlaceConstantBuffer);
	bd.Usage = D3D11_USAGE_DEFAULT;
	bd.BindFlags = D3D11_BIND_CONSTANT_BUFFER;

	hr = m_dev->CreateBuffer(&bd, NULL, &m_interlace.cb);

	theApp.LoadResource(IDR_INTERLACE_FX, shader);
	for(size_t i = 0; i < countof(m_interlace.ps); i++)
	{
		CompileShader((const char *)shader.data(), shader.size(), "interlace.fx", nullptr, format("ps_main%d", i).c_str(), nullptr, &m_interlace.ps[i]);
	}

	// Shade Boost	

	int ShadeBoost_Contrast = theApp.GetConfig("ShadeBoost_Contrast", 50);
	int ShadeBoost_Brightness = theApp.GetConfig("ShadeBoost_Brightness", 50);
	int ShadeBoost_Saturation = theApp.GetConfig("ShadeBoost_Saturation", 50);
		
	string str[3];		
		
	str[0] = format("%d", ShadeBoost_Saturation);
	str[1] = format("%d", ShadeBoost_Brightness);
	str[2] = format("%d", ShadeBoost_Contrast);

	D3D_SHADER_MACRO macro[] =
	{			
		{"SB_SATURATION", str[0].c_str()},
		{"SB_BRIGHTNESS", str[1].c_str()},
		{"SB_CONTRAST", str[2].c_str()},
		{NULL, NULL},
	};

	memset(&bd, 0, sizeof(bd));

	bd.ByteWidth = sizeof(ShadeBoostConstantBuffer);
	bd.Usage = D3D11_USAGE_DEFAULT;
	bd.BindFlags = D3D11_BIND_CONSTANT_BUFFER;

	hr = m_dev->CreateBuffer(&bd, NULL, &m_shadeboost.cb);

	theApp.LoadResource(IDR_SHADEBOOST_FX, shader);
	CompileShader((const char *)shader.data(), shader.size(), "shadeboost.fx", nullptr, "ps_main", macro, &m_shadeboost.ps);

	// External fx shader

	memset(&bd, 0, sizeof(bd));

	bd.ByteWidth = sizeof(ExternalFXConstantBuffer);
	bd.Usage = D3D11_USAGE_DEFAULT;
	bd.BindFlags = D3D11_BIND_CONSTANT_BUFFER;

	hr = m_dev->CreateBuffer(&bd, NULL, &m_shaderfx.cb);

	// Fxaa

	memset(&bd, 0, sizeof(bd));

	bd.ByteWidth = sizeof(FXAAConstantBuffer);
	bd.Usage = D3D11_USAGE_DEFAULT;
	bd.BindFlags = D3D11_BIND_CONSTANT_BUFFER;

	hr = m_dev->CreateBuffer(&bd, NULL, &m_fxaa.cb);

	//

	memset(&rd, 0, sizeof(rd));

	rd.FillMode = D3D11_FILL_SOLID;
	rd.CullMode = D3D11_CULL_NONE;
	rd.FrontCounterClockwise = false;
	rd.DepthBias = false;
	rd.DepthBiasClamp = 0;
	rd.SlopeScaledDepthBias = 0;
	rd.DepthClipEnable = false; // ???
	rd.ScissorEnable = true;
	rd.MultisampleEnable = true;
	rd.AntialiasedLineEnable = false;

	hr = m_dev->CreateRasterizerState(&rd, &m_rs);

	m_ctx->RSSetState(m_rs);

	//

	memset(&sd, 0, sizeof(sd));

	sd.Filter = theApp.GetConfig("MaxAnisotropy", 0) && !theApp.GetConfig("paltex", 0) ? D3D11_FILTER_ANISOTROPIC : D3D11_FILTER_MIN_MAG_MIP_LINEAR;
	sd.AddressU = D3D11_TEXTURE_ADDRESS_CLAMP;
	sd.AddressV = D3D11_TEXTURE_ADDRESS_CLAMP;
	sd.AddressW = D3D11_TEXTURE_ADDRESS_CLAMP;
	sd.MinLOD = -FLT_MAX;
	sd.MaxLOD = FLT_MAX;
	sd.MaxAnisotropy = theApp.GetConfig("MaxAnisotropy", 0);
	sd.ComparisonFunc = D3D11_COMPARISON_NEVER;

	hr = m_dev->CreateSamplerState(&sd, &m_convert.ln);

	sd.Filter = theApp.GetConfig("MaxAnisotropy", 0) && !theApp.GetConfig("paltex", 0) ? D3D11_FILTER_ANISOTROPIC : D3D11_FILTER_MIN_MAG_MIP_POINT;

	hr = m_dev->CreateSamplerState(&sd, &m_convert.pt);

	//

	Reset(1, 1);

	//

	CreateTextureFX();

	//

	memset(&dsd, 0, sizeof(dsd));

	dsd.DepthEnable = false;
	dsd.StencilEnable = true;
	dsd.StencilReadMask = 1;
	dsd.StencilWriteMask = 1;
	dsd.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
	dsd.FrontFace.StencilPassOp = D3D11_STENCIL_OP_REPLACE;
	dsd.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
	dsd.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_KEEP;
	dsd.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
	dsd.BackFace.StencilPassOp = D3D11_STENCIL_OP_REPLACE;
	dsd.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
	dsd.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_KEEP;

	m_dev->CreateDepthStencilState(&dsd, &m_date.dss);

	D3D11_BLEND_DESC blend;

	memset(&blend, 0, sizeof(blend));

	m_dev->CreateBlendState(&blend, &m_date.bs);

	// Exclusive/Fullscreen flip, issued for legacy (managed) windows only.  GSopen2 style
	// emulators will issue the flip themselves later on.

	if(m_wnd->IsManaged())
	{
		SetExclusive(!theApp.GetConfig("windowed", 1));
	}

	return true;
}
예제 #8
0
파일: GuiServer.cpp 프로젝트: G-VAR/ConEmu
//// Эта функция пайп не закрывает!
//void CGuiServer::GuiServerThreadCommand(HANDLE hPipe)
BOOL CGuiServer::GuiServerCommand(LPVOID pInst, CESERVER_REQ* pIn, CESERVER_REQ* &ppReply, DWORD &pcbReplySize, DWORD &pcbMaxReplySize, LPARAM lParam)
{
	BOOL lbRc = FALSE;
	CGuiServer* pGSrv = (CGuiServer*)lParam;

	if (!pGSrv)
	{
		_ASSERTE(((CGuiServer*)lParam)!=NULL);
		pGSrv = &gpConEmu->m_GuiServer;
	}
	
	if (pIn->hdr.bAsync)
		pGSrv->mp_GuiServer->BreakConnection(pInst);

	gpSetCls->debugLogCommand(pIn, TRUE, timeGetTime(), 0, pGSrv ? pGSrv->ms_ServerPipe : NULL);

	#ifdef _DEBUG
	UINT nDataSize = pIn->hdr.cbSize - sizeof(CESERVER_REQ_HDR);
	#endif
	// Все данные из пайпа получены, обрабатываем команду и возвращаем (если нужно) результат

	#ifdef ALLOW_WINE_MSG
	if (gbIsWine)
	{
		wchar_t szMsg[128];
		msprintf(szMsg, countof(szMsg), L"CGuiServer::GuiServerCommand.\nGUI TID=%u\nSrcPID=%u, SrcTID=%u, Cmd=%u",
			GetCurrentThreadId(), pIn->hdr.nSrcPID, pIn->hdr.nSrcThreadId, pIn->hdr.nCmd);
		MessageBox(szMsg, MB_ICONINFORMATION);
	}
	#endif

	switch (pIn->hdr.nCmd)
	{
		case CECMD_NEWCMD:
		{
			// Приходит из другой копии ConEmu.exe, когда она запущена с ключом /single, /showhide, /showhideTSA
			DEBUGSTRCMD(L"GUI recieved CECMD_NEWCMD\n");

			if (pIn->NewCmd.isAdvLogging && !gpSetCls->isAdvLogging)
			{
				gpSetCls->isAdvLogging = pIn->NewCmd.isAdvLogging;
				gpConEmu->CreateLog();
			}

			if (gpSetCls->isAdvLogging && (pIn->NewCmd.isAdvLogging > gpSetCls->isAdvLogging))
			{
				wchar_t szLogLevel[80];
				_wsprintf(szLogLevel, SKIPLEN(countof(szLogLevel)) L"Changing log level! Old=%u, New=%u", (UINT)gpSetCls->isAdvLogging, (UINT)pIn->NewCmd.isAdvLogging);
				gpConEmu->LogString(szLogLevel);
				gpSetCls->isAdvLogging = pIn->NewCmd.isAdvLogging;
			}

			if (gpSetCls->isAdvLogging)
			{
				size_t cchAll = 120 + _tcslen(pIn->NewCmd.szConEmu) + _tcslen(pIn->NewCmd.szCurDir) + _tcslen(pIn->NewCmd.szCommand);
				wchar_t* pszInfo = (wchar_t*)malloc(cchAll*sizeof(*pszInfo));
				if (pszInfo)
				{
					_wsprintf(pszInfo, SKIPLEN(cchAll) L"CECMD_NEWCMD: Wnd=x%08X, Act=%u, ConEmu=%s, Dir=%s, Cmd=%s",
						(DWORD)(DWORD_PTR)pIn->NewCmd.hFromConWnd, pIn->NewCmd.ShowHide,
						pIn->NewCmd.szConEmu, pIn->NewCmd.szCurDir, pIn->NewCmd.szCommand);
					gpConEmu->LogString(pszInfo);
					free(pszInfo);
				}
			}

			BOOL bAccepted = FALSE;

			if (pIn->NewCmd.szConEmu[0])
			{
				bAccepted = (lstrcmpi(gpConEmu->ms_ConEmuExeDir, pIn->NewCmd.szConEmu) == 0);
			}
			else
			{
				bAccepted = TRUE;
			}

			if (bAccepted)
			{
				bool bCreateTab = (pIn->NewCmd.ShowHide == sih_None || pIn->NewCmd.ShowHide == sih_StartDetached)
					// Issue 1275: When minimized into TSA (on all VCon are closed) we need to restore and run new tab
					|| (pIn->NewCmd.szCommand[0] && !CVConGroup::isVConExists(0));
				gpConEmu->DoMinimizeRestore(bCreateTab ? sih_SetForeground : pIn->NewCmd.ShowHide);

				// Может быть пусто
				if (bCreateTab && pIn->NewCmd.szCommand[0])
				{
					RConStartArgs *pArgs = new RConStartArgs;
					pArgs->Detached = (pIn->NewCmd.ShowHide == sih_StartDetached) ? crb_On : crb_Off;
					pArgs->pszSpecialCmd = lstrdup(pIn->NewCmd.szCommand);
					if (pIn->NewCmd.szCurDir[0] == 0)
					{
						_ASSERTE(pIn->NewCmd.szCurDir[0] != 0);
					}
					else
					{
						pArgs->pszStartupDir = lstrdup(pIn->NewCmd.szCurDir);
					}

					if (gpSetCls->IsMulti() || CVConGroup::isDetached())
					{
						gpConEmu->PostCreateCon(pArgs);
					}
					else
					{
						// Если хотят в одном окне - только одну консоль
						gpConEmu->CreateWnd(pArgs);
						SafeDelete(pArgs);
					}
				}
				else
				{
					_ASSERTE(pIn->NewCmd.ShowHide==sih_ShowMinimize || pIn->NewCmd.ShowHide==sih_ShowHideTSA || pIn->NewCmd.ShowHide==sih_Show);
				}
			}

			pcbReplySize = sizeof(CESERVER_REQ_HDR)+sizeof(BYTE);
			lbRc = ExecuteNewCmd(ppReply, pcbMaxReplySize, pIn->hdr.nCmd, pcbReplySize);
			if (lbRc)
			{
				ppReply->Data[0] = bAccepted;
			}

			break;
		} //CECMD_NEWCMD

		case CECMD_TABSCMD:
		{
			// 0: спрятать/показать табы, 1: перейти на следующую, 2: перейти на предыдущую, 3: commit switch
			DEBUGSTRCMD(L"GUI recieved CECMD_TABSCMD\n");
			_ASSERTE(nDataSize>=1);
			DWORD nTabCmd = pIn->Data[0];
			gpConEmu->TabCommand((ConEmuTabCommand)nTabCmd);

			pcbReplySize = sizeof(CESERVER_REQ_HDR)+sizeof(BYTE);
			if (ExecuteNewCmd(ppReply, pcbMaxReplySize, pIn->hdr.nCmd, pcbReplySize))
			{
				lbRc = TRUE;
				ppReply->Data[0] = TRUE;
			}
			break;
		} // CECMD_TABSCMD

		#if 0
		case CECMD_GETALLTABS:
		{
			int nConCount = gpConEmu->GetConCount();
			int nActiveCon = gpConEmu->ActiveConNum();
			size_t cchMax = nConCount*16;
			size_t cchCount = 0;
			CVirtualConsole* pVCon;
			CESERVER_REQ_GETALLTABS::TabInfo* pTabs = (CESERVER_REQ_GETALLTABS::TabInfo*)calloc(cchMax, sizeof(*pTabs));
			for (int V = 0; (pVCon = gpConEmu->GetVCon(V)) != NULL; V++)
			{
				if (!pTabs)
				{
					_ASSERTE(pTabs!=NULL);
					break;
				}

				CRealConsole* pRCon = pVCon->RCon();
				if (!pRCon)
					continue;

				ConEmuTab tab;
				wchar_t szModified[4];
				for (int T = 0; pRCon->GetTab(T, &tab); T++)
				{
					if (cchCount >= cchMax)
					{
						pTabs = (CESERVER_REQ_GETALLTABS::TabInfo*)realloc(pTabs, (cchMax+32)*sizeof(*pTabs));
						if (!pTabs)
						{
							_ASSERTE(pTabs!=NULL);
							break;
						}
						cchMax += 32;
						_ASSERTE(cchCount<cchMax);
					}

					pTabs[cchCount].ActiveConsole == (V == nActiveCon);
					pTabs[cchCount].ActiveTab == (tab.Current != 0);
					pTabs[cchCount].Disabled = ((tab.Type & fwt_Disabled) == fwt_Disabled);
					pTabs[cchCount].ConsoleIdx = V;
					pTabs[cchCount].TabIdx = T;

					// Text
					wcscpy_c(szModified, tab.Modified ? L" * " : L"   ");
					if (V == nActiveCon)
					{
						if (T < 9)
							_wsprintf(pTabs[cchCount].Title, SKIPLEN(countof(pTabs[cchCount].Title)) L"[%i/&%i]%s", V+1, T+1, szModified);
						else if (T == 9)
							_wsprintf(pTabs[cchCount].Title, SKIPLEN(countof(pTabs[cchCount].Title)) L"[%i/1&0]%s", V+1, szModified);
						else
							_wsprintf(pTabs[cchCount].Title, SKIPLEN(countof(pTabs[cchCount].Title)) L"[%i/%i]%s", V+1, T+1, szModified);
					}
					else
					{
						_wsprintf(pTabs[cchCount].Title, SKIPLEN(countof(pTabs[cchCount].Title)) L"[%i/%i]%s", V+1, T+1, szModified);
					}

					cchCount++;
				}
			}
			if (cchCount && pTabs)
			{
				pcbReplySize = sizeof(CESERVER_REQ_HDR)+sizeof(CESERVER_REQ_GETALLTABS)+((cchCount-1)*sizeof(CESERVER_REQ_GETALLTABS::TabInfo));
				if (ExecuteNewCmd(ppReply, pcbMaxReplySize, pIn->hdr.nCmd, pcbReplySize))
				{
					lbRc = TRUE;
					ppReply->GetAllTabs.Count = cchCount;
					memmove(ppReply->GetAllTabs.Tabs, pTabs, cchCount*sizeof(*pTabs));
				}
			}
			SafeFree(pTabs);
			break;
		} // CECMD_GETALLTABS

		case CECMD_ACTIVATETAB:
		{
			BOOL lbTabOk = FALSE;
			CVirtualConsole *pVCon = gpConEmu->GetVCon(pIn->dwData[0]);
			if (pVCon && pVCon->RCon())
			{
				lbTabOk = pVCon->RCon()->ActivateFarWindow(pIn->dwData[1]);
			}

			pcbReplySize = sizeof(CESERVER_REQ_HDR)+sizeof(DWORD);
			if (ExecuteNewCmd(ppReply, pcbMaxReplySize, pIn->hdr.nCmd, pcbReplySize))
			{
				lbRc = TRUE;
				ppReply->dwData[0] = lbTabOk;
			}
			break;
		} // CECMD_ACTIVATETAB
		#endif

		case CECMD_ATTACH2GUI:
		{
			MCHKHEAP;

			// Получен запрос на Attach из сервера
			pcbReplySize = sizeof(CESERVER_REQ_HDR)+sizeof(CESERVER_REQ_SRVSTARTSTOPRET);
			if (!ExecuteNewCmd(ppReply, pcbMaxReplySize, pIn->hdr.nCmd, pcbReplySize))
				goto wrap;
			//CESERVER_REQ* pOut = ExecuteNewCmd(CECMD_ATTACH2GUI, sizeof(CESERVER_REQ_HDR)+sizeof(CESERVER_REQ_STARTSTOPRET));

			CVConGroup::AttachRequested(pIn->StartStop.hWnd, &(pIn->StartStop), &(ppReply->SrvStartStopRet));

			_ASSERTE((ppReply->StartStopRet.nBufferHeight == 0) || ((int)ppReply->StartStopRet.nBufferHeight > (pIn->StartStop.sbi.srWindow.Bottom-pIn->StartStop.sbi.srWindow.Top)));

			MCHKHEAP;

			lbRc = TRUE;
			//ExecuteFreeResult(pOut);
			break;
		} // CECMD_ATTACH2GUI

		case CECMD_SRVSTARTSTOP:
		{
			MCHKHEAP;

			pcbReplySize = sizeof(CESERVER_REQ_HDR)+sizeof(CESERVER_REQ_SRVSTARTSTOPRET);
			if (!ExecuteNewCmd(ppReply, pcbMaxReplySize, pIn->hdr.nCmd, pcbReplySize))
				goto wrap;

			if (pIn->SrvStartStop.Started == srv_Started)
			{
				// Запущен процесс сервера
				HWND hConWnd = (HWND)pIn->dwData[1];
				_ASSERTE(hConWnd && IsWindow(hConWnd));

				DWORD nStartTick = timeGetTime();

				//LRESULT l = 0;
				//DWORD_PTR dwRc = 0;
				//2010-05-21 Поскольку это критично - лучше ждать до упора, хотя может быть DeadLock?
				//l = SendMessageTimeout(ghWnd, gpConEmu->mn_MsgSrvStarted, (WPARAM)hConWnd, pIn->hdr.nSrcPID,
				//	SMTO_BLOCK, 5000, &dwRc);

				//111002 - вернуть должен HWND окна отрисовки (дочернее окно ConEmu)
				MsgSrvStartedArg arg = {hConWnd, pIn->hdr.nSrcPID, pIn->SrvStartStop.dwKeybLayout, nStartTick};
				SendMessage(ghWnd, gpConEmu->mn_MsgSrvStarted, 0, (LPARAM)&arg);
				HWND hWndDC = arg.hWndDc;
				HWND hWndBack = arg.hWndBack;
				_ASSERTE(hWndDC!=NULL);

				#ifdef _DEBUG
				DWORD dwErr = GetLastError(), nEndTick = timeGetTime(), nDelta = nEndTick - nStartTick;
				if (hWndDC && nDelta >= EXECUTE_CMD_WARN_TIMEOUT)
				{
					if (!IsDebuggerPresent())
					{
						//_ASSERTE(nDelta <= EXECUTE_CMD_WARN_TIMEOUT || (pIn->hdr.nCmd == CECMD_CMDSTARTSTOP && nDelta <= EXECUTE_CMD_WARN_TIMEOUT2));
						_ASSERTEX(nDelta <= EXECUTE_CMD_WARN_TIMEOUT);
					}
				}
				#endif

				//pIn->dwData[0] = (DWORD)ghWnd; //-V205
				//pIn->dwData[1] = (DWORD)dwRc; //-V205
				//pIn->dwData[0] = (l == 0) ? 0 : 1;
				ppReply->SrvStartStopRet.Info.hWnd = ghWnd;
				ppReply->SrvStartStopRet.Info.hWndDc = hWndDC;
				ppReply->SrvStartStopRet.Info.hWndBack = hWndBack;
				ppReply->SrvStartStopRet.Info.dwPID = GetCurrentProcessId();
				// Limited logging of console contents (same output as processed by CECF_ProcessAnsi)
				gpConEmu->GetAnsiLogInfo(ppReply->SrvStartStopRet.AnsiLog);
				// Return GUI info, let it be in one place
				gpConEmu->GetGuiInfo(ppReply->SrvStartStopRet.GuiMapping);
			}
			else if (pIn->SrvStartStop.Started == srv_Stopped)
			{
				// Процесс сервера завершается
				CRealConsole* pRCon = NULL;
				CVConGuard VCon;

				for (size_t i = 0;; i++)
				{
					if (!CVConGroup::GetVCon(i, &VCon))
						break;

					pRCon = VCon->RCon();
					if (pRCon && (pRCon->GetServerPID(true) == pIn->hdr.nSrcPID || pRCon->GetServerPID(false) == pIn->hdr.nSrcPID))
					{
						break;
					}
					pRCon = NULL;
				}

				if (pRCon)
					pRCon->OnServerClosing(pIn->hdr.nSrcPID);

				//pIn->dwData[0] = 1;
			}
			else
			{
				_ASSERTE((pIn->dwData[0] == 1) || (pIn->dwData[0] == 101));
			}

			MCHKHEAP;

			lbRc = TRUE;
			//// Отправляем
			//fSuccess = WriteFile(
			//               hPipe,        // handle to pipe
			//               pOut,         // buffer to write from
			//               pOut->hdr.cbSize,  // number of bytes to write
			//               &cbWritten,   // number of bytes written
			//               NULL);        // not overlapped I/O

			//ExecuteFreeResult(pOut);
			break;
		} // CECMD_SRVSTARTSTOP

		case CECMD_ASSERT:
		{
			DWORD nBtn = MessageBox(NULL, pIn->AssertInfo.szDebugInfo, pIn->AssertInfo.szTitle, pIn->AssertInfo.nBtns);

			pcbReplySize = sizeof(CESERVER_REQ_HDR)+sizeof(DWORD);
			if (ExecuteNewCmd(ppReply, pcbMaxReplySize, pIn->hdr.nCmd, pcbReplySize))
			{
				lbRc = TRUE;
				ppReply->dwData[0] = nBtn;
			}

			//ExecutePrepareCmd(&pIn->hdr, CECMD_ASSERT, sizeof(CESERVER_REQ_HDR) + sizeof(DWORD));
			//pIn->dwData[0] = nBtn;
			//// Отправляем
			//fSuccess = WriteFile(
			//               hPipe,        // handle to pipe
			//               pIn,         // buffer to write from
			//               pIn->hdr.cbSize,  // number of bytes to write
			//               &cbWritten,   // number of bytes written
			//               NULL);        // not overlapped I/O
			break;
		} // CECMD_ASSERT

		case CECMD_ATTACHGUIAPP:
		{
			pcbReplySize = sizeof(CESERVER_REQ_HDR)+sizeof(CESERVER_REQ_ATTACHGUIAPP);
			if (!ExecuteNewCmd(ppReply, pcbMaxReplySize, pIn->hdr.nCmd, pcbReplySize))
				goto wrap;
			ppReply->AttachGuiApp = pIn->AttachGuiApp;

			//CESERVER_REQ Out;
			//ExecutePrepareCmd(&Out.hdr, CECMD_ATTACHGUIAPP, sizeof(CESERVER_REQ_HDR)+sizeof(Out.AttachGuiApp));
			//Out.AttachGuiApp = pIn->AttachGuiApp;
			
			#ifdef SHOW_GUIATTACH_START
			if (pIn->AttachGuiApp.hWindow == NULL)
			{
				wchar_t szDbg[1024];
				_wsprintf(szDbg, SKIPLEN(countof(szDbg)) L"AttachGuiApp requested from:\n%s\nPID=%u", pIn->AttachGuiApp.sAppFilePathName, pIn->AttachGuiApp.nPID);
				//MBoxA(szDbg);
				MessageBox(NULL, szDbg, L"ConEmu", MB_SYSTEMMODAL);
			}
			#endif

			// Уведомить ожидающую вкладку
			CRealConsole* pRCon = gpConEmu->AttachRequestedGui(pIn->AttachGuiApp.nServerPID, pIn->AttachGuiApp.sAppFilePathName, pIn->AttachGuiApp.nPID);
			if (pRCon)
			{
				CVConGuard VCon(pRCon->VCon());
				RECT rcPrev = ppReply->AttachGuiApp.rcWindow;
				HWND hBack = pRCon->VCon()->GetBack();

				//// Размер должен быть независим от возможности наличия прокрутки в VCon
				//GetWindowRect(hBack, &ppReply->AttachGuiApp.rcWindow);
				//ppReply->AttachGuiApp.rcWindow.right -= ppReply->AttachGuiApp.rcWindow.left;
				//ppReply->AttachGuiApp.rcWindow.bottom -= ppReply->AttachGuiApp.rcWindow.top;
				//ppReply->AttachGuiApp.rcWindow.left = ppReply->AttachGuiApp.rcWindow.top = 0;
				////MapWindowPoints(NULL, hBack, (LPPOINT)&ppReply->AttachGuiApp.rcWindow, 2);
				//pRCon->CorrectGuiChildRect(ppReply->AttachGuiApp.nStyle, ppReply->AttachGuiApp.nStyleEx, ppReply->AttachGuiApp.rcWindow);
				
				// Уведомить RCon и ConEmuC, что гуй подцепился
				// Вызывается два раза. Первый (при запуске exe) ahGuiWnd==NULL, второй - после фактического создания окна
				pRCon->SetGuiMode(pIn->AttachGuiApp.nFlags, pIn->AttachGuiApp.hAppWindow, pIn->AttachGuiApp.Styles.nStyle, pIn->AttachGuiApp.Styles.nStyleEx, pIn->AttachGuiApp.sAppFilePathName, pIn->AttachGuiApp.nPID, rcPrev);

				ppReply->AttachGuiApp.nFlags = agaf_Success | (pRCon->isActive(false) ? 0 : agaf_Inactive);
				ppReply->AttachGuiApp.nServerPID = pRCon->GetServerPID();
				ppReply->AttachGuiApp.nPID = ppReply->AttachGuiApp.nServerPID;
				ppReply->AttachGuiApp.hConEmuDc = pRCon->GetView();
				ppReply->AttachGuiApp.hConEmuBack = hBack;
				ppReply->AttachGuiApp.hConEmuWnd = ghWnd;
				ppReply->AttachGuiApp.hAppWindow = pIn->AttachGuiApp.hAppWindow;
				ppReply->AttachGuiApp.hSrvConWnd = pRCon->ConWnd();
				ppReply->AttachGuiApp.hkl = (DWORD)(LONG)(LONG_PTR)GetKeyboardLayout(gpConEmu->mn_MainThreadId);
				ZeroStruct(ppReply->AttachGuiApp.Styles.Shifts);
				CRealConsole::CorrectGuiChildRect(pIn->AttachGuiApp.Styles.nStyle, pIn->AttachGuiApp.Styles.nStyleEx, ppReply->AttachGuiApp.Styles.Shifts, pIn->AttachGuiApp.sAppFilePathName);
			}
			else
			{
				ppReply->AttachGuiApp.nFlags = agaf_Fail;
			}

			lbRc = TRUE;

			//// Отправляем
			//fSuccess = WriteFile(
			//               hPipe,        // handle to pipe
			//               &Out,         // buffer to write from
			//               Out.hdr.cbSize,  // number of bytes to write
			//               &cbWritten,   // number of bytes written
			//               NULL);        // not overlapped I/O
			break;
		} // CECMD_ATTACHGUIAPP

		case CECMD_GUICLIENTSHIFT:
		{
			pcbReplySize = sizeof(CESERVER_REQ_HDR)+sizeof(GuiStylesAndShifts);
			if (!ExecuteNewCmd(ppReply, pcbMaxReplySize, pIn->hdr.nCmd, pcbReplySize))
				goto wrap;
			ppReply->GuiAppShifts = pIn->GuiAppShifts;

			ZeroStruct(ppReply->GuiAppShifts.Shifts);
			CRealConsole::CorrectGuiChildRect(pIn->GuiAppShifts.nStyle, pIn->GuiAppShifts.nStyleEx, ppReply->GuiAppShifts.Shifts, pIn->GuiAppShifts.szExeName);

			lbRc = TRUE;
			break;
		} // CECMD_GUICLIENTSHIFT

		case CECMD_GUIMACRO:
		{
			// Допустимо, если GuiMacro пытаются выполнить извне
			CVConGuard VCon; CVConGroup::GetActiveVCon(&VCon);

			DWORD nFarPluginPID = VCon->RCon()->GetFarPID(true);
			LPWSTR pszResult = ConEmuMacro::ExecuteMacro(pIn->GuiMacro.sMacro, VCon->RCon(), (nFarPluginPID==pIn->hdr.nSrcPID));

			int nLen = pszResult ? _tcslen(pszResult) : 0;

			pcbReplySize = sizeof(CESERVER_REQ_HDR)+sizeof(CESERVER_REQ_GUIMACRO)+nLen*sizeof(wchar_t);
			if (!ExecuteNewCmd(ppReply, pcbMaxReplySize, pIn->hdr.nCmd, pcbReplySize))
				goto wrap;

			if (pszResult)
			{
				lstrcpy(ppReply->GuiMacro.sMacro, pszResult);
				ppReply->GuiMacro.nSucceeded = 1;
				free(pszResult);
			}
			else
			{
				ppReply->GuiMacro.sMacro[0] = 0;
				ppReply->GuiMacro.nSucceeded = 0;
			}

			lbRc = TRUE;
			break;
		} // CECMD_GUIMACRO

		//case CECMD_DEFTERMSTARTED:
		//{
		//	if (gpConEmu->mp_DefTrm)
		//		gpConEmu->mp_DefTrm->OnDefTermStarted(pIn);

		//	pcbReplySize = sizeof(CESERVER_REQ_HDR);
		//	if (!ExecuteNewCmd(ppReply, pcbMaxReplySize, pIn->hdr.nCmd, pcbReplySize))
		//		goto wrap;
		//	lbRc = TRUE;
		//	break;
		//} // CECMD_DEFTERMSTARTED

		default:
			_ASSERTE(FALSE && "Command was not handled in CGuiServer::GuiServerCommand");
	}

	//// Освободить память
	//if (pIn && (LPVOID)pIn != (LPVOID)&in)
	//{
	//	free(pIn); pIn = NULL;
	//}
wrap:
	return lbRc;
}
예제 #9
0
void MyAssertDumpToFile(const wchar_t* pszFile, int nLine, const wchar_t* pszTest)
{
	wchar_t dmpfile[MAX_PATH+64] = L"", szVer4[8] = L"", szLine[64];

	typedef HRESULT (WINAPI* SHGetFolderPath_t)(HWND hwnd, int csidl, HANDLE hToken, DWORD dwFlags, LPWSTR pszPath);
	HMODULE hShell = LoadLibrary(L"shell32.dll");
	SHGetFolderPath_t shGetFolderPath = hShell ? (SHGetFolderPath_t)GetProcAddress(hShell, "SHGetFolderPathW") : NULL;
	HRESULT hrc = shGetFolderPath ? shGetFolderPath(NULL, CSIDL_DESKTOPDIRECTORY, NULL, 0/*SHGFP_TYPE_CURRENT*/, dmpfile) : E_FAIL;
	if (hShell) FreeLibrary(hShell);
	if (FAILED(hrc))
	{
		memset(dmpfile, 0, sizeof(dmpfile));
		if (!GetTempPath(MAX_PATH, dmpfile) || !*dmpfile)
		{
			//pszError = L"CreateDumpForReport called, get desktop or temp folder failed";
			return;
		}
	}

	wcscat_c(dmpfile, (*dmpfile && dmpfile[lstrlen(dmpfile)-1] != L'\\') ? L"\\ConEmuTrap" : L"ConEmuTrap");
	CreateDirectory(dmpfile, NULL);

	int nLen = lstrlen(dmpfile);
	lstrcpyn(szVer4, _T(MVV_4a), countof(szVer4));
	static LONG snAutoIndex = 0;
	LONG nAutoIndex = InterlockedIncrement(&snAutoIndex);
	msprintf(dmpfile+nLen, countof(dmpfile)-nLen, L"\\Assert-%02u%02u%02u%s-%u-%u.txt", MVV_1, MVV_2, MVV_3, szVer4, GetCurrentProcessId(), nAutoIndex);

	HANDLE hFile = CreateFile(dmpfile, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, 0, NULL);
	if (hFile == INVALID_HANDLE_VALUE)
	{
		//pszError = L"Failed to create dump file";
		return;
	}

	DWORD nWrite;

	msprintf(szLine, countof(szLine), L"CEAssert PID=%u TID=%u\r\nAssertion in ", GetCurrentProcessId(), GetCurrentThreadId());
	WriteFile(hFile, szLine, (nWrite = lstrlen(szLine)*2), &nWrite, NULL);
	if (!GetModuleFileNameW(NULL, dmpfile, countof(dmpfile)-2))
		lstrcpyn(dmpfile, L"<unknown>\r\n", countof(dmpfile));
	else
		wcscat_c(dmpfile, L"\r\n");
	WriteFile(hFile, dmpfile, (nWrite = lstrlen(dmpfile)*2), &nWrite, NULL);

	// File.cpp: 123\r\n
	if (pszFile)
	{
		WriteFile(hFile, pszFile, (nWrite = lstrlen(pszFile)*2), &nWrite, NULL);
		msprintf(szLine, countof(szLine), L": %i\r\n\r\n", nLine);
		WriteFile(hFile, szLine, (nWrite = lstrlen(szLine)*2), &nWrite, NULL);
	}

	if (pszTest)
	{
		WriteFile(hFile, pszTest, (nWrite = lstrlen(pszTest)*2), &nWrite, NULL);
		WriteFile(hFile, L"\r\n", 4, &nWrite, NULL);
	}

	CloseHandle(hFile);
}
예제 #10
0
	void NextPbo() {
		m_current_pbo = (m_current_pbo + 1) & (countof(m_pool)-1);
		// Mark new PBO as free
		m_offset[m_current_pbo] = 0;
	}
예제 #11
0
#include "mui.h"

#include "drive.h"
#include "uidrivepetcbm2.h"
#include "intl.h"
#include "translate.h"

static int drive_number_strings_translate[] = {
    IDMS_DRIVE_8,
    IDMS_DRIVE_9,
    IDMS_DRIVE_10,
    IDMS_DRIVE_11,
    0
};

static char *drive_number_strings[countof(drive_number_strings_translate)];

static int drive_type_strings_translate[] = {
    IDS_NONE,
    -1
};

static char *drive_type_strings_8[] = {
    NULL,		/* "None" placeholder */
    "2031",
    "2040",
    "3040",
    "4040",
    "1001",
    "8050",
    "8250",
예제 #12
0
파일: file.cpp 프로젝트: maxim-zhao/meka
//-----------------------------------------------------------------------------
// Initialize filenames of various path/files (configuration files, etc).
// FIXME-BUFFER: Potential buffer overflows here.
//-----------------------------------------------------------------------------
void    Filenames_Init()
{
    // Get and save current directory
    getcwd(g_env.Paths.StartingDirectory, countof(g_env.Paths.StartingDirectory));

    // Find emulator directory --------------------------------------------------

#if defined(ARCH_MACOSX)
    GetResourcePath( g_env.Paths.EmulatorDirectory, sizeof(g_env.Paths.EmulatorDirectory) );
    ConsolePrintf ("Resource path = %s\n", g_env.Paths.EmulatorDirectory);
#else
    strcpy(g_env.Paths.EmulatorDirectory, g_env.argv[0]);
    #ifdef ARCH_WIN32
        StrReplace(g_env.Paths.EmulatorDirectory, '\\', '/');
    #endif
    char* p = strrchr(g_env.Paths.EmulatorDirectory, '/');
    if (p)
        *p = EOSTR;
    else
        strcpy(g_env.Paths.EmulatorDirectory, g_env.Paths.StartingDirectory);
#endif

#if defined(ARCH_UNIX) || defined(ARCH_MACOSX)
    char* rp = realpath(g_env.Paths.EmulatorDirectory, NULL);
    if (rp != NULL)
    {
        strcpy(g_env.Paths.EmulatorDirectory, rp);
        //strcat(g_env.Paths.EmulatorDirectory, "/");
        free(rp);
    }
#endif

    char data_dir[FILENAME_LEN];
    char internal_resources_dir[FILENAME_LEN];
    char external_resources_dir[FILENAME_LEN];
    strcpy(data_dir, g_env.Paths.EmulatorDirectory);
#ifdef ARCH_MACOSX
    GetWritableInternalResourcePath( internal_resources_dir, sizeof(internal_resources_dir) );
    GetWritableExternalResourcePath( external_resources_dir, sizeof(external_resources_dir) );
    const char* files_to_copy_internal_resources[2] = 
    {
        "meka.inp",
        NULL
    };
    PopulateWritableInternalResourcesPath(internal_resources_dir, files_to_copy_internal_resources);
#else
    strcpy(internal_resources_dir, g_env.Paths.EmulatorDirectory);
    strcpy(external_resources_dir, g_env.Paths.EmulatorDirectory);
#endif

    //ConsolePrintf("Data Directory = %s\n", data_dir);
    //ConsolePrintf("Internal Writable Resources Directory = %s\n", internal_resources_dir);
    //ConsolePrintf("External Writable Resources Directory = %s\n", external_resources_dir);

    // Datafiles
    sprintf(g_env.Paths.DataFile,       "%s/meka.dat",    data_dir);
    sprintf(g_env.Paths.DataBaseFile,   "%s/meka.nam",    data_dir);
    sprintf(g_env.Paths.SkinFile,       "%s/meka.thm",    data_dir);

    sprintf(Patches.filename,           "%s/meka.pat",    data_dir);
    sprintf(Blitters.filename,          "%s/meka.blt",    data_dir);
    sprintf(Messages.FileName,          "%s/meka.msg",    data_dir);

    // files that are written to
    sprintf(Desktop.filename,           "%s/meka.dsk",    internal_resources_dir);
    sprintf(VLFN_DataBase.filename,     "%s/meka.fdb",    internal_resources_dir);
    sprintf(Inputs.FileName,            "%s/meka.inp",    internal_resources_dir);

    // Documentations
    sprintf(g_env.Paths.DocumentationMain,       "%s/meka.txt",      data_dir);
    sprintf(g_env.Paths.DocumentationCompat,     "%s/compat.txt",    data_dir);
    sprintf(g_env.Paths.DocumentationMulti,      "%s/multi.txt",     data_dir);
    sprintf(g_env.Paths.DocumentationChanges,    "%s/changes.txt",   data_dir);
    sprintf(g_env.Paths.DocumentationDebugger,   "%s/debugger.txt",  data_dir);

    // Configuration file
#ifdef ARCH_WIN32
    sprintf(g_env.Paths.ConfigurationFile,       "%s/mekaw.cfg",     g_env.Paths.EmulatorDirectory);
#else /* unix */
    sprintf(g_env.Paths.ConfigurationFile,       "%s/meka.cfg",      internal_resources_dir);
#endif

    // Directories
    sprintf(g_env.Paths.ScreenshotDirectory,     "%s/Screenshots",   external_resources_dir);
    sprintf(g_env.Paths.SavegameDirectory,       "%s/Saves",         external_resources_dir);
    sprintf(g_env.Paths.MusicDirectory,          "%s/Music",         external_resources_dir);
    sprintf(g_env.Paths.DebugDirectory,          "%s/Debug",         external_resources_dir);

    // ROM
    strcpy(g_env.Paths.MediaImageFile,  "");
    strcpy(g_env.Paths.BatteryBackedMemoryFile, "");
}
예제 #13
0
파일: cabutil.cpp 프로젝트: BMurri/wix3
static __callback INT_PTR DIAMONDAPI CabExtractCallback(__in FDINOTIFICATIONTYPE iNotification, __inout FDINOTIFICATION *pFDINotify)
{
    Assert(pFDINotify->pv);

    HRESULT hr = S_OK;
    INT_PTR ipResult = 0;   // result to return on success

    CAB_CALLBACK_STRUCT* pccs = static_cast<CAB_CALLBACK_STRUCT*>(pFDINotify->pv);
    LPCSTR sz;
    WCHAR wz[MAX_PATH];
    FILETIME ft;

    switch (iNotification)
    {
    case fdintCOPY_FILE:  // begin extracting a resource from cabinet
        ExitOnNull(pFDINotify->psz1, hr, E_INVALIDARG, "No cabinet file ID given to convert");
        ExitOnNull(pccs, hr, E_INVALIDARG, "Failed to call cabextract callback, because no callback struct was provided");

        if (pccs->fStopExtracting)
        {
            ExitFunction1(hr = S_FALSE);   // no more extracting
        }

        // convert params to useful variables
        sz = static_cast<LPCSTR>(pFDINotify->psz1);
        if (!::MultiByteToWideChar(CP_ACP, 0, sz, -1, wz, countof(wz)))
        {
            ExitWithLastError1(hr, "failed to convert cabinet file id to unicode: %s", sz);
        }

        if (pccs->pfnProgress)
        {
            hr = pccs->pfnProgress(TRUE, wz, pccs->pvContext);
            if (S_OK != hr)
            {
                ExitFunction();
            }
        }

        if (L'*' == *pccs->pwzExtract || 0 == lstrcmpW(pccs->pwzExtract, wz))
        {
            // get the created date for the resource in the cabinet
            FILETIME ftLocal;
            if (!::DosDateTimeToFileTime(pFDINotify->date, pFDINotify->time, &ftLocal))
            {
                ExitWithLastError1(hr, "failed to get time for resource: %ls", wz);
            }
            ::LocalFileTimeToFileTime(&ftLocal, &ft);
            

            WCHAR wzPath[MAX_PATH];
            hr = ::StringCchCopyW(wzPath, countof(wzPath), pccs->pwzExtractDir);
            ExitOnFailure2(hr, "failed to copy in extract directory: %ls for file: %ls", pccs->pwzExtractDir, wz);
            hr = ::StringCchCatW(wzPath, countof(wzPath), wz);
            ExitOnFailure2(hr, "failed to concat onto path: %ls file: %ls", wzPath, wz);

            ipResult = reinterpret_cast<INT_PTR>(::CreateFileW(wzPath, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL));
            if (INVALID_HANDLE_VALUE == reinterpret_cast<HANDLE>(ipResult))
            {
                ExitWithLastError1(hr, "failed to create file: %s", wzPath);
            }

            ::SetFileTime(reinterpret_cast<HANDLE>(ipResult), &ft, &ft, &ft);   // try to set the file time (who cares if it fails)

            if (::SetFilePointer(reinterpret_cast<HANDLE>(ipResult), pFDINotify->cb, NULL, FILE_BEGIN))   // try to set the end of the file (don't worry if this fails)
            {
                if (::SetEndOfFile(reinterpret_cast<HANDLE>(ipResult)))
                {
                    ::SetFilePointer(reinterpret_cast<HANDLE>(ipResult), 0, NULL, FILE_BEGIN);  // reset the file pointer
                }
            }
        }
        else  // resource wasn't requested, skip it
        {
            hr = S_OK;
            ipResult = 0;
        }

        break;
    case fdintCLOSE_FILE_INFO:  // resource extraction complete
        Assert(pFDINotify->hf && pFDINotify->psz1);
        ExitOnNull(pccs, hr, E_INVALIDARG, "Failed to call cabextract callback, because no callback struct was provided");

        // convert params to useful variables
        sz = static_cast<LPCSTR>(pFDINotify->psz1);
        ExitOnNull(sz, hr, E_INVALIDARG, "Failed to convert cabinet file id, because no cabinet file id was provided");

        if (!::MultiByteToWideChar(CP_ACP, 0, sz, -1, wz, countof(wz)))
        {
            ExitWithLastError1(hr, "failed to convert cabinet file id to unicode: %s", sz);
        }

        if (NULL != pFDINotify->hf)  // just close the file
        {
            ::CloseHandle(reinterpret_cast<HANDLE>(pFDINotify->hf));
        }

        if (pccs->pfnProgress)
        {
            hr = pccs->pfnProgress(FALSE, wz, pccs->pvContext);
        }

        if (S_OK == hr && L'*' == *pccs->pwzExtract)   // if everything is okay and we're extracting all files, keep going
        {
            ipResult = TRUE;
        }
        else   // something went wrong or we only needed to extract one file
        {
            hr = S_OK;
            ipResult = FALSE;
            pccs->fStopExtracting = TRUE;
        }

        break;
    case fdintPARTIAL_FILE: __fallthrough;   // no action needed for these messages, fall through
    case fdintNEXT_CABINET: __fallthrough;
    case fdintENUMERATE: __fallthrough;
    case fdintCABINET_INFO:
        break;
    default:
        AssertSz(FALSE, "CabExtractCallback() - unknown FDI notification command");
    };

LExit:
    return (S_OK == hr) ? ipResult : -1;
}
예제 #14
0
파일: cabutil.cpp 프로젝트: BMurri/wix3
/********************************************************************
 CabOperation - helper function that enumerates or extracts files
                   from cabinet

 NOTE: wzCabinet must be full path to cabinet file
       wzExtractFile can be a single file id or "*" to extract all files
       wzExttractDir must be normalized (end in a "\")
       if pfnBeginFile is NULL pfnEndFile must be NULL and vice versa
       pfnNotify is callback function to get notified for each file
       in the cabinet. If it's NULL, files will be extracted.
********************************************************************/
static HRESULT DAPI CabOperation(
    __in LPCWSTR wzCabinet,
    __in LPCWSTR wzExtractFile,
    __in_opt LPCWSTR wzExtractDir,
    __in_opt CAB_CALLBACK_PROGRESS pfnProgress,
    __in_opt LPVOID pvContext,
    __in_opt STDCALL_PFNFDINOTIFY pfnNotify,
    __in DWORD64 dw64EmbeddedOffset
    )
{
    HRESULT hr = S_OK;
    BOOL fResult;

    LPWSTR sczCabinet = NULL;
    LPWSTR pwz = NULL;
    CHAR szCabDirectory[MAX_PATH * 4]; // Make sure these are big enough for UTF-8 strings
    CHAR szCabFile[MAX_PATH * 4];

    CAB_CALLBACK_STRUCT ccs;
    PFNFDINOTIFY pfnFdiNotify;

    //
    // ensure the cabinet.dll is loaded
    //
    if (!vhfdi)
    {
        hr = LoadCabinetDll();
        ExitOnFailure(hr, "failed to load CABINET.DLL");
    }

    hr = StrAllocString(&sczCabinet, wzCabinet, 0);
    ExitOnFailure1(hr, "Failed to make copy of cabinet name:%ls", wzCabinet);

    //
    // split the cabinet full path into directory and filename and convert to multi-byte (ick!)
    //
    pwz = FileFromPath(sczCabinet);
    ExitOnNull1(pwz, hr, E_INVALIDARG, "failed to process cabinet path: %ls", wzCabinet);

    if (!::WideCharToMultiByte(CP_UTF8, 0, pwz, -1, szCabFile, countof(szCabFile), NULL, NULL))
    {
        ExitWithLastError1(hr, "failed to convert cabinet filename to ASCII: %ls", pwz);
    }

    *pwz = '\0';

    // If a full path was not provided, use the relative current directory.
    if (wzCabinet == pwz)
    {
        hr = ::StringCchCopyA(szCabDirectory, countof(szCabDirectory), ".\\");
        ExitOnFailure(hr, "Failed to copy relative current directory as cabinet directory.");
    }
    else
    {
        if (!::WideCharToMultiByte(CP_UTF8, 0, sczCabinet, -1, szCabDirectory, countof(szCabDirectory), NULL, NULL))
        {
            ExitWithLastError1(hr, "failed to convert cabinet directory to ASCII: %ls", sczCabinet);
        }
    }

    //
    // iterate through files in cabinet extracting them to the callback function
    //
    ccs.fStopExtracting = FALSE;
    ccs.pwzExtract = wzExtractFile;
    ccs.pwzExtractDir = wzExtractDir;
    ccs.pfnProgress = pfnProgress;
    ccs.pvContext = pvContext;

    vdw64EmbeddedOffset = dw64EmbeddedOffset;

    // if pfnNotify is given, use it, otherwise use default callback
    if (NULL == pfnNotify)
    {
        pfnFdiNotify = CabExtractCallback; 
    }
    else
    {
        v_pfnNetFx11Notify = pfnNotify;
        pfnFdiNotify = FDINotify;
    }
    fResult = vpfnFDICopy(vhfdi, szCabFile, szCabDirectory, 0, pfnFdiNotify, NULL, static_cast<void*>(&ccs));
    if (!fResult && !ccs.fStopExtracting)   // if something went wrong and it wasn't us just stopping the extraction, then return a failure
    {
        ExitWithLastError1(hr, "failed to extract cabinet file: %ls", sczCabinet);
    }

LExit:
    ReleaseStr(sczCabinet);
    v_pfnNetFx11Notify = NULL;

    return hr;
}
예제 #15
0
bool CPluginW1900::InputBox(LPCWSTR Title, LPCWSTR SubTitle, LPCWSTR HistoryName, LPCWSTR SrcText, wchar_t*& DestText)
{
	_ASSERTE(DestText==NULL);
	if (!InfoW1900)
		return false;

	wchar_t strTemp[MAX_PATH+1];
	if (!InfoW1900->InputBox(&guid_ConEmu, &guid_ConEmuInput, Title, SubTitle, HistoryName, SrcText, strTemp, countof(strTemp), NULL, FIB_BUTTONS))
		return false;
	DestText = lstrdup(strTemp);
	return true;
}
예제 #16
0
int MyAssertProc(const wchar_t* pszFile, int nLine, const wchar_t* pszTest, bool abNoPipe)
{
	HooksUnlocker;

	#ifdef _DEBUG
	if (MyAssertSkip(pszFile, nLine, pszTest, abNoPipe))
		return 1;
	#endif

	MyAssertDumpToFile(pszFile, nLine, pszTest);

	HANDLE hHeap = GetProcessHeap();
	MyAssertInfo* pa = (MyAssertInfo*)HeapAlloc(hHeap, HEAP_ZERO_MEMORY, sizeof(MyAssertInfo));
	if (!pa)
		return -1;
	wchar_t *szExeName = (wchar_t*)HeapAlloc(hHeap, HEAP_ZERO_MEMORY, (MAX_PATH+1)*sizeof(wchar_t));
	if (szExeName && !GetModuleFileNameW(NULL, szExeName, MAX_PATH+1)) szExeName[0] = 0;
	pa->bNoPipe = abNoPipe;
	msprintf(pa->szTitle, countof(pa->szTitle), L"CEAssert PID=%u TID=%u", GetCurrentProcessId(), GetCurrentThreadId());
	wchar_t szVer4[2] = WSTRING(MVV_4a);
	msprintf(pa->szDebugInfo, countof(pa->szDebugInfo), L"Assertion in %s [%02u%02u%02u%s]\n%s\n\n%s: %i\n\nPress 'Retry' to trap.",
	                szExeName ? szExeName : L"<HeapAllocFailed>",
					MVV_1, MVV_2, MVV_3, szVer4,
					pszTest ? pszTest : L"", pszFile, nLine);
	DWORD dwCode = 0;

	if (gAllowAssertThread == am_Thread)
	{
		DWORD dwTID;
		HANDLE hThread = apiCreateThread(MyAssertThread, pa, &dwTID, "MyAssertThread");

		if (hThread == NULL)
		{
			dwCode = IDRETRY;
			goto wrap;
		}

		WaitForSingleObject(hThread, INFINITE);
		GetExitCodeThread(hThread, &dwCode);
		CloseHandle(hThread);
		goto wrap;
	}
	
#ifdef ASSERT_PIPE_ALLOWED
#ifdef _DEBUG
	if (!abNoPipe && (gAllowAssertThread == am_Pipe))
	{
		HWND hConWnd = GetConEmuHWND(2);
		HWND hGuiWnd = ghConEmuWnd;

		// -- искать - нельзя. Если мы НЕ в ConEmu - нельзя стучаться в другие копии!!!
		//#ifndef CONEMU_MINIMAL
		//if (hGuiWnd == NULL)
		//{
		//	hGuiWnd = FindWindowEx(NULL, NULL, VirtualConsoleClassMain, NULL);
		//}
		//#endif

		if (hGuiWnd && gnInMyAssertTrap <= 0)
		{
			InterlockedIncrement(&gnInMyAssertTrap);
			InterlockedIncrement(&gnInMyAssertPipe);
			gnInMyAssertThread = GetCurrentThreadId();
			ResetEvent(ghInMyAssertTrap);
			
			dwCode = GuiMessageBox(abNoPipe ? NULL : hGuiWnd, pa->szDebugInfo, pa->szTitle, MB_SETFOREGROUND|MB_SYSTEMMODAL|MB_RETRYCANCEL);
			InterlockedDecrement(&gnInMyAssertTrap);
			InterlockedDecrement(&gnInMyAssertPipe);
			SetEvent(ghInMyAssertTrap);
			gnInMyAssertThread = 0;
			goto wrap;
		}
	}

	while (gnInMyAssertPipe>0 && (gnInMyAssertThread != GetCurrentThreadId()))
	{
		Sleep(250);
	}
#endif
#endif

	// В консольных приложениях попытка запустить CreateThread(MyAssertThread) может зависать
	dwCode = MyAssertThread(pa);

wrap:
	if (pa)
		HeapFree(hHeap, 0, pa);
	if (szExeName)
		HeapFree(hHeap, 0, szExeName);
	return (dwCode == IDRETRY) ? -1 : 1;
}
예제 #17
0
bool CPluginW1900::GetPanelItemInfo(const CEPanelInfo& PnlInfo, bool bSelected, INT_PTR iIndex, WIN32_FIND_DATAW& Info, wchar_t** ppszFullPathName)
{
	if (!InfoW1900 || !InfoW1900->PanelControl)
		return false;

	FILE_CONTROL_COMMANDS iCmd = bSelected ? FCTL_GETSELECTEDPANELITEM : FCTL_GETPANELITEM;
	INT_PTR iItemsNumber = bSelected ? ((PanelInfo*)PnlInfo.panelInfo)->SelectedItemsNumber : ((PanelInfo*)PnlInfo.panelInfo)->ItemsNumber;

	if ((iIndex < 0) || (iIndex >= iItemsNumber))
	{
		_ASSERTE(FALSE && "iItem out of bounds");
		return false;
	}

	INT_PTR sz = PanelControlApi(PANEL_ACTIVE, iCmd, iIndex, NULL);

	if (sz <= 0)
		return false;

	PluginPanelItem* pItem = (PluginPanelItem*)calloc(sz, 1); // размер возвращается в байтах
	if (!pItem)
		return false;

	FarGetPluginPanelItem gppi = {sizeof(gppi), pItem};
	if (PanelControlApi(PANEL_ACTIVE, iCmd, iIndex, &gppi) <= 0)
	{
		free(pItem);
		return false;
	}

	ZeroStruct(Info);

	Info.dwFileAttributes = LODWORD(pItem->FileAttributes);
	Info.ftCreationTime = pItem->CreationTime;
	Info.ftLastAccessTime = pItem->LastAccessTime;
	Info.ftLastWriteTime = pItem->LastWriteTime;
	Info.nFileSizeLow = LODWORD(pItem->FileSize);
	Info.nFileSizeHigh = HIDWORD(pItem->FileSize);

	if (pItem->FileName)
	{
		LPCWSTR pszName = pItem->FileName;
		int iLen = lstrlen(pszName);
		// If full paths exceeds MAX_PATH chars - return in Info.cFileName the file name only
		if (iLen >= countof(Info.cFileName))
			pszName = PointToName(pItem->FileName);
		lstrcpyn(Info.cFileName, pszName, countof(Info.cFileName));
		if (ppszFullPathName)
			*ppszFullPathName = lstrdup(pItem->FileName);
	}
	else if (ppszFullPathName)
	{
		_ASSERTE(*ppszFullPathName == NULL);
		*ppszFullPathName = NULL;
	}

	if (pItem->AlternateFileName)
	{
		lstrcpyn(Info.cAlternateFileName, pItem->AlternateFileName, countof(Info.cAlternateFileName));
	}

	free(pItem);

	return true;
}
예제 #18
0
  {"+rotate", ".screenflip.rotate", XrmoptionNoArg, "false" },
  {"-rotate", ".screenflip.rotate", XrmoptionNoArg, "true" },
};

char *imageDirectory = "";
Bool chooseRandomImages = False;
Bool grabDesktopImages = True;

static argtype vars[] = {
  {&rotate, "rotate", "Rotate", DEF_ROTATE, t_Bool},
  {&imageDirectory, "imageDirectory", NULL, "", t_String},
  {&chooseRandomImages, "chooseRandomImages", NULL, "False", t_Bool},
  {&grabDesktopImages, "grabDesktopImages", NULL, "True", t_Bool},
};

ENTRYPOINT ModeSpecOpt screenflip_opts = {countof(opts), opts, countof(vars), vars, NULL};

#ifdef USE_MODULES
ModStruct   screenflip_description =
{"screenflip", "init_screenflip", "draw_screenflip", "release_screenflip",
 "draw_screenflip", "init_screenflip", NULL, &screenflip_opts,
 1000, 1, 2, 1, 4, 1.0, "",
 "Screenflips", 0, NULL};
#endif

typedef struct {
  GLXContext *glx_context;
  Window window;

  int winw, winh;
  int tw, th; /* texture width, height */
예제 #19
0
void GSDevice9::SetupVS(VSSelector sel, const VSConstantBuffer* cb)
{
	hash_map<uint32, GSVertexShader9>::const_iterator i = m_vs.find(sel);

	if(i == m_vs.end())
	{
		string str[5];

		str[0] = format("%d", sel.bppz);
		str[1] = format("%d", sel.tme);
		str[2] = format("%d", sel.fst);
		str[3] = format("%d", sel.logz);
		str[4] = format("%d", sel.rtcopy);

		D3D_SHADER_MACRO macro[] =
		{
			{"VS_BPPZ", str[0].c_str()},
			{"VS_TME", str[1].c_str()},
			{"VS_FST", str[2].c_str()},
			{"VS_LOGZ", str[3].c_str()},
			{"VS_RTCOPY", str[4].c_str()},
			{NULL, NULL},
		};

		static const D3DVERTEXELEMENT9 layout[] =
		{
			{0, 0, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0},
			{0, 8, D3DDECLTYPE_D3DCOLOR, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_COLOR, 0},
			{0, 12, D3DDECLTYPE_D3DCOLOR, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_COLOR, 1},
			{0, 16,  D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0},
			D3DDECL_END()
		};

		GSVertexShader9 vs;

		std::vector<char> shader;
		theApp.LoadResource(IDR_TFX_FX, shader);
		CompileShader(shader.data(), shader.size(), "tfx.fx", "vs_main", macro, &vs.vs, layout, countof(layout), &vs.il);

		m_vs[sel] = vs;

		i = m_vs.find(sel);
	}

	VSSetShader(i->second.vs, (const float*)cb, sizeof(*cb) / sizeof(GSVector4));

	IASetInputLayout(i->second.il);
}
예제 #20
0
#include "stdafx.h"
#include "StreamDriveThru.h"
#include "../../../DSUtil/DSUtil.h"

#ifdef REGISTER_FILTER

const AMOVIESETUP_MEDIATYPE sudPinTypesIn[] = {
	{&MEDIATYPE_Stream, &MEDIASUBTYPE_NULL},
};

const AMOVIESETUP_MEDIATYPE sudPinTypesOut[] = {
	{&MEDIATYPE_Stream, &MEDIASUBTYPE_NULL},
};

const AMOVIESETUP_PIN sudpPins[] = {
	{L"Input", FALSE, FALSE, FALSE, FALSE, &CLSID_NULL, NULL, countof(sudPinTypesIn), sudPinTypesIn},
	{L"Output", FALSE, TRUE, FALSE, FALSE, &CLSID_NULL, NULL, countof(sudPinTypesOut), sudPinTypesOut}
};

const AMOVIESETUP_FILTER sudFilter[] = {
	{&__uuidof(CStreamDriveThruFilter), L"MPC StreamDriveThru", MERIT_DO_NOT_USE, countof(sudpPins), sudpPins, CLSID_LegacyAmFilterCategory}
};

CFactoryTemplate g_Templates[] = {
	{sudFilter[0].strName, sudFilter[0].clsID, CreateInstance<CStreamDriveThruFilter>, NULL, &sudFilter[0]}
};

int g_cTemplates = countof(g_Templates);

STDAPI DllRegisterServer()
{
예제 #21
0
void GSDevice11::StretchRect(GSTexture* sTex, const GSVector4& sRect, GSTexture* dTex, const GSVector4& dRect, ID3D11PixelShader* ps, ID3D11Buffer* ps_cb, ID3D11BlendState* bs, bool linear)
{
	if(!sTex || !dTex)
	{
		ASSERT(0);
		return;
	}

	BeginScene();

	GSVector2i ds = dTex->GetSize();

	// om

	OMSetDepthStencilState(m_convert.dss, 0);
	OMSetBlendState(bs, 0);
	OMSetRenderTargets(dTex, NULL);

	// ia

	float left = dRect.x * 2 / ds.x - 1.0f;
	float top = 1.0f - dRect.y * 2 / ds.y;
	float right = dRect.z * 2 / ds.x - 1.0f;
	float bottom = 1.0f - dRect.w * 2 / ds.y;

	GSVertexPT1 vertices[] =
	{
		{GSVector4(left, top, 0.5f, 1.0f), GSVector2(sRect.x, sRect.y)},
		{GSVector4(right, top, 0.5f, 1.0f), GSVector2(sRect.z, sRect.y)},
		{GSVector4(left, bottom, 0.5f, 1.0f), GSVector2(sRect.x, sRect.w)},
		{GSVector4(right, bottom, 0.5f, 1.0f), GSVector2(sRect.z, sRect.w)},
	};



	IASetVertexBuffer(vertices, sizeof(vertices[0]), countof(vertices));
	IASetInputLayout(m_convert.il);
	IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP);

	// vs

	VSSetShader(m_convert.vs, NULL);


	// gs
	/* NVIDIA HACK!!!!
	Not sure why, but having the Geometry shader disabled causes the strange stretching in recent drivers*/

	GSSelector sel;
	//Don't use shading for stretching, we're just passing through - Note: With Win10 it seems to cause other bugs when shading is off if any of the coords is greater than 0
	//I really don't know whats going on there, but this seems to resolve it mostly (if not all, not tester a lot of games, only BIOS, FFXII and VP2)
	//sel.iip = (sRect.y > 0.0f || sRect.w > 0.0f) ? 1 : 0; 
	//sel.prim = 2; //Triangle Strip
	//SetupGS(sel);

	GSSetShader(NULL);

	/*END OF HACK*/
	
	//

	// ps

	PSSetShaderResources(sTex, NULL);
	PSSetSamplerState(linear ? m_convert.ln : m_convert.pt, NULL);
	PSSetShader(ps, ps_cb);

	//

	DrawPrimitive();

	//

	EndScene();

	PSSetShaderResources(NULL, NULL);
}
예제 #22
0
  {&speed,     "speed",     "Speed",      DEF_SPEED,     t_Float},
  {&angle,     "angle",     "Angle",      DEF_ANGLE,     t_Int},
  {&ball_size, "ballSize",  "BallSize",   DEF_BALL_SIZE, t_Float},
  {&meridians, "meridians", "meridians",  DEF_MERIDIANS, t_Int},
  {&parallels, "parallels", "parallels",  DEF_PARALLELS, t_Int},
  {&tiles,     "tiles",     "Tiles",      DEF_TILES,     t_Int},
  {&thickness, "thickness", "Thickness",  DEF_THICKNESS, t_Float},
  {&ball_color1_str, "ballColor1", "BallColor1", DEF_BALL_COLOR1, t_String},
  {&ball_color2_str, "ballColor2", "BallColor2", DEF_BALL_COLOR2, t_String},
  {&grid_color_str,  "gridColor",  "GridColor",  DEF_GRID_COLOR,  t_String},
  {&shadow_str,      "shadowColor","ShadowColor",DEF_SHADOW_COLOR,t_String},
  /* dammit, -background is too magic... */
  {&bg_str,        "boingBackground", "Background", DEF_BACKGROUND, t_String},
};

ENTRYPOINT ModeSpecOpt boing_opts = {countof(opts), opts, countof(vars), vars, NULL};

static void
parse_color (ModeInfo *mi, const char *name, const char *s, GLfloat *a)
{
  XColor c;
  a[3] = 1.0;  /* alpha */

  if (! XParseColor (MI_DISPLAY(mi), MI_COLORMAP(mi), s, &c))
    {
      fprintf (stderr, "%s: can't parse %s color %s", progname, name, s);
      exit (1);
    }
  a[0] = c.red   / 65536.0;
  a[1] = c.green / 65536.0;
  a[2] = c.blue  / 65536.0;
예제 #23
0
/**
 * @brief Compare two list view items.
 * @param lParam1 - 1st item index.
 * @param lParam2 - 2nd item index.
 * @param lParamSort - sort argument.
 * @return comparison result.
 */
int CALLBACK ListViewCompareFunc(LPARAM lParam1, LPARAM lParam2, LPARAM lParamSort)
{
	LISTVIEW_SORT_PARAMS* pLVSortParams = (LISTVIEW_SORT_PARAMS*)lParamSort;
	TCHAR szItem1Text[256];
	ListView_GetItemText(pLVSortParams->hwndList, lParam1, pLVSortParams->iColumnNumber, szItem1Text, countof(szItem1Text));
	TCHAR szItem2Text[256];
	ListView_GetItemText(pLVSortParams->hwndList, lParam2, pLVSortParams->iColumnNumber, szItem2Text, countof(szItem2Text));
	int iResult;
	switch (pLVSortParams->eCompareType)
	{
	case LISTVIEW_SORT_PARAMS::ICT_STRING:
		iResult = _tcscmp(szItem1Text, szItem2Text);
		break;
	case LISTVIEW_SORT_PARAMS::ICT_INTEGER:
		{
			int iItemValue1 = _ttoi(szItem1Text);
			int iItemValue2 = _ttoi(szItem2Text);
			iResult = Comparator(iItemValue1, iItemValue2);
		}
		break;
	case LISTVIEW_SORT_PARAMS::ICT_HEXADECIMAL:
		{
			unsigned uItemValue1 = _tcstoul(szItem1Text, NULL, 16);
			unsigned uItemValue2 = _tcstoul(szItem2Text, NULL, 16);
			iResult = Comparator(uItemValue1, uItemValue2);
		}
		break;
	default:
		iResult = 0;
		break;
	}
	return (pLVSortParams->bAscending ? iResult : -iResult);
}
예제 #24
0
BOOL LoadPanelInfoA(BOOL abActive)
{
	if (!InfoA) return FALSE;

	CeFullPanelInfo* pcefpi = NULL;
	PanelInfo pi = {};
	int nCmd = abActive ? FCTL_GETPANELINFO : FCTL_GETANOTHERPANELINFO;
	int nRc = InfoA->Control(INVALID_HANDLE_VALUE, nCmd, &pi);

	if (!nRc)
	{
		TODO("Показать информацию об ошибке");
		return FALSE;
	}

	// Даже если невидима - обновить информацию!
	//// Проверим, что панель видима. Иначе - сразу выходим.
	//if (!pi.Visible) {
	//	TODO("Показать информацию об ошибке");
	//	return NULL;
	//}

	if (pi.Flags & PFLAGS_PANELLEFT)
		pcefpi = &pviLeft;
	else
		pcefpi = &pviRight;

	pcefpi->cbSize = sizeof(*pcefpi);
	//pcefpi->hPanel = hPanel;

	// Если элементов на панели стало больше, чем выделено в (pviLeft/pviRight)
	if (pcefpi->ItemsNumber < pi.ItemsNumber) //-V104
	{
		if (!pcefpi->ReallocItems(pi.ItemsNumber))
			return FALSE;
	}

	// Копируем что нужно
	pcefpi->bLeftPanel = (pi.Flags & PFLAGS_PANELLEFT) == PFLAGS_PANELLEFT;
	pcefpi->bPlugin = pi.Plugin;
	pcefpi->PanelRect = pi.PanelRect;
	pcefpi->ItemsNumber = pi.ItemsNumber; //-V101
	pcefpi->CurrentItem = pi.CurrentItem; //-V101
	pcefpi->TopPanelItem = pi.TopPanelItem; //-V101
	pcefpi->Visible = (pi.PanelType == PTYPE_FILEPANEL) && pi.Visible;
	pcefpi->ShortNames = pi.ShortNames;
	pcefpi->Focus = pi.Focus;
	pcefpi->Flags = pi.Flags; // CEPANELINFOFLAGS
	pcefpi->PanelMode = pi.ViewMode;
	pcefpi->IsFilePanel = (pi.PanelType == PTYPE_FILEPANEL);
	// Настройки интерфейса
	LoadFarSettingsA(&pcefpi->FarInterfaceSettings, &pcefpi->FarPanelSettings);
	// Цвета фара
	BYTE FarConsoleColors[0x100];
	INT_PTR nColorSize = InfoA->AdvControl(InfoA->ModuleNumber, ACTL_GETARRAYCOLOR, FarConsoleColors);
#ifdef _DEBUG
	INT_PTR nDefColorSize = COL_LASTPALETTECOLOR;
	_ASSERTE(nColorSize==nDefColorSize);
#endif
	pcefpi->nFarColors[col_PanelText] = FarConsoleColors[COL_PANELTEXT];
	pcefpi->nFarColors[col_PanelSelectedCursor] = FarConsoleColors[COL_PANELSELECTEDCURSOR];
	pcefpi->nFarColors[col_PanelSelectedText] = FarConsoleColors[COL_PANELSELECTEDTEXT];
	pcefpi->nFarColors[col_PanelCursor] = FarConsoleColors[COL_PANELCURSOR];
	pcefpi->nFarColors[col_PanelColumnTitle] = FarConsoleColors[COL_PANELCOLUMNTITLE];
	pcefpi->nFarColors[col_PanelBox] = FarConsoleColors[COL_PANELBOX];
	pcefpi->nFarColors[col_HMenuText] = FarConsoleColors[COL_HMENUTEXT];
	pcefpi->nFarColors[col_WarnDialogBox] = FarConsoleColors[COL_WARNDIALOGBOX];
	pcefpi->nFarColors[col_DialogBox] = FarConsoleColors[COL_DIALOGBOX];
	pcefpi->nFarColors[col_CommandLineUserScreen] = FarConsoleColors[COL_COMMANDLINEUSERSCREEN];
	pcefpi->nFarColors[col_PanelScreensNumber] = FarConsoleColors[COL_PANELSCREENSNUMBER];
	pcefpi->nFarColors[col_KeyBarNum] = FarConsoleColors[COL_KEYBARNUM];


	// Текущая папка панели
	int nSize = lstrlenA(pi.CurDir); //-V303
	pcefpi->nMaxPanelDir = nSize + MAX_PATH; // + выделим немножко заранее
	SafeFree(pcefpi->pszPanelDir);
	pcefpi->pszPanelDir = (wchar_t*)calloc(pcefpi->nMaxPanelDir,2); //-V106
	MultiByteToWideChar(CP_OEMCP, 0, pi.CurDir, nSize+1, pcefpi->pszPanelDir, nSize + MAX_PATH);
	// Готовим буфер для информации об элементах
	pcefpi->ReallocItems(pcefpi->ItemsNumber);

	// Копирование элементов панели в нашу внутреннюю структуру
	wchar_t szName[MAX_PATH+1], szDescription[255];
	LARGE_INTEGER liFileSize;
	PluginPanelItem *ppi = pi.PanelItems;

	for(int i = 0; i < pi.ItemsNumber; i++, ppi++)
	{
		liFileSize.LowPart = ppi->FindData.nFileSizeLow; liFileSize.HighPart = ppi->FindData.nFileSizeHigh;
		MultiByteToWideChar(CP_OEMCP, 0, ppi->FindData.cFileName, -1, szName, countof(szName));

		if (ppi->Description)
			MultiByteToWideChar(CP_OEMCP, 0, ppi->Description, -1, szDescription, countof(szDescription));
		else
			szDescription[0] = 0;

		pcefpi->FarItem2CeItem(i,
		                       szName,
		                       szDescription[0] ? szDescription : NULL,
		                       ppi->FindData.dwFileAttributes,
		                       ppi->FindData.ftLastWriteTime,
		                       liFileSize.QuadPart,
		                       (pcefpi->bPlugin && (pi.Flags & CEPFLAGS_REALNAMES) == 0) /*abVirtualItem*/,
							   NULL,
		                       ppi->UserData,
							   NULL,
		                       ppi->Flags,
		                       ppi->NumberOfLinks);
	}

	return TRUE;
}
예제 #25
0
파일: Actions.cpp 프로젝트: ForNeVeR/ConEmu
int DoInjectRemote(LPWSTR asCmdArg, bool abDefTermOnly)
{
	gbInShutdown = TRUE; // чтобы не возникло вопросов при выходе
	gnRunMode = RM_SETHOOK64;
	LPWSTR pszNext = asCmdArg;
	LPWSTR pszEnd = NULL;
	DWORD nRemotePID = wcstoul(pszNext, &pszEnd, 10);
	wchar_t szStr[16];
	wchar_t szTitle[128];
	wchar_t szInfo[120];
	wchar_t szParentPID[32];


	#ifdef _DEBUG
	extern int ShowInjectRemoteMsg(int nRemotePID, LPCWSTR asCmdArg);
	if (ShowInjectRemoteMsg(nRemotePID, asCmdArg) != IDOK)
	{
		return CERR_HOOKS_FAILED;
	}
	#endif


	if (nRemotePID)
	{
		#if defined(SHOW_ATTACH_MSGBOX)
		if (!IsDebuggerPresent())
		{
			wchar_t szTitle[100]; _wsprintf(szTitle, SKIPLEN(countof(szTitle)) L"%s PID=%u /INJECT", gsModuleName, gnSelfPID);
			const wchar_t* pszCmdLine = GetCommandLineW();
			MessageBox(NULL,pszCmdLine,szTitle,MB_SYSTEMMODAL);
		}
		#endif

		CEStr lsName, lsPath;
		{
		CProcessData processes;
		processes.GetProcessName(nRemotePID, lsName.GetBuffer(MAX_PATH), MAX_PATH, lsPath.GetBuffer(MAX_PATH*2), MAX_PATH*2, NULL);
		CEStr lsLog(L"Remote: PID=", _ultow(nRemotePID, szStr, 10), L" Name=`", lsName, L"` Path=`", lsPath, L"`");
		LogString(lsLog);
		}

		// Go to hook
		// InjectRemote waits for thread termination
		DWORD nErrCode = 0;
		CINFILTRATE_EXIT_CODES iHookRc = InjectRemote(nRemotePID, abDefTermOnly, &nErrCode);

		_wsprintf(szInfo, SKIPCOUNT(szInfo) L"InjectRemote result: %i (%s)", iHookRc,
			(iHookRc == CIR_OK) ? L"CIR_OK" :
			(iHookRc == CIR_AlreadyInjected) ? L"CIR_AlreadyInjected" :
			L"?");
		LogString(szInfo);

		if (iHookRc == CIR_OK/*0*/ || iHookRc == CIR_AlreadyInjected/*1*/)
		{
			return iHookRc ? CERR_HOOKS_WAS_ALREADY_SET : CERR_HOOKS_WAS_SET;
		}
		else if ((iHookRc == CIR_ProcessWasTerminated) || (iHookRc == CIR_OpenProcess))
		{
			// Don't show error message to user. These codes are logged to file only.
			return CERR_HOOKS_FAILED;
		}

		DWORD nSelfPID = GetCurrentProcessId();
		PROCESSENTRY32 self = {sizeof(self)}, parent = {sizeof(parent)};
		// Not optimal, needs refactoring
		if (GetProcessInfo(nSelfPID, &self))
			GetProcessInfo(self.th32ParentProcessID, &parent);

		// Ошибку (пока во всяком случае) лучше показать, для отлова возможных проблем
		//_ASSERTE(iHookRc == 0); -- ассерт не нужен, есть MsgBox

		_wsprintf(szTitle, SKIPLEN(countof(szTitle))
			L"%s %s, PID=%u", gsModuleName, gsVersion, nSelfPID);

		_wsprintf(szInfo, SKIPCOUNT(szInfo)
			L"Injecting remote FAILED, code=%i:0x%08X\n"
			L"%s %s, PID=%u\n"
			L"RemotePID=%u ",
			iHookRc, nErrCode, gsModuleName, gsVersion, nSelfPID, nRemotePID);

		_wsprintf(szParentPID, SKIPCOUNT(szParentPID)
			L"\n"
			L"ParentPID=%u ",
			self.th32ParentProcessID);

		CEStr lsError(lstrmerge(
			szInfo,
			lsPath.IsEmpty() ? lsName.IsEmpty() ? L"<Unknown>" : lsName.ms_Val : lsPath.ms_Val,
			szParentPID,
			parent.szExeFile));

		LogString(lsError);
		MessageBoxW(NULL, lsError, szTitle, MB_SYSTEMMODAL);
	}
	else
	{
		//_ASSERTE(pi.hProcess && pi.hThread && pi.dwProcessId && pi.dwThreadId);
		wchar_t szDbgMsg[512], szTitle[128];
		_wsprintf(szTitle, SKIPLEN(countof(szTitle)) L"ConEmuC, PID=%u", GetCurrentProcessId());
		_wsprintf(szDbgMsg, SKIPLEN(countof(szDbgMsg)) L"ConEmuC.X, PID=%u\nCmdLine parsing FAILED (%u)!\n%s",
			GetCurrentProcessId(), nRemotePID,
			asCmdArg);
		LogString(szDbgMsg);
		MessageBoxW(NULL, szDbgMsg, szTitle, MB_SYSTEMMODAL);
	}

	return CERR_HOOKS_FAILED;
}
예제 #26
0
	FString GetIdentifier()
	{
		char id[16];
		mysnprintf(id, countof(id), "JS:%d", DeviceIndex);
		return id;
	}
예제 #27
0
int CIconList::CreateTabIconInt(LPCWSTR asIconDescr, bool bAdmin, LPCWSTR asWorkDir)
{
	wchar_t* pszExpanded = ExpandEnvStr(asIconDescr);

	// Need to be created!
	int iIconIdx = -1;
	HICON hFileIcon = NULL;
	wchar_t szTemp[MAX_PATH];
	LPCWSTR pszLoadFile = pszExpanded ? pszExpanded : asIconDescr;
	LPCWSTR lpszExt = (wchar_t*)PointToExt(pszLoadFile);

	bool bDirChanged = false;
	if (asWorkDir && *asWorkDir)
	{
		// Executable (or icon) file may be not availbale by %PATH%, let "cd" to it...
		bDirChanged = gpConEmu->ChangeWorkDir(asWorkDir);
	}

	if (!lpszExt)
	{
		LPWSTR pszFile = NULL;
		if (SearchPath(NULL, pszLoadFile, L".exe", countof(szTemp), szTemp, &pszFile))
		{
			pszLoadFile = szTemp;
			lpszExt = (wchar_t*)PointToExt(pszLoadFile);
		}

		if (!lpszExt)
			goto wrap;
	}

	if (lstrcmpi(lpszExt, L".ico") == 0)
	{
		hFileIcon = (HICON)LoadImage(0, pszLoadFile, IMAGE_ICON,
		                             GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON), LR_DEFAULTCOLOR|LR_LOADFROMFILE);
	}
	else if ((lstrcmpi(lpszExt, L".exe") == 0) || (lstrcmpi(lpszExt, L".dll") == 0))
	{
		//TODO: May be specified index of an icon in the file
		HICON hIconLarge = NULL;
		ExtractIconEx(pszLoadFile, 0, &hIconLarge, &hFileIcon, 1);
		if (hIconLarge) DestroyIcon(hIconLarge);
	}
	else
	{
		//TODO: Shell icons for registered files (cmd, bat, sh, pl, py, ...)
	}

	if (hFileIcon)
	{
		int iIconIdxAdm = -1;
		iIconIdx = ImageList_ReplaceIcon(mh_TabIcons, -1, hFileIcon);

		TabIconCache NewIcon = {lstrdup(asIconDescr), false, iIconIdx};
		m_Icons.push_back(NewIcon);

		HIMAGELIST hAdmList = ImageList_Merge(mh_TabIcons, iIconIdx, mh_TabIcons, mn_AdminIcon+2, 0,0);
		if (hAdmList)
		{
			HICON hNewIcon = ImageList_GetIcon(hAdmList, 0, ILD_TRANSPARENT);
			if (hNewIcon)
			{
				iIconIdxAdm = ImageList_ReplaceIcon(mh_TabIcons, -1, hNewIcon);
				DestroyIcon(hNewIcon);

				TabIconCache AdmIcon = {lstrdup(asIconDescr), true, iIconIdxAdm};
				m_Icons.push_back(AdmIcon);

				if (bAdmin && (iIconIdxAdm > 0))
				{
					iIconIdx = iIconIdxAdm;
				}
			}
		}

		//TODO: bAdmin!!!

		DestroyIcon(hFileIcon);
	}

wrap:
	if (bDirChanged)
	{
		gpConEmu->ChangeWorkDir(NULL);
	}
	SafeFree(pszExpanded);
	return iIconIdx;
}
예제 #28
0
void I_PrintStr(const char *cp)
{
	if (ConWindow == NULL && StdOut == NULL)
		return;

	HWND edit = ConWindow;
	char buf[256];
	wchar_t wbuf[countof(buf)];
	int bpos = 0;
	CHARRANGE selection;
	CHARRANGE endselection;
	LONG lines_before = 0, lines_after;
	CHARFORMAT format;

	if (edit != NULL)
	{
		// Store the current selection and set it to the end so we can append text.
		SendMessage(edit, EM_EXGETSEL, 0, (LPARAM)&selection);
		endselection.cpMax = endselection.cpMin = GetWindowTextLength(edit);
		SendMessage(edit, EM_EXSETSEL, 0, (LPARAM)&endselection);

		// GetWindowTextLength and EM_EXSETSEL can disagree on where the end of
		// the text is. Find out what EM_EXSETSEL thought it was and use that later.
		SendMessage(edit, EM_EXGETSEL, 0, (LPARAM)&endselection);

		// Remember how many lines there were before we added text.
		lines_before = (LONG)SendMessage(edit, EM_GETLINECOUNT, 0, 0);
	}

	while (*cp != 0)
	{
		// 28 is the escape code for a color change.
		if ((*cp == 28 && bpos != 0) || bpos == 255)
		{
			buf[bpos] = 0;
			if (edit != NULL)
			{
				ToEditControl(edit, buf, wbuf, bpos);
			}
			if (StdOut != NULL)
			{
				DWORD bytes_written;
				WriteFile(StdOut, buf, bpos, &bytes_written, NULL);
			}
			bpos = 0;
		}
		if (*cp != 28)
		{
			buf[bpos++] = *cp++;
		}
		else
		{
			const BYTE *color_id = (const BYTE *)cp + 1;
			EColorRange range = V_ParseFontColor(color_id, CR_UNTRANSLATED, CR_YELLOW);
			cp = (const char *)color_id;

			if (range != CR_UNDEFINED)
			{
				// Change the color of future text added to the control.
				PalEntry color = V_LogColorFromColorRange(range);
				if (StdOut != NULL && FancyStdOut)
				{
					// Unfortunately, we are pretty limited here: There are only
					// eight basic colors, and each comes in a dark and a bright
					// variety.
					float h, s, v, r, g, b;
					WORD attrib = 0;

					RGBtoHSV(color.r / 255.f, color.g / 255.f, color.b / 255.f, &h, &s, &v);
					if (s != 0)
					{ // color
						HSVtoRGB(&r, &g, &b, h, 1, 1);
						if (r == 1)  attrib  = FOREGROUND_RED;
						if (g == 1)  attrib |= FOREGROUND_GREEN;
						if (b == 1)  attrib |= FOREGROUND_BLUE;
						if (v > 0.6) attrib |= FOREGROUND_INTENSITY;
					}
					else
					{ // gray
						     if (v < 0.33) attrib = FOREGROUND_INTENSITY;
						else if (v < 0.90) attrib = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE;
						else			   attrib = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY;
					}
					SetConsoleTextAttribute(StdOut, attrib);
				}
				if (edit != NULL)
				{
					// GDI uses BGR colors, but color is RGB, so swap the R and the B.
					swapvalues(color.r, color.b);
					// Change the color.
					format.cbSize = sizeof(format);
					format.dwMask = CFM_COLOR;
					format.dwEffects = 0;
					format.crTextColor = color;
					SendMessage(edit, EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&format);
				}
			}
		}
	}
	if (bpos != 0)
	{
		buf[bpos] = 0;
		if (edit != NULL)
		{
			ToEditControl(edit, buf, wbuf, bpos);
		}
		if (StdOut != NULL)
		{
			DWORD bytes_written;
			WriteFile(StdOut, buf, bpos, &bytes_written, NULL);
		}
	}

	if (edit != NULL)
	{
		// If the old selection was at the end of the text, keep it at the end and
		// scroll. Don't scroll if the selection is anywhere else.
		if (selection.cpMin == endselection.cpMin && selection.cpMax == endselection.cpMax)
		{
			selection.cpMax = selection.cpMin = GetWindowTextLength (edit);
			lines_after = (LONG)SendMessage(edit, EM_GETLINECOUNT, 0, 0);
			if (lines_after > lines_before)
			{
				SendMessage(edit, EM_LINESCROLL, 0, lines_after - lines_before);
			}
		}
		// Restore the previous selection.
		SendMessage(edit, EM_EXSETSEL, 0, (LPARAM)&selection);
		// Give the edit control a chance to redraw itself.
		I_GetEvent();
	}
	if (StdOut != NULL && FancyStdOut)
	{ // Set text back to gray, in case it was changed.
		SetConsoleTextAttribute(StdOut, FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
	}
}
예제 #29
0
HRESULT CpiSubscriptionsRead(
    CPI_ASSEMBLY_LIST* pAsmList,
    CPI_SUBSCRIPTION_LIST* pSubList
    )
{
    HRESULT hr = S_OK;
    UINT er = ERROR_SUCCESS;

    PMSIHANDLE hView, hRec;

    CPI_SUBSCRIPTION* pItm = NULL;
    LPWSTR pwzData = NULL;
    BOOL fMatchingArchitecture = FALSE;

    // loop through all applications
    hr = WcaOpenExecuteView(vcsSubscriptionQuery, &hView);
    ExitOnFailure(hr, "Failed to execute view on ComPlusSubscription table");

    while (S_OK == (hr = WcaFetchRecord(hView, &hRec)))
    {
        // get component
        hr = WcaGetRecordString(hRec, sqComponent, &pwzData);
        ExitOnFailure(hr, "Failed to get component");

        // check if the component is our processor architecture
        hr = CpiVerifyComponentArchitecure(pwzData, &fMatchingArchitecture);
        ExitOnFailure(hr, "Failed to get component architecture.");

        if (!fMatchingArchitecture)
        {
            continue; // not the same architecture, ignore
        }

        // create entry
        pItm = (CPI_SUBSCRIPTION*)::HeapAlloc(::GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(CPI_SUBSCRIPTION));
        if (!pItm)
            ExitFunction1(hr = E_OUTOFMEMORY);

        // get component install state
        er = ::MsiGetComponentStateW(WcaGetInstallHandle(), pwzData, &pItm->isInstalled, &pItm->isAction);
        ExitOnFailure(hr = HRESULT_FROM_WIN32(er), "Failed to get component state");

        // get key
        hr = WcaGetRecordString(hRec, sqSubscription, &pwzData);
        ExitOnFailure(hr, "Failed to get key");
        StringCchCopyW(pItm->wzKey, countof(pItm->wzKey), pwzData);

        // get com+ component
        hr = WcaGetRecordString(hRec, sqComPlusComponent, &pwzData);
        ExitOnFailure(hr, "Failed to get COM+ component");

        hr = ComponentFindByKey(pAsmList, pwzData, &pItm->pAssembly, &pItm->pComponent);

        if (S_FALSE == hr)
        {
            // component not found
            ExitOnFailure1(hr = E_FAIL, "Failed to find component, key: %S", pwzData);
        }

        // get id
        hr = WcaGetRecordFormattedString(hRec, sqID, &pwzData);
        ExitOnFailure(hr, "Failed to get id");

        if (pwzData && *pwzData)
        {
            hr = PcaGuidToRegFormat(pwzData, pItm->wzID, countof(pItm->wzID));
            ExitOnFailure2(hr, "Failed to parse id guid value, key: %S, value: '%S'", pItm->wzKey, pwzData);
        }

        // get name
        hr = WcaGetRecordFormattedString(hRec, sqName, &pwzData);
        ExitOnFailure(hr, "Failed to get name");
        StringCchCopyW(pItm->wzName, countof(pItm->wzName), pwzData);

        // get event clsid
        hr = WcaGetRecordFormattedString(hRec, sqEventCLSID, &pwzData);
        ExitOnFailure(hr, "Failed to get event clsid");
        StringCchCopyW(pItm->wzEventCLSID, countof(pItm->wzEventCLSID), pwzData);

        // get publisher id
        hr = WcaGetRecordFormattedString(hRec, sqPublisherID, &pwzData);
        ExitOnFailure(hr, "Failed to get publisher id");
        StringCchCopyW(pItm->wzPublisherID, countof(pItm->wzPublisherID), pwzData);

        // get properties
        if (CpiTableExists(cptComPlusSubscriptionProperty))
        {
            hr = CpiPropertiesRead(vcsSubscriptionPropertyQuery, pItm->wzKey, pdlSubscriptionProperties, &pItm->pProperties, &pItm->iPropertyCount);
            ExitOnFailure(hr, "Failed to get subscription properties");
        }

        // set references & increment counters
        if (WcaIsInstalling(pItm->isInstalled, pItm->isAction))
        {
            CpiApplicationAddReferenceInstall(pItm->pAssembly->pApplication);
            pItm->pAssembly->fReferencedForInstall = TRUE;
            pSubList->iInstallCount++;
            if (pItm->pAssembly->iAttributes & aaRunInCommit)
                pSubList->iCommitCount++;
        }
        if (WcaIsUninstalling(pItm->isInstalled, pItm->isAction))
        {
            CpiApplicationAddReferenceUninstall(pItm->pAssembly->pApplication);
            pItm->pAssembly->fReferencedForUninstall = TRUE;
            pSubList->iUninstallCount++;
        }

        // add entry
        if (pSubList->pFirst)
            pItm->pNext = pSubList->pFirst;
        pSubList->pFirst = pItm;
        pItm = NULL;
    }

    if (E_NOMOREITEMS == hr)
        hr = S_OK;

LExit:
    // clean up
    if (pItm)
        FreeSubscription(pItm);

    ReleaseStr(pwzData);

    return hr;
}
예제 #30
0
int
wr_parse_matrix(l2p_t *l2p, char *str)
{
	char      *lcore_port[MAX_MATRIX_ENTRIES];
	char buff[256];
	int i, m, k, lid_type, pid_type;
	uint32_t pid, lid;
	lp_t lp;
	rxtx_t cnt, n;

	wr_strccpy(buff, str, " \r\n\t\"");

	/* Split up the string into <lcore-port>, ... */
	k = wr_strparse(buff, ",", lcore_port, countof(lcore_port));
	if (k <= 0) {
		fprintf(stderr, "%s: could not parse (%s) string\n",
		        __FUNCTION__, buff);
		return 0;
	}

	for (i = 0; (i < k) && lcore_port[i]; i++) {
		char      *arr[3];
		char str[64];

		/* Grab a private copy of the string. */
		strncpy(str, lcore_port[i], sizeof(str));

		/* Parse the string into <lcore-list> and <port-list> */
		m = wr_strparse(lcore_port[i], ".", arr, 3);
		if (m != 2) {
			fprintf(stderr, "%s: could not parse <lcore-list>.<port-list> (%s) string\n",
			        __FUNCTION__, lcore_port[i]);
			return 0;
		}

		memset(&lp, '\0', sizeof(lp));

		if (wr_parse_lcore_list(arr[0], lp.lcores) ) {
			fprintf(stderr, "%s: could not parse <lcore-list> (%s) string\n",
			        __FUNCTION__, arr[0]);
			return 0;
		}

		if (wr_parse_port_list(arr[1], lp.ports) ) {
			fprintf(stderr, "%s: could not parse <port-list> (%s) string\n",
			        __FUNCTION__, arr[1]);
			return 0;
		}

		/* Handle the lcore and port list maps */
		fprintf(stderr, "%-16s lcores: ", str);
		wr_dump_lcore_map("RX", lp.lcores[RX_IDX].ls);
		wr_dump_lcore_map("TX", lp.lcores[TX_IDX].ls);
		fprintf(stderr, " ports: ");
		wr_dump_port_map("RX", lp.ports[RX_IDX].ps);
		wr_dump_port_map("TX", lp.ports[TX_IDX].ps);
		fprintf(stderr, "\n");

		for (lid = 0; lid < RTE_MAX_LCORE; lid++) {
			lid_type = 0;
			if (_btst(lp.lcores[RX_IDX].ls, lid) )
				lid_type |= RX_TYPE;
			if (_btst(lp.lcores[TX_IDX].ls, lid) )
				lid_type |= TX_TYPE;
			if (lid_type == 0)
				continue;

			for (pid = 0; pid < RTE_MAX_ETHPORTS; pid++) {
				pid_type = 0;
				if (_btst(lp.ports[RX_IDX].ps, pid) )
					pid_type |= RX_TYPE;
				if (_btst(lp.ports[TX_IDX].ps, pid) )
					pid_type |= TX_TYPE;
				if (pid_type == 0)
					continue;
				wr_l2p_connect(l2p, pid, lid, lid_type);
			}
		}
	}

	for (pid = 0; pid < RTE_MAX_ETHPORTS; pid++) {
		n.rxtx = 0;
		for (lid = 0; lid < RTE_MAX_LCORE; lid++)
			if ( (cnt.rxtx = wr_get_map(l2p, pid, lid)) > 0) {
				if (cnt.tx > 0)
					n.tx++;
				if (cnt.rx > 0)
					n.rx++;
			}
		l2p->map[pid][lid].rxtx = n.rxtx;	/* Update the lcores per port */
	}
	for (lid = 0; lid < RTE_MAX_LCORE; lid++) {
		n.rxtx = 0;
		for (pid = 0; pid < RTE_MAX_ETHPORTS; pid++)
			if ( (cnt.rxtx = wr_get_map(l2p, pid, lid)) > 0) {
				if (cnt.tx > 0)
					n.tx++;
				if (cnt.rx > 0)
					n.rx++;
			}
		l2p->map[pid][lid].rxtx = n.rxtx;	/* Update the ports per lcore */
	}

	return 0;
}